From arnodel at googlemail.com Sat Nov 15 05:13:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Nov 2008 10:13:12 +0000 Subject: Official definition of call-by-value (Re: Finding the instance reference...) References: <6nul1qF100urU1@mid.individual.net> <6nvts2F15nlmU1@mid.individual.net> Message-ID: rurpy at yahoo.com writes: > I have yet to see any reasonable definition of a Python > value in the Python docs or elsewhere, despite the fact > that a value is one of the three defining characteristics > of an object, a central concept in Python. I don't remember how the expression 'object value' is used in the Python docs (and python.org is unreachable from where I am at the moment) but I know that I don't need such a concept to understand, or code in, Python. Objects have a type, may have attributes, and that's it! -- Arnaud From steve at holdenweb.com Fri Nov 21 18:48:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Nov 2008 18:48:07 -0500 Subject: Custom Formatting The Output Of subprocess.Popen In-Reply-To: References: <1fa5b276-cd38-44b4-ac79-0d85775a67e0@a12g2000yqm.googlegroups.com> Message-ID: thedsadude at gmail.com wrote: > On Nov 21, 8:50 pm, Scott David Daniels wrote: >> thedsad... at gmail.com wrote: >>> Hello, >>> I'm launching a script as follows: >>> >>> p = subprocess.Popen(['./p.py', 'aa']) >>> p.wait() >>> >>> If p.py writes to sys.stdout, then it is shown on the console.... >> You seem to be missing the fact that ./py is run in a different process. >> The "sys.stdout" that p.py uses is different from that in the program >> calling Popen. In fact, it could be using a different Python. The >> situation is really similar to >> p = subprocess.Popen([, 'aa']) >> in that you have no way to "muck with the guts" of the subprocess, you >> can only post-process its output. >> >> --Scott David Daniels >> Scott.Dani... at Acm.Org > > > Hello, > > Thanks Diez & Scott for your replies. > > The subprocess.Popen documentation states, concerning the stding, > stdout, stderr, arguments, that: > > stdin, stdout and stderr specify the executed programs' standard > input, standard output and standard error file handles, respectively. > Valid values are PIPE, an existing file descriptor (a positive > integer), an existing file object, and None. PIPE indicates that a new > pipe to the child should be created. With None, no redirection will > occur; the child's file handles will be inherited from the parent. > Additionally, stderr can be STDOUT, which indicates that the stderr > data from the applications should be captured into the same file > handle as for stdout. > > so, it seems to me that if I would know how to write a file object, > then I could write one that prefixes each line, and that would be > fine, no? I don't see how this would necessitate waiting for p.py's > termination, or matter that it is a different process. I just don't > know how to create a file object. > It was an astute observation that you could provide your own "file-like object" as the output for the subprocess. However, you may find that due to buffering effects the subprocess's output doesn't get completely intermingled with the calling process's output. Although you can specify "unbuffered", which is the default for subprocess.popen, I don't believe this guarantees that the subprocess itself won't perform buffering. Others may know better. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan_ml at behnel.de Thu Nov 27 08:52:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Nov 2008 14:52:19 +0100 Subject: Exhaustive Unit Testing In-Reply-To: References: <8ae042c1-9a6c-412a-83f6-92b1d58e1ce5@j32g2000yqn.googlegroups.com> Message-ID: <492ea611$0$32680$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > If you don't test all the paths, then by definition you > have program paths which have never been tested. Unless those paths are > so trivially simple that you can see that they must be correct just by > looking at the code, then the chances are very high that they will hide > bugs. Not to mention that you can sometimes look at awfully trivial code three times and only see the obvious bug in that code the fourth time you put an eye on it a good night's sleep later. Expecting code paths in a nested if statement with nine conditions that are not worth testing due to obvious triviality, is pretty hubristic. Stefan From johnroth1 at gmail.com Thu Nov 13 10:12:27 2008 From: johnroth1 at gmail.com (John Roth) Date: Thu, 13 Nov 2008 07:12:27 -0800 (PST) Subject: what should we use instead of the 'new' module? References: Message-ID: On Nov 12, 8:32?pm, Flavio wrote: > How is this code going to look like in Python 3.0? (it's deprecated > according tohttp://docs.python.org/library/new.html#module-new, but > it does not tell what to use instead) > > ?method = new.instancemethod(raw_func, None, cls) > ?setattr(cls, name, method) > > Can we write code in python2.5/2.6 that will work in 3.0? I'm not sure why your example works: instancemethod is used internally to wrap the function object when it's invoked. The only other use for it is to add a method to an instance, not to a class. As another poster said, an instance method in a class is simply the function object. Static and class methods require wrappers, but those are both built-in functions and they also have decorators. John Roth From joe at strout.net Mon Nov 10 10:39:58 2008 From: joe at strout.net (Joe Strout) Date: Mon, 10 Nov 2008 08:39:58 -0700 Subject: Finding the instance reference of an object In-Reply-To: References: <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <01203bbd$0$20642$c3e8da3@news.astraweb.com> <3c4edf32-acda-4244-ba46-bad5ea623303@w39g2000prb.googlegroups.com> <0120cb30$0$20642$c3e8da3@news.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <6nkparFlu2nqU1@mid.individual.net> <8b8a629c-b2bc-401b-9102-c88bfc8c3f2b@l33g2000pri.googlegroups.com> <6nnrrfFmpa9lU1@mid.individual.net> <6nqfq2F837kU1@mid.individual.net> Message-ID: On Nov 10, 2008, at 8:30 AM, Terry Reedy wrote: >> That hinges on what exactly is meant by "changes to >> the arguments". > > Mutating them, like Python does, which is why calling Python CBV > leads people to write buggy code. > > >In Python it can only mean assigning >> directly to the bare name -- anything else isn't >> changing the argument itself, but something else to >> which the argument refers. > > Hogwash. The argument is the object and mutable objects can be > changed as seen by the caller. By that definition, Java, REALbasic, C++, and VB.NET are all call-by- reference too (even when explicitly using the "ByVal" keyword in RB/ VB.NET). This will come as quite a shock to the designers and users of those languages. For what it's worth, I think Greg (double-quoted above) has it exactly right. The argument in any of these languages is an object reference; changing the object and changing the object reference are two different things. Best, - Joe From james at agentultra.com Sat Nov 15 23:25:13 2008 From: james at agentultra.com (J Kenneth King) Date: Sat, 15 Nov 2008 23:25:13 -0500 Subject: Multiprocessing vs. [Pyro, RPyC] References: <18717.58823.533948.327676@montanaro-dyndns-org.local> Message-ID: <85vduocn6e.fsf@agentultra.com> Jeffrey Barish writes: > skip at pobox.com wrote: > >> >> Jeffrey> With the release of multiprocessing in Python 2.6, is there >> any Jeffrey> reason to use Pyro or RPyC? >> >> As far as I know the multiprocessing module only works on one machine >> (multi-cpu or multi-core), not across machines. > > So I thought at first, but then I saw this statement in the documentation: > > It is possible to run a manager server on one machine and have clients use > it from other machines (assuming that the firewalls involved allow it). Depends. I don't know much about the multiprocessing module in 2.6, but I have built a distributed application on Pyro. Pyro has many advantages -- a query-able name server, GUI tools for monitoring your setup, and remote agents. It is also rather simple in comparison to other similar tools (*cough*twisted.pb*cough*). However, it is essentially an RPC style system, so some people might not be too comfortable with it. YMMV. From kyosohma at gmail.com Wed Nov 19 14:17:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Nov 2008 11:17:12 -0800 (PST) Subject: calling python scripts as a sub-process References: Message-ID: <256d0997-84dd-40da-bd20-3d73ee9fe3b9@1g2000prd.googlegroups.com> On Nov 19, 1:03?pm, Catherine Moroney wrote: > I have one script (Match1) that calls a Fortran executable as a > sub-process, and I want to write another script (Match4) that > spawns off several instances of Match1 in parallel and then waits > until they all finish running. ?The only way I can think of doing this > is to call it as a sub-process, rather than directly. > > I'm able to get Match1 working correctly in isolation, using the > subprocess.Popen command, but calling an instance of Match1 as a > subprocess spawned from Match4 isn't working. > > The command (stored as an array of strings) that I'm executing is: > > ['python ../src_python/Match1.py ', > '--file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ', > '--file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf ', > '--block_start=62 ', '--block_end=62 ', '--istep=16 ', "--chmetric='M2' > ", "--use_textid='true '"] > > and I'm calling it as: > > sub1 = subprocess.Popen(command) > > I get the error below. ?Does anybody know what this error refers > to and what I'm doing wrong? ?Is it even allowable to call another > script as a sub-process rather than calling it directly? > > ? File "../src_python/Match4.py", line 24, in RunMatch4 > ? ? ?sub1 = subprocess.Popen(command1) > ? ?File "/usr/lib64/python2.5/subprocess.py", line 593, in __init__ > ? ? ?errread, errwrite) > ? ?File "/usr/lib64/python2.5/subprocess.py", line 1051, in _execute_child > ? ? ?raise child_exception > OSError: [Errno 2] No such file or directory > > Thanks for any help, > > Catherine Try giving an absolute path to the python file rather than a relative path. I don't think the subprocess module "knows" where to look otherwise. Mike From Scott.Daniels at Acm.Org Sun Nov 30 13:16:18 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 30 Nov 2008 10:16:18 -0800 Subject: unicode and hashlib In-Reply-To: References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> Message-ID: Jeff H wrote: > ... > decode vs encode > You decode from on character set to a unicode object > You encode from a unicode object to a specifed character set Pretty close: encode: Think of characters a "conceptual" -- you encode a character string into a bunch of bytes (unicode -> bytes) in order to send the characters along a wire, into an e-mail, or put in a database. decode: You got the bytes from the wire, database, Morse code, whatever. You decode the byte stream into characters, and now you really have characters. Thinking of it this way makes it clear which name is which, unless (as I did once in this thread) you switch opposite concepts carelessly. Characters are content (understood by humans), bytes are gibberish carried by hardware which likes that kid of thing. You encode a message into nonsense for your carrier to carry to your recipient, and the recipient decodes the nonsense back into the message. --Scott David Daniels Scott.Daniels at Acm.Org From lie.1296 at gmail.com Sun Nov 9 05:36:56 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 9 Nov 2008 10:36:56 +0000 (UTC) Subject: Are .pyc files portable? References: <0a47b9e7-c07b-4a25-a7c1-0ee894803b74@x16g2000prn.googlegroups.com> Message-ID: On Fri, 07 Nov 2008 18:36:41 -0800, Roy Smith wrote: > I'm using Python as part of a test fixture for a large (mostly C++) > software project. We build on a lot of different platforms, but Solaris > is a special case -- we build on Solaris 8, and then run our test suite > on Solaris 8, 9, and 10. The way the build system is set up (driven by > Build Forge), the Sol 8, 9, and 10 test passes can happen in any order. > The tests all run in a common directory, shared by NFS on all three > machines. > > If (for example) the Sol 10 tests run first, and create .pyc files, will > those .pyc files work correctly when the Sol 8 and Sol 9 test passes > come along and run them in the same directories? > > The python binary is a build of 2.5.1 that we did on Solaris 8. The > same binary is used on all Solaris platforms. Although we do separate > 32-bit and 64-bit builds of our product, the python binary we use for > the test driver is the same 32-bit build on all of them. > > A related question: is there any way to tell Python to put the .pyc > files in some other directory, i.e. NOT the same directory where the .py > sources are. That would make things cleaner, since we could just tell > each system to put its .pyc's in a different place. > > We've also got some games we play with symlink farms (lndir), which may > be part of the solution here, but I want to explore all the > possibilities first. If all that responses confuse you, the simple answer is: 1. Python bytecode is cross-platform 2. but is not cross-version i.e. as long as the .pyc can be run accross different platforms as long as the version number of the compiling python and executing python is equal. A simple solution if you've got different version of python across many platform is to provide a .py file that redirects the program to each version-specific .pyc (cross-platform and cross-version if written with some care) From ldo at geek-central.gen.new_zealand Tue Nov 18 01:33:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 18 Nov 2008 19:33:02 +1300 Subject: possible newline problems References: Message-ID: Robocop wrote: > for line in fileinput.input(['/proc/mounts']): This will include the newline at the end of every line. > if line == 'sshfs#root at website.com:/usr/home/sites/www.website.com/ > web/PICTURES/django /www/htdocs/hatProductAdd/media/images/PICTURES/ > django fuse rw,nosuid,nodev,user_id=0,group_id=0,max_read=65536 0 0': You're comparing the line against a string that doesn't end with a newline. From bearophileHUGS at lycos.com Sun Nov 16 02:44:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 15 Nov 2008 23:44:28 -0800 (PST) Subject: Clustering the keys of a dict according to its values References: <491d6b57$0$32671$9b4e6d93@newsspool2.arcor-online.net> <323e1137-de0f-453d-ba73-41cc028c4da7@l33g2000pri.googlegroups.com> <491d9fd4$0$16270$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers: > What is data is another type of sequence or iterable ?-)< The original problem statement was: Florian Brucker: >Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: [...] Another requirement is that it should also work on lists, in that case with indices instead of keys. We may assume that all values in the original dict/list can be used as dict keys.< If the problem changes, then the code has to/can change. When you write code it's better to avoid over-generalization (this is also a rule in Agile programming practices). Bye, bearophile From joe at strout.net Wed Nov 12 10:10:27 2008 From: joe at strout.net (Joe Strout) Date: Wed, 12 Nov 2008 08:10:27 -0700 Subject: How can a function know what module it's in? In-Reply-To: References: <660C0EFD-A8FD-4F97-919B-62387FC7CF57@strout.net> Message-ID: <94C7C05A-7F2E-42B2-A503-337FB1F3E223@strout.net> On Nov 11, 2008, at 9:49 PM, Rafe wrote: >>> I'm sure there is a magic identifier somewhere that lets a code get >>> a reference to its own module, but I haven't been able to find it. > > import sys > this_module = sys.modules[__name__] Beautiful! Thanks very much. For the archives, here is my standard module-testing idiom now: def _test(): import doctest, sys doctest.testmod(sys.modules[__name__]) if __name__ == "__main__": _test() Now, when I execute the module directly, it will test itself; and if I need to test it from the outside (for example, under pdb) I can import the module and then run themodule._test(). To whom should I make the suggestion that this go into doctest docs? Cheers, - Joe From clp at rebertia.com Thu Nov 6 15:11:48 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 6 Nov 2008 12:11:48 -0800 Subject: List to Text back to List In-Reply-To: References: Message-ID: <47c890dc0811061211o4a4eab6ei25c4da0fe16413a4@mail.gmail.com> On Thu, Nov 6, 2008 at 12:04 PM, SimonPalmer wrote: > Hi, I am looking for a way to convert a List of floating point numbers > to and from text. I am embedding it in an XML document and am looking > for a neat way to serialise and de-serialise a list from a text node. > I can easily write something to do it manually but I wondered whether > List had native support to go to and from text. > > If not List, are there any other collections/arrays that do this? It's not really a matter of the collection, but more a matter of serialization format/library. If you want the serialized representation to be human-readable, use JSON (http://docs.python.org/library/json.html#module-json). If that's not a requirement, use pickle (http://docs.python.org/library/pickle.html#module-pickle). Both modules can convert simple Python data, such as your list of floats, to a bytestream and back again. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > TIA > Simon > -- > http://mail.python.org/mailman/listinfo/python-list > From fabiofz at gmail.com Tue Nov 4 20:33:44 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 4 Nov 2008 22:33:44 -0300 Subject: developing python extensions with CDT and Pydev in Eclipse In-Reply-To: <0c8999b4-4340-4ff1-b2db-7f95df5b7d96@u18g2000pro.googlegroups.com> References: <0c8999b4-4340-4ff1-b2db-7f95df5b7d96@u18g2000pro.googlegroups.com> Message-ID: > Has anyone been able to use both Pydev and CDT to debug extension > modules? > > The question was asked about a year ago on this list, and I am hoping > that > someone has figured it out in meantime. Previous answers on that: https://sourceforge.net/forum/message.php?msg_id=4268986 https://sourceforge.net/mailarchive/forum.php?thread_name=47347f490810251544k2794aeeak175ac23c4c57fbf3%40mail.gmail.com&forum_name=pydev-users Cheers, Fabio From joe at strout.net Thu Nov 6 18:34:23 2008 From: joe at strout.net (Joe Strout) Date: Thu, 6 Nov 2008 16:34:23 -0700 Subject: Finding the instance reference of an object In-Reply-To: <99574ae4-2019-4e79-9865-a4a6d8ed76dc@w39g2000prb.googlegroups.com> References: <6mv3bnFj2qd8U1@mid.individual.net> <011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> <011ac754$0$20643$c3e8da3@news.astraweb.com> <8862f5ae-c482-4f53-a020-629eb45a5c3f@c22g2000prc.googlegroups.com> <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <99574ae4-2019-4e79-9865-a4a6d8ed76dc@w39g2000prb.googlegroups.com> Message-ID: On Nov 5, 2008, at 2:06 PM, Lie wrote: >> > > I'm fed up with you. I'm sorry -- I'm really not trying to be difficult. And it's odd that you're fed up with me, yet you seem to be agreeing with me on at least most points. > In Von Neumann Architecture computers, only pass-by-value is natively > supported. Other idioms are made on top of pass-by-value. Well, sure. But a language may or may not naturally support the others. > That's why exclusively pass-by-value languages like C is most flexible > than other exclusively pass-by-. > > BUT the difference is clear, if you want to do pass-by-reference in C > (I prefer to call it faux pass-by-reference), you'd have to manually > find a variable's address, pass it by-value, then dereference the > address. Agreed. > Compare with VB's ByRef or C++'s &, which does all that > _automatically_ for you behind the scene. Agreed again. > Another example: pass-by-object. Here's where we depart, I guess. I think there's no such thing (see for example, and the dead-tree references I have on hand agree). > I disagree with the term pass-by-object-reference, since the notion > of object reference is unnecessary > in a true pass-by-object mechanism (i.e. we should travel outside VNA > realm for a true pass-by-object mechanism). Problem is: I'm not aware > of any computer architecture that can accommodate pass-by-object > natively or whether such architecture is feasible to be made. I don't think it's necessary (or helpful) to reach down into the architecture or implementation details. What matters is the behavior as seen by the language user. Variables in a language could hold actual object data (in which case "a = b" would copy the data from b into a), or they could hold just references to object data that lives elsewhere (in which case "a = b" would copy that reference, giving you two references to the same object). In Python, they are of course just references. Then, and completely independent of that, variables could be passed into a method by value or by reference (or by several other more esoteric evaluation strategies that are rarely used, but "call by object" isn't one of them). Again, it's easy to tell these apart with a simple behavioral test. Python passes its object references by value; changes to the formal parameter have no effect on the actual parameter. > In pass-by-object, the whole object is passed around, not a copy of > the object like in pass-by-value or a copy of the pointer to the > object like in faux pass-by-reference. I can't understand what that would mean, unless we imagine the variable actually containing the object data; but it doesn't, or "a = b" would copy that data, which clearly it does not. Understanding that a name in Python is merely a reference to the object, and not the object itself, seems to me to be one of the fundamental truths that any beginning Python programmer must know. > This makes pass-by-object > actually closer to pass-by-reference than to pass-by-value, since the > notion of VNA's requirement for Object Reference means passing > pointers around. But don't let it confuse you, the pass-by-object > mechanism itself does not recognize Object Reference, unlike pass-by- > reference recognition of reference/pointer. Sorry, it's confusing me whether I want it to or not. And here's what I don't understand: object references are so simple, why do people go to such great lengths to pretend that Python doesn't have them, resulting in a far more complex and convoluted explanation that is much harder to understand? > Now that I have clearly defined the line between pass-by-object and > pass-by-value, I'm left with you thinking what's the difference > between pass-by-object and pass-by-reference. If they're that hard to tell apart, then Python doesn't have either, since it is very clear and obvious that Python does not have pass-by- reference (since you can't write a function to swap two parameters, for example). > In pass-by-reference, names are _mnemonic to location in memory_. > In pass-by-object, names are _mnemonic to objects_. These would be equivalent if objects live at some location in memory, wouldn't they? > In pass-by-reference, when we assign a > value to the name, we'd assign a value _to the location in memory_. In > pass-by-object, when we assign a value to the name, we assign an > object _to the name_. When passing parameters, pass-by-reference > systems passed the memory address and alias that memory address to a > local name. In pass-by-object system, since the object itself has no > idea of its own name, so it is rebound to a local name. You can say > that pass-by-reference system is memory-location-centered, while pass- > by-object system is name-centered. Hmm. I can only interpret "the object is rebound to a local name" sounds the same to me as "a local variable is assigned a reference to the object." Can you explain how they're different? I see how what you're describing is different from pass by reference; I just don't see how it's any different from pass by value. > To summarize, the key bit you're missing is built-in _automatic_ > abstraction from pass-by-value. All pass-by- except > pass-by-value is an emulation over an architecture that can only > natively pass-by-value. Yes, OK, that's great. But there are several standard pass-by- somethings that are defined by the CS community, and which are simple and clear and apply to a wide variety of languages. "Pass by object" isn't one of them. I guess if you want to campaign for it as a shorthand for "object reference passed by value," you could do that, and it's not outrageous. But to anybody new to the term, you should explain it as exactly that, rather than try to claim that Python is somehow different from other OOP languages where everybody calls it simply pass by value. > pass-by-reference is emulated in C, C++, and > VB by passing memory address/pointer but C isn't a by-ref system > because C doesn't provide the automatization. Yes, that's true of C. I never argued that C had a by-ref mode. C++, VB, and REALbasic all do, however. Python and Java do not. > What makes python's parameter passing called as pass-by-object is > because python provides > the automatization to make it seems that you can do true pass-by- > object. OK, if there were such a thing as "pass-by-object" in the standard lexicon of evaluation strategies, I would be perfectly happy saying that a system has it if it behaves as though it has it, regardless of the underpinnings. My objection to this term is simply that it is made up and nonstandard, and adds no new value to the discussion. To me, "object references passed by value" is simple and clear, where as "pass by object" means nothing (until you explain that it means the former). However, if you really think the term is that handy, and we want to agree to say "Python uses pass by object" and answer the inevitable "huh?" question with "that's shorthand for object references passed by value," then I'd be OK with that. Best, - Joe From xdicry at gmail.com Mon Nov 3 17:47:05 2008 From: xdicry at gmail.com (Evan) Date: Mon, 3 Nov 2008 14:47:05 -0800 (PST) Subject: problem with single-quote and double-quote when using subprocess. Message-ID: Hello - i'm trying to call subprocess.popen on the 'command-based' function in linux. When I run the command from the shell, like so: goset -f ' "%s %s" name addr ' file_name it works fine however when I try to do it in python like so: p = subprocess.Popen(["goest",'-f \'\"%s %s\" name addr\' ', 'file_name'], shell=True) It always failed. I also try like so: p = subprocess.Popen(["goest","-f '\"%s %s\" name addr' ", 'file_name'], shell=True) It also failed. Does anybody have a good suggestion for this matter? thanks in advance. Evan From pavlovevidence at gmail.com Wed Nov 5 08:20:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 5 Nov 2008 05:20:15 -0800 (PST) Subject: False and 0 in the same dictionary References: Message-ID: <42f1af3b-adf4-4745-b922-096ba09695c5@e38g2000prn.googlegroups.com> On Nov 4, 3:48?pm, Prateek wrote: > I've been using Python for a while (4 years) so I feel like a moron > writing this post because I think I should know the answer to this > question: > > How do I make a dictionary which has distinct key-value pairs for 0, > False, 1 and True. > As I have learnt, 0 and False both hash to the same value (same for 1 > and True). > > >>> b = {0:'xyz', False:'abc'} > >>> b > > {0: 'abc'} ?# Am I the only one who thinks this is weird? > > This obviously stems from the fact that 0 == False but 0 is not False > etc. etc. > > That doesn't help my case where I need to distinguish between the two > > The same issue applies in a list: > > Suppose I do: > > >>> a = [0, 1, True, False] > >>> a.index(False) > > 0 > > Wha??? Help. Let me suggest using surrogate objects instead of True and False: class TrueObject(object): def __nonzero__(self): return True class FalseObject(object): def __nonzero__(self): return False DistinctTrue = TrueObject() DistinctFalse = FalseObject() If that doesn't work and you really need the actual True and False objects to be distinct, it's not too hard to special case a dict to get it: class special_dict(dict): def __init__(self,*args,**kwargs): self.true_surrogate = object() self.false_surrogate = object() super(special_dict,self).__init__(*args,**kwargs) def __getitem__(self,value): if value is True: value = self.true_surrogate elif value is False: value = self.false_surrogate super(special_dict,self).__getitem__(value) ## etc. Carl Banks From stef.mientki at gmail.com Sat Nov 29 20:18:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 30 Nov 2008 02:18:40 +0100 Subject: Emacs vs. Eclipse vs. Vim In-Reply-To: References: Message-ID: <4931E9F0.7050903@gmail.com> Mario Testinori wrote: > On Sat, 29 Nov 2008 12:44:14 -0800, Josh wrote: > > >> If you were a beginning programmer and willing to make an investment in >> steep learning curve for best returns down the road, which would you pick? >> >> I know this topic has been smashed around a bit already, but 'learning >> curve' always seems to be an arguement. If you feel that one is easier >> or harder than the others to learn feel free to tell, but let's not make >> that the deciding factor. Which one will be most empowering down the >> road as a development tool? >> >> Thanks in advance, >> >> JR >> > > First, you must understand that this is an extremelly dangerous > question to ask on a public newsgroup (expecially regarding the first > and the third in the series). Wars have began over this. Many people > were harmed in those wars. Many a land have been conquered and many a > land lost. Many cows were killed. Many chickens were eaten in those > wars. > Don't we have something like a poll to solve this peacefully ? cheers, Stef From bellman at lysator.liu.se Mon Nov 24 04:22:02 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Mon, 24 Nov 2008 09:22:02 +0000 (UTC) Subject: Security implications of using open() on untrusted strings. References: Message-ID: r0g wrote: > Although it's a desktop (not internet facing) app I'm a little squeamish > piping raw user input into a filesystem function like that and this app > will be dealing with some particularly sensitive data so I want to be > careful and minimize exposure where practical. > Has programming PHP and Web stuff for years made me overly paranoid > about this or do I should I still be scrubbing input like this before I > feed it to filesystem functions? If so does anyone know of a module > that may help or have any other advice. > Note: In this particular case the user input is only specifying the name > of a file that will be opened for writing _not_ reading and the > interface is GUI only (wxWidgets). Is the user *running* the application the same as the user who feeds it input? If it is, then there is no need to filter the filenames, since that user could just do "rm bad-file" (or "DEL BAD-FILE" on MS-Windows) anyway to destroy it. (Of course, if you are passing the filename to, e.g, os.system(), you would need to quote it properly, but that is to avoid surprising the user; it is one thing to let the user overwrite a file named "foo; rm -rf $HOME", quite another to pass that string unquoted to /bin/sh when the user thought he was just typing a filename.) -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "I don't think [that word] means what you ! bellman @ lysator.liu.se think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! From sjmachin at lexicon.net Mon Nov 10 18:14:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Nov 2008 15:14:55 -0800 (PST) Subject: Memory error due to the huge/huge input file size References: <5f12daa1-b777-4653-bdc8-6c1f8787c2f7@a29g2000pra.googlegroups.com> Message-ID: On Nov 11, 8:47?am, tejsu... at gmail.com wrote: > import linecache Why??? > reader2 = csv.reader(open(sys.argv[2],"rb")) > reader2_list = [] > reader2_list.extend(reader2) > > for data2 in reader2_list: > ? ?refSeqIDsinTransPro.append(data2[3]) > for data2 in reader2_list: > ? ?promoterSequencesinTransPro.append(data2[4]) All you need to do is replace the above by: reader2 = csv.reader(open(sys.argv[2],"rb")) for data2 in reader2: refSeqIDsinTransPro.append(data2[3]) promoterSequencesinTransPro.append(data2[4]) From prologic at shortcircuit.net.au Tue Nov 11 01:36:25 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 11 Nov 2008 16:36:25 +1000 Subject: concurrency program design stackless python tasklet or python thread? In-Reply-To: <81f2badd0811102157y4813ad85gd1ac5305bc806dfa@mail.gmail.com> References: <81f2badd0811102157y4813ad85gd1ac5305bc806dfa@mail.gmail.com> Message-ID: On Tue, Nov 11, 2008 at 3:57 PM, davy zhang wrote: > first here is my basic idea is every actor holds their own msg queue, > the process function will handle the message as soon as the dispatcher > object put the message in. > > This idea naturally leads me to place every actor in a separate thread > waiting for msg > > but the rumor has it, stackless python with tasklet and channel can do > much more better in concurrency program, so I dive my head into it. > > but I found the tasklet is really a lined-up sequence , that means if > a tasklet blocked or do some time consuming calculation, the other > tasklets can not get the cpu slice > > so we must design very carefully to avoid the big job for single task > > I am just confused why the stackless python is said to be good at > concurrency program model or just I get a wrong idea to practice? You could try circuits [1] - An event driven way to concurrency. --JamesMills [1] http://trac.softcircuit.com.au/circuits/ -- -- -- "Problems are solved by method" From denis.papathanasiou at gmail.com Thu Nov 13 15:22:02 2008 From: denis.papathanasiou at gmail.com (dpapathanasiou) Date: Thu, 13 Nov 2008 12:22:02 -0800 (PST) Subject: Avoiding local variable declarations? Message-ID: <8d695469-348d-483d-8fcb-2ed43cfd2a75@s1g2000prg.googlegroups.com> I have some old Common Lisp functions I'd like to rewrite in Python (I'm still new to Python), and one thing I miss is not having to declare local variables. For example, I have this Lisp function: (defun random-char () "Generate a random char from one of [0-9][a-z][A-Z]" (if (< 50 (random 100)) (code-char (+ (random 10) 48)) ; ascii 48 = 0 (code-char (+ (random 26) (if (< 50 (random 100)) 65 97))))) ; ascii 65 = A, 97 = a My Python version looks like this: def random_char (): '''Generate a random char from one of [0-9][a-z][A-Z]''' if random.randrange(0, 100) > 50: return chr( random.randrange(0, 10) + 48 ) # ascii 48 = 0 else: offset = 65 # ascii 65 = A if random.randrange(0, 100) > 50: offset = 97 # ascii 97 = a return chr( random.randrange(0, 26) + offset ) Logically, it's equivalent of the Lisp version. But is there any way to avoid using the local variable (offset) in the Python version? From felipevaldez at gmail.com Wed Nov 26 15:58:16 2008 From: felipevaldez at gmail.com (fel) Date: Wed, 26 Nov 2008 12:58:16 -0800 (PST) Subject: hello from colombia Message-ID: <5c451e65-4e51-40ab-97d4-e5853927dedb@d42g2000prb.googlegroups.com> I work in a small software company using php all day, I wish the usage of Python was more common within my company they are starting a new project (insurance stuff) using Java, and I just hate that eventually I'l be debugging someone-else's java code how can I convince them that Python is better, and get them to re- think their strategy? also, kuddos on the language, you serve mankind as few do. fel. From Slaunger at gmail.com Fri Nov 21 19:18:52 2008 From: Slaunger at gmail.com (Slaunger) Date: Fri, 21 Nov 2008 16:18:52 -0800 (PST) Subject: Best strategy for finding a pattern in a sequence of integers References: <84d521eb-9e5f-40e1-9bbe-9a2713d37ce8@13g2000yql.googlegroups.com> <502f6a91-fe02-4137-b40e-e7c0dce414b2@l39g2000yqn.googlegroups.com> Message-ID: <86c91d64-32aa-42e2-90ef-9ad95abcb9b1@13g2000yql.googlegroups.com> On 21 Nov., 23:36, Mensanator wrote: > Your rules appear to be incomplete and inconsistent. OK. Let me try to clarify then... > > 3. Pattern A only consists of the numbers 0, 3, and 9. 3, 3 is always > > followed by 0 > > But does a 3 always follow a 3? Can you have 3, 0, 3, 0? > Can 0's occur without 3's, such as 0, 0, 0? Yes, 3s always comes in pairs. So, 3, 0, 3, 0 is not allowed. And of the numbers 0, 3, and 9; 0 will always be the first after the pair of 3s > > > 4. Pattern B only consists of the numbers 1, 6, and 10. 6, 6, is > > always followed by 1 > > 5. There may be other numbers interspersed within the sequence, but > > they can be ignored > > So, I can have 3, 3, 0, 7, 3, 3, 0? Yes, there is a point I did not mention propery in my first description: The number 7 for instance could appear in that position, but it would not be repetitive; as a matter of fact these other numbers can be filtered away before looking for the pattern, so let us just forgot about those. > > What if the 7 occurs after the pair of 3's? Is the number following > the 7 forced to be 0, i.e., is 3, 3, 7, 3, 3, 0 legal? No, it would have to be 3, 3, 0, 7, 3, 3, 0, it is sequeezed in - but as mentioned they can be prefiltered out of the problem > > > 7. The beginning of a pattern is marked by the transition from oner > > pattern to the other. > > Can there be an ignored number between the patterns? Is > 9,3,3,0,7,10,6,6,1 > legal? If NO, you violate Rule 5. If YES, you violate the second Rule > 7. Yes you are right. This complication is again eliminated by prefiltering "other" numbers out -- Slaunger From banibrata.dutta at gmail.com Tue Nov 4 05:13:56 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Tue, 4 Nov 2008 15:43:56 +0530 Subject: locating the chorus in a MIDI song? In-Reply-To: <6c8622d4-ca1c-4ad1-9982-a6326155b88c@1g2000prd.googlegroups.com> References: <6c8622d4-ca1c-4ad1-9982-a6326155b88c@1g2000prd.googlegroups.com> Message-ID: <3de8e1f70811040213h6202b1b3ue658af126869461f@mail.gmail.com> Without pretending to be an expert on the subject of music-theory or audio-processing, my n00b'ish doubt is -- MIDI, unlike MP3 would be devoid of voice... and in my overtly simplistic thinking -- presence / absence of which (i.e. voice) could be a "brute-force" way of detecting refrain/chorus ... unless a lot of "grammar" (i.e. semantic constraints) of music-theory are enforced, and I am afraid such a grammer could only be made for a small subset of a particular genre at best. IMHO, some heuristics could be used to "train" a statistical model, to identify refrain sections, s.a. a Bayesian model. You use some heuristic parameters to detect refrain, and then use a large corpus of human responses to validate the identification, there by tuning the model. On Tue, Nov 4, 2008 at 3:11 PM, alex23 wrote: > On Nov 4, 2:20 pm, Joe Strout wrote: > > We've got a need to generate short "samples" of songs that are in MIDI > > format, to provide a preview function in a web app. We'd like to do > > something more clever than just taking the middle 20 seconds (or > > whatever) of the song -- ideally, we'd like to find the chorus, since > > that's likely to be the most easily recognized part of the song. > > > > I believe this could be done fairly reliably by looking for patterns > > in the MIDI file, though I'm sure there are plenty of complications to > > this simple idea. > > My first thought is that would be incredibly difficult, but a quick > google search pulled up a couple of papers: > > "Music Scene Description Project: > Toward Audio-based Real-time Music Understanding" > http://ismir2003.ismir.net/papers/Goto.PDF > > The RefraiD (Refrain Detecting Method) detects sections > being repeated and identifies the chorus (refrain) sections > of songs in popular-music CDs. Most previous methods > detected as a chorus a repeated section of a given length > (Logan and Chu, 2000; Cooper and Foote, 2002) and had > difficulty identifying both ends of a chorus section and > dealing with modulations (key changes) (Peeters et al., > 2002; Dannenberg and Hu, 2002). By analyzing relation- > ships between various repeated sections, RefraiD can de- > tect all the chorus sections in a song and identify both > ends of each section. It can also detect modulated chorus > sections by introducing a similarity measure that enables > modulated repetition to be judged correctly. > > The paper doesn't go into much detail beyond that, but does refer to > more that do. > > "A chorus-section detecting method for musical audio signals" > > http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?tp=&arnumber=1200000&isnumber=26996 > > By the same authors, I believe. Although they're talking about audio, > I would expect the technique used could be readily applied to midi as > well (probably more easily, in fact). > > Note that: "Experimental results with a popular-music database show > that this method detects the correct chorus sections in 80 of 100 > songs." So it's going to be wrong 1 in 5 times, if that's an > influencing factor in trying to do this programmatically. How many > MIDI files are you talking about here? Could it be easier to just > manually mark the chorus for each? > > > 2. Anybody have an interest in music theory, as well as mad Python > > skills? Want a paying contract job? If so, please contact me off- > > list. I'd enjoy pursuing this myself, but if you think you can do a > > better job at a reasonable rate, I'm happy to let you do so. > > Give me a few days to see what my upcoming schedule is like and I may > get back to you on this. I have a friend who has worked on > computationally generating emotional expression with MIDI just > recently, I'll pass this on to him as well. > > Is Python a strict requirement for this? > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mr.spoon21 at gmail.com Thu Nov 6 13:29:51 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Thu, 6 Nov 2008 19:29:51 +0100 Subject: More __init__ methods In-Reply-To: <6ngijnFlbequU3@mid.uni-berlin.de> References: <6ngijnFlbequU3@mid.uni-berlin.de> Message-ID: <8f67b6f80811061029j30671d3v293935069c1ebdf2@mail.gmail.com> On Thu, Nov 6, 2008 at 4:59 PM, Marc 'BlackJack' Rintsch wrote: > class A(object): > def __init__(self, a, b, c): > self.a = a > # ... > > @classmethod > def from_string(cls, s): > # ... > return cls(a, b, c) Thanks. I think it's time to study decorators. From p at ulmcnett.com Fri Nov 14 13:26:33 2008 From: p at ulmcnett.com (Paul McNett) Date: Fri, 14 Nov 2008 10:26:33 -0800 Subject: Building musical chords starting from (a lot of) rules In-Reply-To: <8f67b6f80811141000p59fbd638q5f482f654e839faa@mail.gmail.com> References: <8f67b6f80811141000p59fbd638q5f482f654e839faa@mail.gmail.com> Message-ID: <491DC2D9.4080607@ulmcnett.com> Mr.SpOOn wrote: > Anyway, I think I can use a chain of if-clauses, one per rule and at > the end remove the notes marked with "no". But this seems to me a very > bad solution, not so pythonic. Before I proceed for this way, do you > have any suggestion? Hope the problem is not too complicated. I say, start with what you can think of (the chain of if clauses). Get it working. Then, you'll likely find ways to refactor if needed. Get it working first. Make it "right" iteratively over time. At least that's what I do. And it works for me. Paul From __peter__ at web.de Fri Nov 7 03:15:18 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Nov 2008 09:15:18 +0100 Subject: Fastest way to tint an image with PIL References: <45f979ae-1628-498d-be62-a88da2e9c0d1@s1g2000prg.googlegroups.com> Message-ID: Dan Moskowitz wrote: > I'm using PIL to tint and composite images together. Here's how I'm > currently tinting images, it's really slow and I know there's got to > be a better way: > > def TintImage( im, tintColor ): > tint = (tintColor[0]/255.0, tintColor[1]/255.0, tintColor[2]/255.0, > tintColor[3]/255.0) > pix = im.load() > for x in xrange( im.size[0] ): > for y in xrange( im.size[1] ): > c = pix[x,y] > pix[x,y] = (int(c[0]*tint[0]), int(c[1]*tint[1]), > int(c[2]*tint[2]), c[3]) > > I thought maybe there's a way to do it using the transform method, but > I haven't figure it out yet. Anyone? Too lazy to read the manual? How about def tint_image(im, color): color_map = [] for component in color: color_map.extend(int(component/255.0*i) for i in range(256)) return im.point(color_map) Peter From kay.schluehr at gmx.net Sun Nov 9 00:14:18 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Nov 2008 21:14:18 -0800 (PST) Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <98d19d75-123d-47ae-a975-ea013b9239f2@v16g2000prc.googlegroups.com> Message-ID: On 9 Nov., 05:49, Alex_Gaynor wrote: > On Nov 8, 11:36 pm, Kay Schluehr wrote: > > > > > On 9 Nov., 05:04, Terry Reedy wrote: > > > > Have you written any Python code where you really wanted the old, > > > unpredictable behavior? > > > Sure: > > > if len(L1) == len(L2): > > return sorted(L1) == sorted(L2) # check whether two lists contain > > the same elements > > else: > > return False > > > It doesn't really matter here what the result of the sorts actually is > > as long as the algorithm leads to the same result for all permutations > > on L1 ( and L2 ). > > that same thing could be done with a multiset type, which would also > have better performance(O(n) vs. O(nlogn)). I guess building a multiset is a little more expensive than just O(n). It is rather like building a dict from a list which is O(k*n) with a constant but small factor k. The comparison is of the same order. To enable the same behavior as the applied sorted() a multiset must permit unhashable elements. dicts don't do the job. From kyosohma at gmail.com Wed Nov 12 14:55:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 12 Nov 2008 11:55:28 -0800 (PST) Subject: pygoocanvas binaries for windows? References: Message-ID: <160b00d1-aba4-49aa-b5ba-df2289afa798@v16g2000prc.googlegroups.com> On Nov 12, 11:16?am, sandro wrote: > Hi, > > ? I really need binaries for goocanva s for windows. > ? There are plenty of places in innternet of people that tried to > ? compile with no success. Have anybody of you managed to get them? > > thanks > sandro Are you talking about this: https://developer.berlios.de/projects/pygoocanvas/ ? I looked at the source and it looks like it's mostly C code. There's no setup.py file and the INSTALL instructions look kind of obtuse, so it's no wonder people have trouble compiling it. If the developers would put together a setup.py file, then compiling a binary would be much easier. Otherwise I think you're looking at Cygwin + some hoodoo black magic involving snakes and virgins... Mike From kay.schluehr at gmx.net Sun Nov 9 01:53:14 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Nov 2008 22:53:14 -0800 (PST) Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <01267674$0$20668$c3e8da3@news.astraweb.com> Message-ID: On 9 Nov., 07:06, Steven D'Aprano wrote: > On Sat, 08 Nov 2008 20:36:59 -0800, Kay Schluehr wrote: > > On 9 Nov., 05:04, Terry Reedy wrote: > > >> Have you written any Python code where you really wanted the old, > >> unpredictable behavior? > > > Sure: > > > if len(L1) == len(L2): > > return sorted(L1) == sorted(L2) # check whether two lists contain > > the same elements > > else: > > return False > > > It doesn't really matter here what the result of the sorts actually is > > as long as the algorithm leads to the same result for all permutations > > on L1 ( and L2 ). > > How often do you care about equality ignoring order for lists containing > arbitrary, heterogeneous types? A few times. Why do you care, Steven? > In any case, the above doesn't work now, since either L1 or L2 might > contain complex numbers. > The sorted() trick only works because you're > making an assumption about the kinds of things in the lists. If you want > to be completely general, the above solution isn't guaranteed to work. You are right. I never used complex numbers in Python so problems were not visible. Otherwise the following comp function in Python 2.X does the job: def comp(x1, x2): try: if x1 Here is a way to > solve the problem assuming only that the items support equality: > > def unordered_equals2(L1, L2): > if len(L1) != len(L2): > return False > for item in L1: > if L1.count(item) != L2.count(item): > return False > return True Which is O(n**2) as you might have noted. From andrey.balaguta at gmail.com Sun Nov 2 02:54:09 2008 From: andrey.balaguta at gmail.com (Andrey Balaguta) Date: Sun, 2 Nov 2008 00:54:09 -0700 (PDT) Subject: Ping monitor - monitor ip in the background? References: Message-ID: <82f2235a-0b4c-4e8f-af5c-ff3ae9904805@t18g2000prt.googlegroups.com> Hi, ScottZ. I I have to write such a thing, I'll wrap the whole thing into some class, say Pinger. It will have "do" method, which will perform one particular pinging action. It'll also have a start/stop mechanism, which will start a thread to continuously pinging a host. To notify environment (say, yours tray icon) about host state change (dead/ alive), it will have callback mechanism (register_callback/ unregister_callback). Here, I've written a simple implementation, maybe this will be helpful. ====== pinger.py ================ import os import threading import subprocess import re import time class Pinger: def __init__(self, ip = None): self.ip = None self.running = False self.callbacks = list() self.setAddress(ip) def setAddress(self, ip): if self.ip != ip: if self.running: self.stop() self.ip = ip def do(self): if os.name == "nt": # Windows pcmd = "ping -n 1 -w 1000 " else: # *nix pcmd = "ping -c1 -W1 " p = subprocess.Popen(pcmd + self.ip, shell=True, stdout=subprocess.PIPE) # give it time to respond p.wait() a = re.search('(.*)ms', p.stdout.read()) if a: return True else: return False def start(self): def run(): result = False while self.running: next = self.do() if next != result and self.running: [ callback(next) for callback in self.callbacks ] result = next self.ping_thread = threading.Thread(target = run) self.running = True self.ping_thread.start() def stop(self): self.running = False def register_callback(self, callback): if callback not in self.callbacks: self.callbacks.append(callback) def unregister_callback(self, callback): if callback in self.callbacks: self.callbacks.remove(callback) if __name__ == '__main__': p = Pinger('192.168.1.1') def printout(alive): if alive: print 'Host is alive.' else: print 'Host is dead.' p.register_callback(printout) p.start() while True: print "Ding..." time.sleep(1) ================ Note that printout will be called ONLY if host state has changed, not on EVERY ping. -- Best Regards, Andrey Balaguta From mnordhoff at mattnordhoff.com Sun Nov 16 20:40:04 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 17 Nov 2008 01:40:04 +0000 Subject: Need help in understanding a python code In-Reply-To: References: <46f2ec46-8589-4176-87c0-1c7547d19ac4@z6g2000pre.googlegroups.com> <47c890dc0811152054q1187f128i4784c72197219f51@mail.gmail.com> <1ffbea5c-f5a9-4284-94c5-082de0307b08@a17g2000prm.googlegroups.com> <012feec2$0$20662$c3e8da3@news.astraweb.com> <013004b3$0$20662$c3e8da3@news.astraweb.com> <1c1524a2-1443-450b-8b8f-b7aa4661e74e@r36g2000prf.googlegroups.com> Message-ID: <4920CB74.3000808@mattnordhoff.com> Benjamin Kaplan wrote: > If you really believe that, you haven't been following this list long > enough. Every terminology dispute always includes at least 1 Wikipedia > link. > > Also, you might want to look at this study: > http://news.cnet.com/2100-1038_3-5997332.html That study has been disputed; see the links at the top of . /me ducks -- From megiacomonadeau at gmail.com Fri Nov 21 03:13:46 2008 From: megiacomonadeau at gmail.com (megiacomonadeau at gmail.com) Date: Fri, 21 Nov 2008 00:13:46 -0800 (PST) Subject: african american singles - Free Online Dating Message-ID: <84f7d586-83a1-42fc-ba2d-972bcff23c86@d32g2000yqe.googlegroups.com> african american singles . . . *******CLICK HERE******** http://dating365.co.cc/african-american-singles ***************************** . . . . . . . . . . . . african american singles From straton at lampsacos.demon.co.uk Mon Nov 17 06:32:19 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 17 Nov 2008 11:32:19 +0000 Subject: Midi manipulation In-Reply-To: <4f45a617-a969-4af0-b105-6bae06275d09@t39g2000prh.googlegroups.com> References: <7671i4dvnudr4ssh4j54ummqa589r8tleb@4ax.com> <4f45a617-a969-4af0-b105-6bae06275d09@t39g2000prh.googlegroups.com> Message-ID: <9DcUk.81217$Bk7.50124@newsfe29.ams2> Massi wrote: > On 16 Nov, 23:23, Tim Roberts wrote: >> Massi wrote: >> >>> Hi everyone, I'm searching for "something" which allows me to write >>> scripts which handle midi files. I'm totally a newbie in audio >>> manipulation, therefore any suggestion or link related to this field >>> is welcome. Thanks in advance. >> Google is much faster than this newsgroup. Search for "python midi >> library" and the first page gives you a number of good hits. >> >> However, there's a lot to manipulating MIDI. What kinds of things are you >> hoping to accomplish? MIDI, for example, is not a particularly good way to >> store music for composition. >> -- >> Tim Roberts, t... at probo.com >> Providenza & Boekelheide, Inc. > > I'm writing a script for didactic musical purpose. As first step I > need something as simple as possible, for example a library of > functions which are able to play a certain note, with a given > instrument and a given length. I thought midi was good for this aim, > am I wrong? Oh dear, I'm going to point you away from Python ... but I am not intending to start a flame war... The Apache Cocoon project (NOT the latest version 2.2 though) might appeal to you: http://cocoon.zones.apache.org/demos/release/samples/blocks/midi/ quote: The MIDI block currently gives you an XMidiGenerator to generate an XML representation of any MIDI file (called XMidi by its author Peter Loeb). There is also the XMidiSerializer to render XMidi back as a MIDI file. I have used XSLT to provide some basic musical manipulations such as transposition, and inversion. Retrograde is harder, but I shall see what I can come up with. Hopefully I shall also add some transformers to generate SVG visualisations of the XMidi, starting with normal western musical notation. MIDI Documentation - Documentation available on the Cocoon Wiki. From http Wed Nov 19 21:39:27 2008 From: http (Paul Rubin) Date: 19 Nov 2008 18:39:27 -0800 Subject: sorting list of complex numbers References: <6nobt3Fmg32fU1@mid.individual.net> <7x63mlwcqw.fsf@ruckus.brouhaha.com> <87fxloauwy.fsf@mulj.homelinux.net> Message-ID: <7xiqqj6rz4.fsf@ruckus.brouhaha.com> Terry Reedy writes: > >> Do your tuple destructuring in the first statement in your body and > >> nothing will break. Why get rid of a useful feature that unclutters code? > > Unless you were using a lambda, which is quite useful as argument to > > "sort". > > So write a separate def statement. > If you do not want to do that, don't run with 3.0. You are advising avoiding downgrading from 2.5 to 3.0, which is maybe the best plan for some users under the circumstances, but some of us normally expect a new major release to be an upgrade rather than a downgrade. From stefan_ml at behnel.de Wed Nov 26 11:42:43 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 Nov 2008 17:42:43 +0100 Subject: what's so difficult about namespace? In-Reply-To: References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> Message-ID: <492d7c83$0$30225$9b4e6d93@newsspool1.arcor-online.net> Xah Lee wrote: >> The IT community has enough trouble getting a few ISPs to upgrade their >> DNS software. How are you going to get millions of general users to >> upgrade? > > alright, that's speaks for Javascript. > > But how's that apply to, say, Scheme lisp, Emacs lisp, PHP? Think before you write. It's exactly the same thing. How would you get all Emacs users in the world to upgrade? Stefan From opsbat at infomed.sld.cu Sun Nov 2 16:16:05 2008 From: opsbat at infomed.sld.cu (Michel Perez) Date: Sun, 02 Nov 2008 16:16:05 -0500 Subject: find an object ancestor Message-ID: <1225660565.6607.10.camel@cerebellum> HI all: imagine something like this: class father: pass class son( father ): pass I need to know the son ancestor class how can i know this. Thanks --------------------------------------- Red Telematica de Salud - Cuba CNICM - Infomed From steve at holdenweb.com Mon Nov 17 18:44:24 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Nov 2008 18:44:24 -0500 Subject: Installation on Vista (Was: ANN: ActivePython 2.6.0.0 is now available) In-Reply-To: <4921DD45.5000007@activestate.com> References: <9d0c1bb6-8920-4941-84f7-c644dd4f1927@o40g2000prn.googlegroups.com> <936d7511-6c34-43c1-929a-e12f236879a9@p35g2000prm.googlegroups.com> <4921DD45.5000007@activestate.com> Message-ID: <492201D8.6050002@holdenweb.com> Trent Mick wrote: > Mensanator wrote: >>>> What about Vista? Do you need to use the Administrator account to >>>> install it? >>> My currently understanding is that the ActivePython installer will >>> prompt for administrator privileges if required. I know that if the >>> current user is a member of the administrators *group* (different from >>> being the "Administrator" *user*), that this is sufficient to install >>> and use ActivePython. >> >> I'll have to try that, as it is NOT the case with the Windows >> installer >> from Python.org. Admin privelleges are NOT sufficient if you want IDLE >> to work. You have to use the Administrator account (which is disabled >> by default on Vista). If you have a way around that, then great. > > I believe that IDLE ran just fine when installed as a user in the admin > group. I found the only satisfactory way to install Python all-users on Vista was to log in as a member of the administrators group, run a command shell window "as administrator", then run the installer in that window. That worked fine. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From almar.klein at gmail.com Fri Nov 21 08:57:35 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 21 Nov 2008 14:57:35 +0100 Subject: Dynamic features used In-Reply-To: References: <0404d520-554a-4356-bfd2-0f44b9a4053a@y18g2000yqn.googlegroups.com> <223c08ca-f38f-45ec-a253-4693dce6c060@c2g2000pra.googlegroups.com> Message-ID: > > - Is it good for Python to become two languages in one, a fast > statically typed one and a dynamically one, like pypy shows to like > with RPython, or is it better to go the way of the Boo language, that > (while being mostly static) is mixing dynamic and static typing in the > same code, but that must rely on a very complex virtual machine to > work? I was going to ask about what the difference between dynamic and static types was again, but remebered there was a thread on this some time ago where this link was posted: http://eli.thegreenplace.net/2006/11/25/a-taxonomy-of-typing-systems/ IMO you would not want to mix two typing systems in one language, unless you can very explicitly say for a variable "this one is static". Is this not what pyrex does in a way? Moreover, such a change would be quite fundamental, I don't think you'll easily convince Guido on this :) Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick.fabry.maillists at coredump.us Wed Nov 19 09:31:48 2008 From: nick.fabry.maillists at coredump.us (Nicholas Ferenc Fabry) Date: Wed, 19 Nov 2008 09:31:48 -0500 Subject: More elegant way to try running a function X times? In-Reply-To: References: Message-ID: On Nov 19, 2008, at 09:09, Gilles Ganault wrote: > Hello > > As a newbie, it's pretty likely that there's a smarter way to do this, > so I'd like to check with the experts: > > I need to try calling a function 5 times. If successful, move on; If > not, print an error message, and exit the program: > > ===== > success = None > > for i in range(5): > #Try to fetch public IP > success = CheckIP() > if success: > break > > if not success: > print "Exiting." > sys.exit() > ===== > A little simpler: for i in range(5): if CheckIP(): break else: print "Exiting." sys.exit() The else part will only fire if the for finishes without breaking. Hope this helps a bit... Nick Fabry > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list From sylvain.thenault at logilab.fr Thu Nov 20 01:51:07 2008 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Thu, 20 Nov 2008 07:51:07 +0100 Subject: [ANN] logilab-astng 0.17.4 Message-ID: <20081120065107.GH9983@logilab.fr> Hi there! Back from holidays, I finally took a few hours to fix a few bugs in astng an publish a 0.17.4 release. It fixes some crashes, the "using possibly undefined loop variable" false positive reported by Maarteen and Skip and add some support for python 2.5 relative imports. See the ChangeLog or the version's page [1] for more details. [1] http://www.logilab.org/project/logilab-astng/0.17.4 -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From castironpi at gmail.com Sat Nov 22 05:58:13 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 22 Nov 2008 02:58:13 -0800 (PST) Subject: Dynamic features used References: <0404d520-554a-4356-bfd2-0f44b9a4053a@y18g2000yqn.googlegroups.com> Message-ID: <074fed95-60da-409f-b077-12ee22baa76d@d23g2000yqc.googlegroups.com> On Nov 21, 3:17?am, bearophileH... at lycos.com wrote: snip > Compared to other languages Python generally allows me to write a > correctly working program in the shorter time (probably because of the > Python shell, the built-in safeties, the doctests, the clean and short > and handy syntax, the quick write-run-test cycle, the logical design, > its uniformity, the availability of standard data structures and many > standard or external modules, and the low number (compared to other > languages) of corner cases and tricky semantic corners). I like the brevity (conciseness). The Python implementation of a program is shorter on average than the C++ implementation. You don't have to declare your types, which is just extra words and handcuffs, looking at everything but performance. Some of the things that C++ can do are irrelevant to some programs, and Python keeps them off your mind. C++ gives you much finer control of a machine, but you don't always need it. I think the central decision-making has the advantage that there is only one Python, whereas C has many versions. It makes it easier to share and communicate about programs in the language. Plus I don't even need new files to cut-and-paste a snippet from the newsgroup into the interpreter. > Today Python is defined a dynamic language (and not a scripting > language, a term that few languages today seem to want attached to > them) but being dynamic isn't a binary thing, it's an analog quality, > a language can be less or be more dynamic. For example I think Ruby is > more dynamic than Python, Python is more dynamic than CLisp, CLips > seems more dynamic than C#/Java, Java is more dynamic than D, and D is > more dynamic than C++. Often such differences aren't sharp, and you > can find ways to things more dynamically, even with a less nice syntax > (or creating less idiomatic code). (In C#4 they have even added a > dynamic feature that may make languages like IronPython/Boo faster and > simpler to write on the dotnet). Python can be written in C. Thus, anything Python can do, C can do, not to mention the equal expressiveness of the languages. But I have a non-trivial observation. With an STL 'map' and a union, you could make a quick and dirty quasi- Python in C++. Dynamic assignment is just a __dict__ member anyway. Functions (and classes) are first-class objects, but the 'functor' pattern can approximate it, even including decorators. Variable- length arguments are just an STL 'vector', and keyword arguments are just an STL dict. You can't get the same flexibility in C++ though, without parsing the text of a function, and storing argument info about it. Syntax can't leave the realm of C++, but just a few classes could be able to bring C++ a lot closer to Python. > In the last two years I have seen many answers in the Python > newsgroups, and I have seen that some of the dynamic features of > Python aren't much used/appreciated: > - Metaclasses tricks > - exec and eval > - monkey patching done on classes > - arbitrary cmp among different types removed from Python 3 > While some new static-looking/related features are being introduced: > - ABCs and function signatures added > - More tidy exception tree snip > What are the dynamic features of Python more used in your programs? > (From this set try to remove the things that can be done with a > flexible static template system, like the D one, that for some things > is more handy and powerful than the C++ template system, and for other > things less powerful). You didn't mention 'metaprogramming', which is writing a program to generate the text code of a program, which you then compile/ interpret. I think 'exec' enables you to keep such a program in one piece. For a rough example, a C++ program might have a dozen repetitive classes, which you would have to write by hand or generate externally. The Python program can just execute the definitions in place. That is, if 'setattr' doesn't already do the trick. The ability to return a class or a function obsoletes some of the Gamma et al Design Patterns, such as the Factory pattern, IIRC. And you didn't mention garbage collection. > If very little or no dynamic features are used in a program it may > seem a "waste" to use Python to write the code, because the final > program may be quite slow with no gain from the other features of > Python. (I think in such situations Python can be a good choice > anyway, because it's good to write working prototypes in a short > time). Some of the value of that comes from the instant gratification that Python gives one. 'Now' is a good time to test your code. 'Later' is ok. I'm thinking of writing graphics with pygame, which lacks the same quality in C++. Python is eloquent, whereas I'd feel I'd just beaten a dead horse by the time I got the C++ equivalents up and running, though perhaps less so with practice. snip > In the last year I have found two situations where exec/eval is a way > to reduce a lot of the complexity of the code, so if used with care > the dynamic features can be quite useful. snip I'm not sure how much of my like of Python comes from the pioneer's spirit, the feeling that it's new and hot and secret, undiscovered country, like I'm out in the wilderness. But nifty tricks such as with decorators are part of the fun. The coolest two lines of Python are pretty cool. From michele.petrazzo at TOGLIunipex.it Wed Nov 5 07:12:28 2008 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 05 Nov 2008 13:12:28 +0100 Subject: subprocess and PPID Message-ID: Hi all, I believe that this is a *nix question, but since I'm developing in python, I'm here. I have a code that execute into a "Popen" a command (ssh). I need that, if the python process die, the parent pid (PPID) of the child don't become 1 (like I can seen on /proc/$pid$/status ), but it has to die, following it's parent It's possible in linux and with subprocess? Thanks, Michele From ludlam.2008 at rediffmail.com Sat Nov 22 14:57:54 2008 From: ludlam.2008 at rediffmail.com (LUDLAM) Date: Sat, 22 Nov 2008 11:57:54 -0800 (PST) Subject: CHASE CREDIT CARDS Message-ID: <7902cdaa-e99d-4c8e-b9e6-1e1c77fa333f@b31g2000prb.googlegroups.com> Compare and choose the best Chase credit card for your needs.... http://chasecreditcardsnews.blogspot.com From george.sakkis at gmail.com Tue Nov 25 21:34:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 25 Nov 2008 18:34:54 -0800 (PST) Subject: Instance attributes vs method arguments References: <9a32bd30-0b54-4d3c-9e8c-99f6d46cdb90@v39g2000pro.googlegroups.com> Message-ID: <3a6b193e-aa2f-4d18-a038-9fae1dc6c486@h5g2000yqh.googlegroups.com> On Nov 25, 8:49?pm, John O'Hagan wrote: > is there an > difference in efficiency (for large enough number of methods and arguments) > between > > a) passing all arguments to __init__() and accessing them via self within > individual methods: > > class = Class(all_class_args) > class.method_a() > class.method_b() > ... > or > > b) passing the arguments needed by each method when it is called on an > instance: > > class = Class() > class.method_a(a_args) > class.method_b(b_args) > ... The difference in API here is more crucial than the difference in performance. Deciding between the two based on the (guessed or measured) performance improvement misses the point of OO design. George From ldo at geek-central.gen.new_zealand Tue Nov 25 02:40:57 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Nov 2008 20:40:57 +1300 Subject: Security implications of using open() on untrusted strings. References: Message-ID: Jorgen Grahn wrote: > Seems to me you simply want to know beforehand that the reading will > work. But you can never check that! You can stat(2) the file, or > open-and-close it -- and then a microsecond later, someone deletes the > file, or replaces it with another one, or write-protects it, or mounts > a file system on top of its directory, or drops a nuke over the city, > or ... Depends on what exactly you're trying to guard against. Your comments would apply, for example, to a set-uid program being run by a potentially hostile local user (except that Linux doesn't allow set-uid scripts). But if the script is being run, for example, via a Web interface, where processes on the local system can be trusted but the remote user cannot, then it is perfectly legitimate to use calls like stat(2) to enforce your own permission checks before allowing an operation. From james at agentultra.com Wed Nov 26 15:00:50 2008 From: james at agentultra.com (J Kenneth King) Date: Wed, 26 Nov 2008 15:00:50 -0500 Subject: Python equivalent of Common Lisp Macros? References: <7e4a9462-eaa2-483a-9da6-59cc54050bba@w39g2000prb.googlegroups.com> Message-ID: <85wseq5kb1.fsf@dozer.localdomain> dpapathanasiou writes: > I'm using the feedparser library to extract data from rss feed items. > > After I wrote this function, which returns a list of item titles, I > noticed that most item attributes would be retrieved the same way, > i.e., the function would look exactly the same, except for the single > data.append line inside the for loop. > > In CL, I could simply write a macro, then replace the data.append line > depending on which attribute I wanted. > > Is there anything similar in Python? > > Here's the function: > > def item_titles (feed_url): > """Return a list of the item titles found in this feed url""" > data = [] > feed = feedparser.parse(feed_url) > if feed: > if len(feed.version) > 0: > for e in feed.entries: > data.append(e.title.encode('utf-8')) > return data No macros -- need the whole "code as data" paradigm which doesn't exist in python. The pythonic way to create the sort of abstraction you're looking for would be to use the *attr functions and either a map of attribute identities or inspect the attributes from the objects. Some UNTESTED code... def extract_entry(e, attrs=['title', 'datetime', 'article']): out = [] for attr in attrs: assert hasattr(e, attr) out.append(getattr(e, attr)) return out Using the inspect module would give an even more generic function, but with more complex code of course. Then your code would look more like: def items(feed_url): feed = feedparser.feed(feed_url) if feed and len(feed) > 0: return [extract_entry(entry) for entry in feed.entries] Of course, I'm making liberal assumptions about what you're looking for in your ouput here... but it's just an example, not a full solution. YMMV. Hope it helps. :) From billg3000 at hos.twgg.org Wed Nov 5 01:35:23 2008 From: billg3000 at hos.twgg.org (3000 billg) Date: Wed, 5 Nov 2008 14:35:23 +0800 Subject: Django or TurboGears or Pylons? for python web framework. Message-ID: Hi Senior, There was a case for web site that will be public to Internet for me. I like python so I do not consider the use of Ruby on Rails. I searched more web framework of python from Google. The good solution just only there are Django, TurboGears and Pylons. Just from my preferences, I want to use Django but the AJAX support will be a problem. Also I need to select a JavaScript framework and lean it, maybe JQuery, mootools or other. And I can not write python as it is written in general javascript. I need to learn a different syntax. TurboGears or Pylons, I am worried that the issue of performance because CherryPy. Could everybody give me a hand for your select? Django or Turbegears or Pylons? and Why? If Django, how to do Ajax support for you? and why? thanks eveybody first. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Wed Nov 26 16:36:03 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 26 Nov 2008 22:36:03 +0100 Subject: Is it possible (and wise) to extend the None-type ? In-Reply-To: References: <492D8D84.9070405@gmail.com> Message-ID: <492DC143.7010007@gmail.com> Jason Scheirer wrote: > On Nov 26, 11:40 am, Terry Reedy wrote: > >> Stef Mientki wrote: >> >>> hello, >>> >>> I've the idea that I always have a lot of useless code in my programs, >>> like the next example. >>> >>> def _On_Menu_File_Open ( self, event = None ): >>> if event : >>> event.Skip () >>> >>> instead of >>> >>> def _O >>> >>> So I would like to extend the None-type (if that's possible), >>> with a dummy Skip() method. >>> >> def Skipper(object): >> def Skip(): pass >> skipper = Skipper() >> >> def _On_Menu_File_Open ( self, event = skipper ): >> event.Skip () >> >> etc. >> > > I think this methods works best, but quite frankly, if a method is > only two lines long, then you've likely got a code smell and no amount > of over-design is going to cover for it. > Sorry I should have said that I only showed the relevant (to this issue) part, and this kind of if statements occurs quit a lot. Probably I should not say this here on this list, but to give you the whole truth, I often forget the if-statement ( because it has really nothing to do with the functionality I intend to write), and then my program crashes (unexpected) :-( cheers, Stef From stef.mientki at gmail.com Thu Nov 20 14:36:11 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 20 Nov 2008 20:36:11 +0100 Subject: Module Structure/Import Design Problem In-Reply-To: References: <1adf50fc-c351-4bbd-85ee-bc60e53e8fec@r15g2000prh.googlegroups.com> <4925AA74.6050608@gmail.com> Message-ID: <4925BC2B.7000504@gmail.com> >>> >>> >> I'm not an expert, I even don't fully understand your problem, >> but having struggled with imports in the past, >> I've a solution now, which seems to work quit well. >> >> > That's not very helpful, is it? Were you planning to keep the solution > secret? > sorry slip of the keyboard ;-) http://mientki.ruhosting.nl/data_www/pylab_works/pw_importing.html cheers, Stef From skip at pobox.com Tue Nov 4 14:56:18 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 4 Nov 2008 13:56:18 -0600 Subject: Regexp parser and generator In-Reply-To: <629c7630-6687-4f98-9400-f16fe75a9208@40g2000prx.googlegroups.com> References: <629c7630-6687-4f98-9400-f16fe75a9208@40g2000prx.googlegroups.com> Message-ID: <18704.43234.996207.869458@montanaro-dyndns-org.local> George> Is there any package that parses regular expressions and returns George> an AST ? Maybe not directly, but this might provide a starting point for building such a beast: >>> import re >>> re.compile("[ab]", 128) in literal 97 literal 98 <_sre.SRE_Pattern object at 0x47b7a0> >>> re.compile("ab*c[xyz]", 128) literal 97 max_repeat 0 65535 literal 98 literal 99 in literal 120 literal 121 literal 122 <_sre.SRE_Pattern object at 0x371f90> Skip From jon.harrop.ms.sharp at gmail.com Thu Nov 27 09:59:16 2008 From: jon.harrop.ms.sharp at gmail.com (jon.harrop.ms.sharp at gmail.com) Date: Thu, 27 Nov 2008 06:59:16 -0800 (PST) Subject: what's so difficult about namespace? References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> Message-ID: On Nov 26, 7:29?am, Xah Lee wrote: > ... It's mostly a problem of culture. If you look, for example, at chinese names, the name space is not that much important: "Xee Laa" only takes this space: " " ^^^^^^^ Instead, if you take a typical english name, say, "Abraham Lincoln", you instantly recognize the waste of space used by this name: " " ^^^^^^^^^^^^^^ Concluding: I think that americans are very good at wasting name spaces, whereas chinese ones seem less name space hungry. Sure, you could make some other example, proving for the contrary, but I think the one cited above already suffices. Peace. From tekion at gmail.com Thu Nov 27 15:33:53 2008 From: tekion at gmail.com (tekion) Date: Thu, 27 Nov 2008 12:33:53 -0800 (PST) Subject: Help with capturing error Message-ID: <73731647-d177-4e80-9cca-0a95ed49199e@g38g2000yqd.googlegroups.com> Hello, I am getting the following error and my script is bailing out because of it. I have tried capturing it but it does not seem to work. Below is the error: ValueError: I/O operation on closed file the above error is received when, the following code snippet is executed: try: 117 self.xml_file.close() 118 except ValueError: 119 print "file, %s is already closed" % self.seek_file Any idea why line 118, is not capturing the error? Thanks. From v+python at g.nevcal.com Mon Nov 3 20:57:44 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Mon, 03 Nov 2008 17:57:44 -0800 Subject: Structures In-Reply-To: <11b141710811031538q37f8a1eauef846700da7c82e1@mail.gmail.com> References: <87d4hcmql2.fsf@benfinney.id.au> <11b141710811031538q37f8a1eauef846700da7c82e1@mail.gmail.com> Message-ID: <490FAC18.8070904@g.nevcal.com> On approximately 11/3/2008 3:38 PM, came the following characters from the keyboard of Paulo J. Matos: > On Mon, Nov 3, 2008 at 10:19 PM, Aaron Brady wrote: > >> On Nov 3, 3:45 pm, Ben Finney >> wrote: >> >>> "Paulo J. Matos" writes: >>> >>> >>>> On Mon, Nov 3, 2008 at 12:32 PM, Ben Finney >>>> wrote: >>>> >>>>> I'm wondering a more fundamental question: What are structures? >>>>> That is, what do *you* mean by that term; without knowing that, an >>>>> answer isn't likely to be meaningful. >>>>> >>>> Well, I guess that everyone pretty much gets since it exists in >>>> every other language as struct, or define-structure, or whatever is >>>> the syntax. >>>> >>> Take care with broad sweeping statements about "every other language", >>> or even "most other languages". They are usually flat-out wrong: >>> there is a stunning variety of different approaches and concepts in >>> programming languages, with very little common to even a majority of >>> them. >>> >> Yea, verily. How many languages do you think that is? Feel free to >> count C and C++ as different ones. >> >> "Four shalt thou not count, neither count thou two...." >> http://en.wikipedia.org/wiki/Holy_Hand_Grenade_of_Antioch#Usage_instructions >> > > Well, I wouldn't dare to say I know a lot of languages but the ones I > do provide mechanisms to define structures / records: C, C++, Scheme, > Common Lisp, Haskell, SML, Ocaml. > This is obviously a minority if you count all available programming > languages in the world, but I would dare to say these cover a lot of > ground. > There are languages that do not have structs; but usually there is some way to obtain something similar. > However, I wouldn't dare to say Python needs structures to be a good > language, or anything similar. My question was more directed to : if > there aren't structures in Python, what do Pythonists use instead? > (I have seen dicts might be an alternative, but as I said in previous > post, they seem to flexible [making them a canon to shoot a fly, and > they probably lack constant-time access, right?] > Dicts have constant time access. On the other hand, the constant is significantly larger than the constant for accessing a C struct. Note that classes, by default, are based on a contained dict! There are games to be played with slots that can apparently improve that. I am not yet experienced enough with Python to know if a slot is as fast as a C struct, but perhaps it is. You can have both slots and a dict, to get both speed and flexibility, or you can eliminate the dict and use slots only, but that limits your flexibility. But structs aren't flexible, except at compile time, so that might not be a problem for you. Another thing I don't know is if slots are as fast as tuples. Perhaps a slots-only class and a tuple might be speed rivals? But the former is mutable, and the latter not. Perhaps a more experience Python user can answer that question, at least for some particular implementation. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From stef.mientki at gmail.com Sat Nov 29 17:10:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 29 Nov 2008 23:10:56 +0100 Subject: Debugging in Python In-Reply-To: References: <38a89d61-9dfd-491c-b9dc-946709eec8c7@v42g2000yqv.googlegroups.com> Message-ID: <4931BDF0.6020907@gmail.com> Scott David Daniels wrote: > Stef Mientki wrote: >> >>> >>> The debugging ability of the Komodo IDE is _significantly_ better than >>> the freely available debuggers. If you like the Komodo Editor, you'll >>> love the debugger. >> hi Scott, can you tell us, > why Komodo debugger is better than >> PyScripter >> or even Winpdb(rpdb2) used in most python build IDE's ? > > Sorry, "better at the time I investigated it" is more like it. > At this point it is fine for me, and it was years ago when I > was looking. The impression I got was, "this product actually > paid for itself in debugging time in under five days," including > the amount of toll-learning I had to do as lost time. That made > the purchase clearly worth it. Since then, I've been happy enough > to not have done any further investigations. Thanks for the information Scott. I asked the question, because I'm not completely satisfied with even the "best" debuggers, most of the good ones are too difficult, so I want to wrap rpdb2 and don't want to miss any great features ;-) cheers, Stef From wuwei23 at gmail.com Fri Nov 21 00:26:31 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 Nov 2008 21:26:31 -0800 (PST) Subject: Optional parameter object re-used when instantiating multiple objects References: <5df8e227-1977-48eb-80ec-c905b7701bba@f37g2000pri.googlegroups.com> <0fbf3fca-2615-47de-989f-97ba6aa15bf1@w1g2000prk.googlegroups.com> <131f3d2b-af48-4657-8d12-5fb9f682390b@35g2000pry.googlegroups.com> <39422951-995d-4577-bc19-814215ce8806@p35g2000prm.googlegroups.com> <59mdnSY8fY7_yLnUnZ2dnUVZ_qXinZ2d@earthlink.com> <0283873b-0f35-4d05-8760-f2fceaef19c2@k19g2000yqg.googlegroups.com> <5763330a-2498-44d1-9c77-074076a2c4e1@j39g2000yqn.googlegroups.com> <61b66781-27c8-41cd-9799-6e8469795451@i20g2000prf.googlegroups.com> Message-ID: <85599194-e378-4f17-9b44-4fe7d8444f7a@g17g2000prg.googlegroups.com> On Nov 21, 10:07?am, Aaron Brady wrote: > Why, I would expect the interpreter to define the functions when it > first hits the def, that is, at the point of definition. Then why are you arguing that the parameters should be re-defined at the point of calling? From mccredie at gmail.com Fri Nov 7 14:23:05 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 7 Nov 2008 11:23:05 -0800 (PST) Subject: Extending Logger References: <766eb94f-f2bd-4514-b3fb-cab7e7d09e69@w1g2000prk.googlegroups.com> <332e6a09-f1eb-40d3-aaeb-a6cc0282da79@o40g2000prn.googlegroups.com> Message-ID: <0b53ae88-504a-4463-995c-15781842da7c@v16g2000prc.googlegroups.com> > Yes but in the other hand :http://docs.python.org/library/logging.html#logger-objects > "Note that Loggers are never instantiated directly, but always through > the module-level function logging.getLogger(name)." That is part of the power of the logging module. If you ask for a logger of the same name in two different place you will get the same object. That way you don't have to pass the logger instances around, and it always has the same properties (same handlers attached, same level, etc.). If you want to add functionality you getLoggerClass, inherit from that, then setLoggerClass, and use the regular logging facilities to instantiate them. The only limitation here is that you can't change the constructor. Well, it isn't useful to change the constructor. You can add a method that does the same thing. I can't help but feel that if you have a problem with this, you simply aren't using the Logging module the way it was meant to be used. Matt From tjreedy at udel.edu Tue Nov 11 13:52:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Nov 2008 13:52:25 -0500 Subject: Python 3.0 - is this true? In-Reply-To: <49198283.3060802@egenix.com> References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <49198283.3060802@egenix.com> Message-ID: M.-A. Lemburg wrote: > > I think the special case for None should be readded to Python 3.0. Quick summary of thread that MAL started on Python-3000-dev list: Once upon a time, 0 < None was true. When rich comparisons were added, None < 0 (and *most* other things) become true as an intentionally undocumented implementation detail. The None rule only applies for sure when None controls the comparison: ob < None is true or undefined if type(ob) says so. Guido's pronouncement: "In short, I'll have None of it." summarizing We're not going to add the "feature" back that None compares smaller than everything. It's a slippery slope that ends with all operations involving None returning None -- I've seen a proposal made in all earnestness requesting that None+42 == None, None() == None, and so on. This Nonesense was wisely rejected; a whole slew of early-error-catching would have gone out of the window. It's the same with making None smaller than everything else. For numbers, you can already use -inf; for other types, you'll have to invent your own Smallest if you need it. tjr From m.echavarriagregory at umiami.edu Mon Nov 17 09:20:27 2008 From: m.echavarriagregory at umiami.edu (Pekeika) Date: Mon, 17 Nov 2008 06:20:27 -0800 (PST) Subject: Question: what to do, my Python is getting crazy References: Message-ID: <83a41173-6e68-4983-9349-31494b79eafc@a17g2000prm.googlegroups.com> Good morning, thanks for the answer Gabriel. THE WEIRD MESSAGE IS NOT APPEARING ANYMORE! I DON'T KNOW WHAT HAPPENED, my PC seems to be doing extra bad things, I better back up my info... For Tim Roberts who wrote: >This looks like a problem with mixed versions. Are you saying that you >built Python and Python-Win32 from source? If so, may I ask why? There >is virtually no benefit to doing so on Windows. The pre-built >executables provide everything you need. NO, OFF COURSE I DO NOT HAVE OTHER VERSION in addition to PythonWin, that'd be silly as you imply. What I was talking about are modules like sympy, numpy, Rpy, scipy, mayavi2, vtk, etc; that I have included in my directories for my constant use and definetely don't want to loose. Is any problem that I use them along with PythonWin? Thanks very much, Angelica. From python.list at tim.thechases.com Mon Nov 17 14:41:08 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 17 Nov 2008 13:41:08 -0600 Subject: Multiple equates In-Reply-To: References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <4921C8D4.70302@tim.thechases.com> > It doesn't matter as none of this is valid Python. In Python you have to > write > > array[x1] = False > array[x2] = False Uh...not so much... >>> a = [1,2,3,4,5] >>> x1, x2 = 1, 3 >>> a[x1] = a[x2] = False >>> a [1, False, 3, False, 5] Works for me. To the OP, I think rather than cluttering my code, I'd just create a loop for i in [x1,x2,x3,x4,...x1024]: a[i] = False From Diez's disassembly of it (as an aside, nifty little intro to dis.dis()...thanks, Diez!), it looks like it boils down to "is DUP_TOP faster than LOAD_CONST" because the rest of the operations. At this point, it's pretty nitty-gritty. Unless the code is in an inner loop somewhere, the simple loop should be more than fast enough. Without knowing the source of the [x1,...] index variables, it's hard to tell if there's a more optimal way to do this. -tkc From rt8396 at gmail.com Wed Nov 26 17:17:08 2008 From: rt8396 at gmail.com (r) Date: Wed, 26 Nov 2008 14:17:08 -0800 (PST) Subject: hello from colombia References: <5c451e65-4e51-40ab-97d4-e5853927dedb@d42g2000prb.googlegroups.com> Message-ID: <46dcf77a-a25c-47d1-a638-65ba2cbc033e@r37g2000prr.googlegroups.com> On Nov 26, 2:58?pm, fel wrote: > I work in a small software company using php all day, I wish the usage > of Python was more common within my company > they are starting a new project (insurance stuff) using Java, and I > just hate that eventually I'l be debugging someone-else's java code > how can I convince them that Python is better, and get them to re- > think their strategy? > > also, kuddos on the language, you serve mankind as few do. > > fel. Just show them a side by side comparison of Python and Java, the choice will be obvious! ;) From george.sakkis at gmail.com Fri Nov 21 13:00:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 21 Nov 2008 10:00:58 -0800 (PST) Subject: Need help converting text to csv format References: <6e21bcdc-a5e6-4b1e-8658-05a47df0d076@l42g2000yqe.googlegroups.com> <33ec332e-1cdc-4c06-8660-8b061bc8d816@l39g2000yqn.googlegroups.com> Message-ID: <67f50a2d-98f3-47aa-9e1e-51e7171112eb@q9g2000yqc.googlegroups.com> On Nov 21, 11:05?am, Steve Holden wrote: > George Sakkis wrote: > > On Nov 21, 10:18 am, Chuck Connors wrote: > > >> Any help, pseudo code, or whatever push in the right direction would > >> be most appreciated. ?I am a novice Python programmer but I do have a > >> good bit of PHP programming experience. > > > I'm wondering if PHP experience precludes the ability to use a search > > engine before asking for help... > > I'm wondering why you bothered to write that. Next time, save yourself > the ten seconds and just skip to the next message. The world will be a > better place. RTFM and doing an elementary search is an even better way to making the world a better place. George From mr.spoon21 at gmail.com Fri Nov 14 13:00:52 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Fri, 14 Nov 2008 19:00:52 +0100 Subject: Building musical chords starting from (a lot of) rules Message-ID: <8f67b6f80811141000p59fbd638q5f482f654e839faa@mail.gmail.com> Hi, I'm writing a method to create musical chords. This method must follow a specific set of syntax rules. At least, this is my idea, but maybe there's a better way. Anyway, in the code I have class Chord which is a set. The costrunction of a chord is based on a root note and a structure, so by default, giving just a note, it creates a major chord adding the third and fifth note. So, in pseudo-code: Chord(C) -> [C, E, G] And this is the base case. All the other rules must specify what kind of note to add or which one should be modified. For example: C min, means to add the third minor note: C Eb G C 9 is a base chord plus a the ninth note, but this implies the presence of the seventh too, so it results in: C E G B D But I can also say: C 9 no7, so it should just be: C E G D, without the seventh. There are also more complex rules. For the eleventh, for example, it should add also the ninth and seventh note. In the normal case it adds their major version, but I can specify to add an augmented nine, so this modification must have precedence over the base case. Anyway, I think I can use a chain of if-clauses, one per rule and at the end remove the notes marked with "no". But this seems to me a very bad solution, not so pythonic. Before I proceed for this way, do you have any suggestion? Hope the problem is not too complicated. Thanks, Carlo From rt8396 at gmail.com Fri Nov 28 16:23:35 2008 From: rt8396 at gmail.com (r) Date: Fri, 28 Nov 2008 13:23:35 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <492feed6$0$26606$426a74cc@news.free.fr> Message-ID: Oh Python, where art thy faithful followers, thy house is crumbling, thy last breath spent, thy season draweth nigh...Ye have fought bravely for all that is good. But ye are encompassed on all sides by evil. Those who proclaim to love you are only the very same who seek your end! Weep oh lovers of Python...Weep. For your silence brings about the hideous end to a great awesome power. Never again shall the sun shine on calm waters. Never again shall the people be free. For the betrayers have thrush the knife of iniquity slowly into thou heart, and as ye lay dying, desacrate your body like the scoundrels they are. Weep, Weep, for yourself you scondrels, you vipers...for you have done a great injustice to yourself and the world. From wuwei23 at gmail.com Tue Nov 25 20:22:41 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Nov 2008 17:22:41 -0800 (PST) Subject: end of print = lower productivity ? References: Message-ID: On Nov 26, 1:52?am, s... at pobox.com wrote: > I hope there was a missing smiley in that post. ?If a couple extra parens > destroys your debugging productivity I suspect you need a fresh approach to > the task. I'm always inclined to suggest 6 months working in a role that requires hard manual labour whenever programmers raise the whole "effort of extra typing" argument. From bj_666 at gmx.net Fri Nov 7 13:02:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Nov 2008 18:02:11 GMT Subject: More __init__ methods References: <6ngijnFlbequU3@mid.uni-berlin.de> <8f67b6f80811061029j30671d3v293935069c1ebdf2@mail.gmail.com> <49133AF4.4070509@timgolden.me.uk> Message-ID: <6nje53FkevajU5@mid.uni-berlin.de> On Fri, 07 Nov 2008 17:23:21 +0100, Mr.SpOOn wrote: > On Fri, Nov 7, 2008 at 4:16 PM, Duncan Booth > wrote: >> There is a really big advantage to being explicit in this situation: >> you no longer have to make sure that all your constructors use a unique >> set of types. Consider: >> >> class Location(object): >> def __init__(self, lat, long): ... >> >> @classmethod >> def from_city(name): ... >> >> @classmethod >> def from_postcode(name): ... >> >> 'from_string' is a bad name here for your factory method: you should >> try to make it clear what sort of string is expected. > > Yes, that's what I was going to do. > But, for example, I have a parse method to create such object from a > string. So I need to call this method to actually create the object. Now > I must put the code of the parse method into the @classmethod > constructor. You can still spread it over other `classmethod()`\s or `staticmethod()`s or even plain functions at module level. > What if I need the parse method to be called in other parts of the > program? I don't understand!? Then you call it from those other parts. Ciao, Marc 'BlackJack' Rintsch From skip at pobox.com Fri Nov 21 17:18:01 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 21 Nov 2008 16:18:01 -0600 Subject: matching exactly a 4 digit number in python In-Reply-To: <7424ff80-c645-4b30-b963-67997be29108@j38g2000yqa.googlegroups.com> References: <7424ff80-c645-4b30-b963-67997be29108@j38g2000yqa.googlegroups.com> Message-ID: <18727.13209.765566.220208@montanaro-dyndns-org.local> >> I am a few months new into python. I have used regexps before in perl >> and java but am a little confused with this problem. >> I want to parse a number of strings and extract only those that >> contain a 4 digit number anywhere inside a string >> However the regexp >> p = re.compile(r'\d{4}') >> Matches even sentences that have longer than 4 numbers inside strings >> ..for example it matches "I have 3324234 and more" Try this instead: >>> pat = re.compile(r"(?>> for s in x: ... m = pat.search(s) ... print repr(s), ... print (m is not None) and "matches" or "does not match" ... ' I have 2004 rupees ' matches ' I have 3324234 and more' does not match ' As 3233 ' matches '2323423414 is good' does not match '4444 dc sav 2412441 asdf ' matches 'random1341also and also' matches '' does not match '13' does not match ' a 1331 saves' matches ' and and as dad' does not match ' A has 13123123' does not match 'A 13123' does not match '123 adn' does not match '1312 times I have told you' matches -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From martin at v.loewis.de Mon Nov 24 17:19:08 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Nov 2008 23:19:08 +0100 Subject: Python 3.0 - is this true? In-Reply-To: References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <4919E931.5030704@v.loewis.de> Message-ID: <492b285c$0$4013$9b622d9e@news.freenet.de> > Sorry for the delay in replying. Thanks, and I'm in turn sorry myself, too. Here is my experiment: I only looked at the first test case, where a bigfile.txt has occasionally None lines. To run this test, I created a file with 33079296 and 704512 lines, by repeatedly cat'ing /etc/passwd. I then ran this program: import time,random l = [] t=time.time() for line in open("x"): x = random.randint(0,100) if x < 4: l.append(None) else: l.append(line) print(time.time()-t) t=time.time() for i in range(10): L = l[:] L.sort() print(time.time()-t) def key(n): return n or "" t=time.time() for i in range(10): L = l[:] L.sort(key=key) print(time.time()-t) This key function is based on the assumption that there won't be any strings in l, which is reasonable, because they are all lines read from the input file (i.e. contain \n at least). If truly empty strings where possible, I'd map them to chr(0), which I would assume couldn't occur elsewhere in the input. With 2.5, I get these results (rounded) 3.8s 7.6s 14.3s So with the key function, the overhead appears to have doubled. I think the ratio should decrease as lists grow larger (because the key function is linear, and the sort is nlogn, assuming the overhead is in computing the key function), but I haven'd done any series varying the file size. With 3.0(rc3), I get (omitting the key-less sorting, as it won't work) 24.8s 15.9s So now the IO is much larger than the actual sorting, which is about the same in 2.5 and 3.0. If you wonder where the overhead of IO comes from: part of it probably from the UTF-8 decoding, that the IO library now does transparently. I don't know whether this overhead qualifies as "not insignificant", most people probably would claim that a doubling in time is indeed significant. OTOH, not knowing what the original problem is (e.g. whether it's interactive or in a batch mode, and whether bigfile.txt is much smaller or much larger than 32MiB), I would probably a) evaluate whether the increase in IO time is acceptable, and b) if it is, just go with 3.0, as the increase in sorting time is much smaller than the increase in IO time. Regards, Martin From rmcorrespond at gmail.com Fri Nov 14 14:03:03 2008 From: rmcorrespond at gmail.com (rm) Date: Fri, 14 Nov 2008 11:03:03 -0800 (PST) Subject: What is the best Python GUI API? References: <3719fa8e-379a-4b0a-83a9-0af3e0daa3a9@c36g2000prc.googlegroups.com> <8ce20505-2ed7-413f-af12-5868116478e8@u29g2000pro.googlegroups.com> Message-ID: <7f9f9087-ffef-4e29-af18-fc61db29eea6@k36g2000pri.googlegroups.com> On Nov 14, 1:59?pm, rm wrote: > On Nov 13, 7:08?pm, Stef Mientki wrote: > > > rm wrote: > > > On Nov 13, 2:23 pm, James Harris > > > wrote: > > > >> On 13 Nov, 18:59, Stef Mientki wrote: > > > >>> Abah Joseph wrote: > > > >>>> ?What is the best Python GUI API? I am planning to start my first GUI > > >>>> application and I need something easy and cross platform. Qt > > >>>> applications look beautiful but I hate the license. What do you advice? > > > >>> I agree about the Qt-license, > > >>> and I'm now a happy wxPython user. > > > >> I too have had good results with wxwidgets when developing a GUI. The > > >> cross-platform native look and feel was a major benefit from my point > > >> of view allowing screens to "look native" under different OSs with no > > >> code changes. > > > >> -- > > >> James > > > > Not so good if your native Linux look is KDE. ;) ?I also hate the fact > > > that the GTK File Save/Open dialog box does not allow file/folder > > > renames. ?On Windows, however, wxPython is great. ?I guess it depends > > > on how big your application is and what is the target audience/ > > > clientele. > > My very first GUI application ever was a wxPython Windows > application. ?You can get it from here if you like: > > http://rmcorrespond.googlepages.com/DirClean_1_0b1_exe.zip > > Source Code: > > http://rmcorrespond.googlepages.com/CocoRename_1.0_Source.zip > > (Keep in mind that I was just learning at the time, so I am not > particularly proud of the code, and I am sure most of it is deprecated > by now.) > > You can say that wxPython was my first love as far as GUI development > goes. ?I still think it is awesome because it is very rich and > mature. ?But, coding with it is not as clean as it could be. ?There is > a lot of boiler plate code needed. ?And I find it a lot less > 'Pythonic' than other alternatives. > > If I was just going to code a small (and I mean small) GUI app for > Windows (and possibly for Gnome) I would look into PythonCard. ?It > uses wxPython in the background, but it provides a much nicer API. > Unfortunately, not all the power of wxPython is available that way. > (Although you can drop down to straight wxPython if needed.) > > An example of a PythonCard application I wrote (for Windows) can be > obtained here: > > http://rmcorrespond.googlepages.com/CocoRename_1_0_exe.zip > > Source Code: > > http://rmcorrespond.googlepages.com/CocoRename_1.0_Source.zip > > My needs were covered between the two options above. ?However, two > things were bugging me. ?First, I wanted a better (faster) development > environment. ?It had to be free since all I code is Free as well. ?The > ones I had tried for wxPython were not cutting it. ?And second, in > Linux, I prefer KDE. ?So, I wanted something that was native to KDE. > When Trolltech released QT as a GPL toolkit I figured I would give it > a try. > > What I found was very eye opening. ?The API was beautiful and > intuitive. ?The tools and IDE (Eric, QT Designer, etc.) were more > along the lines of what I was looking for. ?So, I became a QT > believer. ?Unfortunately, my work circumstances have changed and I > haven't done any more GUI programming since then. ?(I am a Django > coder now. :) ?But, if I was going to do another GUI coding project > today, I would go with QT. ?So, you can see where I am coming from. > Your needs may vary. > > > Ok you only guess, but ... > > .. you're suggesting > > - that if the application is too big, wxPython is not a good choice. > > What's big ? > > - if the target is ... ??? ... it's not a good choice, for what audience > > is wxPython not suited ? > > thanks, > > Stef Mientki > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > Oops! Here is the source code for DirClean: http://rmcorrespond.googlepages.com/DirClean_1.0b1_Source.zip From ppearson at nowhere.invalid Fri Nov 21 11:48:50 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Nov 2008 16:48:50 GMT Subject: Problem with writing fast UDP server References: Message-ID: <6oo73iF4au6fU2@mid.individual.net> On Fri, 21 Nov 2008 08:14:19 -0800 (PST), Krzysztof Retel wrote: > I am not sure what do you mean by CPU-bound? How can I find out if I > run it on CPU-bound? CPU-bound is the state in which performance is limited by the availability of processor cycles. On a Unix box, you might run the "top" utility and look to see whether the "%CPU" figure indicates 100% CPU use. Alternatively, you might have a tool for plotting use of system resources. -- To email me, substitute nowhere->spamcop, invalid->net. From clp at rebertia.com Thu Nov 13 05:16:32 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 13 Nov 2008 02:16:32 -0800 Subject: multiple breaks In-Reply-To: References: Message-ID: <47c890dc0811130216n3afb46d4gdee1d066b16d86a7@mail.gmail.com> On Thu, Nov 13, 2008 at 2:07 AM, TP wrote: > Hi everybody, > > Several means to escape a nested loop are given here: > > http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python > > According to this page, the best way is to modify the loop by affecting the > variables that are tested in the loops. Otherwise, use exception: > > "If, for some reason, the terminating conditions can't be worked out, > exceptions are a fall-back plan." > > In the following example, is this possible to affect the two iterators to > escape the two loops once one "j" has been printed: > Non-exception alternative: done = False > for i in range(5): > for j in range(i): > print j done = True break > # I would type "break 2" in shell bash > # In C, I would set j=i-1 and i=4 > # In Python, is this possible to affect the two iterators? if done: break > > Or the only means is to use exception? No, you could add a boolean variable and a break condition like above. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) > -- > http://mail.python.org/mailman/listinfo/python-list > From vimy2010 at gmail.com Mon Nov 10 08:41:41 2008 From: vimy2010 at gmail.com (www.netnavigation.net) Date: Mon, 10 Nov 2008 05:41:41 -0800 (PST) Subject: My first Python program -- a lexer References: <9b30f3ba-5096-4a00-9b72-765c72d4fe3c@a29g2000pra.googlegroups.com> <9LidnfWOH6U4AIrUnZ2dnUVZ_hCdnZ2d@earthlink.com> <20ccbe1d-cb3b-4fa3-8b19-99c8c90b760a@s1g2000prg.googlegroups.com> Message-ID: BLAST YOUR AD TO 5,000 Yahoo groups for only $5.95 or less! ncrease Web Traffic & Sales Overnight! Get Massive Website Exposure Huge Profits Of Up To $117,209 Every Month I'm going to show you how I earn $7,400 + a week and have extra money to spend on myself and my family. Skyrocket YOUR traffic today! Email millions of targeted opt-in prospects daily with one single click! Increased My Traffic, Sales, and Profits By At Least 100%+! Make $3500 Weekly. I'll Show You Proof! Send 2.7 million emails everyday forever! 100% SPAM Free $3198.50 in 2 days! Imagine a money making system that requires absolutely no selling, advertising, recruiting or websites! Blast your ad once per day to over 3.1 million targeted prospects Increase Web Traffic & Sales Overnight! ONE CLICK MAILING FROM OUR SERVERS! I make several million dollars every year on the internet, doing almost nothing This is a profitable, easy and real work from home business Auto Submit To 3,000,000+ Websites Submit Your Ads To 735 Million Double Opt-in Members! Instantly Explode Your Web Traffic & Sales. Above all these, you can find here http://www.netnavigation.net From timr at probo.com Thu Nov 20 01:12:06 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Nov 2008 06:12:06 GMT Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: jzakiya wrote: > >I looked online and in books, but couldn't find a definitive answer to >this. > >I have an array and set multiple elements to either True or False at >one time. > >Question: Which way is faster (or does it matter)? Answer: it does not matter. This is premature optimization. First, make it work. Then, figure out whether it is fast enough. THEN, figure out what's taking the most time. I'd be very, very surprised if this was an important part of your run time. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sturlamolden at yahoo.no Thu Nov 6 08:56:49 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 6 Nov 2008 05:56:49 -0800 (PST) Subject: 2.6, 3.0, and truly independent intepreters References: <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <16acff7d-e3a4-4be0-a042-e74845501cb3@k16g2000hsf.googlegroups.com> <49057647$0$26690$9b622d9e@news.freenet.de> <49078e11$0$8568$9b622d9e@news.freenet.de> <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> <0c939463-ea77-4ead-8bb4-d411ab610f91@i20g2000prf.googlegroups.com> Message-ID: <7312b0f4-8e55-4eaf-b501-21958acbd4b5@v22g2000pro.googlegroups.com> On Nov 4, 6:51?pm, Paul Boddie wrote: > The language features look a lot like what others have already been > offering for a while: keywords for parallelised constructs (clik_for) > which are employed by solutions for various languages (C# and various C > ++ libraries spring immediately to mind); spawning and synchronisation > are typically supported in existing Python solutions, although > obviously not using language keywords. Yes, but there is not a 'concurrency platform' that takes care of things like load balancing and testing for race conditions. If you spawn with cilk++, the result is not that a new process or thread is spawned. The task is put in a queue (scheduled using work stealing), and executed by a pool of threads/processes. Multiprocessing makes it easy to write concurrent algorithms (as opposed to subprocess or popen), but automatic load balancing is something it does not do. It also does not identify and warn the programmer about race conditions. It does not have a barrier synchronization paradigm, but it can be constructed. java.util.concurrent.forkjoin is actually based on cilk. Something like cilk can easily be built on top of the multiprocessing module. Extra keywords can and should be avoided. But it is easier in Python than C. Keywords are used in cilk++ because they can be defined out by the preprocessor, thus restoring the original seqential code. In Python we can e.g. use a decorator instead. From steve at holdenweb.com Sun Nov 16 09:02:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Nov 2008 09:02:23 -0500 Subject: Official definition of call-by-value (Re: Finding the instance reference...) In-Reply-To: <012fb0ab$0$20662$c3e8da3@news.astraweb.com> References: <6nul1qF100urU1@mid.individual.net> <6nvts2F15nlmU1@mid.individual.net> <8fcccfa8-3bc9-454c-b898-dfc080f0dc1d@f37g2000pri.googlegroups.com> <012fb0ab$0$20662$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sat, 15 Nov 2008 11:17:07 -0800, rurpy wrote: [...] >> * How can I find an object's value (if I don't believe >> .str(), .repr(), etc)? Use gdb. :-) > > I would say the object's value is the value, so if you have the object, > you have its value. > [...] There's also the question, if you say that an object is different from its value, of determining what the value's value is ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Pidgeot18 at verizon.invalid Wed Nov 26 08:45:38 2008 From: Pidgeot18 at verizon.invalid (Joshua Cranmer) Date: Wed, 26 Nov 2008 08:45:38 -0500 Subject: what's so difficult about namespace? In-Reply-To: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> Message-ID: Xah Lee wrote: > In many languages, they don't have namespace and is often a well known > sour point for the lang. For example, Scheme has this problem up till > R6RS last year. PHP didn't have namespace for the past decade till > about this year. Javascript, which i only have working expertise, > didn't have namespace as he mentioned in his blog. Elisp doesn't have > name space and it is a well known major issue. Namespaces are useful for one reason: they allow you to have conflicts with names in some cases. In Java, there are two Lists: java.awt.List and java.util.List. Since a name must only be unique within a namespace, you can use shorter names without fear of conflict. In languages without these namespaces, you end up with stuff like g_type_init, e_data_server_module_init, mysql_connect, etc., where the prefixes are used to emulate the unique nature of namespaces. > Of languages that do have namespace that i have at least working > expertise: Mathematica, Perl, Python, Java. Knowing these langs > sufficiently well, i do not see anything special about namespace. Most features aren't sufficiently appreciated until one has to do without it. The avoidance of collision that comes with namespaces has shown to be sufficiently useful that I doubt we'll ever see a future major language that doesn't have some sort of namespace feature. > The > _essence_ of namespace is that a char is choosen as a separator, and > the compiler just use this char to split/connect identifiers. That's just composition of namespace names. It's not what namespaces is about. > i cannot fathom what could possibly be difficult of > introducing or implementing a namespace mechanism into a language. Namespaces go to the very core of a language, name resolution. Retroactively adding such a feature is extremely difficult because there is a strong chance of accidentally breaking existing code. > I > do not understand, why so many languages that lacks so much needed > namespace for so long? If it is a social problem, i don't imagine they > would last so long. It must be some technical issue? It's technical: it would be difficult to retroactively implement such a feature. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth From stefan_ml at behnel.de Sun Nov 9 10:41:04 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 09 Nov 2008 16:41:04 +0100 Subject: Python 3.0 - is this true? In-Reply-To: <6nob2mFmds4kU1@mid.individual.net> References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <01264714$0$20668$c3e8da3@news.astraweb.com> <6nob2mFmds4kU1@mid.individual.net> Message-ID: <4917048e$0$31332$9b4e6d93@newsspool4.arcor-online.net> Duncan Booth wrote: > Roy Smith wrote: > >> In 3.0, can you still order types? In 2.x, you can do: >> >>>>> t1 = type(1) >>>>> t2 = type(1j) >>>>> t1 < t2 >> False >> >> If this still works in 3.0, then you can easily do something like: >> >> def total_order(o1, o2): >> "Compare any two objects of arbitrary types" >> try: >> return o1 <= o2 >> except UncomparableTypesError: # whatever the right name is >> return type(o1) <= type(o2) >> >> and get the same effect as you had in 2.x. > > No, that won't work. You can compare types for equality/inequality, but > they are not orderable: > >>>> type(1)==type('a') > False >>>> sorted([1, 'a'], key=lambda x:(type(x),x)) > Traceback (most recent call last): > File "", line 1, in > TypeError: unorderable types: type() < type() However, for an arbitrary ordering of types, id(type(o1)) <= id(type(o2)) will work well enough. Stefan From salimfadhley at gmail.com Mon Nov 3 15:25:00 2008 From: salimfadhley at gmail.com (Salim Fadhley) Date: Mon, 3 Nov 2008 12:25:00 -0800 (PST) Subject: How do I find the memory used by a python process Message-ID: <31324fb8-964d-4fc9-96c2-61190e940ef7@e1g2000pra.googlegroups.com> I'm trying to create a python unit-test which will test a complex program which includes a number of functions which have been implemented in C or C++. The unit-test needs to check that after the functions have been run a few thousand times all of the memory used by those functions has been un-allocated, i.e. that there are no memory leaks. I was wondering if there is some way of finding out how much memory the current thread is using. I would like some kind of simple function call that gives me the current memory usage of the current process or thread. So each test would check the amount of memory available, call the function N times and then check the amount of memory available afterwards. If the amount of memory before and after changes by a certain amount then the test is failed. All of our unit-tests are single threaded processes. We run Windows and Python 2.4. Any suggestions? Thanks! Sal From gagsl-py2 at yahoo.com.ar Tue Nov 18 17:55:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Nov 2008 20:55:08 -0200 Subject: Avoiding local variable declarations? References: <8d695469-348d-483d-8fcb-2ed43cfd2a75@s1g2000prg.googlegroups.com> <482bf887-b7f3-4528-badd-3605d7628881@f40g2000pri.googlegroups.com> <6od6j3F2utseU1@mid.uni-berlin.de> <6of6ucF36or7U1@mid.uni-berlin.de> Message-ID: En Tue, 18 Nov 2008 16:27:46 -0200, Arnaud Delobelle escribi?: > Marc 'BlackJack' Rintsch writes: >> On Tue, 18 Nov 2008 00:18:51 +0000, Steven D'Aprano wrote: >>> On Mon, 17 Nov 2008 12:32:35 +0000, Marc 'BlackJack' Rintsch wrote: >>> >>>> Not such illogical crap like >>>> ``a = a + 1`` which must be obviously false unless 1 is defined as the >>>> neutral element for the definition of ``+`` here. >>> >>> I don't quite know what you mean by "neutral element". I think you mean >>> the identity element [?] >> I knew I should have looked it up instead of "translating" it from my >> mother tongue -- yes I ment "identity element". Sorry for the >> confusion. > Neutral element is correct. But maybe its use is limited to > mathematicians in the english-speaking word. In Spanish I've seen "elemento neutro" and "elemento identidad" used interchangeably. -- Gabriel Genellina From steve at holdenweb.com Thu Nov 13 10:07:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Nov 2008 10:07:41 -0500 Subject: Problem with sqlite3 cursor and imbricated for loop In-Reply-To: References: <200811120044.38554.charles.vejnar@unige.ch> <200811121227.51197.charles.vejnar@unige.ch> Message-ID: Gerhard H?ring wrote: > Steve Holden wrote: [...] >>> >> It's also why SQLite's not a real RDBMS. Fortunately this doesn't stop >> it being very useful. > > What does pysqlite extending the DB-API have to do with *SQLite* not > being a "real" RDBMS? > Nothing at all. I was just being pissy. Sorry about that. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Charlie.Xia.FDU at gmail.com Sun Nov 16 21:56:40 2008 From: Charlie.Xia.FDU at gmail.com (Charlie) Date: Sun, 16 Nov 2008 18:56:40 -0800 (PST) Subject: C Function Pointer Wrapping Example not working References: Message-ID: <5e766d7f-ad2f-4e7c-883f-120e214e1472@40g2000prx.googlegroups.com> > > > ?But when I try to import test in python, it complains: > > ?import _test > > ?ImportError: ./_test.so undefined symbol: _Z9binary_opiiPFiiiE > > The above is a mangled name so you've got some C vs C++ problems I'd > say. > > You could try putting some extern "C" {} in around all the functions > which are imported and exported. ?Have a look at the code SWIG > generates and see if it puts some extern "C" in and match what it > does in your code. > > We used to use SWIG in for python embedding in our C++ project, but we > found that using ctypes is a lot easier. ?You just write C .so/.dll > and use ctypes to access them. ?You can do callbacks and embedding > python like this too. Thanks Nick. I tried your method, if I am right(please see the attached details), and I still got the undefined symbol error like previous. The only difference is "_Z9binary_opiiPFiiiE" changed to "binary_op". Could you help me more on this. It seems to have a mixed problems here and I guess what you've pointed out is one of them. But really, what I do now is just try to reproduce the example, how can this fails? What my ultimate need is wrapping up a template function taking template function pointer as argument. Did you ever try that? Many thanks already anyway. FILE and ERROR details: ---------test.i-------------- %module test %{ #include "test.h" %} %include "test.h" %callback("%s_cb"); int myadd( int, int ); //myadd_cb int mysub( int, int ); //mysub_cb int mymul( int, int ); //mymul_cb %nocallback; -------------------------------- -----------test.h-------------- extern "C"{ int binary_op(int a, int b, int (*op)(int,int) ); int myadd( int a, int b ) { return a+b; }; int mysub( int a, int b ) { return a-b; }; int mymul( int a, int b ) { return a*b; }; } --------------------------------- ------error message---------- Traceback (most recent call last): File "", line 1, in File "test.py", line 7, in import _test ImportError: ./_test.so: undefined symbol: binary_op ---------------------------------- -------compiling message----- swig -v -python -c++ -o test_wrap.cpp test.i LangSubDir: python Search paths: ./ ./swig_lib/python/ /usr/local/share/swig/1.3.36/python/ ./swig_lib/ /usr/local/share/swig/1.3.36/ Preprocessing... Starting language-specific parse... Processing types... C++ analysis... Generating wrappers... python setup-test.py build running build running build_py copying test.py -> build/lib.linux-i686-2.5 running build_ext building '_test' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall - Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c test_wrap.cpp -o build/temp.linux-i686-2.5/test_wrap.o cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++ g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux- i686-2.5/test_wrap.o build/temp.linux-i686-2.5/test.o -o build/ lib.linux-i686-2.5/_test.so --------------------------------- From james at agentultra.com Thu Nov 20 18:31:12 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 20 Nov 2008 18:31:12 -0500 Subject: function parameter scope python 2.5.2 Message-ID: <854p229dq7.fsf@dozer.localdomain> I recently encountered some interesting behaviour that looks like a bug to me, but I can't find the appropriate reference to any specifications to clarify whether it is a bug. Here's the example code to demonstrate the issue: class SomeObject(object): def __init__(self): self.words = ['one', 'two', 'three', 'four', 'five'] def main(self): recursive_func(self.words) print self.words def recursive_func(words): if len(words) > 0: word = words.pop() print "Popped: %s" % word recursive_func(words) else: print "Done" if __name__ == '__main__': weird_obj = SomeObject() weird_obj.main() The output is: Popped: five Popped: four Popped: three Popped: two Popped: one Done [] Of course I expected that recursive_func() would receive a copy of weird_obj.words but it appears to happily modify the object. Of course a work around is to explicitly create a copy of the object property befor passing it to recursive_func, but if it's used more than once inside various parts of the class that could get messy. Any thoughts? Am I crazy and this is supposed to be the way python works? From arnodel at googlemail.com Mon Nov 24 15:25:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Nov 2008 20:25:10 +0000 Subject: My first Python program -- a lexer References: <9b30f3ba-5096-4a00-9b72-765c72d4fe3c@a29g2000pra.googlegroups.com> <1a2c1b73-ca9a-4234-b0bf-3b8bbbeee6da@w24g2000prd.googlegroups.com> Message-ID: Thomas Mlynarczyk writes: > John Machin schrieb: > >> *IF* you need to access the regex associated with a token in O(1) >> time, a dict is indicated. > > O(1) - Does that mean `mydict[mykey]` takes the same amount of time, > no matter if mydict has 10 or 1000000000 entries? How does this magic > work? O(log n) I would understand, but constant time? As I understand it, in theory it's not O(1) - I guess it's O(n). But for any non-cunningly crafted data it's as if it was O(1). Dictionaries are implemented as hashtables, not as trees. >> If you have *both* requirements simultaneously, then *both* list and >> dict are indicated. > > So I would have to duplicate my data and store it once in a list, once > in a dict? Or should I decide for one way and accept that one type of > access will not be optimal? Depends what you want to do! -- Arnaud From sillyhat at yahoo.com Sun Nov 2 16:34:40 2008 From: sillyhat at yahoo.com (sillyhat at yahoo.com) Date: Sun, 2 Nov 2008 13:34:40 -0800 (PST) Subject: Unyeilding a permutation generator Message-ID: <7041caa5-df2b-45e4-bb99-dc1ed4de3f6a@e38g2000prn.googlegroups.com> Hello, can someone please help. I found the following code at http://code.activestate.com/recipes/252178/ def all_perms(str): if len(str) <=1: yield str else: for perm in all_perms(str[1:]): for i in range(len(perm)+1): #nb str[0:1] works in both string and list contexts yield perm[:i] + str[0:1] + perm[i:] which allows me to do things like for x in all_permx("ABCD"): print x I believe it is making use of the plain changes / Johnson Trotter algorithm. Can someone please confirm? Anyway what I want to do is experiment with code similar to this (i.e. same algorithm and keep the recursion) in other languages, particularly vbscript and wondered what it would look like if it was rewritten to NOT use the yield statement - or at least if it was amended so that it can be easily translated to other languages that dont have python's yield statement. I think the statement "for perm in all_perms(str[1:]):" will be hardest to replicate in a recursive vbscript program for example. Thanks for any constructive help given. Hal From tjreedy at udel.edu Wed Nov 19 13:11:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Nov 2008 13:11:55 -0500 Subject: Quick nested loop syntax? In-Reply-To: References: Message-ID: Johannes Bauer wrote: > Hi group, > > if I remember correctly, wasn't there a way to quickly iterate through > nested loops? Something like > > a = { "a", "b", "c" } > b = { 4, 9, 13} > for (x, y) in someoperator(a, b): > print(x, y) from itertools import product a = { "a", "b", "c" } b = { 4, 9, 13} for (x, y) in product(a, b): print(x, y) From kay.schluehr at gmx.net Sat Nov 29 03:19:20 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 29 Nov 2008 00:19:20 -0800 (PST) Subject: Python docs and enumeration of sections Message-ID: <41d2b969-a1ab-4993-9c33-cc5cc3fd1de4@3g2000yqs.googlegroups.com> Is there a reason why enumeration of sections and subsections has been dropped after the switch to the Sphinx documentation tool? It doesn't really make quoting library sections easier or do you know what I mean when I refer to "How It Works"? From google at mrabarnett.plus.com Sun Nov 30 20:09:53 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 01 Dec 2008 01:09:53 +0000 Subject: Do more imported objects affect performance In-Reply-To: <1be78d220811301626s5ed79dcfv109afcb54ea8d323@mail.gmail.com> References: <1be78d220811301626s5ed79dcfv109afcb54ea8d323@mail.gmail.com> Message-ID: <49333961.1030102@mrabarnett.plus.com> Filip Gruszczy?ski wrote: > I have following question: if I use > > from module import * > > instead > > from module import Class > > am I affecting performance of my program? I believe, that all those > names must be stored somewhere, when they are imported and then > browsed when one of them is called. So am I putting a lot of "garbage" > to this storage and make those searches longer? > Importing many (or all) names will take longer than importing a few, but you probably won't notice the difference. You'll also be filling the namespace with a lot of unwanted names. Will it affect how long it takes to look up a name? No. From bj_666 at gmx.net Mon Nov 3 03:52:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Nov 2008 08:52:58 GMT Subject: Why does numpy.array(a[0],b[0]) have this meaning? References: <11088de9-aca2-4dba-bdbc-62ccbda24d8f@t18g2000prt.googlegroups.com> Message-ID: <6n7sf9Fk8mutU2@mid.uni-berlin.de> On Sun, 02 Nov 2008 23:26:24 -0800, Rick Giuly wrote: > Case 1 > This generates an error, which makes sense because the argument should > be a list of numbers: > numpy.array(10,10) > > Case 2 > This does not generate an error and the result is an array with a single > element: > a = numpy.array([10]) > b = numpy.array([10]) > numpy.array(a[0],b[0]) > > The only different I see here between the numpy.array call in the cases > is that > a[0] is a numpy int32 > 10 is an int > > Why would this minor difference in integer types cause a totally > different result for the two cases - or is something else causing the > difference in results? >From the `numpy.array` docstring: Inputs: object - an array, any object exposing the array interface, any object whose __array__ method returns an array, or any (nested) sequence. And `numpy.int32` instances have an `__array__()` method: In [225]: ten = numpy.int32(10) In [226]: ten.__array__() Out[226]: array(10) Ciao, Marc 'BlackJack' Rintsch From joe at strout.net Wed Nov 19 17:31:19 2008 From: joe at strout.net (Joe Strout) Date: Wed, 19 Nov 2008 15:31:19 -0700 Subject: Problem with writing a long line in a text file In-Reply-To: <460597290811191427q463cf79dk684906e70889dbae@mail.gmail.com> References: <460597290811191427q463cf79dk684906e70889dbae@mail.gmail.com> Message-ID: <44A638E2-E41A-47EA-ADE3-E40F137DBF9C@strout.net> On Nov 19, 2008, at 3:27 PM, Mohsen Akbari wrote: > I'm a newbie in python and I have this problem with the code that > I'm writing. There is a very long line which I wish to output it to > a text file.But when I do this, in the output file, the result > appears in two lines. Appears that way where? Using what tool to view it? My guess is that there is nothing wrong with the file, but that whatever you're using to view it is simply displaying it as two lines even though it is actually one. HTH, - Joe From steve at holdenweb.com Fri Nov 7 10:50:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Nov 2008 10:50:55 -0500 Subject: Finding the instance reference of an object In-Reply-To: <012417ea$0$20668$c3e8da3@news.astraweb.com> References: <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <01203bbd$0$20642$c3e8da3@news.astraweb.com> <3c4edf32-acda-4244-ba46-bad5ea623303@w39g2000prb.googlegroups.com> <0120cb30$0$20642$c3e8da3@news.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <0123b317$0$20668$c3e8da3@news.astraweb.com> <012417ea$0$20668$c3e8da3@news.astraweb.com> Message-ID: <491463DF.3080000@holdenweb.com> Steven D'Aprano wrote: > On Fri, 07 Nov 2008 00:44:21 -0500, Steve Holden wrote: > >> Steven D'Aprano wrote: >>> On Thu, 06 Nov 2008 09:59:37 -0700, Joe Strout wrote: >> [...] >>> And by definition, "call by value" means that the parameter is a copy. >>> So if you pass a ten megabyte data structure to a function using >>> call-by- value semantics, the entire ten megabyte structure is copied. >>> >>> Since this does not happen in Python, Python is not a call-by-value >>> language. End of story. >>> >>> >>> >>>> Without knowing that, you don't know what assignments to the formal >>>> parameter will do, or even what sort of arguments are valid. Answer: >>>> it's a copy of it. >>> Lies, all lies. Python doesn't copy variables unless you explicitly ask >>> for a copy. That some implementations of Python choose to copy pointers >>> rather than move around arbitrarily large blocks of memory instead is >>> an implementation detail. It's an optimization and irrelevant to the >>> semantics of argument passing in Python. >> [...] >> >> Are you sure you meant to write this? > > I'm not sure I understand what you're getting at. The only thing I can > imagine is that you think there's some sort of contradiction between my > two statements. I don't see why you think so. In principle one could > create an implementation of Python with no stack at all, where everything > lives in the heap, and all argument passing is via moving the actual > objects ("large blocks of memory") rather than references to the objects. > > I don't mean to imply that this is a practical way to go about > implementing Python, particularly given current computer hardware where > registers are expensive and the call stack is ubiquitous. But there are > other computing models, such as the "register machine" model which uses a > hypothetically-infinite number of registers, no stack and no heap. With > sufficient effort, one could implement a Python compiler using only a > Turing Machine. Turing Machines don't have call-by-anything semantics. > What would that say about Python? > > Alternatively, you're commenting about my comment about copying pointers. > I thought I had sufficiently distinguished between what takes place at > the level of the Python VM (nothing is copied without an explicit request > to copy it) and what takes place in the VM's implementation (the > implementation is free to copy whatever pointers it wants as an > optimization). If I failed to make that clear, I hope I have done so now. > > Pointers do not exist at the level of the Python VM, but they clearly > exist in the C implementation. We agree that C is call-by-value. CPython > is (obviously) built on top of C's call-by-value semantics, by passing > pointers (or references if you prefer) to objects. But that doesn't imply > that Python's calling semantics are the same as C's. > > Algol is call-by-name. Does anyone doubt that we could develop an Algol > implementation of Python that used nothing but call-by-name semantics at > the implementation level? Would that mean that Python was call-by-name? > > The point is that Joe's argument is based on a confusion between the C > implementation (calling a function with argument x makes a copy of a > pointer to x and puts it into the stack for the function) and what > happens at the level of the Python language. > > > I am probably egregiously misunderstanding. The practical difficulty with the "moving huge blocks of data" approach would appear to emerge when a function that gets passed an instance of some container then calls another function that references the same container as a global, for example. Again, I don't think we disagree about how Python actually works, but it seemed to me that your statement obscured rather than helped. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Krzysztof.Retel at googlemail.com Thu Nov 20 10:44:48 2008 From: Krzysztof.Retel at googlemail.com (Krzysztof Retel) Date: Thu, 20 Nov 2008 07:44:48 -0800 (PST) Subject: Problem with writing fast UDP server References: <87y6zeza0h.fsf@mulj.homelinux.net> Message-ID: On Nov 20, 3:34?pm, Hrvoje Niksic wrote: > Krzysztof Retel writes: > > But the server only handles 700 -- 870 packets, when it is non- > > blocking, and only 670 ? 700 received with blocking sockets. > > What are your other threads doing? ?Have you tried the same code > without any threading? I have only this one thread, which I can run couple of times. I tried without a threading and was the same result, not all packets were processed. From nospam at nospam.com Thu Nov 27 06:46:21 2008 From: nospam at nospam.com (Gilles Ganault) Date: Thu, 27 Nov 2008 12:46:21 +0100 Subject: [2.5.1] ShiftJIS to Unicode? References: Message-ID: On Thu, 27 Nov 2008 01:00:28 +0000, MRAB wrote: >No problem here: > > >>> import urllib > >>> data = urllib.urlopen("http://www.amazon.co.jp/").read() > >>> decoded_data = data.decode("shift-jis") > >>> Thanks, but it seems like some pages contain ShiftJIS mixed with some other code page, and Python complains when trying to display this. I ended up not displaying the string, and just sending it directly to the database: ======== title = None m = firsttry.search(the_page) if m: try: title = m.group(1).decode('shift-jis').strip() except UnicodeEncodeError: title = m.group(1).decode('iso8859-1').strip() except: title = "" else: m = secondtry.search(the_page) if m: try: title = m.group(1).decode('shift-jis').strip() except UnicodeEncodeError: title = m.group(1).decode('iso8859-1').strip() except: title = "" else: print "Nothing found for ISBN %s" % isbn if title: #UnicodeEncodeError: 'charmap' codec can't encode characters in position 49-55: character maps to #print "Found : %s" % title print "Found stuff" sql = 'INSERT INTO books (title) VALUES (?)' cursor.execute(sql,(title,)) ======== Thank you From george.sakkis at gmail.com Fri Nov 21 11:53:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 21 Nov 2008 08:53:17 -0800 (PST) Subject: Dynamic features used References: <0404d520-554a-4356-bfd2-0f44b9a4053a@y18g2000yqn.googlegroups.com> <223c08ca-f38f-45ec-a253-4693dce6c060@c2g2000pra.googlegroups.com> Message-ID: <289c16dd-a027-4b97-832c-fb9647f119ac@j35g2000yqh.googlegroups.com> On Nov 21, 7:55?am, bearophileH... at lycos.com wrote: > It's not easy to define what my point was :-) I try again, but the > following questions don't cover all the points: > - What are the dynamic features of Python that you use in your code? > (excluding ones that can can be done with a good static template > system). Off the top of my head, getattr/setattr are the most frequent dynamic features I use. > - Are them worth the decrease in running speed? > - Is it good for Python to become two languages in one, a fast > statically typed one and a dynamically one, like pypy shows to like > with RPython, or is it better to go the way of the Boo language, that > (while being mostly static) is mixing dynamic and static typing in the > same code, but that must rely on a very complex virtual machine to > work? > - Or maybe is it better to find other ways like CLips ones, that allow > to mix dynamic and static features, generally keeping programs fast > enough (Lisp-like syntax can lead to high performance too, as shown by > the Stalin Scheme compilerhttp://en.wikipedia.org/wiki/Stalin_(Scheme_implementation) Very valid points, and I also often think that dynamic typing is overrated; most programs don't need to add or remove attributes at will or change the class hierarchy. I don't know which of the alternatives you mention would be better but I would welcome changes towards the "static by default" direction, provided that (1) it *is* still possible to write dynamic code if necessary and (2) the extra effort in writing and reading it is not off-putting (e.g. no C++ template metaprogramming atrocities) George From sjmachin at lexicon.net Wed Nov 12 06:38:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Nov 2008 03:38:56 -0800 (PST) Subject: Does Python mess with CRLFs? References: <3sdlh4pmdem42bq5u3fvd7mc1o04hgc542@4ax.com> Message-ID: <368bdb22-1a47-47d7-b0fe-1d7baabdbaa3@a26g2000prf.googlegroups.com> On Nov 12, 10:04?pm, Gilles Ganault wrote: > Hello > > I'm stuck at understanding why Python can't extract some bit from an > HTML file using regexes, although I can find it just fine with > UltraEdit. > > I wonder if Python rewrites CRLFs when reading a text file with > open/read? Don't wonder; do some very elementary debugging and find out for yourself. > Here's the code: > ========== > f = open("content.html", "r") > content = f.read() > f.close() Consider inserting print repr(content) here. From rurpy at yahoo.com Thu Nov 13 14:58:18 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 13 Nov 2008 11:58:18 -0800 (PST) Subject: Official definition of call-by-value (Re: Finding the instance reference...) References: <6nvts2F15nlmU1@mid.individual.net> Message-ID: On Nov 12, 7:09 pm, George Sakkis wrote: > On Nov 12, 4:05 pm, Fredrik Lundh wrote: > >> greg wrote: >> >> It's not only misleading, it's also a seriously flawed reading of the >> >> original text - the Algol 60 report explicitly talks about assignment >> >> of *values*. >> >> > Do you agree that an expression in Python has a value? >> >> > Do you agree that it makes sense to talk about assigning >> > that value to something? >> >> Python's definition of the word "value" can be found in the language >> reference: >> >> http://docs.python.org/reference/datamodel.html#objects-values-and-types > > Quoting the relevant part: > > "The value of some objects can change. Objects whose value can change > are said to be mutable; objects whose value is unchangeable once they > are created are called immutable." > > Strictly speaking that's not a definition; it doesn't say what a value > is, only how it relates to objects. But regardless, according to this, > a Python value is what the rest of the world usually calls "state", ...snip... That just pushes the question to, "what's state?" doesn't it? Is a method part of an object's state (and hence "value"?) Are an object's data attribute values part of it's state? Are the values of a, b, and c different below? a = int(1) class myint(int): pass b = myint(1) c = myint(1) c.foo = 2 I have yet to see any reasonable definition of a Python value in the Python docs or elsewhere, despite the fact that a value is one of the three defining characteristics of an object, a central concept in Python. From sjmachin at lexicon.net Wed Nov 19 17:56:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Nov 2008 14:56:23 -0800 (PST) Subject: Problem with writing a long line in a text file References: <460597290811191427q463cf79dk684906e70889dbae@mail.gmail.com> Message-ID: On Nov 20, 9:31?am, Joe Strout wrote: > On Nov 19, 2008, at 3:27 PM, Mohsen Akbari wrote: > > > I'm a newbie in python and I have this problem with the code that ? > > I'm writing. There is a very long line which I wish to output it to ? > > a text file.But when I do this, in the output file, the result ? > > appears in two lines. > > Appears that way where? ?Using what tool to view it? > > My guess is that there is nothing wrong with the file, but that ? > whatever you're using to view it is simply displaying it as two lines ? > even though it is actually one. Or the "line" contains an embedded newline. The OP may like to insert some debug code just before he writes the line: print line.find('\n'), len(line), repr(line) and tell us how long is "very long". From Lie.1296 at gmail.com Wed Nov 5 16:06:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 5 Nov 2008 13:06:56 -0800 (PST) Subject: Finding the instance reference of an object References: <6mv3bnFj2qd8U1@mid.individual.net> <011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> <011ac754$0$20643$c3e8da3@news.astraweb.com> <8862f5ae-c482-4f53-a020-629eb45a5c3f@c22g2000prc.googlegroups.com> <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> Message-ID: <99574ae4-2019-4e79-9865-a4a6d8ed76dc@w39g2000prb.googlegroups.com> On Nov 4, 9:33?am, Joe Strout wrote: > On Nov 3, 2008, at 5:27 PM, Marc 'BlackJack' Rintsch wrote: > > > Maybe this is a surprise for you, because we haven't discussed this in > > much detail in this group lately, but it applies to Python which does > > call-by-object or call-by-sharing. ?;-) > > There's no such thing. ?Those are just terms made up by the Python ? > community to in place of the more standard "call-by-value" terminology ? > to make Python seem more mysterious than it really is. ?I guess you ? > can call it "purple bananas" if you want, but the behavior is exactly ? > the same as what every other language calls call-by-value. > > But I really am trying not to continue this debate. ?So that's my last ? > reply about it for tonight, I promise. ?:) > > Cheers, > - Joe > I'm fed up with you. In Von Neumann Architecture computers, only pass-by-value is natively supported. Other idioms are made on top of pass-by-value. That's why exclusively pass-by-value languages like C is most flexible than other exclusively pass-by-. BUT the difference is clear, if you want to do pass-by-reference in C (I prefer to call it faux pass-by-reference), you'd have to manually find a variable's address, pass it by-value, then dereference the address. Compare with VB's ByRef or C++'s &, which does all that _automatically_ for you behind the scene. Another example: pass-by-object. I disagree with the term pass-by- object-reference, since the notion of object reference is unnecessary in a true pass-by-object mechanism (i.e. we should travel outside VNA realm for a true pass-by-object mechanism). Problem is: I'm not aware of any computer architecture that can accommodate pass-by-object natively or whether such architecture is feasible to be made. Solution: Emulate such architecture on a VNA computer. Limitations: pass-by-object implementation on a VNA computer requires the notion of object reference/pointer because VNA computers cannot pass object, it can only pass numbers. In pass-by-object, the whole object is passed around, not a copy of the object like in pass-by-value or a copy of the pointer to the object like in faux pass-by-reference. This makes pass-by-object actually closer to pass-by-reference than to pass-by-value, since the notion of VNA's requirement for Object Reference means passing pointers around. But don't let it confuse you, the pass-by-object mechanism itself does not recognize Object Reference, unlike pass-by- reference recognition of reference/pointer. Now that I have clearly defined the line between pass-by-object and pass-by-value, I'm left with you thinking what's the difference between pass-by-object and pass-by-reference. In pass-by-reference, names are _mnemonic to location in memory_. In pass-by-object, names are _mnemonic to objects_. In pass-by-reference, when we assign a value to the name, we'd assign a value _to the location in memory_. In pass-by-object, when we assign a value to the name, we assign an object _to the name_. When passing parameters, pass-by-reference systems passed the memory address and alias that memory address to a local name. In pass-by-object system, since the object itself has no idea of its own name, so it is rebound to a local name. You can say that pass-by-reference system is memory-location-centered, while pass- by-object system is name-centered. To summarize, the key bit you're missing is built-in _automatic_ abstraction from pass-by-value. All pass-by- except pass-by-value is an emulation over an architecture that can only natively pass-by-value. pass-by-reference is emulated in C, C++, and VB by passing memory address/pointer but C isn't a by-ref system because C doesn't provide the automatization. What makes python's parameter passing called as pass-by-object is because python provides the automatization to make it seems that you can do true pass-by- object. From google at mrabarnett.plus.com Mon Nov 17 18:38:48 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 17 Nov 2008 15:38:48 -0800 (PST) Subject: regular expressions ... slow References: <333a6421-79fb-4d0c-a0a7-f9978a5bcb3f@v13g2000pro.googlegroups.com> <16651e80811171410s5dbbe49dn5e7a36fd723a02b7@mail.gmail.com> Message-ID: On Nov 17, 10:24?pm, Terry Reedy wrote: > Jerry Hill wrote: > > On Mon, Nov 17, 2008 at 4:37 PM, Uwe Schmitt > > wrote: > >> Hi, > > >> Is anobody aware of this post: ?http://swtch.com/~rsc/regexp/regexp1.html? > > > Yes, it's been brought up here, on python-dev and python-ideas several > > times in the past year and a half. > > >> Are there any plans ?to speed up Pythons regular expression module ? > >> Or > >> is the example in this artricle too far from reality ??? > > > I don't think anyone has taken any concrete steps towards re-writing > > the regular expression module. ?My understanding from previous threads > > on the topic is that the core developers would be willing to accept a > > re-written regular expression engine, but none of them are interested > > in doing it themselves. ?The general consensus seemed to be that the > > pathological cases hilited in that article are not very common in the > > real world, and that simply switching to the alternative approach > > advocated there would require giving up things like backreferences > > that are actually used in the real world, which is probably > > unacceptable. > > > Some references: > >http://mail.python.org/pipermail/python-dev/2007-March/072241.html > >http://mail.python.org/pipermail/python-list/2007-February/427604.html > >http://mail.python.org/pipermail/python-ideas/2007-April/000405.html > > > Personally, I know very little about the nitty gritty of regular > > expression engines, but there's some reference material for you to > > chew on. > > Searching the tracker for open items with 'regular expression' in the > text brings up about 20 items to also consider. Work is currently being done on the re module. I don't think the DFA approach works permits backreferences, capture groups or non-greedy repetition, but it certainly could be used if those features aren't required by the regular expression, so the answer is definitely maybe! :-) From mail at timgolden.me.uk Fri Nov 21 11:22:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 21 Nov 2008 16:22:16 +0000 Subject: Need help converting text to csv format In-Reply-To: <4926DDBE.9000901@tim.thechases.com> References: <6e21bcdc-a5e6-4b1e-8658-05a47df0d076@l42g2000yqe.googlegroups.com> <4926DDBE.9000901@tim.thechases.com> Message-ID: <4926E038.4080207@timgolden.me.uk> Tim Chase wrote: >> >>> qfields = ['"' + fld.strip() + '"' for fld in (num,desc,date)] >> >>> out = qfields.join(',') > > Just a quick note here to prevent the confusion of the OP...this should be > > ','.join(qfields) To be honest, it's so easy to use the stdlib csv module that I'd always recommend that, especially as it covers all those annoying corner cases with embedded commas and quotes and stuff. And it's tested to hell and back. In general, for a list of field tuples: import csv fields = [ ("Tim Golden", 40, "inf,o1"), ("Fred Smith", 25, "info2"), ("Joe O'Reilly", 55, 'inf,"blah",o3'), ## lots of messiness ] ofile = open ("data.csv", "wb") try: writer = csv.writer (ofile) writer.writerows ([[str (i) for i in f] for f in fields]) finally: ofile.close () From invalid at invalid Wed Nov 12 10:59:14 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 12 Nov 2008 09:59:14 -0600 Subject: Official definition of call-by-value (Re: Finding the instance reference...) References: <6nul1qF100urU1@mid.individual.net> <6nvts2F15nlmU1@mid.individual.net> Message-ID: On 2008-11-12, Steve Holden wrote: > greg wrote: I stopped paying much attention to this thread a while ago, but you've got to admire the persistence of somebody who soldiers on even though Aahz, Fredrik Lund, and Steve Holden are all on the other side of the argument... -- Grant Edwards grante Yow! Look DEEP into the at OPENINGS!! Do you see any visi.com ELVES or EDSELS ... or a HIGHBALL?? ... From david.lyon at preisshare.net Tue Nov 25 22:28:12 2008 From: david.lyon at preisshare.net (david.lyon at preisshare.net) Date: Tue, 25 Nov 2008 22:28:12 -0500 Subject: Python surpasses Perl in popularity? In-Reply-To: <391214e2-464d-483d-87b0-d2c8a732c690@r15g2000prd.googlegroups.com> References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <77450bcf-ec47-44ac-820b-c214b300ee68@a3g2000prm.googlegroups.com> <391214e2-464d-483d-87b0-d2c8a732c690@r15g2000prd.googlegroups.com> Message-ID: <20081125222812.od96hywupogc0ksc@syd-srv02.ezyreg.com> Quoting John Machin : > pyExcelerator is abandonware. Check out xlwt (a fork of pyExcelerator) > at http://pypi.python.org/pypi/xlwt Thanks John. That is very helpful. I will move to that product.. From bearophileHUGS at lycos.com Fri Nov 21 07:55:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Nov 2008 04:55:11 -0800 (PST) Subject: Dynamic features used References: <0404d520-554a-4356-bfd2-0f44b9a4053a@y18g2000yqn.googlegroups.com> <223c08ca-f38f-45ec-a253-4693dce6c060@c2g2000pra.googlegroups.com> Message-ID: Almar Klein: > but I fail to see the point you're trying > to make or the question you're asking... :) It's not easy to define what my point was :-) I try again, but the following questions don't cover all the points: - What are the dynamic features of Python that you use in your code? (excluding ones that can can be done with a good static template system). - Are them worth the decrease in running speed? - Is it good for Python to become two languages in one, a fast statically typed one and a dynamically one, like pypy shows to like with RPython, or is it better to go the way of the Boo language, that (while being mostly static) is mixing dynamic and static typing in the same code, but that must rely on a very complex virtual machine to work? - Or maybe is it better to find other ways like CLips ones, that allow to mix dynamic and static features, generally keeping programs fast enough (Lisp-like syntax can lead to high performance too, as shown by the Stalin Scheme compiler http://en.wikipedia.org/wiki/Stalin_(Scheme_implementation) ). Bye, bearophile From george.sakkis at gmail.com Fri Nov 28 08:58:12 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 28 Nov 2008 05:58:12 -0800 (PST) Subject: Great exercise for python expert ! References: <9138e8c8-136a-4ac0-a1a4-dbf0469507e7@h5g2000yqh.googlegroups.com> Message-ID: <6abd5bf1-f642-4592-9ec1-4248912226ff@j35g2000yqh.googlegroups.com> On Nov 28, 5:36?am, manatlan wrote: > I'd like to make a "jquery python wrapper" ... > > here is my code : > =================================================================== > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > class JQueryCaller(object): > ? ? def __init__(self,callback): > ? ? ? ? self.__callback=callback > ? ? ? ? self._s=[] > > ? ? def __getattr__(self,name): > ? ? ? ? def _caller(*args): > ? ? ? ? ? ? sargs=["'%s'"%i for i in args] > ? ? ? ? ? ? self._s.append("%s(%s)"%(name,",".join(sargs))) > ? ? ? ? ? ? return self > ? ? ? ? return _caller > > ? ? def __call__(self): > ? ? ? ? return self.__callback(".".join(self._s)) > > class MyObject(object): > ? ? def __init__(self): > ? ? ? ? self.js = JQueryCaller(self.__add) > > ? ? def __add(self,j): > ? ? ? ? print "Add:"+j > > if __name__ == "__main__": > ? ? o=MyObject() > > ? ? o.js.kiki(12).kuku()() > =================================================================== > If i run the script : it will display : > > Add:kiki('12').kuku() > > Because the JQueryCaller caller is called, by the "()" trick at the > end of the last line > > I'd like to display the same thing, but without the need to put the > "()" at then end ! > (by calling simply : "o.js.kiki(12).kuku()" not "o.js.kiki(12).kuku() > ()") > (or how to call the MyObject._add (callback) without using the caller > on my JQueryCaller) Why don't you rename __call__ to __str__ and have MyObject.__add return a string instead of printing it directly? class MyObject(object): def __add(self,j): return "Add:"+j if __name__ == "__main__": o = MyObject() s = o.js.kiki(12).kuku() print s HTH, George From davidgshi at yahoo.co.uk Thu Nov 6 13:01:03 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Thu, 6 Nov 2008 18:01:03 +0000 (GMT) Subject: .pyc keeps running and never stops Message-ID: <340397.80830.qm@web26304.mail.ukl.yahoo.com> Dear All, ? I am using Python 2.5 and used py_compile to produce a .pyc file.? The script runs well.? However, the .pyc keeps running and never stops. ? Advices will be deeply appreciated. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Sat Nov 29 03:59:58 2008 From: vginer at gmail.com (Vicent Giner) Date: Sat, 29 Nov 2008 00:59:58 -0800 (PST) Subject: Debugging in Python Message-ID: <38a89d61-9dfd-491c-b9dc-946709eec8c7@v42g2000yqv.googlegroups.com> Hello again. Thank you for the answers I got to my previous question. All of them were very useful to me. I want to know if I have understood well the way I can work with Python. As far as I've understood, [the free version of] ActivePython is just a [good, ready-to-work] Python distribution. Also, it contains and editor, PythonWin Editor. Has that editor the ability of performing good debugging tasks? I mean, is it enough for doing debugging? I pose this question because I've seen there is Komodo Editor and its non-free version Komodo IDE. For me, Komodo Editor has a very good interface. And the only feature I would like to get from the non-free version of Komodo is the ability of debugging. But I won't by it if I can have nearly the same with PythonWin Editor. In your opinion, what other benefits from non-free Komodo are worth it, if compared with PythonWin? Can people with more experience in Python programming help me?? Thank you in advance! -- Vicent From pruebauno at latinmail.com Fri Nov 14 14:27:10 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Fri, 14 Nov 2008 11:27:10 -0800 (PST) Subject: duck-type-checking? References: <2b6000bf-fd9a-4330-be33-3a798a7ca387@z6g2000pre.googlegroups.com> <012ceefc$0$20662$c3e8da3@news.astraweb.com> <5828ef60-66df-4bb0-9a7d-aa08490f9e49@40g2000prx.googlegroups.com> Message-ID: <39d83435-5304-4be2-9dfe-c50f70eb4b6a@d10g2000pra.googlegroups.com> On Nov 14, 12:47 am, George Sakkis wrote: > On Nov 13, 10:55 pm, Steven D'Aprano > cybersource.com.au> wrote: > > Take this example: > > > def foo(alist): > > alist.sort() > > alist.append(5) > > > The argument can be any object with sort and append methods (assumed to > > act in place). But what happens if you pass it an object with a sort > > method but no append? The exception doesn't occur until *after* the > > object is sorted, which leaves it in an inconsistent state. This can be > > undesirable: you might need the function foo to be atomic, either the > > entire function succeeds, or none of it. > > In this example atomicity is not guaranteed even if alist is a builtin > list (if it contains a complex number or other unorderable object), > let alone if not isistance(alist, list). It gets worse: false > positives are less likely for full-spelled methods with well-known > names such as "sort" and "append" (i.e. if hasattr(alist, 'append'), > alist.append *probably* does what you think it does), but good luck > with that when testing for __getitem__, __iter__ for more than one > pass, __call__, and other special methods with ambiguous or undefined > semantics. > > Let's face it, duck typing is great for small to medium complexity > projects but it doesn't scale without additional support in the form > of ABCs/interfaces, explicit type checking (at compile and/or run > time), design by contract, etc. It must not be a coincidence that both > Zope and Twisted had to come up with interfaces to manage their > massive (for Python at least) complexity. > > George What would be actually interesting would be an switch to the python interpreter that internally annotated function parameters with how they are used in the function and raised an exception as soon as the function is called instead of later. Failing earlier rather than later. Example: def sub(x,y): ...run some stuff ...print x[2] ...return y.strip().replace('a','b') internally python generates: def sub(x: must have getitem, y: must have strip and replace) sub([1,2,3,4],5) Error calling sub(x,y): y has to have strip() method. From claird at lairds.us Mon Nov 3 12:50:31 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 3 Nov 2008 17:50:31 +0000 Subject: Anyone in the Houston / College Station / Austin area? Looking to do some sprints / joint projects. References: Message-ID: <78q3u5-f6p.ln1@lairds.us> In article , xkenneth wrote: >All, > > I'm in Houston/College Station/Austin quite often and I'm looking >for other coders to do some joint projects with, share experiences, or >do some sprints. Let me know if you're interested. . . . You'll want to see , , and so on. From bcd240 at gmail.com Sun Nov 23 18:59:17 2008 From: bcd240 at gmail.com (bMotu) Date: Mon, 24 Nov 2008 00:59:17 +0100 Subject: 3.0rc3: 'os.extsep' gone ... ? Message-ID: <1e18d73c0811231559v2de31837g952fa8fdd0963f9e@mail.gmail.com> IDLE 2.6 >>> import os >>> os.extsep '.' running XP this result is fine ... ! IDLE 3.0rc3 >>> import os >>> os.extsep Traceback (most recent call last): File "", line 1, in os.extsep AttributeError: 'module' object has no attribute 'extsep' why is this attribute gone in 3.0rc3 ? where is this documented ? ciao, motu From digitig at gmail.com Wed Nov 12 12:45:49 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 12 Nov 2008 17:45:49 +0000 Subject: duck-type-checking? In-Reply-To: <9D538BAC-4C29-4DB5-8F33-5783B7359196@strout.net> References: <9D538BAC-4C29-4DB5-8F33-5783B7359196@strout.net> Message-ID: 2008/11/12 Joe Strout : > Let me preface this by saying that I think I "get" the concept of > duck-typing. > > However, I still want to sprinkle my code with assertions that, for example, > my parameters are what they're supposed to be -- too often I mistakenly pass > in something I didn't intend, and when that happens, I want the code to fail > as early as possible, so I have the shortest possible path to track down the > real bug. Also, a sufficiently clever IDE could use my assertions to know > the type of my identifiers, and so support me better with autocompletion and > method tips. > > So I need functions to assert that a given identifier quacks like a string, > or a number, or a sequence, or a mutable sequence, or a certain class, or so > on. (On the class check: I know about isinstance, but that's contrary to > duck-typing -- what I would want that check to do instead is verify that > whatever object I have, it has the same public (non-underscore) methods as > the class I'm claiming.) > > Are there any standard methods or idioms for doing that? What do you actually mean by "Quacks like a string"? Supports the 'count()' method? Then you find out if it doesn't when you try to apply the 'count()' method. Supports some method that you don't actually use? Then why do you care? The point about duck typing is that something might quack like a duck but not walk like a duck -- one of those duck calls that hunters use, for instance. Quacking like a duck doesn't actually mean it /is/ a duck, it means that it will do instead of a duck if the quack is all you want. If all you care about is that 'foo' quacks like a duck then all you need to know is that hasattr(foo, "quack") and (if so) callable(foo.quack) If you need to know that it walks like a duck, mates like a duck and tastes like a duck when roasted, you probably want it to really /be/ a duck and should go back to inheritance. -- Tim Rowe From rapidshareboobs6 at gmail.com Sun Nov 30 18:11:53 2008 From: rapidshareboobs6 at gmail.com (boobs) Date: Sun, 30 Nov 2008 15:11:53 -0800 (PST) Subject: * Sexy Bouncy Enormous Jugs! * Free Downloads! Message-ID: <49e5f2b9-1b93-46e6-b520-62a233f10898@d36g2000prf.googlegroups.com> http://enormusjugs.blogspot.com/2008/11/cia-director-claims-osama-bin-laden.html - The best tits in town people for the love of god already these great pictures and videos wont last long download them while you can ! From jeremy+complangpython at jeremysanders.net Mon Nov 17 05:26:17 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 17 Nov 2008 10:26:17 +0000 Subject: os.pipe and subprocess under Windows Message-ID: Hi - I have some code which works under linux. It starts a remote python process using subprocess and communicates to it via a pipe created by os.pipe. As far as I understand, child processes should inherit file descriptors from the parent if close_fds=False on the suprocess.Popen command line. This code doesn't work under Window, but gives "bad file descriptor" when trying to read from the pipe in the child process. I have some example code which fails. It consists of two files, master.py and slave.py. The file descriptor for reading from the pipe is passed as a argument to slave.py. ---------------------------------------------------------------- #!/usr/bin/env python # This is master.py import os import os.path import sys import subprocess def runMaster(): # create pipe to communicate with remote process rpipe, wpipe = os.pipe() # start remote process cmdline = [sys.executable, os.path.join( os.path.dirname( os.path.abspath(__file__)), 'slave.py' ), str(rpipe) ] remote = subprocess.Popen(cmdline, shell=False, bufsize=0, close_fds=False) # send text to remote process via pipe os.write(wpipe, 'hi there$') # wait until remote exit remote.wait() if __name__ == '__main__': runMaster() ------------------------------------------------------------------ # This is slave.py import sys import os def runSlave(fd): """Copy text to stderr from file descriptor until a $ symbol.""" while True: intext = os.read(fd, 1) if intext == '$': break elif intext: # write text from pipe to stderr sys.stderr.write('* %s\n' % intext) if __name__ == '__main__': fd = int(sys.argv[1]) runSlave(fd) ------------------------------------------------------------------- Does anyone have any ideas how to get this to work under Windows? Is it correct code under unix? Thanks Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From http Sun Nov 23 00:23:08 2008 From: http (Paul Rubin) Date: 22 Nov 2008 21:23:08 -0800 Subject: build minimal python 2.6 on linux References: <9069001b-5188-4b47-bbd4-e84c5ed890a4@z1g2000yqn.googlegroups.com> Message-ID: <7x7i6vggn7.fsf@ruckus.brouhaha.com> r writes: > The files weigh in at 51MB and some change. > Since transfer from USB on the laptop is painfully slow, and the cdrom > is toast, i need to slim down the 2.6 source as much as possible, so > it doesn't take 2 days to copy, Even with USB 1.0, 51 mb should only take a minute or so to copy. From mail at microcorp.co.za Mon Nov 17 14:20:58 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 17 Nov 2008 21:20:58 +0200 Subject: Official definition of call-by-value (Re: Finding the instancereference...) References: <6nul1qF100urU1@mid.individual.net> <6nvts2F15nlmU1@mid.individual.net> <8fcccfa8-3bc9-454c-b898-dfc080f0dc1d@f37g2000pri.googlegroups.com><012fb0ab$0$20662$c3e8da3@news.astraweb.com> Message-ID: <004001c948e9$b738c2a0$0d00a8c0@hendrik> "Steve Holden" wrote: > There's also the question, if you say that an object is different from > its value, of determining what the value's value is ... This one is easy - its obviously the value that is returned when the value is returned when you call for the value that you are interested in, unless you are interested in the bare value, in which case its the value that is returned. I am beginning to suspect that Steven de'A is hammering away at this to take his mind off the recent cricket game between his country's team and India. Anything is better than contemplating that. It was enough to shake one's faith in Southern Supremacy... :-) - Hendrik -- And there was wailing and gnashing of teeth... From malaclypse2 at gmail.com Mon Nov 3 13:45:47 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 Nov 2008 14:45:47 -0400 Subject: Problem using urllib to download images In-Reply-To: <4578f1f1-425f-4d46-a65a-b85a9410e8de@p10g2000prf.googlegroups.com> References: <34d40c32-e9d6-4f69-8843-b6bf68197891@v13g2000pro.googlegroups.com> <4578f1f1-425f-4d46-a65a-b85a9410e8de@p10g2000prf.googlegroups.com> Message-ID: <16651e80811031045w7a04e16epa64f9f04b3e3c2fd@mail.gmail.com> On Mon, Nov 3, 2008 at 2:21 PM, wrote: > Then perhaps it's a problem with my os. > [TERMINAL SESSION] > [18:16:33 Mon Nov 03] python > Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import urllib >>>> url = 'http://www.google.com/webhp?hl=en' That's not the URL of an image file. Maybe you're looking for url = 'http://www.google.com/intl/en_ALL/images/logo.gif' >>>> filename = 'logo.gif' >>>> image = urllib.URLopener() >>>> image.retrieve(url, filename) > ('logo.gif', ) > [/TERMINAL SESSION] > And here's the error message I get when I try to open it: "File Error: > Couldn't open the file. It may be corrupt or a file format that > Preview doesn't recognize.". > I have had a similar result trying to open it with other programs. That's because you downloaded some HTML and saved it in a file named logo.gif. That's unlikely to work in any image viewing program. Try opening the file you downloaded in a text editor and you'll see. -- Jerry From matthieu.brucher at gmail.com Tue Nov 25 13:47:12 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 25 Nov 2008 19:47:12 +0100 Subject: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0) In-Reply-To: References: <6p2k5hF62p1vU1@mid.uni-berlin.de> <433d6186-a9db-42d9-9e53-b579d8bb09c7@e12g2000yqm.googlegroups.com> Message-ID: Boost.Python is difficult to understand, far more than SWIG. It may be faster, but I don't think it is worth it ATM. Binding C++ classes with SWIG is really simple. Matthieu 2008/11/25 Olivier Grisel : > 2008/11/25 : >> On Nov 25, 4:34 pm, "Diez B. Roggisch" wrote: >>> >>> You can't use ctypes for C++, only for C-style APIs. >>> >>> Diez >> >> With some work, you can convert your C++ objects to PyObject* and then >> return the latter in a function with C bindings. > > http://cython.org also has some support for C++ bindings. > > I also heard that Boost.Python is very well suited to make full > featured C++ / python bindings though I never tried myself. > > -- > Olivier > -- > http://mail.python.org/mailman/listinfo/python-list > -- Information System Engineer, Ph.D. 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 jjalocha at gmail.com Fri Nov 21 07:24:40 2008 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Fri, 21 Nov 2008 09:24:40 -0300 Subject: Can't find Python Library packages in Ubuntu (Debian) Message-ID: <9b72f9a90811210424g113ec6a0yb74b8ccff484d818@mail.gmail.com> >> So, the first question is: How do I install the complete Python test >> framework under Ubuntu (Debian)? >> >> So, my second question: What (meta?-)package(s) do I have to install >> under Ubuntu (Debian) in order to get a full (as in the official >> release) Python installation? > I don't have the slightest idea where the tests are - but you can of course > always install the source package :) I think, I will take the chance, and install Python 2.6 which isn't available as an Ubuntu package yet. :) And my third question could be: Do all Python developers that work with Debian (or derivations) have to compile Python? > The one thing you will definitely need is the python-dev-package. It will > contain things such as headers and distutils that are needed to build and > install 3rd-party-packages. Thanks for your comments, Diez! Jerzy From zac256 at gmail.com Wed Nov 5 14:34:44 2008 From: zac256 at gmail.com (Zac Burns) Date: Wed, 5 Nov 2008 11:34:44 -0800 Subject: Dictionary membership check failure Message-ID: <333edbe80811051134w1306ccc5s3242a4b1cd53dc7c@mail.gmail.com> Greetings, I have a dictionary that seems to be misbehaving on a membership check. This test code: 1: import types 2: assert myDict.__class__ is types.DictionaryType 3: assert (key in myDict.keys()) == (key in myDict) raises AssertionError on line three. The dictionary items are all of type (string, function). There are no threads. Python version is 2.5.1, I cannot go to 2.5.2 right now because of a module that we use that depends on 2.5.1 (maya standalone), but does anyone know if this bug has been fixed in 2.5.2 or if I can give anyone more information to help fix this bug? -- Zachary Burns Aim - Zac256FL Production Engineer Zindagi Games From Scott.Daniels at Acm.Org Wed Nov 12 17:37:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Nov 2008 14:37:40 -0800 Subject: Using the result of type() in a boolean statement? In-Reply-To: References: Message-ID: dpapathanasiou wrote: > ... I'd like to define a loop like this, ... > for key, value in my_dict.items(): > if type{value) is : > # do the dictionary logic > elif type(value) is : > # do the string logic > # etc You're searching for "isinstance" (or possibly issubclass) for key, value in my_dict.items(): if isinstance(value, dict): # do the dictionary logic elif isinstance(value, str): # use basestring for str & unicode # do the string logic Or, if you _must_ use type: if issubclass(type(value), dict): # do the dictionary logic elif issubclass(type(value), str): # do the string logic --Scott David Daniels Scott.Daniels at Acm.Org From dundeemt at gmail.com Sat Nov 29 09:27:41 2008 From: dundeemt at gmail.com (Jeff H) Date: Sat, 29 Nov 2008 06:27:41 -0800 (PST) Subject: unicode and hashlib References: Message-ID: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> On Nov 28, 2:03?pm, Terry Reedy wrote: > Jeff H wrote: > > hashlib.md5 does not appear to like unicode, > > ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xa6' in > > position 1650: ordinal not in range(128) > > It is the (default) ascii encoder that does not like non-ascii chars. > I suspect that is you encode to bytes first with an encoder that does > work (latin-???), md5 will be happy. > > Reports like this should include Python version. > > > After googling, I've found BDFL and others on Py3K talking about the > > problems of hashing non-bytes (i.e. buffers) > > http://www.mail-archive.com/python-3... at python.org/msg09824.html > > > So what is the canonical way to hash unicode? > > ?* convert unicode to local > > ?* hash in current local > > ??? > > but what if local has ordinals outside of 128? > > > Is this just a problem for md5 hashes that I would not encounter using > > a different method? ?i.e. Should I just use the built-in hash function? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Python v2.52 -- however, this is not really a bug report because your analysis is correct. I am converting cp1252 strings to unicode before I persist them in a database. I am looking for advice/direction/ wisdom on how to sling these strings -Jeff From manu3d at gmail.com Thu Nov 27 08:37:49 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Nov 2008 05:37:49 -0800 (PST) Subject: Exhaustive Unit Testing References: <8ae042c1-9a6c-412a-83f6-92b1d58e1ce5@j32g2000yqn.googlegroups.com> Message-ID: On Nov 27, 5:00?am, Steven D'Aprano wrote: > Refactor until your code is simple enough to unit-test effectively, then > unit-test effectively. I suspect you are right... Ok, thank you! Manu From rocksportrocker at googlemail.com Mon Nov 17 16:37:18 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Mon, 17 Nov 2008 13:37:18 -0800 (PST) Subject: regular expressions ... slow Message-ID: <333a6421-79fb-4d0c-a0a7-f9978a5bcb3f@v13g2000pro.googlegroups.com> Hi, Is anobody aware of this post: http://swtch.com/~rsc/regexp/regexp1.html ? Are there any plans to speed up Pythons regular expression module ? Or is the example in this artricle too far from reality ??? Greetings, Uwe From cab938 at mail.usask.ca Wed Nov 12 21:51:38 2008 From: cab938 at mail.usask.ca (Chris Brooks) Date: Wed, 12 Nov 2008 18:51:38 -0800 (PST) Subject: memory mapped tar file contents Message-ID: <20473925.post@talk.nabble.com> Hi, I would like to read directly from a tar file into memory so I can manipulate a file (quickly) and write its changes out to another file. I thought I could do something like: #!/usr/bin/env python import tarfile import mmap fil = tarfile.open( "out.tar.gz" , "r:gz" ) tarinf = fil.next() myfils = {} while tarinf != None: tarinf = fil.next() ref = fil.extractfile( tarinf ) myfils[ tarinf.name ] = mmap.mmap( ref.fileno() , 0 ) But the extractfile() function of TarInfo doesn't seem to give me a fileno, so I can't pass this to mmap. Thoughts on a way to accomplish this? Chris -- View this message in context: http://www.nabble.com/memory-mapped-tar-file-contents-tp20473925p20473925.html Sent from the Python - python-list mailing list archive at Nabble.com. From thomas at mlynarczyk-webdesign.de Tue Nov 18 18:14:14 2008 From: thomas at mlynarczyk-webdesign.de (Thomas Mlynarczyk) Date: Wed, 19 Nov 2008 00:14:14 +0100 Subject: Generators and their next() and send() methods In-Reply-To: References: Message-ID: alex23 schrieb: > http://www.python.org/dev/peps/pep-0342/ > That links to the original proposal to extend the generator behaviour After some searching, I found this as a remark in parentheses: "Introducing a new method instead of overloading next() minimizes overhead for simple next() calls." And also a (little) more detailed explanation. So, basically, allowing an argument for next() would have meant more overhead in the Python implementation. Still, I don't quite see why, as this could be detected at compile time, couldn't it? On the other hand, if I understood correctly, I can use send(None) as an equivalent of next(). So, while I cannot have next(argument) instead of send(argument), I can have send(None) instead of next(). > At a guess, I'd expect a new method was chosen to provide semantic > distinctness with the original behaviour. But the semantics would not have changed, they would only be "extended" and thus remain "compatible", wouldn't they? Greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux ? avoir tort qu'ils ont raison! (Coluche) From clp at rebertia.com Fri Nov 14 19:01:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 14 Nov 2008 16:01:28 -0800 Subject: Unsubscriptable object when using Exec In-Reply-To: References: Message-ID: <47c890dc0811141601q4c3babc8gd27d4567112bf16d@mail.gmail.com> On Fri, Nov 14, 2008 at 10:40 AM, Indian wrote: > Hi Friends > > I'm getting the TypeError Unsubscriptable object when using Exec in a class > > Here's the example > > class Fake(object): > def __init__(self, reg): > self._reg = reg > > def OpenKey(self, rootkey, path): > open_key = self._reg > path_string='[\'HKLM\']' > for key in path.split('\\'): > path_string += '[\'%s\']'%key > a='d=open_key%s'%path_string > exec(a) > return d > > When i create a claassobject and call the method Openkey i get the above > error but it works fine in the below example without class > > def OpenKey(rootkey, path, reg): > open_key = reg > path_string='[\'HKLM\']' > for key in path.split('\\'): > path_string += '[\'%s\']'%key > a='d=open_key%s'%path_string > print a > exec(a) > return d You don't need and shouldn't be using `exec` here. It appears as though you're just doing the following in a much more obtuse and unnecessarily complicated manner: def OpenKey(rootkey, path, reg): open_key = reg['HKLM'] for key in path.split('\\'): open_key = open_key[key] return open_key Lesson: Don't use `exec`. More importantly, what led you to think you needed to use it here in the first place? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > What am i doing wrong in the class?Any thought on this would be helpful :) > > Thanks in Advance > > -- > http://mail.python.org/mailman/listinfo/python-list > From peter.sabaini at gmail.com Tue Nov 25 11:05:34 2008 From: peter.sabaini at gmail.com (peter) Date: Tue, 25 Nov 2008 08:05:34 -0800 (PST) Subject: end of print = lower productivity ? References: Message-ID: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> On Nov 25, 4:44?pm, cptnwill... at gmail.com wrote: > I want my productivity back. > > In Python 2.x, I could easily write things like -- print "f" / print > "add" / print "done" -- to a lot of different places in my code, which > allowed me to find bugs that I could not track otherwise. When I found > out that "f" was not at fault, I could write -- print "g" -- to some > other place... etc, so that a significant part of the time spent > debugging was actually used to write print statements. > > Now the print statement disappeared, and I have to write print("f") > instead. These parentheses not only take time to write, they also make > me think twice about using print for debugging purposes. Pressing < > SHIFT > then < ( > then < " > makes the whole process quite a hassle. > > I agree with most of the arguments that have been made against using > the print statement to build code, but I did care about the efficient > debugging tool it was. BUT you now can do >>> p = print >>> p("f") Voila, 4 keystrokes saved :-) From elbertlev at hotmail.com Sun Nov 30 23:23:21 2008 From: elbertlev at hotmail.com (Lev Elbert) Date: Sun, 30 Nov 2008 20:23:21 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: Message-ID: <1ded1134-4933-4e05-953d-f93ac27c17e8@x16g2000prn.googlegroups.com> If Python for Windows you can use Py2Exe package. It works very well in simple cases and requires a few tweaks to make it recognize some dependencies. From javed044 at gmail.com Mon Nov 10 22:34:42 2008 From: javed044 at gmail.com (javed044) Date: Mon, 10 Nov 2008 19:34:42 -0800 (PST) Subject: hello Message-ID: THIS IS MY NEW BLOG. BLOG TYPE COOL WALLPAPERS AND PICTURE. PLEASE VISIT MY BLOG THANK YOU. http://picturewallpapers.blogspot.com/ From google at mrabarnett.plus.com Thu Nov 27 09:21:30 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 27 Nov 2008 14:21:30 +0000 Subject: special editor support for indentation needed. In-Reply-To: <492E3C22.10401@harvee.org> References: <491DD44F.8010208@harvee.org> <7bce0749-a13e-4100-8b6c-dc1dd6134690@h23g2000prf.googlegroups.com> <47fe3a4f-0905-42c5-a358-ba82855fdc6c@e38g2000prn.googlegroups.com> <6a0c30ed-f3e3-45ec-9186-9fa8df56111a@e38g2000prn.googlegroups.com> <090e20b8-2a6e-41bc-a8c4-cfb802898f2b@40g2000prx.googlegroups.com> <12cbbbfc0811162315n6133da6ct19b69508034b6fe2@mail.gmail.com> <49217F09.3060309@harvee.org> <49227217.1090200@online.de> <49232312.1080500@harvee.org> <4926FBAA.2090605@online.de> <492E3C22.10401@harvee.org> Message-ID: <492EACEA.100@mrabarnett.plus.com> Eric S. Johansson wrote: > Andreas Roehler wrote: >> with python-mode.el from >> >> http://sourceforge.net/projects/python-mode/ > > I think there's something wrong with the site because it tells me it's version > 1.0 from year 2005. > >> Meanwhile I'll reflect a draft addressing your needs. > > there is a rather sizable set of things that could be added to assist speech > during programming. I'm mostly concerned about the editing aspect of speech > driven programming. > >> BTW, what about this stuff?: >> >> http://www.cb1.com/~john/computing/emacs/handsfree/index.html > > it's interesting but most of it is very low level user interface orientation. > Lo level stuff is relatively easy to implement. High-level stuff is much more > difficult than the equivalent GUI abstraction. > > a narrow channel interface stuff is very interesting especially if you take > full advantage of the concept. With regards to programming, a narrow channel > interface would let you choose a relatively low number of "big" items in the > field of vision and then let you continue to narrow until you can easily operate > on the item of interest. > That reminds me of the text editor "sam": http://doc.cat-v.org/plan_9/4th_edition/papers/sam/ Worth a read. From see.signature at no.spam Thu Nov 27 11:43:28 2008 From: see.signature at no.spam (Eric Brunel) Date: Thu, 27 Nov 2008 17:43:28 +0100 Subject: Tkinter and asyncronous socket References: <0810698f-e4b2-4a6c-9434-4abe285f9e24@n10g2000yqm.googlegroups.com> <19334165-eea8-4514-8feb-2183a61d1c47@3g2000yqs.googlegroups.com> Message-ID: On Fri, 28 Nov 2008 04:20:22 +0100, Hendrik van Rooyen wrote: > If you are not already doing it, you need to make a "stutter thread" > by using the after() call on some gui object to periodically check for > input on the queue. You don't need to in fact: from the secondary thread, it seems to be safe to post a user-defined event in the GUI event loop on which you can set a binding in the GUI thread. This allows a thread switch without having to do a periodical check. Here is an example: ------------------------------------ import time from threading import Thread from Tkinter import * root = Tk() v = IntVar() v.set(0) Label(root, width=8, textvariable=v).pack() def incr_counter(event=None): v.set(v.get() + 1) root.bind('<>', incr_counter) def heartbeat(): while 1: time.sleep(1) root.event_generate('<>', when='tail') th = Thread(None, heartbeat) th.setDaemon(True) th.start() root.mainloop() ------------------------------------ The custom event '<>' is posted in the event loop from the secondary thread. Note the when='tail' option, which is absolutely necessary or the binding might be called immediatly without even an actual event posting. The binding on this event will then be executed in the thread that launched the mainloop. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From martin at v.loewis.de Sat Nov 8 07:39:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Nov 2008 13:39:52 +0100 Subject: best way to accelerate xmlrpc? In-Reply-To: References: Message-ID: <49158898$0$11537$9b622d9e@news.freenet.de> > I've got some python xmlrpc servers and clients. > What's the best way to accelerate them? You mean, fastest? > xmlrpclib.py attempts to import these modules: > > import _xmlrpclib > import sgmlop > from xml.parsers import expat > > and falls back to defining the SlowParser class. Why does it fall back on your system? It should definitely find expat - that is included with the Python distribution. > So, which of these modules is the preferred one to build > for python 2.5? for python 2.6? sgmlop is faster than expat. _xmlrpclib apparently is no longer available. Regards, Martin From bearophileHUGS at lycos.com Mon Nov 3 10:10:57 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 3 Nov 2008 07:10:57 -0800 (PST) Subject: length of a tuple or a list containing only one element References: <6bd670f7-89cd-4e27-80de-f82646a1658c@r37g2000prr.googlegroups.com> Message-ID: <79375523-8279-489f-a4df-d272ec6cd20c@q26g2000prq.googlegroups.com> Steve Holden: > While this kind of beginner > mistake is common it isn't one that's frequently repeated once the > learner understands the syntax. You may be right, but I don't have to like it. When you teach programming to people that have never done it before, and you use Python, they spot similar inconsistences in the blink of an eye and often look annoyed. They want a clean language, so you have to explain them the difference between a practical engineering system (like Python/Scheme or on the opposite C++) and an abstract system that you can use to reason (like some parts of mathematics they know). The good thing is that Python3 fixes some of those things :-) Bye, bearophile From steve at holdenweb.com Wed Nov 5 15:43:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Nov 2008 15:43:14 -0500 Subject: Dictionary membership check failure In-Reply-To: <333edbe80811051134w1306ccc5s3242a4b1cd53dc7c@mail.gmail.com> References: <333edbe80811051134w1306ccc5s3242a4b1cd53dc7c@mail.gmail.com> Message-ID: Zac Burns wrote: > Greetings, > > I have a dictionary that seems to be misbehaving on a membership > check. This test code: > > 1: import types > 2: assert myDict.__class__ is types.DictionaryType [...] For the record, it would be much simpler and more readable to say assert type(myDict) is dict not to mention it avoids the unnecessary import. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From newptcai at gmail.com Mon Nov 3 09:21:48 2008 From: newptcai at gmail.com (=?GB2312?B?0rvK18qr?=) Date: Mon, 3 Nov 2008 06:21:48 -0800 (PST) Subject: Efficient way to remove objects from a list References: Message-ID: <8209d5af-2e22-489d-803e-950e5f4afd3e@u18g2000pro.googlegroups.com> Thanks! That's a more clear way! On Nov 3, 9:38 pm, Peter Otten <__pete... at web.de> wrote: > Chris Rebert wrote: > > On Mon, Nov 3, 2008 at 1:40 AM, ??? wrote: > >> Hi all, > > >> Today I wrote some code like this: > > > Build a new list as you go, then overwrite the old list with it. > > > unfinished = [] > > >> for m in self.messages: > >> if not m.finished: > > unfinished.append(m) > >> continue > > >> #process the message > > > Remove the following code > > >> fini = [m for m in self.messages if m.finished] > >> for m in fini: > >> self.messages.remove(m) > > > self.messages[:] = unfinished > > Just > > self.messages = unfinished > > if also OK unless you have multiple references to the self.messages list. > > > This way you aren't calling .remove() multiple times and only iterate > > through the list once. > > From gagsl-py2 at yahoo.com.ar Mon Nov 17 16:55:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Nov 2008 19:55:40 -0200 Subject: Pythonwin not loading DLL, should I change extensions by .pyo or pyd? References: <11ff6c49-7205-42f6-a1eb-ce01d8f28a38@o40g2000prn.googlegroups.com> Message-ID: En Mon, 17 Nov 2008 13:01:11 -0200, Pekeika escribi?: > Python 2.5 doesn't support/load .dll anymore. Is PythonWin 2.5 the > same case? > > If a .DLL file is not loading, should I change its extension for it to > work? > What extensions should be now, .pyo, .pyd, etc? which one? > What is the meaning of each extension? Python supports being extended using "extension modules"; on Windows they are dynamic libraries (DLL). Before 2.5, the extensions ".dll" and ".pyd" were both valid; starting with 2.5, only files ending in ".pyd" are recognized. Note that this applies to extension modules *only*, not generic DLLs. All binary packages targeted to 2.5 use the right name for their extension modules, at least all that I know of. You don't have to rename anything. A .pyo file is a totally different thing; it's a compiled Python source (like a .pyc) but with optimization turned on. -- Gabriel Genellina From steve at holdenweb.com Thu Nov 13 14:45:19 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Nov 2008 14:45:19 -0500 Subject: using "private" parameters as static storage? In-Reply-To: References: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> Message-ID: Steve Holden wrote: > Joe Strout wrote: >> One thing I miss as I move from REALbasic to Python is the ability to >> have static storage within a method -- i.e. storage that is persistent >> between calls, but not visible outside the method. I frequently use >> this for such things as caching, or for keeping track of how many >> objects a factory function has created, and so on. >> [...] > I think you'd be much better off creating an instance of a class and > using that. > Or, as JP suggested, a generator function. This allows you to maintain whatever state you need in the function's local namespace. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From saju.pillai at gmail.com Tue Nov 4 00:58:49 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Mon, 3 Nov 2008 21:58:49 -0800 (PST) Subject: redirection in a file with os.system References: Message-ID: <80b72b3b-41e9-4bc3-8b13-9a92e6dca346@r37g2000prr.googlegroups.com> On Nov 4, 12:06?am, TP wrote: > Hi everybody, > > The following code does not redirect the output of os.system("ls") in a > file: > > import sys, os > saveout = sys.stdout > fd = open( 'toto', 'w' ) > sys.stdout = fd > os.system( "ls" ) > sys.stdout = saveout > fd.close() os.system() will call the libc system() which should fork() and exec() the '/bin/sh' shell with your command. The shell will inherit python's file descriptors. sys.stdout is a python level object, not a process level descriptor. By swapping sys.stdout with another file object you have only changed a python level file object. In the second snippet you have correctly updated the underlying process level descriptors. I imagine a "print" statement just after the "sys.stdout = fd" will not go to your stdout but the 'toto' file. -srp > > Whereas the following works: > > old_stdout = os.dup( sys.stdout.fileno() ) > fd = os.open( 'bar', os.O_CREAT | os.O_WRONLY ) > os.dup2( fd, sys.stdout.fileno() ) > os.system( "ls" ) > os.close( fd ) > os.dup2( old_stdout, sys.stdout.fileno() ) > > Why? > > I have another question: with this last code using os.open, the problem is > that the file 'bar' is not removed before being written. So, it could lead > to errors: the file 'bar' is overwritten, but extra lines from previous > executions could remain. > Am I compelled to use os.unlink (or os.remove) before calling > os.system("ls")? > > Thanks > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) From clp at rebertia.com Wed Nov 26 13:09:18 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 26 Nov 2008 10:09:18 -0800 Subject: best IDE In-Reply-To: <42460837-ef14-4c0c-9d14-dbd8a3082511@l33g2000pri.googlegroups.com> References: <42460837-ef14-4c0c-9d14-dbd8a3082511@l33g2000pri.googlegroups.com> Message-ID: <47c890dc0811261009q5d5f44et93ae5bfc065e783d@mail.gmail.com> On Wed, Nov 26, 2008 at 9:59 AM, asit wrote: > Which one is the best IDE for python ???? This was recently discussed. To avoid needlessly rehashing said discussion, see the thread at http://groups.google.com/group/comp.lang.python/browse_thread/thread/7fd136aef1c63e47/fbaff90068f0fe02 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From paul.nospam at rudin.co.uk Mon Nov 10 05:22:03 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 10 Nov 2008 10:22:03 +0000 Subject: Python COM: Automatic wrap/unwrap? References: <6nkgo1Flqh3hU1@mid.individual.net> <4918075E.1070006@cosc.canterbury.ac.nz> Message-ID: <8763mv7ues.fsf@rudin.co.uk> Tim Golden writes: > greg wrote: >> Larry Bates wrote: >> >>> You should post this on comp.python.windows as Mark and the other >>> Windows/COM gurus hang around there a lot. >> >> I can't find any such newsgroup -- are you sure >> that's what it's called? > > I think that's what it's called on gmane (or some other > newsgroup gateway). On gmane it's gmane.comp.python.windows I think. From pavlovevidence at gmail.com Sat Nov 29 01:51:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Nov 2008 22:51:59 -0800 (PST) Subject: Creating classes and objects more than once? References: <5f3a7d84-d07e-417c-a228-e07bdf3b676b@v42g2000yqv.googlegroups.com> <5037872d-d2a3-4d70-be00-18fbf4279767@j35g2000yqh.googlegroups.com> <874p1syzxh.fsf@benfinney.id.au> <58cfdea8-f75f-43c4-bf60-a2dbb8ceed1d@g38g2000yqn.googlegroups.com> <87zljjy3c5.fsf@benfinney.id.au> <1e035b98-418f-4b7b-86f6-14fbfa5844b6@o2g2000yqd.googlegroups.com> Message-ID: <9e804f42-447a-489e-9e44-b2c81c01ddc9@g38g2000yqd.googlegroups.com> On Nov 28, 11:51?pm, Carl Banks > Absolute versus relative imports don't have anything to do with the > issue here. ?PEP 328 concerns itself with imports relative to the > executing module in package space. ?It has nothing to do with imports > relative to the current directory in filename space. I thought of another way to put this to help explain things. Suppose you have two files in your current directory, a Python script file (app.py) which imports a Python module (work.py). Near the top of the file app.py, there is line like this: import work What happens beneath the covers when this statement is excuted (and from __future__ import absolute_import hasn't been run)? Many people seem to think that the Python interpreter first considers whether this is a relative import and starts by looking for "sister" modules in the same "package" (i.e., directory). Python would thus see the file work.py in the same "package" and complete this as a relative import. Thus, they reason, if one were to add "from __future__ import absolute_import" to the top of app.py, the import would no longer work because implicit relative imports have been disabled. One would have to use "from . import work" instead. Well, this is not how it happens. No top level module, including __main__, is in a package. Thus, when Python sees "import work" in a top-level module, it doesn't consider it to be a relative import, even when implicit relative imports have not been disabled. The point of this is, disabling implicit relative imports has no effect on imports from top-level modules since they were never relative imports anyway. Python is able to find the "sisters" of top- level modules and scripts not because it is doing a relative import, but because those "sister" modules are in one of the directories listed in sys.path. In particular, if "" is listed in sys.path, the current working directory--even when modified by os.chdir--will be searched for "sisters" of top-level modules. Carl Banks From robert.kern at gmail.com Sat Nov 29 03:47:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 29 Nov 2008 02:47:32 -0600 Subject: Python docs and enumeration of sections In-Reply-To: <41d2b969-a1ab-4993-9c33-cc5cc3fd1de4@3g2000yqs.googlegroups.com> References: <41d2b969-a1ab-4993-9c33-cc5cc3fd1de4@3g2000yqs.googlegroups.com> Message-ID: Kay Schluehr wrote: > Is there a reason why enumeration of sections and subsections has been > dropped after the switch to the Sphinx documentation tool? > > It doesn't really make quoting library sections easier or do you know > what I mean when I refer to "How It Works"? If you hover the mouse over the area just to the right of a section title, you will see a paragraph mark which will be a link to the section. You can copy-and-paste that URL. The URL is more convenient answer than a section number. http://docs.python.org/library/pdb.html#how-it-works -- 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 drew at oakwoodft.com Fri Nov 28 13:29:29 2008 From: drew at oakwoodft.com (Drew Schaeffer) Date: Fri, 28 Nov 2008 13:29:29 -0500 Subject: filter func chaining Message-ID: <8C9135F99172334B9A23C78D460BBB9F011CD7BB30@exmb01.netplexity.local> I am trying to chain filter functions together so I created these 2 functions. def AndChain(*filters): return (lambda asset: reduce((lambda r, f: apply(f, asset) and r), filters)) def OrChain(*filters): return (lambda asset: reduce((lambda r, f: apply(f, asset) or r), filters)) Where filters are simply functions that take a single argument and return true or false. My intention is to use these functions like this: f = AndChain(AssetTypeFilter(), CurrencyFilter()) filteredCol = filter(f, col) I am receiving the following error (where Asset is the type of items in my collection) Traceback (most recent call last): File , line 0, in ##44 File c:\proj\ofts\com.oakwoodft.ofts.compliance\complianceframework\filters\assetfilters.py, line 5, in is not enumerable Am I going about this totally wrong? Is there a better solution? Thanks. Drew Schaeffer -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafesacks at gmail.com Tue Nov 25 06:12:18 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 25 Nov 2008 03:12:18 -0800 (PST) Subject: Getting in to metaprogramming References: <6cd0d1c2-90ed-4dad-94bf-3e98ddf89118@o40g2000prn.googlegroups.com> <842a1a1d-42bd-440d-b4b5-57170adb2f37@l42g2000yqe.googlegroups.com> Message-ID: <7832d70e-7bb9-469d-9edd-0864c3bb357d@b38g2000prf.googlegroups.com> On Nov 25, 5:41?pm, Aaron Brady wrote: > On Nov 25, 4:08?am, Rafe wrote: > > > Hi, > > > In the name of self-education can anyone share some pointers, links, > > modules, etc that I might use to begin learning how to do some > > "metaprogramming". That is, using code to write code (right?) > > > Cheers, > > > - Rafe > > Python programs can generate code for themselves. > > >>> for i in range( 10 ): > > ... ? d= { 'cls': i } > ... ? s=""" > ... class Cls%(cls)s: > ... ? def meth%(cls)s( self, arg ): > ... ? ? print 'in meth%(cls)s, arg:', arg > ... """% d > ... ? exec( s ) > ... ? s= """ > ... inst%(cls)s= Cls%(cls)s() > ... """% d > ... ? exec( s ) > ...>>> inst0.meth0( "arg" ) > in meth0, arg: arg > >>> inst1.meth1( "arg" ) > in meth1, arg: arg > >>> inst2.meth2( "arg" ) > > in meth2, arg: arg > > The 'Cls0', 'Cls1', 'Cls2' repetitiveness is taken care of with a for- > loop. Michele, I am thinking about python which writes python. Which makes Aaron's post accurate to my needs. More specifically, I am considering what it might be like to use python to build a script file which can be executed later. Until now I planned to store info to XML and then parse it to run later. There are good reasons that generating a script file would be more useful for me. Aaron, Is it really as simple as gathering strings of code? Sort of like generating HTML or XML directly? Is there any other framework or pattern set that is worth looking in to? Thanks for helping me explore this. - Rafe From matteodellamico at gmail.com Thu Nov 27 04:22:47 2008 From: matteodellamico at gmail.com (della) Date: Thu, 27 Nov 2008 01:22:47 -0800 (PST) Subject: Loading multiple versions of the same package at the same time Message-ID: Hi all, I've got some pickled files representing graphs (using networkx, http://networkx.lanl.gov if you're interested) that were produced using version 0.36 of the library. Now, they have released a new version of the library which is incompatible with respect to pickled files, so what I'd like to do is to write a script that loads the two versions of the library at once, unpickles with the old one, creates a new object with the new version and re-pickles it with the new version. So, I installed the two versions of the package using easy_install -m, but it looks like I can't import the two versions at once: >>> from pkg_resources import require >>> require('networkx==0.36') [networkx 0.36 (/usr/lib/python2.5/site-packages/networkx-0.36- py2.5.egg)] >>> import networkx as nx_old >>> require('networkx==1.0') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 528, in resolve raise VersionConflict(dist,req) # XXX put more info here pkg_resources.VersionConflict: (networkx 0.36 (/usr/lib/python2.5/site- packages/networkx-0.36-py2.5.egg), Requirement.parse('networkx==1.0')) Any ideas? Thanks a lot matteo From callen314 at gmail.com Mon Nov 3 17:20:18 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 3 Nov 2008 14:20:18 -0800 (PST) Subject: Structures References: <87zlkhm1l4.fsf@benfinney.id.au> Message-ID: <50f41188-766d-4be4-9c92-d536a43bb1a3@g17g2000prg.googlegroups.com> > > Care to say more about what they are, not what they're like? > I'm not the OP and I may be biased by C++, I can imagine the complaints when I say, classes are just structures with function members for working on the structure. From exarkun at divmod.com Thu Nov 13 12:19:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 13 Nov 2008 12:19:53 -0500 Subject: Text based screens without ncurses In-Reply-To: <20081113201658.c02c38ec.miratcanbayrak@gmail.com> Message-ID: <20081113171953.20272.652403758.divmod.quotient.4704@ohm> On Thu, 13 Nov 2008 20:16:58 +0200, Mirat Can Bayrak wrote: >On Thu, 13 Nov 2008 12:14:10 -0500 >Jean-Paul Calderone wrote: > >> Why don't you want to use one of these libraries for doing the thing that >> you want to do? > >mmm lets say i want to improve myself with building a curses like module. :) Okay. Then I'd suggest reading the source to the curses module or one of the modules like it in order to learn how to do what it does. In addition to learning how to manipulate terminals like curses does, this will also help you improve at the important skill of reading existing code. Jean-Paul From massi_srb at msn.com Mon Nov 17 10:53:24 2008 From: massi_srb at msn.com (Massi) Date: Mon, 17 Nov 2008 07:53:24 -0800 (PST) Subject: Installing Python2.6 on Mac Os (Leopard) Message-ID: <1a56188f-319a-4937-93ff-8a23004b92f7@k1g2000prb.googlegroups.com> Hi everyone, I'm trying to install Python2.6 on my mac (Leopard 10.5.5), but I'm encountering some problems. To install the package I followed the instructions I found at this link: http://wiki.python.org/moin/MacPython/Leopard If I open wing, it turns out that the installed version is actually 2.6, but if i run python from terminal it displays version 2.5.1, that is the default version for leopard. Furthermore I can't launch idle. I'm pretty new to mac os environment so forgive me if my questions are silly. Any hint? From arnodel at googlemail.com Sun Nov 9 14:39:25 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Nov 2008 19:39:25 +0000 Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <01267674$0$20668$c3e8da3@news.astraweb.com> <49172C07.3050003@v.loewis.de> <491738eb$0$2483$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: >> Even in 2.x it doesn't work (I think I posted this earlier but I'm not >> sure anymore) as this example shows: >> >> 2 < 3j and 3j < True, but True < 2 > > What specific value of x have you been trying? For x=4,5,6, I get > > py> 2 < 3j and 3j < True > Traceback (most recent call last): > File "", line 1, in ? > TypeError: no ordering relation is defined for complex numbers > > Regards, > Martin My example was using the comp function defined by Kay: >> def comp(x1, x2): >> try: >> if x1> return -1 >> else: >> return 1 >> except TypeError: >> if str(x1)> return -1 >> else: >> return 1 It just shows that it doesn't define an order for builtin types. -- Arnaud From clp at rebertia.com Sat Nov 15 23:54:05 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 15 Nov 2008 20:54:05 -0800 Subject: Need help in understanding a python code In-Reply-To: <46f2ec46-8589-4176-87c0-1c7547d19ac4@z6g2000pre.googlegroups.com> References: <46f2ec46-8589-4176-87c0-1c7547d19ac4@z6g2000pre.googlegroups.com> Message-ID: <47c890dc0811152054q1187f128i4784c72197219f51@mail.gmail.com> On Sat, Nov 15, 2008 at 8:41 PM, silverburgh.meryl at gmail.com wrote: > Hi, > > I am trying to understand the following line: > # a is an integer array > > max([(sum(a[j:i]), (j,i)) This code isn't valid. You have a [ with no closing ]. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Can you please tell me what that means, > I think sum(a[j:i] means find the some from a[j] to a[i] > But what is the meaning of the part (j,i)? > > -- > http://mail.python.org/mailman/listinfo/python-list > From rupole at hotmail.com Fri Nov 7 12:58:54 2008 From: rupole at hotmail.com (Roger Upole) Date: Fri, 7 Nov 2008 12:58:54 -0500 Subject: Trying to set a date field in a access databse References: <12d9f626-9e5c-484a-94e4-120122a41214@40g2000prx.googlegroups.com> Message-ID: You should be able to pass a PyTime or datetime.datetime object. Roger wrote in message news:12d9f626-9e5c-484a-94e4-120122a41214 at 40g2000prx.googlegroups.com... > Hi, > I cannot get the following code to work > > import win32com.client > import time > > engine = win32com.client.Dispatch("DAO.DBEngine.36") > db=engine.OpenDatabase(r"testdate2.mdb") > access = db.OpenRecordset("select * from test") > > access.AddNew() > access.Fields("test").value=time.strptime('10:00AM', '%I:%M%p') > access.Update() > > wherer test is a datetime field, > How can I do this??????? > -Ted > > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at googlemail.com Mon Nov 17 14:10:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 17 Nov 2008 19:10:03 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: jzakiya writes: > I looked online and in books, but couldn't find a definitive answer to > this. > > I have an array and set multiple elements to either True or False at > one time. > > Question: Which way is faster (or does it matter)? > > 1) > > array[x1]=array[x2]=........= array[x10] = \ > array[x11]=array[x12]=... = array[x20] = \ > ...... > ...... > array[x40]=array[x41]=....= array[x50] = False (or True) > > > 2) > > array[x1]=array[x2]=........= array[x10] = False > array[x11]=array[x12]=... = array[x20] = False > ...... > ...... > array[x40]=array[x41]=....= array[x50] = False It doesn't matter as none of this is valid Python. In Python you have to write array[x1] = False array[x2] = False Etc... -- Arnaud From martin at v.loewis.de Wed Nov 12 16:50:51 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 12 Nov 2008 22:50:51 +0100 Subject: [Python-Dev] Python 2.5.3: call for patches In-Reply-To: <491A8637.8000602@ubuntu.com> References: <48EB0F5C.602@v.loewis.de> <4919A346.60507@ubuntu.com> <4919DF15.2090406@v.loewis.de> <491A8637.8000602@ubuntu.com> Message-ID: <491B4FBB.4080306@v.loewis.de> >> In principle, this is fine with me, so go ahead. > > Done. Thanks for looking into these! Martin From dfnsonfsduifb at gmx.de Thu Nov 20 18:44:09 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 21 Nov 2008 00:44:09 +0100 Subject: Python 3 __cmp__ semantic change? In-Reply-To: References: <642a426a-74f4-460c-a274-8dc78c3c8611@d42g2000prb.googlegroups.com> <87bpwa59ap.fsf@benfinney.id.au> Message-ID: <9b9hv5x3fj.ln2@joeserver.homelan.net> Steve Holden schrieb: > If it's not present then it would be worth reporting it as a 3.0 bug - > there's still time to get it in, as the release isn't due until early > December. Seems it was removed on purpose - I'm sure there was a good reason for that, but may I ask why? Instead of the sleek __cmp__ function I had earlier, I now have code like: def __lt__(self, other): return self.__cmp__(other) < 0 def __le__(self, other): return self.__cmp__(other) < 0 def __gt__(self, other): return self.__cmp__(other) > 0 def __ge__(self, other): return self.__cmp__(other) >= 0 Does anyone know the reason why __cmp__ was discarded? Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From steve at holdenweb.com Thu Nov 20 15:21:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Nov 2008 15:21:22 -0500 Subject: Fwd: Problem with writing a long line in a text file In-Reply-To: <460597290811201152g2c7c6179s1496f51f9b5987c0@mail.gmail.com> References: <460597290811191427q463cf79dk684906e70889dbae@mail.gmail.com> <460597290811201152g2c7c6179s1496f51f9b5987c0@mail.gmail.com> Message-ID: Mohsen Akbari wrote: > Dear guys, > > I'm a newbie in python and I have this problem with the code that I'm > writing. There is a very long line which I wish to output it to a text > file.But when I do this, in the output file, the result appears in two > lines. I thought maybe that's because the maximum possible length of the > text file has been reached so I opened the file and I tried to put some > space at the end of the first line. It wasn't possible to do that for > the first line and the space was placed before the first character of > the second line. I kept pressing space bar to add more spaces and so the > whole second line was moved to the write till it exceeded the first > line. I mean the length of the second line became longer than the first > line which means the text file can accept longer lines. > As a second guess, I thought maybe I had '\n' somewhere in my input > string so I tried to check that by doing: > temp_ = out_string.find('\n') > print temp_ > > The result was -1 which I think means there is not '\n' in my output > string. Now I'm really confused and I don't know what to do. I really > appreciate it if somebody can help me out. > > BTW, I'm using windows. > Then, later: > --- I use notepad to view my txt file. It appears that way in this tool. > --- Here is the output of the debug lines that you mentioned: > print *line*.find('\n') > -1 > > print len(*line*) > 1528 > > print repr(line) > '0.0\t3.0\t10.0\t24.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t33.0\t40.0\t40.0\t40.0\t40.0\t32.0\t30.0\t32.0\t26.0\t23.0\t30.0\t32.0\t40.0\t40.0\t40.0\t40.0\t40.0\t40.0\t38.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t24.0\t10.0\t11.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t18.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t17.0\t20.0\t23.0\t30.0\t30.0\t30.0\t27.0\t20.0\t20.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t30.0\t23.0\t20.0\t20.0\t20.0\t20.0\t10.0\t10.0\t14.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t27.0\t30.0\t30.0\t27.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t19.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t12.0\t10.0\t13.0\t13.0\t10.0\t2.0\t0.0\t3.0\t5.0\t10.0\t5.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t5.0\t0.0\t2.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t10.0\t16.0\t20 .0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t10.0\t18.0\t20.0\t20.0\t20.0\t20.0\t20.0\t20.0\t27.0\t30.0\t30.0\t35.0\t40.0\t40.0\t31.0\t20.0\t20.0\t21.0\t30.0\t33.0\t46.0\t50.0\t50.0\t50.0\t48.0\t40.0\t43.0\t50.0\t50.0\t50.0\t56.0\t60.0\t60.0\t60.0\t61.0\t70.0\t70.0\t70.0\t70.0\t75.0\t80.0\t83.0\t90.0\t90.0\t92.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t93.0\t86.0\t80.0\t91.0\t100.0\t100.0\t100.0\t100.0\t98.0\t90.0\t90.0\t90.0\t94.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t100.0\t90.0\t83.0\t87.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t90.0\t' > > thanks > Mohsen > > > There is only one line in your file. Notepad just can't display lines beyond a certain length, is all, so it inserts a line break in the window (but not in the file). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From marduk at letterboxes.org Wed Nov 26 14:21:44 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 26 Nov 2008 14:21:44 -0500 Subject: newbie question In-Reply-To: References: Message-ID: <1227727304.5090.6.camel@brotherus.rdu.redhat.com> On Wed, 2008-11-26 at 11:11 -0800, Nan wrote: > Hello, > I just started to use Python. I wrote the following code and > expected 'main' would be called. > > def main(): > print "hello" > > main > > But I was wrong. I have to use 'main()' to invoke main. The python > interpreter does not give any warnings for the above code. Is there > any way/tool to easily detect this kind of errors ? > Syntactically your code is correct, so the interpreter just goes about its business. You can usually use tools such as pylint or pychecker to find find such issues. For example, pylint reports (among other things): W: 4: Statement seems to have no effect From arnodel at googlemail.com Tue Nov 18 16:01:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Nov 2008 21:01:41 +0000 Subject: sorting list of complex numbers References: <7x1vx9wc21.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > for fancier structures you'd need a full blown class implementation > with an init method. Either way you end up temporarily allocating a > lot of extra structures, but at least they're not all in memory > simultaneously like in the DSU pattern. The implementation of python sort uses the DSU patterns. -- Arnaud From icepic1984 at gmx.de Thu Nov 20 10:42:43 2008 From: icepic1984 at gmx.de (Kevin Osthof) Date: Thu, 20 Nov 2008 16:42:43 +0100 Subject: Hooking windowsmessages with python In-Reply-To: <493c2800-5b15-46df-9caa-1ed3f564f7bc@j35g2000yqh.googlegroups.com> References: <493c2800-5b15-46df-9caa-1ed3f564f7bc@j35g2000yqh.googlegroups.com> Message-ID: <49258573$0$31342$9b4e6d93@newsspool4.arcor-online.net> Aaron Brady wrote: > I've done some hooks in C. If no one has a simpler way, I can help > you build a DLL to do it, and call it from Python. Thx for the offer but i will try to do it in python first. ;) From martin at v.loewis.de Fri Nov 21 15:50:06 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Nov 2008 21:50:06 +0100 Subject: Building Python 2.5.2 for Itanium In-Reply-To: <1cb97ff4-9ba3-4ee2-a3fc-3af052fc4eab@u14g2000yqg.googlegroups.com> References: <1cb97ff4-9ba3-4ee2-a3fc-3af052fc4eab@u14g2000yqg.googlegroups.com> Message-ID: <49271eff$0$11541$9b622d9e@news.freenet.de> > I need to compile that module for that release and platform, but I > have been unable to discover which MS compiler version and runtime was > used to generate the binaries. My understanding is that Python 2.5.2 > in general uses Visual Studio 2003, but MS does not appear to have > shipped an Itanium compiler with that version of VS. That's correct. See PCbuild/readme.txt for (somewhat) detailed instructions; in essence, you need to use vsextcomp, if you want to use the official build process. > I know that there is an Itanium compiler in VS2K5 Team System, and > also a pre-release version was shipped with the Windows 2003 SP1 > Platform SDK. I don't think that is a pre-release. The SDK had been shipping with an Itanium compiler for quite some time, and it is the official compiler to build binaries for Win64/IA-64 (to my knowledge, it is the compiler that Windows itself was built with). > However, the compiler in the SDK appears to basically > be an earlier version of the VS2K5 compiler. That might be. The more critical issue is what CRT to link with. I had been building the Python Itanium binaries always with the SDK compiler (of different SDKs, actually); the SDK then would always link with msvcrt.dll. If you use VS2K5, you might end up linking with a different CRT, which would be bad. > When I run setup.py build, the distutils die b/c it is apparently > not the right compiler version. Correct. distutils is not used for building on Windows. Wrt. the original issue: I am quite skeptical that you can make ctypes work on Win64/IA-64. There is are several reasons why it wasn't build, such as it doesn't compile, and, if it would compile, it wouldn't work. So prepare to do some porting of libffi. Alternatively, rewrite the code that requires ctypes to use a plain extension module, which is probably easier to port to Itanium. Regards, Martin From python at bdurham.com Mon Nov 24 08:23:11 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 24 Nov 2008 08:23:11 -0500 Subject: Estimating size of dictionary In-Reply-To: References: <069b036d-b112-4cf9-a80d-d21713acf400@l33g2000pri.googlegroups.com> <6oodhlF4h6kuU1@mid.uni-berlin.de> <03ec4598-2e35-474e-a60d-28502e61b239@e1g2000pra.googlegroups.com> Message-ID: <1227532991.14167.1286453109@webmail.messagingengine.com> Steven, Wonderful! You and your references answered all my questions. I had missed 2.6's new getsizeof() function. Yet another reason to do the 2.5-to-2.6 upgrade. Regards, Malcolm From thorsten at thorstenkampe.de Tue Nov 11 04:45:28 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 11 Nov 2008 10:45:28 +0100 Subject: Python 2.5 and sqlite References: <91bea00c-9ca1-45bb-980a-2a669139e182@n1g2000prb.googlegroups.com> Message-ID: * (Mon, 10 Nov 2008 18:48:28 -0500) > Quoting "timotoole at gmail.com" : > > On a (sun) webserver that I use, there is python 2.5.1 installed. I'd > > like to use sqlite3 with this, however sqlite3 is not installed on the > > webserver. If I were able to compile sqlite using a sun machine (I > > normally use linux machines) and place this in my lunix home account > > would I be able to use python and sqlite? > > > > Any thoughts? I know its a bit of a stretch ... > > Can you ask them if sqlite3 is installed? and if not... to install it? Why would he have to install SQLite?! > You could include in your discussions "well sqlite3 is part of python" > "if it isn't, you haven't installed python properly" Sqlite3 is an optional part of Python. It has no dependencies on SQLite. Thorsten From steve at REMOVE-THIS-cybersource.com.au Fri Nov 21 04:08:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Nov 2008 09:08:41 GMT Subject: How to read space separated file in python? References: Message-ID: <013672c2$0$20662$c3e8da3@news.astraweb.com> On Fri, 21 Nov 2008 14:16:13 +0530, ganesh gajre wrote: > Hi all, > > I want to read file which is mapping file. Used in to map character from > ttf to unicode. > eg > > Map file contain data in the following way: > > 0 ? > 1 ? > 2 ? > 3 ? > 4 ? > 5 ? > 6 ? > 7 ? > 8 ? > 9 ? > > Like this. Please use any unicode editor to view the text if it not > properly shown. > > Now i want to read both the character separately like: > > str[0]=0 and str2[0]=? > > How can i do this? > > please give me solution? Well, because you said please... I assume the encoding of the second column is utf-8. You need something like this: # Untested. column0 = [] column1 = [] for line in open('somefile', 'r'): a, b = line.split() column0.append(a) column1.append(b.decode('utf-8')) -- Steven From barry at python.org Fri Nov 21 10:06:44 2008 From: barry at python.org (Barry Warsaw) Date: Fri, 21 Nov 2008 10:06:44 -0500 Subject: RELEASED Python 3.0rc3 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 third and last planned release candidate for Python 3.0. This is a release candidate, so while it is not quite suitable for production environments, we strongly encourage you to download and test this release on your software. We expect only critical bugs to be fixed between now and the final release, currently planned for 03- Dec-2008. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org Please read the RELNOTES file in the distribution for important details about this release. For more information and downloadable distributions, see the Python 3.0 website: 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) iQCVAwUBSSbOhHEjvBPtnXfVAQLzBwP/dS2j4XhZMNdb28TG3ZblkSmlPS4IU20U Vvq85inUkJ6idwKZBqa6brrD1hbqrl4UjKZh4/ppzhIwsJtFMlMiqnkHVrvIYFBG Yg+pQdO5HQzrw9K04aTdtNiKTiiJNIkqWdQQUd573XBFODRAIaq0qwk9C24kXeZM e3xNgNRxfmY= =TvxY -----END PGP SIGNATURE----- From robin at reportlab.com Mon Nov 10 10:25:41 2008 From: robin at reportlab.com (Robin Becker) Date: Mon, 10 Nov 2008 15:25:41 +0000 Subject: Python 3.0 - is this true? In-Reply-To: <4917295A.4040907@v.loewis.de> References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <4917295A.4040907@v.loewis.de> Message-ID: <49185275.8060800@chamonix.reportlab.co.uk> Martin v. L?wis wrote: >> Sure: >> >> if len(L1) == len(L2): >> return sorted(L1) == sorted(L2) # check whether two lists contain >> the same elements >> else: >> return False >> >> It doesn't really matter here what the result of the sorts actually is >> as long as the algorithm leads to the same result for all permutations >> on L1 ( and L2 ). > > Unfortunately, for many releases, the list's sort algorithm would not > provide that property. Release for release, new cases where found where > the builtin ordering was not transitive (i.e. you get a < b and b < c, > but not a < c). With funny definitions of __cmp__ in some classes, you > can still get this today. ....... In old style python there was a sort of standard behaviour whereby None was comparable with most of the other primitive types. That at least allowed us to performs various stupid tricks with data. Unfortunately it seems that None is no longer orderable even against itself. Is there any advice on how to create N/A float or integer or string values? I assume the DB api will continue to return None for null columns no matter what the column type. Presumably I can always define my own comparator which makes None < x for all x!=None. -- Robin Becker From nick at craig-wood.com Wed Nov 26 08:30:40 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 26 Nov 2008 07:30:40 -0600 Subject: How to get a directory file descriptor? References: <04485416-5d03-476c-89de-089a4685f80c@i20g2000prf.googlegroups.com> <64acbb2a-7129-41ad-96cb-2d742525f43a@s1g2000prg.googlegroups.com> <6p44s0F68rlsU1@mid.individual.net> Message-ID: Cong Ma wrote: > Thanks for your reply. I checked my Python 2.5 install on Linux and there's the > O_DIRECTORY flag. However this is not mentioned anywhere in the Library Reference. > > There's another question regarding to this flag though: I checked the manual of > the Linux system call open(2), in which there's a paragraph on this flag: > > O_DIRECTORY > If pathname is not a directory, cause the open to fail. This > flag is Linux-specific, and was added in kernel version 2.1.126, > to avoid denial-of-service problems if opendir(3) is called on a > FIFO or tape device, but should not be used outside of the > implementation of opendir(3). That says avoid to me! > Note the "should not be used outside of the implementation of opendir(3)" part. > Does that mean using Python's os.open() with the O_DIRECTORY flag is a Bad > Thing? IMHO yes. > In C, I think, calling opendir() followed by dirfd() should be the > correct way of doing this? Here is how you do exactly that in python using ctypes from ctypes import CDLL, c_char_p, c_int, Structure, POINTER from ctypes.util import find_library class c_dir(Structure): """Opaque type for directory entries, corresponds to struct DIR""" c_dir_p = POINTER(c_dir) c_lib = CDLL(find_library("c")) opendir = c_lib.opendir opendir.argtypes = [c_char_p] opendir.restype = c_dir_p dirfd = c_lib.dirfd dirfd.argtypes = [c_dir_p] dirfd.restype = c_int closedir = c_lib.closedir closedir.argtypes = [c_dir_p] closedir.restype = c_int dir_p = opendir(".") print "dir_p = %r" % dir_p dir_fd = dirfd(dir_p) print "dir_fd = %r" % dir_fd print "closed (rc %r)" % closedir(dir_p) Which prints on my linux machine dir_p = dir_fd = 3 closed (rc 0) I don't know why os doesn't wrap - opendir, closedir, dirfd, readdir etc - I guess because except if you are doing something esoteric, then os.list and os.walk do everything you could possibly want. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bearophileHUGS at lycos.com Sun Nov 2 03:24:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 2 Nov 2008 01:24:37 -0700 (PDT) Subject: Fast list traversal References: Message-ID: dineshv: > What is the fastest way to traverse these long_list's sequentially > from the beginning to the end? ?Maybe there is another data structure > that can be used instead of a list. Psyco can help a lot in that kind of code. >The elements of long_list are immutable (ie. don't change).< A tuple too may be fit then, but probably it doesn't improve the situation. Bye, bearophile From iain.murchland at gmail.com Sun Nov 9 21:12:56 2008 From: iain.murchland at gmail.com (Iain) Date: Sun, 9 Nov 2008 18:12:56 -0800 (PST) Subject: creating a block file for file-like object References: <143829f3-da00-4804-a9d9-3362fcd3c9bc@d10g2000pra.googlegroups.com> Message-ID: <15d2b10c-0df8-4791-874c-339cc65a076c@v22g2000pro.googlegroups.com> On Nov 8, 10:00?am, Iain wrote: > On Nov 7, 4:42?pm, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > In message > > , Iain > > wrote: > > > > Can someone give me some pointers as to how I might create some sort > > > of blocking device file or named pipe ... > > > ? ? mkfifo /path/to/named/pipe > > Thanks. > > I did get that far myself with os.mkfifo - my problem is actually > using it. To me it seemed like I wanted to do something like > > streamobj = urllib.urlopen("http://whereever.com/file") > fifoobj = open("/path/to/named/pipe","w") > fifoobj.write(streamobj.read()) > TroublesomeFunction("/path/to/named/pipe") > > But as soon as you get to the second line the code hangs (apparently > because of the blocking behaviour of the named pipe). > > Any pointers here would be much appreciated. Well I did work out *a* solution this way: pipename = os.tmpnam() os.mkfifo(pipename) pid = os.fork() if pid==0: fifoobj = open(pipename,"w") fifoobj.write(streamobj.read()) fifoobj.close() os.unlink(pipename) else: TroublesomeFunction(pipename) I'd have to say it doesn't strike me as the BEST solution, but it works. In particular the use of os.tmpnam() gives a warning that its use is a potential security vulnerability, but this is inevitable if taking the named pipe approach (any other suggestions are most welcome, of course). And it doesn't fail very gracefully in that if TroublesomeFunction stops before attempting to open/read the pipe, then the child process stays hung waiting for the other end of the pipe to open. In an interactive python shell you also get some weird behaviour in this situation, but I'm not entirely sure what the exact cause of that is. From Gardner.Pomper at gmail.com Tue Nov 4 17:28:44 2008 From: Gardner.Pomper at gmail.com (gardnerpomper) Date: Tue, 4 Nov 2008 14:28:44 -0800 (PST) Subject: Distributed unit testing on condor? Message-ID: <8a0dc2ab-b12a-434f-bc96-d59cda8a964f@d10g2000pra.googlegroups.com> Hi, I have a system where I would like to run unittests over our condor distributed cluster. My thoughts have been to write tests which take a list of files, and distribute each file and that test out as a condor job. I have briefly looked at nose and its plugins to see if I could set something up like that, but it isn't clear. My goal is to make this as transparent for the developer as possible. I would like the programmer to just have to write a simple unittest function, which is unaware of condor, that he can run on his own system, but then also be able to run the tests across a larger data set on the condor cluster. Is anyone aware of a system set up to do this? If not, I am anxious to entertain ideas on the cleanest way of implementing it. Thanks, - Gardner From netimen at gmail.com Sat Nov 1 07:27:10 2008 From: netimen at gmail.com (netimen) Date: Sat, 1 Nov 2008 04:27:10 -0700 (PDT) Subject: brackets content regular expression References: <405e1745-2b3e-4ab7-812d-f9dbba2dad45@o40g2000prn.googlegroups.com> <461dc81d-e71f-4c72-ac5f-74afab74af28@o40g2000prn.googlegroups.com> <98f676be-437b-4c32-bca7-ecb32cb6852b@n33g2000pri.googlegroups.com> Message-ID: Yeah, I know it's quite simple to do manually. I was just interested if it could be done by regular expressions. Thank you anyway. On 1 ????, 00:36, Matimus wrote: > On Oct 31, 11:57?am, netimen wrote: > > > > > > > Thank's but if i have several top-level groups and want them match one > > by one: > > > text = "a < b < ? > d > here starts a new group: ?< e < f ?> g >" > > > I want to match first " b < ? > d " and then " e < f ?> g " but not " > > b < ? > d > here starts a new group: ?< e < f ?> g " > > On 31 ???, 20:53, Matimus wrote: > > > > On Oct 31, 10:25?am, netimen wrote: > > > > > I have a text containing brackets (or what is the correct term for > > > > '>'?). I'd like to match text in the uppermost level of brackets. > > > > > So, I have sth like: 'aaaa 123 < 1 aaa < t bbb < a ff > > 2 > > > > > bbbbb'. How to match text between the uppermost brackets ( 1 aaa < t > > > > bbb < a ff > > 2 )? > > > > > P.S. sorry for my english. > > > > I think most people call them "angle brackets". Anyway it should be > > > easy to just match the outer most brackets: > > > > >>> import re > > > >>> text = "aaaa 123 < 1 aaa < t bbb < a ff > > 2 >" > > > >>> r = re.compile("<(.+)>") > > > >>> m = r.search(text) > > > >>> m.group(1) > > > > ' 1 aaa < t bbb < a ff > > 2 ' > > > > In this case the regular expression is automatically greedy, matching > > > the largest area possible. Note however that it won't work if you have > > > something like this: " ". > > > > Matt > > As far as I know, you can't do that with a regular expressions (by > definition regular expressions aren't recursive). You can use a > regular expression to aid you, but there is no magic expression that > will give it to you for free. > > In this case it is actually pretty easy to do it without regular > expressions at all: > > >>> text = "a < b < O > d > here starts a new group: ?< e < f ?> g >" > >>> def get_nested_strings(text, depth=0): > > ... ? ? stack = [] > ... ? ? for i, c in enumerate(text): > ... ? ? ? ? if c == '<': > ... ? ? ? ? ? ? stack.append(i) > ... ? ? ? ? elif c == '>': > ... ? ? ? ? ? ? start = stack.pop() + 1 > ... ? ? ? ? ? ? if len(stack) == depth: > ... ? ? ? ? ? ? ? ? yield text[start:i] > ...>>> for seg in get_nested_strings(text): > > ... ?print seg > ... > ?b < O > d > ?e < f ?> g > > Matt From roy at panix.com Tue Nov 25 10:09:51 2008 From: roy at panix.com (Roy Smith) Date: Tue, 25 Nov 2008 10:09:51 -0500 Subject: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0) References: Message-ID: In article , Ryan Kelly wrote: > * Migrated from SWIG to ctypes for the C binding: Ryan, I'm looking at a doing a Python wrapper for a C++ library. We've already done a Perl wrapper for this library using SWIG (I wasn't personally involved in that effort). I'm debating whether I should do the Python version with SWIG or ctypes. I'd be interested to hear about your experiences with both and why you switched. From __peter__ at web.de Fri Nov 28 03:58:35 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Nov 2008 09:58:35 +0100 Subject: Help with capturing error References: <73731647-d177-4e80-9cca-0a95ed49199e@g38g2000yqd.googlegroups.com> Message-ID: tekion wrote: > Hello, > I am getting the following error and my script is bailing out because > of it. I have tried capturing it but it does not seem to work. Below > is the error: > > ValueError: I/O operation on closed file > > > the above error is received when, the following code snippet is > executed: > try: > 117 self.xml_file.close() > 118 except ValueError: > 119 print "file, %s is already closed" % self.seek_file > > Any idea why line 118, is not capturing the error? Thanks. It seems you didn't read the traceback carefully. Line 117 doesn't cause that error. You can close a file as often as you like, but you can't read/write to a closed file: >>> f = open("tmp.txt", "w") >>> f.close() >>> f.close() >>> f.close() >>> f.write("yadda") Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file Peter From steven.samuel.cole at gmail.com Wed Nov 19 20:14:33 2008 From: steven.samuel.cole at gmail.com (Steven Samuel Cole) Date: Thu, 20 Nov 2008 14:14:33 +1300 Subject: Python / Debian package dependencies Message-ID: Hi all, I am trying to build a debian package for my python modules using stdeb and dpkg-buildpackage. The package building itself works, I also managed to have an entry point created and I can use my python modules on the Ubuntu virtual machine I use to test the package. The problem is that my modules require the psycopg2 python package and the entry point seems to require setuptools. I can't figure out how to declare a dependency that actually results in the dependency Debian packages being installed. I tried adding these lines to setup.py: requires = ['psycopg2', 'setuptools'], requires = ['psycopg2 (>=0.1)', 'setuptools (>=0.1)'], install_requires = ['psycopg2', 'setuptools'], install_requires = ['psycopg2>=0.1', 'setuptools>=0.1'], and then run stdeb_run_setup and dpkg-buildpackage -rfakeroot -uc -us in the deb_dist/ folder created, but when I copy the .deb file over to the virtual machine and do dpkg -i <.deb file>, none of them would actually install psycopg2 and setuptools. What am I doing wrong ? Am I actually somewhat on the right track or am I doing complete nonsense ? Thanks for your help! Cheers, Steve From steve at REMOVE-THIS-cybersource.com.au Sat Nov 22 03:53:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Nov 2008 08:53:14 GMT Subject: Python 3 __cmp__ semantic change? References: <9b9hv5x3fj.ln2@joeserver.homelan.net> <013754b5$0$20662$c3e8da3@news.astraweb.com> Message-ID: <0137c09b$0$20669$c3e8da3@news.astraweb.com> On Sat, 22 Nov 2008 08:27:59 +0000, Arnaud Delobelle wrote: >>> Granted it's not as efficient as a __cmp__ function. >> >> What makes you say that? What do you mean by "efficient"? Are you >> talking about memory footprint, runtime speed, disk-space, programmer >> efficiency, algorithmic complexity, or something else? > > What I'm talking about is very simple - and explained below, with the > help of your __cmp__ method. >> >> As I see it, a __cmp__ method would be written something like this: >> >> def __cmp__(self, other): >> return cmp(self.num*other.den, self.den*other.num) > > I'm talking about runtime speed (*not* asymptotic complexity). My code > makes Fraction.__gt__ about twice as slow as Fraction.__lt__ or > Fraction.__eq__ even though with __cmp__ they would all be equally fast. Sounds like a premature micro-optimization to me. On my machine, running Python 2.5, the speed difference is nothing like twice as slow. >>> class UseCmp(object): ... def __init__(self, num, den=1): ... self.num = num ... self.den = den ... def __cmp__(self, other): ... return cmp(self.num*other.den, self.den*other.num) ... >>> class UseRichCmp(UseCmp): ... __lt__ = lambda self, other: self.__cmp__(other) < 0 ... >>> from timeit import Timer >>> t1 = Timer('x < y', ... 'from __main__ import UseCmp; x=UseCmp(3, 5); y=UseCmp(1, 2)') >>> t2 = Timer('x < y', ... 'from __main__ import UseRichCmp;' ... 'x=UseRichCmp(3, 5); y=UseRichCmp(1, 2)') >>> >>> t1.repeat() [3.3418200016021729, 2.4046459197998047, 2.2295808792114258] >>> t2.repeat() [3.8954730033874512, 3.0240590572357178, 3.5528950691223145] There's a slight speed difference, around 35% slower. But the random variation in speed is almost 50%, so I would conclude from this trial that there is no *significant* speed difference between the methods. -- Steven From danmoskowitz at gmail.com Thu Nov 6 16:08:59 2008 From: danmoskowitz at gmail.com (Dan Moskowitz) Date: Thu, 6 Nov 2008 13:08:59 -0800 (PST) Subject: Fastest way to tint an image with PIL Message-ID: <45f979ae-1628-498d-be62-a88da2e9c0d1@s1g2000prg.googlegroups.com> Hi, I'm using PIL to tint and composite images together. Here's how I'm currently tinting images, it's really slow and I know there's got to be a better way: def TintImage( im, tintColor ): tint = (tintColor[0]/255.0, tintColor[1]/255.0, tintColor[2]/255.0, tintColor[3]/255.0) pix = im.load() for x in xrange( im.size[0] ): for y in xrange( im.size[1] ): c = pix[x,y] pix[x,y] = (int(c[0]*tint[0]), int(c[1]*tint[1]), int(c[2]*tint[2]), c[3]) I thought maybe there's a way to do it using the transform method, but I haven't figure it out yet. Anyone? Thanks -Dan From digitig at gmail.com Wed Nov 26 20:19:03 2008 From: digitig at gmail.com (Tim Rowe) Date: Thu, 27 Nov 2008 01:19:03 +0000 Subject: hello from colombia In-Reply-To: <5c451e65-4e51-40ab-97d4-e5853927dedb@d42g2000prb.googlegroups.com> References: <5c451e65-4e51-40ab-97d4-e5853927dedb@d42g2000prb.googlegroups.com> Message-ID: 2008/11/26 fel : > how can I convince them that Python is better You can't, because it isn't. I'd better explain that, before I'm lynched. The thing is, no language is better than another language. A language is better than another language *for a particular purpose*. SPARK Ada is better than Python for safety-critical software (if only because it's easier to get regulatory approval). INTERCAL is better than Python for obfustication. Before you try to convert them to Python, you need to find out all the reasons for the existing language choice and work out whether Python actually /would/ be better. If you can do that, in the process you will have gathered the evidence you need. If you can't do that, why are you assuming that Python will be better? -- Tim Rowe From rafesacks at gmail.com Wed Nov 12 03:02:36 2008 From: rafesacks at gmail.com (Rafe) Date: Wed, 12 Nov 2008 00:02:36 -0800 (PST) Subject: inspect.findsource problem with llinecache References: <94b2f6c9-8352-46e5-9dd7-43fbe3ef7b1b@o4g2000pra.googlegroups.com> Message-ID: On Nov 12, 2:22?pm, Rafe wrote: > Hi, > > I think I have discovered two bugs with the inspect module and I would > like to know if anyone can spot any traps in my workaround. > > I needed a function which takes a function or method and returns the > code inside it (it also adjusts the indent because I have to paste the > to a text string without indents, which is parsed later...long story). > At first this seemed trivial but then I started getting an error on > line 510 of inspect.py: > 504 ? ?if iscode(object): > 505 ? ? ? ?if not hasattr(object, 'co_firstlineno'): > 506 ? ? ? ? ? ?raise IOError('could not find function definition') > 507 ? ? ? ?lnum = object.co_firstlineno - 1 > 508 ? ? ? ?pat = re.compile(r'^(\s*def\s)|(.*(? (\s*@)') > 509 ? ? ? ?while lnum > 0: > 510 ? ? ? ? ? ?if pat.match(lines[lnum]): break > 511 ? ? ? ? ? ?lnum = lnum - 1 > 512 ? ? ? ?return lines, lnum > > I finally figured out that there was a caching problem. The function I > passed was changed, but the code lines (strings) retrieved by > linecache.getlines() (on lines 464 and 466) didn't update with the new > module contents. The resulting error I was getting occurred when real > module had less lines than the cached module (or the other way around, > whatever.) > > To get around this, I invoke linecache.clearcache(). Here is the > function (minus doc strings)... > > INDENT_SPACES = 4 > > def get_fn_contents(fn, remove_indents=1): > ? ? # Clear the cache so inspect.getsourcelines doesn't try to > ? ? # check an older version of the function's module. > ? ? linecache.clearcache() > ? ? source_lines, n = inspect.getsourcelines(fn) > > ? ? # Skip the first line which contains the function definition. > ? ? # Only want the code inside the function is needed. > ? ? fn_contents = source_lines[1:] > > ? ? # Remove indents > ? ? new_indent_lines = [remove_indent(line, remove_indents) for line > in fn_contents] > > ? ? return "".join(new_indent_lines) > > def remove_indent(in_str, num_indent=1): > ? ? s = in_str > ? ? for i in range(num_indent): > ? ? ? ? if s[:INDENT_SPACES] == " ? ?": ? # Whitespace indents > ? ? ? ? ? ? s = s[INDENT_SPACES:] > ? ? ? ? elif s[:1] == "\t": ? # Tab characters indents > ? ? ? ? ? ? ?s = s[1:] > > ? ? return s > > [END CODE] > > The second issue is that the last line in the passed function's module > seems to be ignored. So, if the last line of the module is also the > last line of the function, the function is returned one line too > short. > > I welcome comments on the bugs or optimization pointers for my code. I > am still quite new to Python. My primary question though is: will > linecache.clearcache() cause me any problems? > > Thanks, > > - Rafe I forgot to add that while inspect uses the cached module to get the text, the line number used to find the block of source lines is retrieved from the passed object. So, if I pass a function which reports that it starts on line 50, but in the cache it starts on line 40 an error isn't raised but the lines of code returned are wrong. The error only occurs when the line number is higher than the number of lines in the cached module. - Rafe From steve at holdenweb.com Mon Nov 17 09:57:40 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Nov 2008 09:57:40 -0500 Subject: install wxPython on windows without admin? In-Reply-To: References: Message-ID: timw.google wrote: > The subject line says it all. Is there a way to install wxPython on a > Windows machine without admin privs? I love the way python doesn't > need admin to install locally, and I'd like to try wxPython w/o having > to get our help desk involved. > > Do I have to compile it from source with Cygwin? > Installing wxPython on Cygwin from source is an uphill battle which I would recommend against, though it's possible it's been done ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From greg at cosc.canterbury.ac.nz Wed Nov 26 00:26:58 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 26 Nov 2008 18:26:58 +1300 Subject: How to get a directory file descriptor? In-Reply-To: <64acbb2a-7129-41ad-96cb-2d742525f43a@s1g2000prg.googlegroups.com> References: <04485416-5d03-476c-89de-089a4685f80c@i20g2000prf.googlegroups.com> <64acbb2a-7129-41ad-96cb-2d742525f43a@s1g2000prg.googlegroups.com> Message-ID: <6p44s0F68rlsU1@mid.individual.net> alex23 wrote: > import os > dirfd = os.open("directory-name", os.O_DIRECTORY) > os.fchdir(dirfd) os.O_DIRECTORY must be fairly new -- it doesn't exist in my 2.5 installation. But os.O_RDONLY seems to work just as well for this purpose. -- Greg From arnodel at googlemail.com Thu Nov 6 15:48:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 06 Nov 2008 20:48:45 +0000 Subject: More __init__ methods References: <6ngijnFlbequU3@mid.uni-berlin.de> <87abcch9c8.fsf@benfinney.id.au> Message-ID: Ben Finney writes: [...] > All you need to know to understand the above is that it will have > essentially the same result as: > > class A(object): > # ... > > def _from_string(cls, s): > # ... > return cls(a, b, c) > from_string = classmethod(_from_string) > del _from_string > > without the intermediate binding of the ?_from_string? name. So you mean it is the same as: class A(object): # ... def from_string(cls, s): # ... from_string = classmethod(from_string) :) -- Arnaud From wuwei23 at gmail.com Thu Nov 13 21:57:37 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 13 Nov 2008 18:57:37 -0800 (PST) Subject: using "private" parameters as static storage? References: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> <4866bea60811130919h518b8054i7477067ef3f93e5a@mail.gmail.com> Message-ID: <1f1a20f7-dc06-4770-bbd9-3b8123c26c95@o4g2000pra.googlegroups.com> On Nov 14, 12:16?pm, Joe Strout wrote: > Argh. ?I've been back in the Python community for about a month, and ? > I've been continually amazed at how every single "how do I do X" or ? > "what do you think of this method of doing X" question is answered by ? > people on high horses claiming "you shouldn't do X". If someone asked you how to hammer together a cabinet with a saw, wouldn't -you- respond with "don't use a saw"? Suggesting the right tool for the job is hardly getting on a high horse... From greg at cosc.canterbury.ac.nz Sat Nov 22 19:13:11 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 23 Nov 2008 13:13:11 +1300 Subject: initialization in argument definitions In-Reply-To: References: <7005ea9f-f803-4c06-831c-7f221a5fd598@r15g2000prh.googlegroups.com> <09787f36-0846-41a5-9075-7d3d80588389@o2g2000yqd.googlegroups.com> Message-ID: <6orlblF5455sU1@mid.individual.net> George Sakkis wrote: > Don't worry, it's not obvious to *anyone* new to Python (and many not- > so-new for that matter). That's by no means certain, because we only hear from the people who guessed the wrong way. We have no way of knowing how many people guessed the right way. -- Greg From philip at semanchuk.com Fri Nov 28 11:41:25 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 28 Nov 2008 11:41:25 -0500 Subject: setting path for python interpretor In-Reply-To: References: Message-ID: <44573AAE-5061-463F-A2A4-655B5DE5AC05@semanchuk.com> On Nov 28, 2008, at 6:41 AM, Beema Shafreen wrote: > Hi all, > Can any body suggest me how to the set path for making python2.4 as > the main > interpretor instead of python 2.5. Hi Beema, This question is about your operating system, not about Python. On my system (OS X), having installed Python to /usr/local, it was sufficient to add this to my ~/.profile export PATH=~/bin:/usr/local/bin:$PATH In general, check out the documentation for the PATH statement for your operating system and make sure your preferred Python appears first in the path. From deets at nospam.web.de Sun Nov 9 10:19:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Nov 2008 16:19:50 +0100 Subject: sorting list of complex numbers In-Reply-To: References: Message-ID: <6nodcmFmk1blU2@mid.uni-berlin.de> skip at pobox.com schrieb: > The thread on sorting in Python 3 got me to thinking. How could I sort a > list of complex numbers using key? > > >>> lst = [random.random()+random.random()*1j for i in range(10)] > >>> lst > [(0.32672251849959244+0.41428983433288791j), (0.35238056484609881+0.92758203977208264j), (0.19337824038125528+0.16527285180541951j), (0.47569307114525849+0.72381960418815128j), (0.21498813135082351+0.2046308266222292j), (0.30142745756937939+0.35216751451102601j), (0.77355676386939132+0.0023447924287695043j), (0.2547736124606309+0.52234837788936905j), (0.38349189081350132+0.62017617694427096j), (0.58362096773561245+0.87702443273108477j)] > > As expected: > > >>> sorted(lst) > Traceback (most recent call last): > File "", line 1, in > TypeError: no ordering relation is defined for complex numbers > > This works: > > >>> sorted(lst, key=lambda x: x.real) > [(0.19337824038125528+0.16527285180541951j), (0.21498813135082351+0.2046308266222292j), (0.2547736124606309+0.52234837788936905j), (0.30142745756937939+0.35216751451102601j), (0.32672251849959244+0.41428983433288791j), (0.35238056484609881+0.92758203977208264j), (0.38349189081350132+0.62017617694427096j), (0.47569307114525849+0.72381960418815128j), (0.58362096773561245+0.87702443273108477j), (0.77355676386939132+0.0023447924287695043j)] > > but what if I want to sort by real, then imaginary parts? Here's a longer > list with 20 elements where there are only 10 distinct reals but 20 distinct > imaginaries: > > >>> pprint.pprint(lst) > [(1+2.73j), > (9+3.77j), > (7+27j), > (8+28j), > (2+2.8600000000000003j), > (4+3.1200000000000001j), > (2+22j), > (9+29j), > (3+2.9900000000000002j), > (6+26j), > 2.6000000000000001j, > (8+3.6400000000000001j), > (3+23j), > (5+3.25j), > (1+21j), > (5+25j), > 20j, > (6+3.3799999999999999j), > (7+3.5100000000000002j), > (4+24j)] > > I can sort by the real parts just fine: > > >>> lst.sort(key=lambda x: x.real) > >>> pprint.pprint(lst) > [2.6000000000000001j, > 20j, > (1+2.73j), > (1+21j), > (2+2.8600000000000003j), > (2+22j), > (3+2.9900000000000002j), > (3+23j), > (4+3.1200000000000001j), > (4+24j), > (5+3.25j), > (5+25j), > (6+26j), > (6+3.3799999999999999j), > (7+27j), > (7+3.5100000000000002j), > (8+28j), > (8+3.6400000000000001j), > (9+3.77j), > (9+29j)] > > but how do I then do a secondary sort by the imaginary part, preserving the > existing ordering on the real parts? Seems like I have to resort to a > Schwartzian transform and map the complex numbers to tuples, sort that, then > map them back. With the cmp key it would have been a fairly trivial task to > define the desired compare-real-then-imag function. > > Is there a way to do this using just the key arg, no extra data structures? Doesn't (untested) key=lambda x: (x.real, x.imag) work? Diez From heyer.mario at googlemail.com Tue Nov 25 11:36:16 2008 From: heyer.mario at googlemail.com (M_H) Date: Tue, 25 Nov 2008 08:36:16 -0800 (PST) Subject: Reg Expression - Get position of > Message-ID: <25468f21-080e-4297-8827-4eb67f2f5343@a12g2000yqm.googlegroups.com> Hey, I need the position of the last char > Let's say I have a string mystr = (second sign) - so I can cut away the first part. The problem is that it can be like "> but also like " > or " > But it is def the quotes and the closing brakets. How do I get the position of the > ???? Hope you can help, Bacco From rtw at freenet.co.uk Sat Nov 29 12:46:45 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 29 Nov 2008 11:46:45 -0600 Subject: 'new' module deprecation in python2.6 References: <558b73fb0811290904y76b736fdifc56e824fa735138@mail.gmail.com> Message-ID: David Pratt wrote in news:mailman.4664.1227980181.3487.python- list at python.org in comp.lang.python: > import new > > class FirstBase(object): > foo = 'bar' > biz = 'baz' > > class SecondBase(object): > bla = 'blu' > buz = 'brr' > > attr = { > 'fiz': 'An attribute', 'fuz': 'Another one'} > > Test = new.classobj( > 'Test', (FirstBase, SecondBase), attr) Test = type( 'Test', (FirstBase, SecondBase), attr) > > class MyNewClass(Test): > pass > > a = MyNewClass() > > print a.foo, a.buz, a.fiz, type(a) print( ( a.foo, a.buz, a.fiz, type(a) ) ) py 3.0: ('bar', 'brr', 'An attribute', ) py 2.4 ('bar', 'brr', 'An attribute', ) Rob. -- http://www.victim-prime.dsl.pipex.com/ From alex at computronix.com Thu Nov 13 01:19:09 2008 From: alex at computronix.com (Alex VanderWoude) Date: Wed, 12 Nov 2008 23:19:09 -0700 Subject: Printing a "status " line from a python script In-Reply-To: <0d3d07fa-5a15-4069-985e-213b02b84513@a17g2000prm.googlegroups.com> References: <0d3d07fa-5a15-4069-985e-213b02b84513@a17g2000prm.googlegroups.com> Message-ID: Chris Seymour wrote: > I am working on a python script for my colleague that will walk a > directory and search in the different files for a specific string. > These pieces I am able to do. What my colleague wants is that when > she runs the script the filename is replaced by the current file that > is being processed. So instead of seeing a series of files being > listed down the page, she only wants to see the file currently being > processed. You should know that printing "\b" issues a backspace. You can couple this with printing without line endings using a trailing comma: print "Now processing file", # Trailing comma = no line ending previous = "" names = ["one", "two", "three"] for name in names: if previous: print "\b" * (len(previous) + 2), # Trailing comma again print name, # Yet another trailing comma previous = name # Do whatever other processing you need here print # At last a line ending Hope this helps. - Alex From electronixtar at gmail.com Wed Nov 12 02:54:08 2008 From: electronixtar at gmail.com (est) Date: Tue, 11 Nov 2008 23:54:08 -0800 (PST) Subject: Where can I get Lucid Toolkit? Message-ID: Hi guys, I tried to grab source code for Lucid Toolkit http://www.clarographics.org/svn_details which was mentioned http://wiki.python.org/moin/GuiProgramming So is this project abandoned? Is there any backup that I can get the code? Any other recommands for simple GUI development, with out large library runtime(qt, gtk, wx) ? From greg at cosc.canterbury.ac.nz Fri Nov 21 20:28:41 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 22 Nov 2008 14:28:41 +1300 Subject: Official definition of call-by-value (Re: Finding the instance reference...) In-Reply-To: <01363334$0$20662$c3e8da3@news.astraweb.com> References: <0120cb30$0$20642$c3e8da3@news.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <0124739f$0$20668$c3e8da3@news.astraweb.com> <6dd2bf03-54fa-4d42-9392-659a8e972598@b38g2000prf.googlegroups.com> <6nsbskFib5vU1@mid.individual.net> <6nul1qF100urU1@mid.individual.net> <6oh3adF3ikb9U1@mid.individual.net> <6ojsa3F41nfsU1@mid.individual.net> <013623f4$0$20662$c3e8da3@news.astraweb.com> <01363334$0$20662$c3e8da3@news.astraweb.com> Message-ID: <6op5d5F4qhgvU1@mid.individual.net> Steven D'Aprano wrote: > You've just *assumed* that assignment in Algol 60 doesn't involving > copying. I've done no such thing. I've *refrained* from assuming that the "assignment" in the definition always has to refer to Algol 60 assignment. You're the one insisting on tying everything to Algol. I don't know whether the Algol committee had such a general meaning in mind when they wrote that document. It's quite likely they weren't thinking that far ahead. But the fact is that it *can* be generalized to other languages in an obvious and useful way, and many language designers after them have generalized it in exactly that way. >>(I wait now with bated breath for somebody to point out some Python >>implementation or feature where assignment doesn't make a copy...) > > Ah crap, I meant *Pascal*. Not in plain Pascal, but Apple's Object Pascal (and probably other OO Pascal dialects) have object types that are implicitly referred to by pointers, like Python objects -- and when you pass one by value, only the pointer is copied, not the whole object. -- Greg From martin at v.loewis.de Tue Nov 4 15:16:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Nov 2008 21:16:03 +0100 Subject: separate shared libraries or different Linux/Unix In-Reply-To: <37c08af8-038e-4e08-b708-8ccb7c261b5d@w1g2000prk.googlegroups.com> References: <11e47aea-942b-4bc8-b54a-4944d8b0181b@u29g2000pro.googlegroups.com> <49081303$0$28848$9b622d9e@news.freenet.de> <37c08af8-038e-4e08-b708-8ccb7c261b5d@w1g2000prk.googlegroups.com> Message-ID: <4910ad83$0$5421$9b622d9e@news.freenet.de> > How do I get zlib available to python? Edit Modules/Setup, and uncomment the zlib line. At your choice, also uncomment the *shared* line (otherwise, zlib would become a builtin module). When you install shared libraries somewhere that also live in /usr/lib, do use ldd to verify that it always picks up the libraries you want. Regards, Martin From thomas at mlynarczyk-webdesign.de Sat Nov 15 13:00:29 2008 From: thomas at mlynarczyk-webdesign.de (Thomas Mlynarczyk) Date: Sat, 15 Nov 2008 19:00:29 +0100 Subject: Generators and their next() and send() methods Message-ID: Hello, I was playing around a bit with generators using next() and send(). And I was wondering why an extra send() method was introduced instead of simply allowing an argument for next(). Also, I find it a bit counter-intuitive that send(42) not only "sets" the generator to the specified value, but yields the next value at the same time. As an exercise, I wanted to somehow "modify" a generator so that it would have a next() method accepting an argument, something like @myway def gen(): pass But I failed to come up with an implementation of the myway() function. Any comments and/or suggestions? Greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux ? avoir tort qu'ils ont raison! (Coluche) From bearophileHUGS at lycos.com Wed Nov 5 07:22:32 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 5 Nov 2008 04:22:32 -0800 (PST) Subject: False and 0 in the same dictionary References: <87bpwvkrpl.fsf@benfinney.id.au> Message-ID: <91cf0315-1818-4793-8036-3ce0b5bbcbb2@1g2000prd.googlegroups.com> Ben Finney: > Is there a later PEP that I've missed which > finally makes ?bool? a type independent from ?int?? In a tidy language like an ObjectPascal or Java bools and integers are different types. In Python if bools become distinct from integers you have to rewrite things like: sum(el == val for el in iterable) as: sum(1 for el in iterable if el == val) In the past here I have stated that boolean operators should return only boolean values, and I believe it still. Because doing otherwise is quite confusing. But in practice I have seen that while being a little untidy, having bools as subtype of int doesn't lead to much bugs, and it has few practical advantages. So purity isn't that useful here. Having an iterable that contains both ints and bools isn't too much common, because while Python isn't statically typed, in practice most of the times in most Python programs types are uniform and predictable (that's why ShedSkin can work). And even if you have a list that contains bools and integers mixed, then having to tell them apart (by hashing, etc) is quite uncommon, I think I have never had to do it in 2-3 years. So maybe is that code that is doing something messy, so maybe is that code that has to change and become more tidy, and not the language itself :-) Bye, bearophile From hayes.tyler at gmail.com Tue Nov 4 13:17:26 2008 From: hayes.tyler at gmail.com (Tyler) Date: Tue, 4 Nov 2008 10:17:26 -0800 (PST) Subject: Parse each line by character location References: Message-ID: <7aec1ab7-c77a-4368-8a97-1bf7136f089a@w39g2000prb.googlegroups.com> Wow! Thanks for the suggestions everyone. Cheers, t. From steve at REMOVE-THIS-cybersource.com.au Sun Nov 2 04:13:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Nov 2008 09:13:43 GMT Subject: Fast list traversal References: Message-ID: <011d67fe$0$20659$c3e8da3@news.astraweb.com> On Sun, 02 Nov 2008 00:25:13 -0700, dineshv wrote: > I want to see if there is an alternative method for fast list traversal. > The code is very simple: > > dict_long_lists = defaultdict(list) > for long_list in dict_long_lists.itervalues() > for element in long_list: > array_a[element] = m + n + p # m,n,p > are variable numbers It might help if you showed some sample data, because your explanation is confusing. You are asking about traversing lists, but your data is in a defaultdict. Why is it in a dict, when you don't seem to be using the key anywhere? Putting that aside, I'm going to make a guess and assume your data looks something like this... dict_long_lists = { 'key1': [0, 1, 2, 3, 4, 5], 'key2': [16, 17, 18, 19], 'key3': [7, 9, 11, 13, 15], 'key4': [6, 8, 10, 12, 14] } Then you do something like this: array_a = [None]*20 Then after running your code, you end up with: array_a == [x0, x1, x2, x3, .... , x19] where each x is calculated from m + n + p. > The long_list's are read from a defaultdict(list) dictionary and so > don't need initializing. The elements of long_list are integers and > ordered (sorted before placing in dictionary). There are > 20,000 > long_list's each with a variable number of elements (>5,000). The > elements of long_list are immutable (ie. don't change). The above code > is within a def function. > > I've tried set() using defaultdict(set) but the elements are not > ordered. It's not clear what you have tried to do with set(), or why the elements need to be ordered. > What is the fastest way to traverse these long_list's sequentially from > the beginning to the end? Maybe there is another data structure that > can be used instead of a list. I doubt you'll find anything faster than a list. You have > 20,000 lists of > 5,000 items each, which means you have a *minimum* of 100,000,000 items to traverse. If each iteration takes 0.1 millisecond, not an unreasonably slow speed depending on the amount of computation each iteration is, that will take 10,000 seconds or nearly three hours. The only solutions to that are to reduce the amount of computation in each loop, reduce the number of items, or get a faster computer. Have you tried running the profiler to see where the time is actually going? I suggest you write a small set of test data (say, 1000 items), and profile it, then write a longer set of test data (say, 100,000 items), and if it's still not clear where the time is being lost, ask for help. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Nov 10 20:27:59 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Nov 2008 01:27:59 GMT Subject: Finding the instance reference of an object References: <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <01203bbd$0$20642$c3e8da3@news.astraweb.com> <3c4edf32-acda-4244-ba46-bad5ea623303@w39g2000prb.googlegroups.com> <0120cb30$0$20642$c3e8da3@news.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <6nkparFlu2nqU1@mid.individual.net> <8b8a629c-b2bc-401b-9102-c88bfc8c3f2b@l33g2000pri.googlegroups.com> <6nnrrfFmpa9lU1@mid.individual.net> <6nqfq2F837kU1@mid.individual.net> Message-ID: On Mon, 10 Nov 2008 23:16:13 +1300, greg wrote: >> (CBV) An evaluation strategy where arguments are evaluated before >> the function or procedure is entered. Only the values of the >> arguments are passed and changes to the arguments within the called >> procedure have no effect on the actual arguments as seen by the >> caller. > > That hinges on what exactly is meant by "changes to the arguments". In > Python it can only mean assigning directly to the bare name -- anything > else isn't changing the argument itself, but something else to which the > argument refers. But the name isn't the argument. The argument to a function is an object, not a name. You can't write a function in Python that takes a name as an argument[1], which would be equivalent to Pascal's "var" parameters. Take a function foo that takes one formal parameter x. Pass an actual argument y to it. The argument is the object currently bound to y, not the name y. Nothing inside foo can rebind the name y because foo doesn't see the name y, it sees the object. Rebinding (or deleting) the name x inside foo does nothing to the object bound to y, or the name y. [1] You can pass a string representing the name to a function, which can then use some combination of setattr, globals(), exec etc to work with the name represented by that string. But you're still passing an object to the function, not a name. -- Steven From jeff at jmcneil.net Tue Nov 11 14:39:19 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Tue, 11 Nov 2008 11:39:19 -0800 (PST) Subject: subprocess communication, exec() References: Message-ID: On Nov 11, 1:23 pm, "Chuckk Hubbard" wrote: > If I run 'python -i subprocessclient.py' I expect to see the nice > level of it go up 2, and the nice level of the subprocess go up 1. > But all I see is the nice level of the client change. What am I doing > wrong? > > subprocessserver.py: > ---------------------------- > #!/usr/bin/python2.5 > > import os > import sys > > while True: > next_line = sys.stdin.readline() > if not next_line: > break > exec(next_line) > # sys.stdout.write(output) > # sys.stdout.write(next_line) > # sys.stdout.flush() > ---------------------------- > > subprocessclient.py: > ---------------------------- > #!/usr/bin/python2.5 > > import subprocess, os > > server = subprocess.Popen(('python2.5', 'subprocessserver.py'), > shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > > os.nice(2) > > server.stdin.write('''os.nice(1)''') > ---------------------------- > > Thanks. > -Chuckk > > --http://www.badmuthahubbard.com Looks like you're dropping an error by redirecting the child process' standard error into a pipe. First off, remove the stderr=subprocess.PIPE from subprocessclient.py. When you do so, you'll start seeing an error message whenever your code runs: [jeff at marvin ~]$ python client.py None [jeff at marvin ~]$ Traceback (most recent call last): File "", line 1, in NameError: name 'os' is not defined That doesn't make a lot of sense at first, until you consider the following: [jeff at marvin ~]$ echo 'os.nice(1)' | python Traceback (most recent call last): File "", line 1, in NameError: name 'os' is not defined The Python interpreter is trying to execute the data you write to the stdin of the child process. Changing the Popen line to use the string form rather than the sequence form remedies the problem, as does changing 'string=True' to 'string=False.' The reason? Because when you set shell=True, additional arguments in args sequence are passed as additional arguments to the shell itself, not to the command. >From subprocess.py: if isinstance(args, types.StringTypes): args = [args] else: args = list(args) if shell: args = ["/bin/sh", "-c"] + args So, in your attempt, you're effectively doing the following: /bin/sh -c "python2.5" "server.py" When you want: /bin/sh -c "python2.5 server.py" HTH, Jeff From steve at holdenweb.com Thu Nov 20 14:00:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Nov 2008 14:00:57 -0500 Subject: Module Structure/Import Design Problem In-Reply-To: <4925AA74.6050608@gmail.com> References: <1adf50fc-c351-4bbd-85ee-bc60e53e8fec@r15g2000prh.googlegroups.com> <4925AA74.6050608@gmail.com> Message-ID: Stef Mientki wrote: > Rafe wrote: >> Hi, >> >> I am in a situation where I feel I am being forced to abandon a clean >> module structure in favor of a large single module. If anyone can save >> my sanity here I would be forever grateful. >> >> My problem is that classes in several modules share a common base >> class which needs to implement a factory method to return instances of >> these same classes. >> >> An example to help illustrate what I mean: >> Lets say I have the following modules with the listed classes: >> - baselib.py with BaseClass >> - types.py with TypeA, ... >> - special.py with SpecialTypeA, ... >> >> Which would be used a bit like this: >> >>>>> type_a = any_type_instance.get_type("TypeA") >>>>> special_type = type_a.get_type("SpecialTypeA") >>>>> >> >> >> Again, I can get around this by dumping everything in to one module, >> but it muddies the organization of the package a bit. This seems like >> a problem that would come up a lot. Are there any design paradigms I >> can apply here? >> >> > I'm not an expert, I even don't fully understand your problem, > but having struggled with imports in the past, > I've a solution now, which seems to work quit well. > That's not very helpful, is it? Were you planning to keep the solution secret? regards steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From deets at nospam.web.de Mon Nov 3 09:58:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Nov 2008 15:58:29 +0100 Subject: How to uninstall setuptools References: Message-ID: <6n8hsbFj5rdeU1@mid.uni-berlin.de> Roger Erens wrote: > On my Ubuntu8.04 box I installed python-all and subsequently setuptools > for both 2.4 and 2.5 interpreters. To make a clean upgrade to 8.10 I > need to uninstall setuptools. Any hints for doing that? It sounds as if you installed it using debian package management. Then you can just deinstall with that (or better yet upgrade). If you installed manually, it should suffice to rip out /usr/lib/python2.*/site-packages/[setuptools*|easy-install*] and /usr/bin/easy_install*. Diez From steve at REMOVE-THIS-cybersource.com.au Thu Nov 20 23:34:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Nov 2008 04:34:42 GMT Subject: function parameter scope python 2.5.2 References: <854p229dq7.fsf@dozer.localdomain> Message-ID: <0136328c$0$20662$c3e8da3@news.astraweb.com> On Thu, 20 Nov 2008 18:31:12 -0500, J Kenneth King wrote: > Of course I expected that recursive_func() would receive a copy of > weird_obj.words but it appears to happily modify the object. I am curious why you thought that. What made you think Python should/did make a copy of weird_obj.words when you pass it to a function? This is a serious question, I'm not trying to trap you into something :) -- Steven From bkamrani at gmail.com Tue Nov 11 08:10:48 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 11 Nov 2008 05:10:48 -0800 (PST) Subject: f2py usage problem Message-ID: <92f28678-cd5a-4998-8623-23b5d7493bce@p35g2000prm.googlegroups.com> Hi Python gurus, I have installed numpy and interested in testing f2py module using the first example in the documentation. First I tried: C:\test>python "C:\Program Files\Python25\Scripts\f2py.py" -c fib1.f running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands -- compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands -- fcompiler options running build_src building extension "untitled" sources f2py options: [] f2py:> c:\docume~1\e6462\locals~1\temp\tmpzcktrq \src.win32-2.5\untitledmodule.c creating c:\docume~1\e6462\locals~1\temp\tmpzcktrq creating c:\docume~1\e6462\locals~1\temp\tmpzcktrq\src.win32-2.5 Reading fortran codes... Reading file 'fib1.f' (format:fix,strict) Post-processing... Block: untitled Block: fib Post-processing (stage 2)... Building modules... Building module "untitled"... Constructing wrapper function "fib"... fib(a,[n]) Wrote C/API module "untitled" to file "c: \docume~1\e6462\locals~1\temp\tmpzcktrq\src.win32-2.5/ untitledmodule.c" adding 'c:\docume~1\e6462\locals~1\temp\tmpzcktrq \src.win32-2.5\fortranobject.c' to sources. adding 'c:\docume~1\e6462\locals~1\temp\tmpzcktrq\src.win32-2.5' to include_dirs. copying C:\Progra~1\python25\lib\site-packages\numpy-1.0.4.0002-py2.5- win32.egg\ numpy\f2py\src\fortranobject.c -> c:\docume~1\e6462\locals~1\temp \tmpzcktrq\src.win32-2.5 copying C:\Progra~1\python25\lib\site-packages\numpy-1.0.4.0002-py2.5- win32.egg\ numpy\f2py\src\fortranobject.h -> c:\docume~1\e6462\locals~1\temp \tmpzcktrq\src.win32-2.5 running build_ext No module named msvccompiler in numpy.distutils; trying from distutils 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. Then I installed mingw32 and tried to pass "-c mingw32" to setup.py as below, but got another error: C:\tests>python "C:\Program Files\Python25\Lib\site-packages \numpy-1.0.4.0002-py2.5-win32.egg\numpy\f2py\setup.py" -c mingw32 Warning: Assuming default configuration (C:\Program Files\Python25\Lib \site-pack ages\numpy-1.0.4.0002-py2.5-win32.egg\numpy\f2py\lib\parser/ {setup_parser,setup}.py was not found) Appending f2py.lib.parser configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.parser') Warning: Assuming default configuration (C:\Program Files\Python25\Lib \site-packages\numpy-1.0.4.0002-py2.5-win32.egg\numpy\f2py\lib\extgen/ {setup_extgen,setup}.py was not found) Appending f2py.lib.extgen configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.extgen') Appending f2py.lib configuration to f2py Ignoring attempt to set 'name' (from 'f2py' to 'f2py.lib') F2PY Version 2_4422 Traceback (most recent call last): File "C:\Program Files\Python25\Lib\site-packages\numpy-1.0.4.0002- py2.5-win32.egg\numpy\f2py\setup.py", line 130, in **config) TypeError: setup() got multiple values for keyword argument 'version' Version (as printed out to be "2_4422") doesn't look like to be multiple value as the message says... I have tried different machine with different python version installation (2.5, 2.4) and also searched the forum without finding my answer. Is there anybody out there so kind as to help me with this? Thanks... /Ben From arnodel at googlemail.com Mon Nov 3 13:44:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 03 Nov 2008 18:44:19 +0000 Subject: Replacing cmp with key for sorting References: <35eff91d-d317-4d24-b61a-fbeeb44e1d99@a29g2000pra.googlegroups.com> Message-ID: George Sakkis writes: > I want to sort sequences of strings lexicographically but those with > longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd', > 'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb', > 'bc', 'bd']. Currently I do it with: > > s.sort(cmp=lambda x,y: 0 if x==y else > -1 if x.startswith(y) else > +1 if y.startswith(x) else > cmp(x,y)) > > Can this be done with an equivalent key function instead of cmp ? Here's an idea: >>> sorted(s, key=lambda x: x+'z'*(3-len(s))) ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] The 3 above is the length of the longest string in the list Here's another idea, probably more practical: >>> sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] HTH -- Arnaud From leon.san.email at gmail.com Sun Nov 9 09:40:23 2008 From: leon.san.email at gmail.com (r3bol) Date: Sun, 9 Nov 2008 06:40:23 -0800 (PST) Subject: break up a value in a list to a list of individual items References: Message-ID: <2c9068e4-98cf-46f2-8a44-fcba055fc20f@p35g2000prm.googlegroups.com> thanks :) and so many different ways! From thomas at mlynarczyk-webdesign.de Tue Nov 18 18:20:11 2008 From: thomas at mlynarczyk-webdesign.de (Thomas Mlynarczyk) Date: Wed, 19 Nov 2008 00:20:11 +0100 Subject: Generators and their next() and send() methods In-Reply-To: <4d30a5db-69b8-4e6a-92ba-a4267fc3df8d@s9g2000prm.googlegroups.com> References: <4d30a5db-69b8-4e6a-92ba-a4267fc3df8d@s9g2000prm.googlegroups.com> Message-ID: Aaron Brady schrieb: > And, if you don't intend to use 'myway' on 'listiterator's and such, > 'send( None )' is equivalent to 'next( )'. I didn't know that. But doesn't that impose a restriction somehow? It makes it impossible to send a None to a generator. Greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux ? avoir tort qu'ils ont raison! (Coluche) From joe at strout.net Fri Nov 14 16:49:00 2008 From: joe at strout.net (Joe Strout) Date: Fri, 14 Nov 2008 14:49:00 -0700 Subject: duck-type-checking? In-Reply-To: <76c7f0b7-f256-4ffe-8711-1b81cd06a0ac@s1g2000prg.googlegroups.com> References: <2b6000bf-fd9a-4330-be33-3a798a7ca387@z6g2000pre.googlegroups.com> <012ceefc$0$20662$c3e8da3@news.astraweb.com> <5828ef60-66df-4bb0-9a7d-aa08490f9e49@40g2000prx.googlegroups.com> <39d83435-5304-4be2-9dfe-c50f70eb4b6a@d10g2000pra.googlegroups.com> <76c7f0b7-f256-4ffe-8711-1b81cd06a0ac@s1g2000prg.googlegroups.com> Message-ID: <5897590C-ED96-47CD-94AF-DF13F07468B0@strout.net> On Nov 14, 2008, at 2:07 PM, Paul McGuire wrote: > Or to be even more thorough: > def sub(x: must have getitem, y: must have strip and strip must be > callable, and y.strip must return something that has replace and > replace must be callable) > > So even this simple example gets nasty in a hurry, let alone the OP's > case where he stuffs y into a list in order to access it much later, > in a completely different chunk of code, only to find out that y > doesn't support the complete string interface as he expected. Very true. That's why I think it's not worth trying to be too pure about it. Most of the time, if a method wants a Duck, you're going to just give it a Duck. However, I would like to also handle the occasional case where I can't give it a Duck, but I can give it something that is a drop-in substitute for a Duck (really, truly, I promise, and if it blows up I'll take responsibility for it). A real-world example from another language (sorry for that, I've been away from Python for ten years): in REALbasic, there is a Database base class, and a subclass for each particular database backend (Postgres, MySQL, whatever). This works fine most of the time, in that you can write general code that takes a Database object and Does Stuff with it. However, all of those database backends are shipped by the vendor, or by plugin authors -- you can't create a useful Database subclass yourself, in RB code, because it has a private constructor. So you end up making your own database class, but that can't be used with all the code that expects a real Database object. Of course, the framework design there is seriously flawed (Database should have been an interface, or at the very least, had a protected rather than private constructor). And in Python, there's no way to prevent subclassing AFAIK, so this particular issue wouldn't come up. But I still suspect that there may be times when I don't want to subclass for some reason (maybe I'm using the Decorator or Adapter or Bridge pattern). Yet I'm willing to guarantee that I've adhered to the interface of another class, and will behave like it in any way that matters. So, the level of assertion that I want to make in a method that expects a Duck is just that its parameter is either a Duck, or something that the caller is claiming is just as good as a Duck. I'm not trying to prevent any possible error; I'm trying to catch the stupid errors where I inadvertently pass in something completely different, not duck-like at all (probably because some other method gave me a result I didn't realize it could produce). So things like this should suffice: # simple element assert(is_stringlike(foo)) assert(is_numeric(foo)) assert(is_like(foo, Duck)) # sequence of elements assert(seqof_stringlike(foo)) assert(seqof_numeric(foo)) assert(seqof_like(foo, Duck)) # (also "listof_" variants for asserting mutable sequence of whatever) # dictionary of elements assert(dictof_like(foo, str, int)) Hmm, I was already forced to change my approach by the time I got to checking dictionaries. Perhaps a better formalism would be a "like" method that takes an argument, and something that indicates the desired type. This could be a tree if you want to check deeper into a container. Maybe something like: assert(fits(foo, dictlike(strlike, seqlike(intlike)))) which asserts that foo is something dictionary-like that maps string- like things to something like a sequence of integer-like things. Most cases would not be this complex, of course, but would be closer to assert(fits(foo, strlike)) But this is still pretty ugly. Hmm. Maybe I'd better wait for ABCs. :) Cheers, - Joe From pavlovevidence at gmail.com Sun Nov 30 03:01:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Nov 2008 00:01:28 -0800 (PST) Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> Message-ID: On Nov 29, 3:31?pm, Lie wrote: > Python's learning > curve shouldn't raise with time, it should get lower so more people > can join in the board. print function should give a newbie less to learn than a print statement, since statements have their own syntax (and the print statement had lots of peculiarities), whereas all function calls follow the same syntax. Carl Banks From lsumnler at gmail.com Fri Nov 14 23:25:39 2008 From: lsumnler at gmail.com (len) Date: Fri, 14 Nov 2008 20:25:39 -0800 (PST) Subject: Little direction please Python MySQL References: <35531549-3359-4e83-97f1-acd3f965db7e@x16g2000prn.googlegroups.com> <491d5093$0$9616$426a74cc@news.free.fr> Message-ID: <729c4379-bd14-4f9e-8918-cbf0e6fdf972@r37g2000prr.googlegroups.com> On Nov 14, 4:19?am, Bruno Desthuilliers wrote: > len a ?crit : > > > > > > > Hi all; > > > I am looking for a little direction in moving from novice python MySQL > > to real world processing. > > > I can connect to MySQL databases and have performed most of the > > various select, create, update, insert, etc given the examples in the > > various books and internet tutorials not to many problems. > > > Here is my problem. ?I need to start doing this in the really world at > > my company converting some older cobol system and data to python > > programs and MySQL. ?I have gotten past packed decimal fields and > > various other little tidbits. ?My problem is the data files aren't > > little three of four field files but Customer File with 98 fields > > etc. ?I understand building dictionaries and building with zip and I > > have even seen a reference to using __setattr__ in an empty class but > > I'm having a hard time moving past the little code snippts to real > > code. > > > As you can image the data coming from old cobol files fieldname are > > generally very large and tons of code that might start looking like; > > > ? ? ?order['ordhdr_sales_amount'] += order['ordlin_sales_qty'] * order > > ['ordlin_sales_price'] > > > could start becoming quite cumbersum. > > > I'm sure that there is someway to make all of this less verbose using > > classes and such but I need some direction. > > You may want to have a look at SQLAlchemy. It will require some > additional learning, but chances are you'll waste less time than trying > to roll your own half-backed ORM-like system. > > My 2 cents... I haved looked at SQLAlchemy and will start using it. I do feel that I need to hand code a few things just to get and understanding of whats involved. I find that this usually making the package a little easier to use and generally makes me a better user of the package or at least it has in the past. Len From ldo at geek-central.gen.new_zealand Thu Nov 6 23:09:28 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 07 Nov 2008 17:09:28 +1300 Subject: Can read() be non-blocking? References: Message-ID: In message , Lawrence D'Oliveiro wrote: > In message , Thomas > Christensen wrote: > >> r = select.select([proc.stdout.fileno()], [], [], 5)[0] >> if r: >> # NOTE: This will block since it reads until EOF >> data = proc.stdout.read() > > No, it will read what data is available. Sorry, maybe not. But you can set O_NOBLOCK on the fd. From steven at REMOVE.THIS.cybersource.com.au Mon Nov 10 04:52:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Nov 2008 09:52:04 GMT Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <01264714$0$20668$c3e8da3@news.astraweb.com> <6no8p6Fm8q70U1@mid.uni-berlin.de> <6nod8uFmk1blU1@mid.uni-berlin.de> Message-ID: On Sun, 09 Nov 2008 10:45:31 -0500, Roy Smith wrote: > As another example, consider a list of items being juggled: > > [RubberChicken(), ChainSaw(), Canteloupe()] > > I could go through contortions to find some common subclass for these > items, but the whole *point* is that they're not of the same type. And > making a list of them is a perfectly reasonable thing to do. Absolutely, and Python 3 does not prevent you from making a list of them. However, sorting them is *not* a reasonable thing to do, just like summing them is not a reasonable thing to do, and Python 3 does prevent you from sorting (or summing) them without extra work. If you've been relying on Python 2.x's "take a guess and hope it works" heuristic for sorting uncomparable types, this will come across as a nuisance. Sorry. I'm afraid you only have two choices in Python 3: (1) find some way to avoid sorting such data; or (2) bite the bullet and spend the time required to define your own ordering relationships between types. After all, you can sort by *anything* once you give Python an appropriate key function. -- Steven From steven at REMOVE.THIS.cybersource.com.au Wed Nov 12 21:32:59 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 13 Nov 2008 02:32:59 GMT Subject: duck-type-checking? References: Message-ID: On Wed, 12 Nov 2008 08:06:31 -0700, Joe Strout wrote: > Let me preface this by saying that I think I "get" the concept of duck- > typing. > > However, I still want to sprinkle my code with assertions that, for > example, my parameters are what they're supposed to be -- too often I > mistakenly pass in something I didn't intend, and when that happens, I > want the code to fail as early as possible, so I have the shortest > possible path to track down the real bug. I'm surprised nobody has pointed you at Alex Martelli's recipe here: http://code.activestate.com/recipes/52291/ While the recipe is great, it can be tiresome to apply all the time. I would factor out the checks into a function, something like this: def isstringlike(obj, methods=None): """Return True if obj is sufficiently string-like.""" if isinstance(obj, basestring): return True if methods is None: methods = ['upper', 'lower', '__len__', '__getitem__'] for method in methods: if not hasattr(obj, method): return False # To really be string-like, the following test should pass. if len(obj) > 0: s = obj[0] if s[0] != s: return False return True -- Steven From rocco.rossi at gmail.com Mon Nov 24 14:51:39 2008 From: rocco.rossi at gmail.com (Rock) Date: Mon, 24 Nov 2008 11:51:39 -0800 (PST) Subject: No complex rationals in Python 3.0 References: <7ce12916-fd9b-44d4-a511-5b48099441d3@j39g2000yqn.googlegroups.com> Message-ID: <2291081f-edae-4d57-8136-489edfaf1651@w34g2000yqm.googlegroups.com> On 24 Nov, 20:31, Christian Heimes wrote: > Rock wrote: > > I appreciate the inclusion of the fractions module in Python 2.6 and > > therefore in Python 3.0. But I feel there's something missing: no > > possibility for complex rationals (or arbitrary precision) integers. I > > was just checking the complex number support in Python, compared, for > > instance, to Common Lisp and Scheme, and I realized that there was > > this subtle omission. The inclusion of rationals and arbitrary > > integers is cool, but the numeric tower (say, compared to Scheme) is > > not complete. I don't think there would be a performance hit if > > complex rationals were provided. Ordinary operations on complex > > floats, in theory, should not be affected and handled separately. But > > it would be nice to be able to do: > > > (3/4 + 1/2j) * (1/4 - j) = 11/16 - 5/8j > > > with no loss of precision. > > > Python is heavily used in math and science all over the world. We've > > even got a recent symbolic math project (sympy) that looks very > > promising, so I guess this could be an important issue. > > Nobody has submitted a PEP and patch to implement the feature in time. > There is still Python 3.1, you know? If you like to contribute the > feature then please start a discussion on the Python Ideas mailing list > (not the developer lists!). > > > Note: there exists a library that implements what I'm talking about: > >http://calcrpnpy.sourceforge.net/clnum.html > > but still I personally would have liked to see this stuff included > > natively in the new Python 3.0. > > The code depends on the CLN library which isn't suited for the Python > core. It's written in C++ and it's licensed under GPL. Neither GPL nor > LGPL software can't be integrated into the core. We also require all > code to be compatible with C89. > > Christian Thanks Christian, will do so as soon as possible. Rock From google at mrabarnett.plus.com Tue Nov 4 18:49:45 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 4 Nov 2008 15:49:45 -0800 (PST) Subject: split() and string.whitespace References: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> <6n12pcFj5ggvU3@mid.uni-berlin.de> <13599bc9-034d-4a04-99f0-138d33f0d84a@o40g2000prn.googlegroups.com> Message-ID: <373aee8a-798f-4060-9404-3701038ad0eb@l33g2000pri.googlegroups.com> On Nov 4, 8:00?pm, bearophileH... at lycos.com wrote: > MRAB: > > > It's interesting, if you think about it, that here we have someone who > > wants to split on a set of characters but 'split' splits on a string, > > and others sometimes want to strip off a string but 'strip' strips on > > a set of characters (passed as a string). > > That can be seen as a little inconsistency in the language. But with > some practice you learn it. > > > You could imagine that if > > Python had had (character) sets from the start then 'split' and > > 'strip' could have accepted a string or a set depending on whether you > > wanted to split on or stripping off a string or a set. > > Too bad you haven't suggested this when they were designing Python > 3 :-) > This may be suggested for Python 3.1. > I might also add that str.startswith can accept a tuple of strings; shouldn't that have been a set? :-) I also had the thought that the backtick (`), which is not used in Python 3, could be used to form character set literals (`aeiou` => set("aeiou")), although that might only be worth while if character sets were introduced as an specialised form of set. From jhofmo at hotmail.com Sat Nov 29 15:44:32 2008 From: jhofmo at hotmail.com (Josh) Date: Sat, 29 Nov 2008 12:44:32 -0800 Subject: Quick Newbie Question In-Reply-To: References: Message-ID: alex23 wrote: > On Nov 29, 5:09 pm, Josh wrote: >> Can Python be used on one Linux machine to drive another Linux machine >> through SSH? I am currently running Putty on my XP box to run tests on a >> Linux box. I need to automate these tests and thought it would be fun to >> do so from a Linux VMWare Image I recently setup. Does this sound >> do-able without too much effort? I already know the Linux commands I >> need to run but just need an interactive shell connection through SSH. >> Again is Python a good choice for this or something else? >> Thanks, > > For something like this, I'd probably use Pexpect: > > http://www.noah.org/wiki/Pexpect#Overview Cool, thanks I'll check it out. From fuzzyman at gmail.com Sat Nov 29 10:44:45 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 29 Nov 2008 07:44:45 -0800 (PST) Subject: double import protection - how to ? References: <49313901$0$2854$ba620e4c@news.skynet.be> <49316253.5010701@skynet.be> Message-ID: <09a6b30d-a6bf-431d-854c-b4b05ca66c36@g38g2000yqd.googlegroups.com> On Nov 29, 3:40?pm, Helmut Jarausch wrote: > Peter Otten wrote: > > Helmut Jarausch wrote: > > >> I have a module which gets imported at several different places > >> not all of which are under my control. > > >> How can I achieve that ?all/some statements within that module > >> get executed only at the very first import? > > > What you describe is Python's default behaviour. A module is executed once > > and then cached in sys.modules. The second import is then just a cache > > lookup. > > > This may only fail if a module is imported under different names, typically > > when you have directory ?in sys.path that is part of a package, or when you > > import the main script. > > > Peter > > Thanks Steven, thanks Peter. > > Then it's a problem with a problem with a webserver written in Python (Karrigell-3.0) > and probably related to multi-threading (the statements in my module get definitely > executed more than once). > Python has an import lock - so multi-threaded code simultaneously executing import statements only do the initial import once. Michael Foord > Thanks for your help, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany -- http://www.ironpythoninaction.com/ From sjmachin at lexicon.net Sun Nov 9 21:39:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Nov 2008 18:39:48 -0800 (PST) Subject: parsing non-ascii characters References: Message-ID: <889dfd9d-9117-48ad-a747-c75a7d643723@e38g2000prn.googlegroups.com> On Nov 10, 1:13?pm, Ronn wrote: > Hello all, > > I have a list: > ? suffix = ["a?", "ad", "a?", "an", "ar"] > > and I'm trying to check a word to see if any of the suffixes exist in > the list for example: > ? if word in suffix: > ? ? ? print "A suffix exist in your word" > > when I run this it give me an error: > ? ?SyntaxError: Non-ASCII character '\xc5' in file vortaro.py on line > 33, but no encoding declared; Read this: http://docs.python.org/tutorial/interpreter.html#source-code-encoding Read all of the tutorial. > is there a way to parse Non-ASCII characters in python? This question is meaningless. From clp at rebertia.com Tue Nov 11 04:20:05 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 11 Nov 2008 01:20:05 -0800 Subject: [Newbie] Strange output from list In-Reply-To: <02iih4p0c3c9lti5m9t3g0oan4t3lul0qm@4ax.com> References: <87wsfbca4p.fsf@benfinney.id.au> <02iih4p0c3c9lti5m9t3g0oan4t3lul0qm@4ax.com> Message-ID: <47c890dc0811110120g328c6915ndeaeaaa107729142@mail.gmail.com> On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault wrote: > On Mon, 10 Nov 2008 20:02:39 -0600, Andrew wrote: >>sql = 'SELECT id FROM master' >>rows=list(cursor.execute(sql)) >>for id in rows: >> sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0] >> result = list(cursor.execute(sql)) >> print "Code=%s, number=%s" % (id[0],result[0][0]) Using liberal "term rewriting", consider the following rough equivalencies in the code: id[0] <==> rows[INDEX_HERE][0] <==> list(cursor.execute(sql))[INDEX_HERE][0] result[0][0] <==> list(cursor.execute(sql))[0][0] Note that in both cases, the list is sliced twice; the for-loop just conceals the `[INDEX_HERE]` implicit slicing that is caused by iterating over the list. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com >>Notice the extra [0] index on the "result" >> >>In English: >>Item zero of the tuple that is item zero of result > > Thanks, it worked. But why does "id[0]" return the value of the first > (and only) column as I expected it, while I need to use "result[0] > [0]" to access the first column? > -- > http://mail.python.org/mailman/listinfo/python-list > From saluk64007 at gmail.com Fri Nov 7 19:14:19 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 7 Nov 2008 16:14:19 -0800 Subject: using exec() to instantiate a new object. In-Reply-To: <6cffedba-b69e-4029-ad4d-aa50d7e8af9c@q26g2000prq.googlegroups.com> References: <6cffedba-b69e-4029-ad4d-aa50d7e8af9c@q26g2000prq.googlegroups.com> Message-ID: On Fri, Nov 7, 2008 at 2:23 PM, RyanN wrote: > > to do this I tried: > > def addCountry(self,country_name): > # create an instance of country > exec(country_name + "= country('" + country_name + "')") > # Add this new instance of a country to a list > exec("self.countries.append(" + country_name + ")") > Don't use exec. It's quite dangerous, and in your case is making things much more complex than necessary. A much simpler way to do what you want: def addCountry(self,country_name): self.countries.append(country(country_name)) There is no need to bind the result of "country(country_name)" to a name at all. From skip at pobox.com Mon Nov 3 09:07:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 3 Nov 2008 08:07:07 -0600 Subject: Simple textual calendar In-Reply-To: <8evtg4d7q4v7dd9hn40amb5utdgmda4dap@4ax.com> References: <8evtg4d7q4v7dd9hn40amb5utdgmda4dap@4ax.com> Message-ID: <18703.1419.758083.147340@montanaro-dyndns-org.local> ostra> It is an example which I've setted myself to try to solve to see ostra> how it would go. An even simpler solution is the cal command on Unix systems: % cal 2009 2009 Jan Feb Mar S M Tu W Th F S S M Tu W Th F S S M Tu W Th F S 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7 4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14 11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21 18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28 25 26 27 28 29 30 31 29 30 31 Apr May Jun S M Tu W Th F S S M Tu W Th F S S M Tu W Th F S 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 Jul Aug Sep S M Tu W Th F S S M Tu W Th F S S M Tu W Th F S 1 2 3 4 1 1 2 3 4 5 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12 12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19 19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 30 31 Oct Nov Dec S M Tu W Th F S S M Tu W Th F S S M Tu W Th F S 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 25 26 27 28 29 30 31 29 30 27 28 29 30 31 :-) If you really want to write something yourself take a look at the datetime module. Here's a trivial (untested) example: import datetime date = datetime.datetime(2009, 1, 1) end = datetime.datetime(2010, 1, 1) oneday = datetime.timedelta(days=1) while date < end: print date.date() date += oneday Correctness, formatting and efficiency are left as an exercise for the reader. ;-) -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From tjreedy at udel.edu Thu Nov 27 18:47:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Nov 2008 18:47:18 -0500 Subject: Exhaustive Unit Testing In-Reply-To: References: <8ae042c1-9a6c-412a-83f6-92b1d58e1ce5@j32g2000yqn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Emanuele D'Arrigo: >> I can fragment the code of the original method into one public method and a few private support methods.< > > Python also support nested functions, that you can put into your > method. The problem is that often unit test functions aren't able to > test nested functions. > > > A question for other people: Can Python change a little to allow > nested functions to be tested? I think this may solve some of my > problems. The problem is that inner functions do not exist until the outer function is called and the inner def is executed. And they cease to exist when the outer function returns unless returned or associated with a global name or collection. A 'function' only needs to be nested if it is intended to be different (different default or closure) for each execution of its def. From callen314 at gmail.com Mon Nov 3 18:46:31 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 3 Nov 2008 15:46:31 -0800 (PST) Subject: PYTHON WORKING WITH PERL ?? References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> Message-ID: <36db1f5b-58e6-478c-bd5a-5c2260e1bc56@v22g2000pro.googlegroups.com> > article:http://www.linuxjournal.com/article/3882 interesting read, thanks From ldo at geek-central.gen.new_zealand Mon Nov 17 03:11:43 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 17 Nov 2008 21:11:43 +1300 Subject: Newbie code review of parsing program Please References: Message-ID: Mark Tolonen wrote: > Point taken...or I could top post ;^) A: A Rolls seats six. Q: What's the saddest thing about seeing a Rolls with five top-posters in it going over a cliff? From Scott.Daniels at Acm.Org Tue Nov 18 18:15:21 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 18 Nov 2008 15:15:21 -0800 Subject: Best practise hierarchy for user-defined exceptions In-Reply-To: References: <1febc4fb-81dd-4b3b-b886-520442626c3d@u29g2000pro.googlegroups.com> Message-ID: Nick Craig-Wood wrote: > Slaunger wrote: >> .... I will not notice that it was an unanticpated condition >> in my own code, which caused the ValueError to be raised. >> If I had just inherited from MyError, it would fall through.... > > I'd say if the above code worries you, then MyParseError isn't a > ValueError and you shouldn't inherit from ValueError. Just from the name, I'd look into making MyParseError inherit from SyntaxError. --Scott David Daniels Scott.Daniels at Acm.Org From pavlovevidence at gmail.com Sat Nov 1 10:04:35 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 Nov 2008 07:04:35 -0700 (PDT) Subject: Simplifying anonymous inner classes? References: Message-ID: On Nov 1, 8:13?am, Tim Chase wrote: > I've got code similar to the following > > ? class Action: > ? ? def __init__(self, ...): ?pass > ? ? def __call__(self, ...): ?pass > ? ? def get_help(self, ...): ?pass > > ? class Backend: > ? ? class _Load(Action): > ? ? ? def __init__(self, ...): pass # override1 > ? ? ? def __call__(self, ...): pass # override1 > ? ? ? def get_help(self, ...): pass # override1 > ? ? load = _Load(...) > ? ? class _Run(Action): > ? ? ? def __call__(self, ...): pass # override2 > ? ? ? def get_help(self, ...): pass # override2 > ? ? run = _Run(...) > [snip] > Is there a more Pythonic way to instantiate sub-classes and > provide instance-specific implementations without the overhead of > an unused "anonymous" class cluttering my code/namespace? Just delete the names after instantiating the class: del _Load del _Run I'm not trying to be snarky, sometimes the straightforward way is the best. I like Peter Otten's class decorator solution to this also, and disagree that such complexity is necessarily unPythonic. If you do it a lot the complexity could result in an overall simplification. It's not something you want to casually throw at users, though. A way to do this in 2.5 and below is to use a class hook (using __metaclass__ attribute): def self_instantiate(name,bases,clsdict): cls = type.__new__(type,name+"_type", bases,clsdict) obj = cls() return obj class load(Action): __metaclass__ = self_instantiate .... Carl Banks From almar.klein at gmail.com Tue Nov 4 10:31:14 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 4 Nov 2008 16:31:14 +0100 Subject: Which was the best Lib of GUI for python In-Reply-To: References: Message-ID: Hi, If you search the newsgroup you'll find loads of similar posts. There is not really an agreement on which GUI library is "the one". Tkinter is a bit limited. Personally, I only have experience with wxpython and like it a lot. But there are others like GTK, FLTK, QT. Cheers, Almar 2008/11/4 3000 billg : > Hi Guy, > I am a leaner. for your experience. Which GUI Lib will be the best for > Python? wxpython, Tkinter or... > > -- > http://mail.python.org/mailman/listinfo/python-list > > From gardsted at yahoo.com Mon Nov 3 04:14:20 2008 From: gardsted at yahoo.com (gardsted) Date: Mon, 03 Nov 2008 10:14:20 +0100 Subject: How to make money with Python! In-Reply-To: References: Message-ID: <490ec0ea$0$90273$14726298@news.sunsite.dk> Grant Edwards wrote: > On 2008-10-31, Duncan Booth wrote: >> If that subject line didn't trip everyone's killfiles, see >> http://pythonide.blogspot.com/2008/10/how-to-make-money-with-free-software.html >> for a fantastic story involving Python. > > Doh! The very clever pun went right past me several times > before I finally caught on (with some help from a poster on /.) > beautiful work of art From wuwei23 at gmail.com Thu Nov 27 20:13:43 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 27 Nov 2008 17:13:43 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <47d07a0a-7b76-42ce-9d49-85e3743ad28d@w34g2000yqm.googlegroups.com> <924805b6-39e4-46b3-8237-f38450f084e6@v4g2000yqa.googlegroups.com> Message-ID: <7771f706-b394-4a07-ac45-1aa0d063be7d@t39g2000prh.googlegroups.com> On Nov 28, 10:09?am, r wrote: > Are you against promoting python? > > Maybe your a Ruby fan, i don't know, but that > would explain your quick disposal of the idea though. Are you intending to come off so patronising? To angrily dismiss someone who has been posting some solid help in this group for the past three months doesn't do your position any favours. There's advocacy and then there's rabid fanboyism.... > -food for thought- Here's something a little more substantial for you to consider: put up or shut up. Create a thin layer that brokers Python requests through to the Ruby interface for SketchUp. Gain support for this approach. Prove how many people are interested in using the Python aspect. Show you're not expecting someone else to bear all the effort. Do something more constructive than post wishful fantasies and snide cutdowns to a mailing list. Stop proclaiming how great Python is and start developing solutions that demonstrate it. From lolekk1444 at wp.pl Fri Nov 28 19:19:51 2008 From: lolekk1444 at wp.pl (I'mSoSexy) Date: Fri, 28 Nov 2008 16:19:51 -0800 (PST) Subject: Sexy girl Webcam erotic show NEW Message-ID: <58683a32-e634-4cb8-95e5-ba9efe2b8a17@41g2000yqf.googlegroups.com> http://yeba.pl/show/movies/5243/Webcam_show http://yeba.pl/show/movies/5244/Webcam_Sexy_show From torf at torfbold.com Fri Nov 14 08:16:11 2008 From: torf at torfbold.com (Florian Brucker) Date: Fri, 14 Nov 2008 14:16:11 +0100 Subject: Clustering the keys of a dict according to its values Message-ID: <491d6b57$0$32671$9b4e6d93@newsspool2.arcor-online.net> Hi everybody! Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: >>> d = {'a':1, 'b':2, 'c':1, 'd':1, 'e':2, 'f':3} >>> cluster(d) {1:['a', 'c', 'd'], 2:['b', 'e'], 3:['f']} That is, generate a new dict which holds for each value of the old dict a list of the keys of the old dict that have that very value. Another requirement is that it should also work on lists, in that case with indices instead of keys. We may assume that all values in the original dict/list can be used as dict keys. Right now I'm doing it like this: def cluster(d): try: # is d a dict? values = unique(d.values()) keys = d.keys() except AttributeError: # assume d is a list values = unique(d) keys = range(len(d)) clusters = {} for value in values: clusters[value] = filter(lambda v: d[v] == value, keys) return clusters where unique() is from O'Reilly's Python Cookbook and returns a list containing each item of the given list exactly once. Now I'm pretty new to Python and chances are rather high that this could be done prettier and/or more efficient. Therefore any comment on the above code is greatly appreciated. Regards, Florian From davidgshi at yahoo.co.uk Thu Nov 6 12:57:23 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Thu, 6 Nov 2008 17:57:23 +0000 (GMT) Subject: Looking for a nitty-gritty Python Ajax middleware script to fire off a number of processors Message-ID: <553465.82301.qm@web26305.mail.ukl.yahoo.com> Dear All, ? I am looking for a nitty-gritty Python Ajax script to fire off a number of processing programmes, periodically checking their operations, sending messages back to an HTML div form by sending back the links of generated data files, to be downloaded by end users. ? I am using .NET IIS 6.0 and Windows Server. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From news123 at free.fr Tue Nov 25 18:16:36 2008 From: news123 at free.fr (News123) Date: Wed, 26 Nov 2008 00:16:36 +0100 Subject: checking for mis-spelled variable names / function names Message-ID: <492c8754$0$8400$426a74cc@news.free.fr> Hi, Let's imagine following code def specialfunc(): print "very special function" name= getuserinput() if name == 'one_name_out_of_a_million': print "Hey your name '%s' is really rare" % namee specialfunk() my python script could survive thousands of runs before falling into the mis-spelled code section. ('namee' instead of 'name' and 'specialfunck()' instead of 'specialfunc()' I know that good designers should always test their code and have complete code coverage, before releasing their beasts into the wild, but in my experience this is not always what happens. I fell already over quite of my own sins, but also over typoes of other python authors. Is there any way in python to check for mis-spelled variable / function names? In perl for example 'use strict;' would detect bad variable names, though it wouldn't detect calls to undeclared functions. I am aware, that there is absolutely valid (and useful) python code with undefined functions / variable names. However for the scripts that I write I would prefer to identify as many typoes as possibe already when trying to run the script the first (and not the millionth) time. Do you have ideas suggestions? Are there any 'lint' like tools trying to analyze python code for potential stupidities? If yes, what would be 'the' way to add these tools / modules at )least during the development cycle) to the scripts. thanks in advance for any thoughts / suggestions. bye N From dfnsonfsduifb at gmx.de Mon Nov 17 04:30:07 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Mon, 17 Nov 2008 10:30:07 +0100 Subject: Python3 - it's awesome Message-ID: Hello list, since I've read so much about Python 3 and ran into some trouble which was supposed to be fixed with 3k, I yesterday came around to compile it and try it out. To sum it up: It's awesome. All the promised things like Unicode support "just work", all significant changes in the lanugage (try/except-Syntax, float division, file opening, print) I've encountered so far made absolute sense and it was quite easy to change over (I've been using 2.5 so far). It was really easy to install it locally as my user (I want to try it out some more before I install it system-wide). So, why I am posting this here: First, thanks to the great work to anyone who has contributed. Secondly, I want to encourage anyone who hasn't tried Python3 out yet to do - it really is easier than you think and you won't be disappointed. Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From nospam at nospam.com Tue Nov 4 14:26:00 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 04 Nov 2008 20:26:00 +0100 Subject: Building loop with some exceptions? References: <0v71h4tsf30aodpjs46rfevgp3of8h73ps@4ax.com> <9d63bcb8-1aac-4d46-8e0b-3ebc86214faf@u18g2000pro.googlegroups.com> Message-ID: On Tue, 4 Nov 2008 11:22:27 -0800 (PST), Aaron Brady wrote: >> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89: > >sorted( list( set( domain ) - set( exceptions ) ) ) > >Set subtraction. Thanks a lot but... I don't know what the above means :-/ From castironpi at gmail.com Mon Nov 17 01:52:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 16 Nov 2008 22:52:54 -0800 (PST) Subject: Optional parameter object re-used when instantiating multiple objects References: <656e29da-591e-4240-88ca-58d6868257fc@k36g2000pri.googlegroups.com> <012fbb65$0$20662$c3e8da3@news.astraweb.com> <13851643-6290-49b4-b417-b751e5e42425@k1g2000prb.googlegroups.com> Message-ID: <53cadceb-158f-41a7-82a9-91e1d0e2a01d@d36g2000prf.googlegroups.com> On Nov 16, 8:16?pm, Aaron Brady wrote: > On Nov 16, 12:52?am, Steven D'Aprano > I've given practical reasons why the > > Python choice is better. If you want default argument to be created from > > scratch when the function is called, you can get it with little > > inconvenience, but the opposite isn't true. It is very difficult to get > > static default arguments given a hypothetical Python where default > > arguments are created from scratch. There's no simple, easy idiom that > > will work. The best I can come up with is a convention: > > I'm not so sure. > > ## Default evaluated at definition time. ?(Current.) > > # Static arg. > def f( a= [] ): > ? ... > > # Non-static arg. > def f( a= None ): > ? if a is None: a= [] Oops. Forgot one, after the subsequent posts. # Non-static arg. @nonstatic( a= list ) def f( a ): ... This can achieve the 'if a is None' effect. 'nonstatic' takes a callable or a string, '@nonstatic( a= "[]" )'. I don't see a way to achieve George Sakkis's example: if y is None: y = x*x if z is None: z = x+y Without a change to the language (the other options don't need one). #emulates 'def foo(x, y=`x*x`, z=`x+y`):' @nonstatic( y= 'x*x' ) #illegal @nonstatic( z= 'x+y' ) #illegal def foo(x, y, z): return x+y+z From clp at rebertia.com Thu Nov 6 15:33:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 6 Nov 2008 12:33:41 -0800 Subject: List to Text back to List In-Reply-To: <534a6647-b16b-4be4-ae18-93f2acb26831@v13g2000pro.googlegroups.com> References: <534a6647-b16b-4be4-ae18-93f2acb26831@v13g2000pro.googlegroups.com> Message-ID: <47c890dc0811061233g641feeb7h70e03ca99a84942e@mail.gmail.com> On Thu, Nov 6, 2008 at 12:18 PM, SimonPalmer wrote: > On Nov 6, 8:11 pm, "Chris Rebert" wrote: >> On Thu, Nov 6, 2008 at 12:04 PM, SimonPalmer wrote: >> > Hi, I am looking for a way to convert a List of floating point numbers >> > to and from text. I am embedding it in an XML document and am looking >> > for a neat way to serialise and de-serialise a list from a text node. >> > I can easily write something to do it manually but I wondered whether >> > List had native support to go to and from text. >> >> > If not List, are there any other collections/arrays that do this? >> >> It's not really a matter of the collection, but more a matter of >> serialization format/library. >> >> If you want the serialized representation to be human-readable, use >> JSON (http://docs.python.org/library/json.html#module-json). >> If that's not a requirement, use pickle >> (http://docs.python.org/library/pickle.html#module-pickle). >> Both modules can convert simple Python data, such as your list of >> floats, to a bytestream and back again. >> >> Cheers, >> Chris >> -- >> Follow the path of the Iguana...http://rebertia.com >> >> >> >> > TIA >> > Simon >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> > > I looked at pickle, but the problem is that I want my XML to be > readable by languages other than python, so it sort of precludes it. > JSON would be perfect, but I think the module only exists in 2.6, is > that right? Unfortunately I am bound to 2.4. > > It is looking more and more like I am going to have to roll my own. The module is available as a third-party library for previous Python versions at http://www.undefined.org/python/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From has.temp3 at virgin.net Thu Nov 27 19:19:43 2008 From: has.temp3 at virgin.net (has) Date: Thu, 27 Nov 2008 16:19:43 -0800 (PST) Subject: [ann] Python appscript 0.19.0 (beta 1) released Message-ID: <81548c13-d8b2-4e98-8faa-3e50a56d4c36@j32g2000yqn.googlegroups.com> Announcing the first beta release of appscript for Python 2.x, a user- friendly Apple event bridge that allows you to control AppleScriptable applications using ordinary Python scripts. Py-appscript 0.19.0 adds Python 2.6 compatibility and 64-bit support, and cleans up the codebase and documentation in preparation for the final 1.0 release. More information, including a list of changes from the previous 0.18.1 distribution, can be found on the appscript website: http://appscript.sourceforge.net/py-appscript/index.html File releases can be downloaded from the Python Package Index: http://pypi.python.org/pypi/appscript A Python 3.x-compatible version is currently under development; see the appscript website for details. From george.sakkis at gmail.com Fri Nov 28 09:49:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 28 Nov 2008 06:49:34 -0800 (PST) Subject: Great exercise for python expert ! References: <9138e8c8-136a-4ac0-a1a4-dbf0469507e7@h5g2000yqh.googlegroups.com> <6abd5bf1-f642-4592-9ec1-4248912226ff@j35g2000yqh.googlegroups.com> <3d7b3c32-0a9a-4b9a-8521-e7414e4022cd@g38g2000yqd.googlegroups.com> Message-ID: <2fbd31c9-1ebe-4e9b-be98-10cbea98fb08@w3g2000yqc.googlegroups.com> On Nov 28, 9:19?am, manatlan wrote: > On 28 nov, 14:58, George Sakkis wrote: > > > > > On Nov 28, 5:36?am, manatlan wrote: > > > > I'd like to make a "jquery python wrapper" ... > > > > here is my code : > > > =================================================================== > > > #!/usr/bin/env python > > > # -*- coding: utf-8 -*- > > > > class JQueryCaller(object): > > > ? ? def __init__(self,callback): > > > ? ? ? ? self.__callback=callback > > > ? ? ? ? self._s=[] > > > > ? ? def __getattr__(self,name): > > > ? ? ? ? def _caller(*args): > > > ? ? ? ? ? ? sargs=["'%s'"%i for i in args] > > > ? ? ? ? ? ? self._s.append("%s(%s)"%(name,",".join(sargs))) > > > ? ? ? ? ? ? return self > > > ? ? ? ? return _caller > > > > ? ? def __call__(self): > > > ? ? ? ? return self.__callback(".".join(self._s)) > > > > class MyObject(object): > > > ? ? def __init__(self): > > > ? ? ? ? self.js = JQueryCaller(self.__add) > > > > ? ? def __add(self,j): > > > ? ? ? ? print "Add:"+j > > > > if __name__ == "__main__": > > > ? ? o=MyObject() > > > > ? ? o.js.kiki(12).kuku()() > > > =================================================================== > > > If i run the script : it will display : > > > > Add:kiki('12').kuku() > > > > Because the JQueryCaller caller is called, by the "()" trick at the > > > end of the last line > > > > I'd like to display the same thing, but without the need to put the > > > "()" at then end ! > > > (by calling simply : "o.js.kiki(12).kuku()" not "o.js.kiki(12).kuku() > > > ()") > > > (or how to call the MyObject._add (callback) without using the caller > > > on my JQueryCaller) > > > Why don't you rename __call__ to __str__ and have MyObject.__add > > return a string instead of printing it directly? > > > class MyObject(object): > > ? ? def __add(self,j): > > ? ? ? ? return "Add:"+j > > > if __name__ == "__main__": > > ? ? o = MyObject() > > ? ? s = o.js.kiki(12).kuku() > > ? ? print s > > > HTH, > > George > > sure, it works like you said ... but it's not what I want. > by doing that, you create an action ... when you will call "print" it > will call the __str__ (__repr__ is better in that case), which will > call the callback of myobject. > In my preceding post, the action was called by the "()" trick at the > end of line ... which you apparently don't like, and rightly so. __getattr__ and __call__ do totally different things in your example, why do you want to conflate them ? > In fact, MyObject will handle a list of all "js call" > If i do : > ? o.js.toto() > ? o.js.toto().titi(12,13) > > I'd like my MyObject contains a list like that ["toto()","toto().titi > (12,23)"] Of course this still happens when you rename __call__ to __str__. > another idea ? Yes, put a little more thought on your design and give a more realistic example of what you're really trying to do; so far it seems more like a pointless hack. George From bearophileHUGS at lycos.com Mon Nov 24 14:25:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 24 Nov 2008 11:25:34 -0800 (PST) Subject: No complex rationals in Python 3.0 References: <7ce12916-fd9b-44d4-a511-5b48099441d3@j39g2000yqn.googlegroups.com> Message-ID: <723fc861-47df-44fa-b9b3-58ef5163d97e@f3g2000yqf.googlegroups.com> Rock: >so I guess this could be an important issue.< What they can be useful for? Bye, bearophile From multiseed at gmail.com Fri Nov 28 10:47:23 2008 From: multiseed at gmail.com (Shiao) Date: Fri, 28 Nov 2008 07:47:23 -0800 (PST) Subject: Unicode regex and Hindi language Message-ID: <7b3d0c69-5496-4c23-9689-66bfed419d84@23g2000pry.googlegroups.com> The regex below identifies words in all languages I tested, but not in Hindi: # -*- coding: utf-8 -*- import re pat = re.compile('^(\w+)$', re.U) langs = ('English', '??', '??????') for l in langs: m = pat.search(l.decode('utf-8')) print l, m and m.group(1) Output: English English ?? ?? ?????? None >From this is assumed that the Hindi text contains punctuation or other characters that prevent the word match. Now, even more alienating is this: pat = re.compile('^(\W+)$', re.U) # note: now \W for l in langs: m = pat.search(l.decode('utf-8')) print l, m and m.group(1) Output: English None ?? None ?????? None How can the Hindi be both not a word and "not not a word"?? Any clue would be much appreciated! Best. From thedsadude at gmail.com Sat Nov 22 12:22:12 2008 From: thedsadude at gmail.com (thedsadude at gmail.com) Date: Sat, 22 Nov 2008 09:22:12 -0800 (PST) Subject: Custom Formatting The Output Of subprocess.Popen References: <1fa5b276-cd38-44b4-ac79-0d85775a67e0@a12g2000yqm.googlegroups.com> Message-ID: > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thanks all for your help! Bye, TD From id.engg at gmail.com Thu Nov 6 09:57:24 2008 From: id.engg at gmail.com (I D) Date: Thu, 6 Nov 2008 09:57:24 -0500 Subject: Plz help..SocketServer UDP server losing lots of packets In-Reply-To: References: Message-ID: Hello James, Thanks for your response. But I cannot use a third party software, I need to use the exisiting API's within python. As I am new to python, I suspected that I should go by a simpler approach and so scrapped off the below code and wrote a very simple UDP server code as follows: logFileName = '/home/msat/gsc/logs/' + compNum + '/logparsertracedump.log' logfile = open(logFileName, "w") from socket import * host = "121.3.0.1" port = PORT buf = 4096 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.setsockopt(SOL_SOCKET, SO_RCVBUF, 8388608) UDPSock.bind(addr) while 1: data,addr = UDPSock.recvfrom(buf) if not fileExists(logFileName): logfile = open(logFileName, "a") logfile.writelines(data) # Close socket UDPSock.close() Even this seems to lose packets, I would really appreciate if any pointers can be provided to improve my code. Thanks, Sam On Wed, Nov 5, 2008 at 7:46 PM, James Mills wrote: > On Thu, Nov 6, 2008 at 9:53 AM, wrote: > > logFileName = 'log.txt' > > logfile = open(logFileName, "a") > > class MyUDPServer(SocketServer.UDPServer): > > def server_bind(self): > > self.socket.setsockopt(socket.SOL_SOCKET, > > socket.SO_RCVBUF, 8388608) > > self.socket.bind(self.server_address) > > > > class LogsDumpHandler(SocketServer.DatagramRequestHandler): > > def handle(self): > > global logfile > > # fileExists is a function which checks the existence of a file > > if not fileExists(logFileName): > > logfile = open(logFileName, "a") > > logfile.writelines(self.rfile.readlines()) > > > > server = MyUDPServer(("",PORT), LogsDumpHandler) > > server.serve_forever() > > logfile.close() > > This is horrible code :/ > > Try these instead: > * UDPServer -> > http://trac.softcircuit.com.au/circuits/browser/examples/udpserver.py > * UDPClient -> > http://trac.softcircuit.com.au/circuits/browser/examples/udpclient.py > > Example usage > ---------------------- > > ~/circuits/examples > $ ./udpserver.py > 127.0.0.1, 9000: > test > 127.0.0.1, 9000: > hi > > ~/circuits/examples > $ ./udpclient.py -b 127.0.0.1:9000 127.0.0.1:8000 > test > 127.0.0.1, 8000: > test > hi > 127.0.0.1, 8000: > hi > > You can download circuits from http://trac.softcircuit.com.au/circuits/ > or get the latest development version by using Mercurial (1): > hg clone http://hg.softcircuit.com.au/projects/circuits/ > > cheers > James > > [1] http://www.selenic.com/mercurial/wiki/ > > -- > -- > -- "Problems are solved by method" > -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Tue Nov 4 11:20:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 4 Nov 2008 08:20:15 -0800 (PST) Subject: Structures References: <87d4hcmql2.fsf@benfinney.id.au> <6n9io4Fk8mutU6@mid.uni-berlin.de> <011fb978$0$20642$c3e8da3@news.astraweb.com> Message-ID: <05f62c92-801f-4380-af69-162d66db07b1@u18g2000pro.googlegroups.com> On Nov 3, 10:26?pm, Steven D'Aprano wrote: > On Tue, 04 Nov 2008 00:19:16 +0000, Marc 'BlackJack' Rintsch wrote: > > On Mon, 03 Nov 2008 23:32:25 +0000, Paulo J. Matos wrote: > > >> What's then the reason for adding named tuples if they are not > >> mutable...??? > > > Names are more descriptive than "magic numbers" as indices. ?See for > > example the "named tuple" returned by `os.stat()`. > > I have no objection to named tuples, but I've sometimes > missed having an equivalent to the Pascal record or C > struct: essentially a named mutable tuple. +1. FWIW, I posted a recipe along these lines, following closely the functionality and implementation of namedtuple: http://code.activestate.com/recipes/576555/ George From badmuthahubbard at gmail.com Tue Nov 11 13:23:51 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 11 Nov 2008 20:23:51 +0200 Subject: subprocess communication, exec() Message-ID: <8200bab70811111023g6a5a3aa4k94a8732c569fd8cd@mail.gmail.com> If I run 'python -i subprocessclient.py' I expect to see the nice level of it go up 2, and the nice level of the subprocess go up 1. But all I see is the nice level of the client change. What am I doing wrong? subprocessserver.py: ---------------------------- #!/usr/bin/python2.5 import os import sys while True: next_line = sys.stdin.readline() if not next_line: break exec(next_line) # sys.stdout.write(output) # sys.stdout.write(next_line) # sys.stdout.flush() ---------------------------- subprocessclient.py: ---------------------------- #!/usr/bin/python2.5 import subprocess, os server = subprocess.Popen(('python2.5', 'subprocessserver.py'), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) os.nice(2) server.stdin.write('''os.nice(1)''') ---------------------------- Thanks. -Chuckk -- http://www.badmuthahubbard.com From jzakiya at mail.com Tue Nov 18 02:53:02 2008 From: jzakiya at mail.com (jzakiya) Date: Mon, 17 Nov 2008 23:53:02 -0800 (PST) Subject: Sieve of Zakiya References: <1992da9f-a844-4e2c-bab4-b930b1c938bd@q26g2000prq.googlegroups.com> Message-ID: <9fee2688-2fdb-4926-b235-d4d6026f993b@d42g2000prb.googlegroups.com> On Nov 4, 4:12?pm, jzakiya wrote: > Update: 2008/11/03 > > Architecture & coding improvements. Renamed generators. > > I am 90% finished writing up a mathematical analysis of my method. > In the process I found an architectural optimization to the sieve > process which is incorporated in the new code. Complexity analysis > showing other interesting stuff for each generator. > > When I finish I will post paper here with the code: > > www.4shared.com/account/dir/7467736/97bd7b71/sharing > > Jabari Another update to SoZ code. Fixed coding "oversight" which caused the SoZ code running under psyco to be slower than SoA, though SoZ was faster than SoA without psyco. Now SoZ is consistently faster by an appreciable amount either way. Some other coding enhancements to optimize algorithmic performance. Enjoy! :-) Jabari From lsumnler at gmail.com Fri Nov 14 23:21:17 2008 From: lsumnler at gmail.com (len) Date: Fri, 14 Nov 2008 20:21:17 -0800 (PST) Subject: Little direction please Python MySQL References: <35531549-3359-4e83-97f1-acd3f965db7e@x16g2000prn.googlegroups.com> Message-ID: On Nov 13, 7:32?pm, Ethan Furman wrote: > len wrote: > > Hi all; > > [snip] > > > Here is my problem. ?I need to start doing this in the really world at > > my company converting some older cobol system and data to python > > programs and MySQL. ?I have gotten past packed decimal fields and > > various other little tidbits. ?My problem is the data files aren't > > little three of four field files but Customer File with 98 fields > > etc. ?I understand building dictionaries and building with zip and I > > have even seen a reference to using __setattr__ in an empty class but > > I'm having a hard time moving past the little code snippts to real > > code. > > [snip] > > > Thanks Len > > I've never had the (mis?)fortune to work with COBOL -- what are the > files like? ?Fixed format, or something like a dBase III style? ?I > presume also that you only need access to them in COBOL format long > enough to transfer them into MySQL -- true? > > ~ethan~ Files are fixed format no field delimiters, fields are position and length records are terminated by newline. In cobol the read statement which read a record from the file automaticly mapped the date to the fieldnames in the cobol file definition. In python you as the programmer have to do the mapping of data to fieldnames whether this is using list and numeric indexing (list[n]), dictionaries file['fieldname'] = value or attribute (self.fieldname = value through some class). Now in my case I literally have a couple of hundred files and each file may have 20 or 30 fieldnames and in several cases 100 to 150 fields (customer file alone has 98). So as you can imagine standardize the mapping is a big deal to me. Now all of the sample code you find (understandably) usually shows SQL code and python code manipulating 3 or 4 fields at the most and one 1 or 2 tables at a time. In the real world I have programs that will need to work on 5, 10, and 15 files at a time and 100's of fields. Basicly it is the difference between writing your jave, C++, or python program to complete your programming language assignment for your college class and then graduating and getting a job and being told to write the companies new CRM or ERP system. You can find plenty of beginning tutorial and code snippets or esotiric code using stuff for landing the lunar lander but where is the middle ground. That is the stuff I'm looking for. Please understand this is not a rant against SQL or python or their communities but at my own progress in these to become a competent programmer and I'm sure as every programmer in the world has experienced, it just never occurs fast enough. Len From prologic at shortcircuit.net.au Wed Nov 5 22:12:18 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 6 Nov 2008 13:12:18 +1000 Subject: damn street venders In-Reply-To: References: <9a2ed6e0-91b2-4ca6-ae7f-6e77cb753e2e@o4g2000pra.googlegroups.com> Message-ID: On Tue, Nov 4, 2008 at 12:13 AM, Aspersieman wrote: > +1 +1 From nagle at animats.com Thu Nov 20 23:40:28 2008 From: nagle at animats.com (John Nagle) Date: Thu, 20 Nov 2008 20:40:28 -0800 Subject: Official definition of call-by-value (Re: Finding the instance reference...) In-Reply-To: <013623f4$0$20662$c3e8da3@news.astraweb.com> References: <3c4edf32-acda-4244-ba46-bad5ea623303@w39g2000prb.googlegroups.com> <0120cb30$0$20642$c3e8da3@news.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <0124739f$0$20668$c3e8da3@news.astraweb.com> <6dd2bf03-54fa-4d42-9392-659a8e972598@b38g2000prf.googlegroups.com> <6nsbskFib5vU1@mid.individual.net> <6nul1qF100urU1@mid.individual.net> <6oh3adF3ikb9U1@mid.individual.net> <6ojsa3F41nfsU1@mid.individual.net> <013623f4$0$20662$c3e8da3@news.astraweb.com> Message-ID: <492635aa$0$2791$742ec2ed@news.sonic.net> Steven D'Aprano wrote: > On Thu, 20 Nov 2008 14:22:50 +1300, greg wrote: > >> Antoon Pardon wrote: >> >>> You are changing your argument. In a follow up you made the point that >>> call by value should be as it was intended by the writers of the algol >>> 60 report. >> No, I was countering the argument that "call by value" is short for >> "call by copying the value". I was pointing out that the inventors of >> the term didn't use any such words. > > Nor did they define what assignment means, and their definition of > "value" seems to exclude such things as strings. > > > >> Arguing that their words were intended to imply copying, as part of the >> essence of the idea, is making an even bigger assumption about their >> intentions, IMO. >> >> Rather it seems to me that the essence of the idea they had in mind is >> that call-by-value is equivalent to assignment. > > You've just *assumed* that assignment in Algol 60 doesn't involving > copying. Based on the very little I know about Algol, I think that is a > very unsafe assumption. I know significantly more about Pascal, and in > Pascal, assignment *is* copying. > > (I wait now with bated breath for somebody to point out some Python > implementation or feature where assignment doesn't make a copy...) In stock ALGOL-60, there are only the primitive types, and assignment of them is a copy. Most useful implementations had strings, and Simula, which was an ALGOL extension, had objects. Simula had value parameters, reference parameter, and name parameters. For assignment, ":=" specified a value assignment, and ":-" specified a reference assignment. John Nagle From ishoej at gmail.com Fri Nov 7 09:35:14 2008 From: ishoej at gmail.com (Holger) Date: Fri, 7 Nov 2008 06:35:14 -0800 (PST) Subject: read() does not read whole file in activepython/DOS References: <6410a2b2-6aa9-493b-859b-e7b6a7c369ef@d42g2000prb.googlegroups.com> Message-ID: <31990f56-d499-46e3-9701-e97cc9c7b475@v22g2000pro.googlegroups.com> On Nov 7, 2:40?pm, Holger wrote: > This is what it looks like in DOS: > ======================================= > C:\production>python > ActivePython 2.5.2.2 (ActiveState Software Inc.) based on > Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information.>>> b = open('boot.bin').read() > >>> len(b) > 1067 > >>> import os > >>> os.path.getsize('boot.bin') > > 18308L > ======================================= > > What is wrong? / What am I doing wrong? > I would expect it to read the whole file. Solution: open(, 'rb') From deets at nospam.web.de Thu Nov 6 08:10:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Nov 2008 14:10:29 +0100 Subject: bind to HTMLayout or ubrowser References: Message-ID: <6ng8llFkfk87U1@mid.uni-berlin.de> oyster wrote: > http://www.terrainformatica.com/htmlayout/ "uses its own lightweight > HTML rendering engine", helps you to create applications with the "Web > style" user interface > > http://ubrowser.com/ "is a library that makes it a little easier to > embed the Mozilla Gecko rendering engine into your application" > > is there any python interface to it/them? If you don't care about the engine itself, you might consider using PyQt4 + the embedded webkit (Safari, chrome, konqueror) engine. Diez From bj_666 at gmx.net Tue Nov 4 07:24:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Nov 2008 12:24:22 GMT Subject: problem with single-quote and double-quote when using subprocess. References: <331a3e98-67bf-4b7a-8f33-003801ac7e16@w1g2000prk.googlegroups.com> Message-ID: <6nat7mFklavsU1@mid.uni-berlin.de> On Tue, 04 Nov 2008 03:26:21 -0800, MRAB wrote: > On Nov 3, 10:47?pm, Evan wrote: >> i'm trying to call subprocess.popen on the 'command-based' function in >> linux. ?When I run the command from the shell, like so: >> >> goset -f ' "%s %s" name addr ' file_name >> >> it works fine > > It looks like there are _4_ items on the command line: > > goset > -f > ' "%s %s" name addr ' > file_name > > so the call should be: > > p = subprocess.Popen(["goest", "-f", "' \"%s %s\" name addr '", > "file_name"], shell=True) The argument after '-f' doesn't have the single quotes at both ends. They tell the shell that it is just one argument and the shell removes them before calling ``goset`` (or ``goest``). Ciao, Marc 'BlackJack' Rintsch From gdamjan at gmail.com Fri Nov 28 18:53:20 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Sat, 29 Nov 2008 00:53:20 +0100 Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <082ed3fd-f194-4ddb-ace8-81c6a9d18a98@k41g2000yqn.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> Message-ID: > Fight with me for Glory not riches. Fight with me and > you shall be free. FREEEEEEEEEDOOOOOOOOOM!!!!! SketchUp is not free -- ?????? ( http://softver.org.mk/damjan/ ) war is peace freedom is slavery restrictions are enablement From thomas at mlynarczyk-webdesign.de Sun Nov 9 09:39:30 2008 From: thomas at mlynarczyk-webdesign.de (Thomas Mlynarczyk) Date: Sun, 09 Nov 2008 15:39:30 +0100 Subject: My first Python program -- a lexer In-Reply-To: References: Message-ID: John Machin schrieb: > Be consistent with your punctuation style. I'd suggest *not* having a > space after ( and before ), as in the previous line. Read > http://www.python.org/dev/peps/pep-0008/ What were the reasons for preferring (foo) over ( foo )? This PEP gives recommendations for coding style, but (naturally) it does not mention the reasons why the recommended way is preferrable. I suppose these matters have all been discussed -- is there a synopsis available? >> self.source = re.sub( r"\r?\n|\r\n", "\n", source ) > Firstly, would you not expect to be getting your text from a text file > (perhaps even one opened with the universal newlines option) i.e. by > the time it's arrived here, source has already had \r\n changed to \n? I was not aware of the universal newlines option. This would then indeed make my newline conversion superfluous. > Secondly, that's equivalent to > re.sub(r"\n|\r\n|\r\n", "\n", source) My mistake. I meant r"\r?\n|\r" ("\n", "\r\n" or "\r"). > Thirdly, if source does contain \r\n and there is an error, the > reported value of offset will be incorrect. Consider retaining the > offset of the last newline seen, so that your error reporting can > include the line number and (include or use) the column position in > the line. Indeed, I had not thought of that detail -- if I mess with the newlines, the offset will be wrong with respect to the original source. But with the universal newlines option mentioned above, the problem is already solved :-) >> while self.offset < len( self.source ): > You may like to avoid getting len(self.source) for each token. Yes, I should change that. Unless there is a more elegant way do detect the end of the source? >> for name, regex in self.tokens.iteritems(): > dict.iter() will return its results in essentially random > order. Ouch! I must do something about that. Thanks for pointing it out. So if I want a certain order, I must use a list of tuples? Or is there a way to have order with dicts? >> return "\n".join( >> [ "[L:%s]\t[O:%s]\t[%s]\t'%s'" % > For avoidance of ambiguity, you may like to change that '%s' to %r In which way would there be ambiguity? The first two are integers, the last two strings. Thanks for your feedback. Greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux ? avoir tort qu'ils ont raison! (Coluche) From martin at v.loewis.de Wed Nov 19 16:12:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 19 Nov 2008 22:12:36 +0100 Subject: 404 not found on for Python 2.6 Itanium In-Reply-To: <4f936967-9cea-46b6-a442-99dd3979abf0@j38g2000yqa.googlegroups.com> References: <3fe83250-0a7f-441d-a763-9761290ad272@d36g2000prf.googlegroups.com> <4f936967-9cea-46b6-a442-99dd3979abf0@j38g2000yqa.googlegroups.com> Message-ID: <49248144$0$15509$9b622d9e@news.freenet.de> > Then why is there a link on the download site? Where specifically did you spot that link? I can't see any. > You are saying that > for python 2.6 forward, there is no plan to support a stock python for > IA64? Is there any particular reason why this is so? Yes. It's too much effort to build, and too few users that actually use it. Users are still free to build it themselves, and to share the build with others. Regards, Martin From paul at boddie.org.uk Mon Nov 24 06:41:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 24 Nov 2008 03:41:54 -0800 (PST) Subject: 3.0rc3: 'os.extsep' gone ... ? References: <1e18d73c0811231559v2de31837g952fa8fdd0963f9e@mail.gmail.com> <492a5b09$0$26317$9b622d9e@news.freenet.de> Message-ID: <41ba0006-4350-450e-9524-b7d3c57da765@j39g2000yqn.googlegroups.com> On 24 Nov, 08:43, "Martin v. L?wis" wrote: > > That doesn't really explain it. It always was os.path.extsep, > but it *also* was os.extsep. I've always known it as the former; a perusal of the Python repository would probably indicate when it became exposed in the os module itself. Support for extension separators (extsep and splitext) has always been somewhat lacklustre in the os(.path) module, perhaps due to "complicated" filename syntax from operating systems like VMS, but it'd be good to improve this support in future, I think. Paul From deets at nospam.web.de Mon Nov 24 14:11:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Nov 2008 20:11:42 +0100 Subject: Install modules with no root privilegies References: Message-ID: <6p0cglF5kin2U1@mid.uni-berlin.de> Philipp Pagel wrote: > Alfons Nonell-Canals wrote: >> Install python modules in a linux computer is really easy, it is because >> the module is a package of the distribution or because the python >> installation is really easy. But, in both situations, you need root >> privilegies. > >> I would like to know how to install modules only for one user, with no >> root privilegies. Do you know if it is possible and easy. > > Yes, there is. You can choose among two strategies referred to as "home > scheme" and "prefix scheme" in the "Installing Python Modules" > documentation: > > http://docs.python.org/install/index.html > > Have a look at Section 3 "Alternate installation". That's waaaaaaaaay much more than is actually needed, as thus each user would end up with a different installation. Setting the PYTHONPATH-env-variable to a user writable location allows e.g. easy_install and friends to install into that location. And installing virtualenv globally, everybody can create a "local" site-packages-directory. Diez From arnodel at googlemail.com Sun Nov 23 14:04:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Nov 2008 19:04:19 +0000 Subject: Python 3 __cmp__ semantic change? References: <9b9hv5x3fj.ln2@joeserver.homelan.net> <013754b5$0$20662$c3e8da3@news.astraweb.com> <0137c09b$0$20669$c3e8da3@news.astraweb.com> <0138a4a9$0$20648$c3e8da3@news.astraweb.com> Message-ID: Terry Reedy writes: > George Sakkis wrote: >> On Nov 23, 6:14 am, Arnaud Delobelle wrote: >> >>> So how did I get it into my head that defining __eq__ would create the >>> correct behaviour for __ne__ automatically? And more puzzlingly, how >>> come it is what actually happens? Which should I believe: the >>> documentation or the implementation? >> >> According to Guido, the implementation: >> http://mail.python.org/pipermail/python-ideas/2008-October/002235.html. > > http://bugs.python.org/issue4395 > > ps to Arnaud: upgrade to rc3, which has bug fixes and many doc changes. This occured to me after I posted the example so I did update before building the docs. When I saw the inconsistency between the docs and python, I also rebuilt python but it behaved the same. I didn't try checking bugs.python.org because I can't access python.org at the moment (thanks Aahz for pointing out it's hosted in the Netherlands - as there are a number of US hosted sites that I can't access I just assumed Python was one of them). I guess the bug report is about updating the docs! -- Arnaud From python-url at phaseit.net Mon Nov 24 08:59:48 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 24 Nov 2008 13:59:48 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Nov 24) Message-ID: QOTW: "One of the reasons for Python's continue march towards world domina- tion (allow me my fantasies) is its consistent simplicity. Those last two words would be my candidate for the definition of 'Pythonicity'." - Steve Holden http://groups.google.com/group/comp.lang.python/msg/e2518ea8388ca1c5 The last Release Candidate (RC3) for Python 3.0 is available http://groups.google.com/group/comp.lang.python/t/fbb62e9c9a08c817/ Survey: which dynamic features of Python do you use most? http://groups.google.com/group/comp.lang.python/t/bdb39a1a4947cdd8/ Beginners looking for problems/challenges/exercises to do: http://groups.google.com/group/comp.lang.python/t/2b8a0b4ffdbdffbf/ Call-by-Object strikes again! This time, a functional mind asks why unrelated functions are allowed to modify the internal state of an object: http://groups.google.com/group/comp.lang.python/t/35511397ad7748cc/ How to detect whether a dictionary has been modified http://groups.google.com/group/comp.lang.python/t/3632f2407640e759/ Function default arguments are only evaluated when the function is defined. Is it intuitive? Ways to change the current behaviour. http://groups.google.com/group/comp.lang.python/t/2e01cc9ce899eb6e/ http://groups.google.com/group/comp.lang.python/t/1209ebf18a5ec561/ Installing Python on Windows Vista may require using the Administrator account http://groups.google.com/group/comp.lang.python/t/a745ed3df47e1be9/ Elegant ways to execute a function at most n times or until succeeds: http://groups.google.com/group/comp.lang.python/t/10d651c2a0eb082e/ __cmp__ is gone in Python 3 - how to implement a total ordering in a simple way? http://groups.google.com/group/comp.lang.python/t/2a672f960e595c76/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From research at johnohagan.com Thu Nov 27 00:20:46 2008 From: research at johnohagan.com (John O'Hagan) Date: Thu, 27 Nov 2008 05:20:46 +0000 Subject: Confused about class relationships Message-ID: <200811270520.47325.research@johnohagan.com> Apologies if this is a D.Q., I'm still learning to use classes, and this little problem has proved too specific to find in the tutorials. I have two classes with a relationship that I find confusing. One is called Engine, and it has a method (bar_builder) which generates instances of the other class, called Bar (not as in Foo but as in bar of music; inherits from list). Also, Bar takes the generating instance of Engine as an argument to its __init__ method: class Bar(list): def __init__(self, a_bar, args, engine): list.__init__ (self, a_bar) self[:] = a_bar self.args = args self.engine = engine #more instance attributes... #methods... class Engine: def __init__(self, args): self.args = args #more instance attributes... def bar_builder(self): #body of method generates lists... yield Bar([generated_list], args, self) #more methods... #(other stuff...) def main(args): engine = Engine(args) bars = engine.bar_builder() for a_bar in bars: #play the music!... While this works (to my surprise!) and solves the problem which motivated it (i.e. Engine instances need to pass some attributes to Bar instances ), it seems too convoluted. Should one class inherit the other? If so, which way around? Or is it fine as is? I'm hoping this is a common trap I've fallen into; I just haven't been able to get my head around it. (I'm a musician...) John O'Hagan From steve at REMOVE-THIS-cybersource.com.au Thu Nov 13 23:25:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Nov 2008 04:25:48 GMT Subject: using "private" parameters as static storage? References: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> <4866bea60811130919h518b8054i7477067ef3f93e5a@mail.gmail.com> <87r65f827d.fsf@benfinney.id.au> Message-ID: <012cf62b$0$20662$c3e8da3@news.astraweb.com> On Fri, 14 Nov 2008 13:35:02 +1100, Ben Finney wrote: > Instead, it looks like you're falling foul of one of the classic > mistakes in the ?How to ask questions the smart way? document: you've > got a goal, but you're assuming that you need to use a specific tool to > get there. Instead, you're being shown that your assumption is false: > there's a better tool available to achieve your goal. For the sake of the argument I will accept your characterization of Joe's question. Even given that, you have still made an error: Joe hasn't been shown that his assumption is wrong, he's merely had a bunch of people declare, without evidence or even reason, that he is wrong. If anyone has given any reason for avoiding the idiom that doesn't boil down to "I don't like it!" (I need a smiley for pursed lips), I haven't read it. I for one do not think he is wrong, and I have given reasons for preferring the idiom: def parrot(public_args, _cache={}) # or similar for implementing caches and similar internal storage. It's quick, it's easy, it's lightweight, and it exposes the cache to those who need it, e.g. for testing. If anyone has a *reason* why this idiom is harmful, please say so. Repeating "That's not the way to do it!!! Use an object!!!" is not a reason. Without such a reason, then the decision whether or not to use a functor (class with a __call__ method) in Python is a matter of personal taste. -- Steven From bignose+hates-spam at benfinney.id.au Tue Nov 4 18:25:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Nov 2008 10:25:06 +1100 Subject: Is there a better/simpler way to filter blank lines? References: <6fa8c5d5-0dee-4f35-a0b5-59cb0d8f7f97@b31g2000prb.googlegroups.com> Message-ID: <873ai7kral.fsf@benfinney.id.au> tmallen writes: > On Nov 4, 4:30?pm, bearophileH... at lycos.com wrote: > > xlines = (line for line in open(filename) if line.strip()) > > I must be missing something: > > >>> xlines = (line for line in open("new.data") if line.strip()) > >>> xlines > A generator is a sequence, but is not a collection. It will generate each item on request, rather than having them all in memory at once. for line in xlines: do something_knowing_the_line_is_not_blank(line) If you later *want* a collection containing all the items from the generator, you can feed the generator (or any iterable) to a type that can turn it into a collection. For example, to get all the filtered lines as a list: all_lines = list(xlines) Note that some generators (not this one, which will end because the file is finite size) never end, so feeding them to a constructor this way will never return. -- \ ?It is far better to grasp the universe as it really is than to | `\ persist in delusion, however satisfying and reassuring.? ?Carl | _o__) Sagan | Ben Finney From simon.palmer at gmail.com Fri Nov 7 04:10:37 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Fri, 7 Nov 2008 01:10:37 -0800 (PST) Subject: List to Text back to List References: <534a6647-b16b-4be4-ae18-93f2acb26831@v13g2000pro.googlegroups.com> Message-ID: On Nov 6, 8:33?pm, "Chris Rebert" wrote: > On Thu, Nov 6, 2008 at 12:18 PM, SimonPalmer wrote: > > On Nov 6, 8:11 pm, "Chris Rebert" wrote: > >> On Thu, Nov 6, 2008 at 12:04 PM, SimonPalmer wrote: > >> > Hi, I am looking for a way to convert a List of floating point numbers > >> > to and from text. ?I am embedding it in an XML document and am looking > >> > for a neat way to serialise and de-serialise a list from a text node. > >> > I can easily write something to do it manually but I wondered whether > >> > List had native support to go to and from text. > > >> > If not List, are there any other collections/arrays that do this? > > >> It's not really a matter of the collection, but more a matter of > >> serialization format/library. > > >> If you want the serialized representation to be human-readable, use > >> JSON (http://docs.python.org/library/json.html#module-json). > >> If that's not a requirement, use pickle > >> (http://docs.python.org/library/pickle.html#module-pickle). > >> Both modules can convert simple Python data, such as your list of > >> floats, to a bytestream and back again. > > >> Cheers, > >> Chris > >> -- > >> Follow the path of the Iguana...http://rebertia.com > > >> > TIA > >> > Simon > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > > > I looked at pickle, but the problem is that I want my XML to be > > readable by languages other than python, so it sort of precludes it. > > JSON would be perfect, but I think the module only exists in 2.6, is > > that right? ?Unfortunately I am bound to 2.4. > > > It is looking more and more like I am going to have to roll my own. > > The module is available as a third-party library for previous Python > versions athttp://www.undefined.org/python/ > > Cheers, > Chris > -- > Follow the path of the Iguana...http://rebertia.com simplejson did the trick. the trouble with a couple of suggestions is that they are only really any good for 1 dimensional lists, although I confess I didn't make that requirement clear in my original question sorry for capitalising list, my mistake, hope you weren't too confused. From joe at strout.net Thu Nov 13 21:16:25 2008 From: joe at strout.net (Joe Strout) Date: Thu, 13 Nov 2008 19:16:25 -0700 Subject: using "private" parameters as static storage? In-Reply-To: <4866bea60811130919h518b8054i7477067ef3f93e5a@mail.gmail.com> References: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> <4866bea60811130919h518b8054i7477067ef3f93e5a@mail.gmail.com> Message-ID: <2254F24F-8539-4790-9CE2-DB6A0D7859A5@strout.net> On Nov 13, 2008, at 10:19 AM, Chris Mellon wrote: > Static storage is a way of preserving state. Objects are a way of > encapsulating state and behavior. Use an object. Argh. I've been back in the Python community for about a month, and I've been continually amazed at how every single "how do I do X" or "what do you think of this method of doing X" question is answered by people on high horses claiming "you shouldn't do X". I know very well about state and objects. I'll be happy to whip out my software engineering credentials and measure them against yours if that's how you like to play. I understand very well when data should be stored as instance data, and when it should be instead tucked away as static data within a method. If you don't understand that, or are happy without having the choice, and have no answer to the question I was asking, then that's fine. I don't always have anything useful to contribute when somebody asks a question either. But in that case, I resist the urge to reply anyway. Maybe we should define some standard tags people could add to the top of their email: "Helpful-Answer" for helpful answers, and "Unhelpful- Preaching" for the other kind. Then those of us not interested in one sort or the other could set up an email filter. Best, - Joe P.S. I'm sorry, Chris, I don't mean to rip your head off in particular. You were just the straw that broke the camels back; there have been plenty of others adding to the frustration. I'll try to just ignore such responses in the future... though it is a little disturbing to think how many newbies are probably driven away by this sort of thing. From python.list at tim.thechases.com Tue Nov 4 14:36:29 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Nov 2008 13:36:29 -0600 Subject: Parse each line by character location In-Reply-To: References: Message-ID: <4910A43D.40506@tim.thechases.com> >> recno_idx = slice(0,10) >> client_idx = slice(10, 11) >> volume_idx = slice(11,11+10) >> order_type_idx = slice(11+10, 11+10+3) > . > !? That seems to me confusingly far from a working solution, > at least in comparison to > > recno_idex = the_line[0:10] > client_idx = the_line[10:11] > ... > > What am I missing? The "11+10" and "11+10+3" are to help show where the magic numbers come from...that they're column-offsets from the previous position...I suppose to have been consistent, I should have used client_idx = the_line[10:10+1] Somewhat like a kludgy version of George Sakkis's more elegant version of slicing, but with the advantage of associating names with the slice-boundaries. It would be possible to write it as something like for line in file('in.txt'): out.write(','.join([ line[0:10], # recno line[10:11], # client line[11:21], # volume line[21:24], # order line[24:], # remainder ])) but it's harder to verify that the slicing doesn't incur a fence-posting error, and makes it harder to follow if manipulations need further checking like if line[client_idx] == 'F': continue # skip this client There are a number of ways to slice & dice the line. I recommend whichever is easiest to read/understand. -tkc From cptnwillard at gmail.com Tue Nov 25 11:21:34 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Tue, 25 Nov 2008 08:21:34 -0800 (PST) Subject: end of print = lower productivity ? References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> Message-ID: <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> On Nov 25, 5:05?pm, peter wrote: > BUT you now can do > > >>> p = print > >>> p("f") > > Voila, 4 keystrokes saved :-) All right. Let's talk about that. When I write "print", it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key, and then the "(" : move the left hand, press SHIFT, move the right hand, aim "(", press, miss, press again. Same thing at the end of the function call. I know it sounds ridiculous, but it does *impair* my debugging productivity. Taylor would agree. From rapidshareboobs1 at gmail.com Sat Nov 1 21:12:19 2008 From: rapidshareboobs1 at gmail.com (rapidshareboobs1 at gmail.com) Date: Sat, 1 Nov 2008 18:12:19 -0700 (PDT) Subject: ** Boobie Breast Plate ARmOr Body Armor ProTecTor Video *** Message-ID: Virginia Chicks Naked! - http://militarybodyarmor.blogspot.com/2008/10/gao-rejects-claim-army-botched-body.html Download exclusive test video of women taking bullets with their transparent body armor!! Watch the video and pics free downloads From adjointmcelroydp at gmail.com Sun Nov 9 16:52:55 2008 From: adjointmcelroydp at gmail.com (adjointmcelroydp at gmail.com) Date: Sun, 9 Nov 2008 13:52:55 -0800 (PST) Subject: Cramer meltdown - Free Message-ID: Cramer meltdown . . . *******CLICK HERE******** http://vids247.cn/Cramer-meltdown ***************************** . . . . . . . . . . . . Cramer meltdown From torriem at gmail.com Tue Nov 4 12:33:40 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Nov 2008 10:33:40 -0700 Subject: Python on iPhone actually rather good In-Reply-To: References: Message-ID: <49108774.2070600@gmail.com> Python Nutter wrote: > I'll be giving iPhone Python 2.5.1 a workout on on of Mark Lutz's > books and report any more gotchas that I come across. Are there any good books on python and objc? I doubt you'll be able to make any decent iPhone apps without having a good working knowledge of Objective C and the python-objc bridge. In my mind that's one of the cool parts of doing cocoa development in python, but also the biggest curse of cocoa. From bborcic at gmail.com Thu Nov 20 12:45:33 2008 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 20 Nov 2008 18:45:33 +0100 Subject: More elegant way to try running a function X times? In-Reply-To: <49242150.1070904@tim.thechases.com> References: <49242150.1070904@tim.thechases.com> Message-ID: Tim Chase wrote: >> success = None >> for i in range(5): >> #Try to fetch public IP >> success = CheckIP() >> if success: >> break >> if not success: >> print "Exiting." >> sys.exit() > > Though a bit of an abuse, you can use > > if not any(CheckIP() for _ in range(5)): > print "Exiting" > sys.exit() I don't see why you speak of abuse, bit of abuse would be, say if you replaced range(5) by '12345' to win a char; but otoh I think you misspelled any() for all(). Cheers BB From dineshbvadhia at hotmail.com Sun Nov 2 02:25:13 2008 From: dineshbvadhia at hotmail.com (dineshv) Date: Sun, 2 Nov 2008 00:25:13 -0700 (PDT) Subject: Fast list traversal Message-ID: I want to see if there is an alternative method for fast list traversal. The code is very simple: dict_long_lists = defaultdict(list) for long_list in dict_long_lists.itervalues() for element in long_list: array_a[element] = m + n + p # m,n,p are variable numbers The long_list's are read from a defaultdict(list) dictionary and so don't need initializing. The elements of long_list are integers and ordered (sorted before placing in dictionary). There are > 20,000 long_list's each with a variable number of elements (>5,000). The elements of long_list are immutable (ie. don't change). The above code is within a def function. I've tried set() using defaultdict(set) but the elements are not ordered. What is the fastest way to traverse these long_list's sequentially from the beginning to the end? Maybe there is another data structure that can be used instead of a list. Dinesh From bj_666 at gmx.net Sun Nov 9 11:10:36 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Nov 2008 16:10:36 GMT Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <01264714$0$20668$c3e8da3@news.astraweb.com> <6no8p6Fm8q70U1@mid.uni-berlin.de> <6nod8uFmk1blU1@mid.uni-berlin.de> Message-ID: <6nogbsFmao91U1@mid.uni-berlin.de> On Sun, 09 Nov 2008 10:45:31 -0500, Roy Smith wrote: > In article <6nod8uFmk1blU1 at mid.uni-berlin.de>, > "Diez B. Roggisch" wrote: >> Roy Smith schrieb: >>> In article <6no8p6Fm8q70U1 at mid.uni-berlin.de>, >>> "Diez B. Roggisch" wrote: >>> >> When I wrote "uniform" I meant objects of the same kind. So for example >> subclasses are of course ok. And all of your examples are these: I want >> a Token-object, keeping file-location and possibly original string >> representation. > > Maybe, but only if the logic of my program says that's the right way to > do it. If I decide that the appropriate way to return an integer is by > returning something of type(int), that's my business. Why should I have > to define a Token class if using the native Python types works just as > well for what I'm doing? I'll write class Token when there's some > added value I get from it which I can't get with raw types. One added value in Python?3.0 would be that they are sortable in a `list`. But seriously, your token example should work fine with Python?3.0 because the wish to sort tokens is a bit exotic IMHO. > I don't want to be forced into it just because a container doesn't like > what I'm doing. The container doesn't say what *you* can do with the content, it is just a bit picky about what the container itself can do. If a function or method doesn't like something about the arguments it's perfectly okay to raise a `TypeError` or a `ValueError`. > As another example, consider a list of items being juggled: > > [RubberChicken(), ChainSaw(), Canteloupe()] > > I could go through contortions to find some common subclass for these > items, but the whole *point* is that they're not of the same type. They are of the same duck type "things to be juggled". And if you use a method on them they have to implement that. Not necessarily through inheritance. > And making a list of them is a perfectly reasonable thing to do. And possible with current Python and Python?3.0. Ciao, Marc 'BlackJack' Rintsch From alanbaljeu at yahoo.com Thu Nov 13 14:01:24 2008 From: alanbaljeu at yahoo.com (Alan Baljeu) Date: Thu, 13 Nov 2008 11:01:24 -0800 (PST) Subject: unittest exits References: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> Message-ID: <376333.89640.qm@web58302.mail.re3.yahoo.com> When I call unittest.main(), it invokes sys.exit(). I would like to run tests without exiting. How can I? Alan Baljeu __________________________________________________________________ Instant Messaging, free SMS, sharing photos and more... Try the new Yahoo! Canada Messenger at http://ca.beta.messenger.yahoo.com/ From tstrogen at googlemail.com Mon Nov 3 11:48:01 2008 From: tstrogen at googlemail.com (tstrogen at googlemail.com) Date: Mon, 3 Nov 2008 08:48:01 -0800 (PST) Subject: Problem using urllib to download images Message-ID: I am using Python 2.6 on Mac OS 10.3.9. I have been trying to use: image = urllib.URLopener() image.retrieve(url, filename) to download images from websites. I am able to do so, and end up with the appropriate file. However, when I try to open the file, I get an error message. It's something about corrupted data, and an unrecognised file. Anyone know what I'm talking about/had similar experiences? -Taidgh From greg at cosc.canterbury.ac.nz Mon Nov 10 23:01:04 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 11 Nov 2008 17:01:04 +1300 Subject: C Module question In-Reply-To: References: <20d7d226-3971-45bf-8636-5010f9219028@35g2000pry.googlegroups.com> Message-ID: <6nse6oFmbmvU1@mid.individual.net> boblatest at googlemail.com wrote: > Sadly this doesn't work on "file-like" > objects like those that are created by opening bz2 files (using the > bz2 lib). If the C code you're calling requires a FILE *, then you're out of luck. There's no way of getting a FILE * from an object that's not based on an actual PyFile object, since there simply isn't one to be had. There is an exception to that -- if the object is one that has a file descriptor underlying it somewhere (such as a pipe or socket) you could get that and wrap it using fdopen(). -- Greg From leesquare at yahoo.com Fri Nov 7 09:04:48 2008 From: leesquare at yahoo.com (leesquare at yahoo.com) Date: Fri, 7 Nov 2008 06:04:48 -0800 (PST) Subject: adodbapi and output parameters in stored procedures Message-ID: Hello, I need some help getting output values from my stored procedures when using adodbapi. There's an example testVariableReturningStoredProcedure in adodbapitest.py, and that works for my system. But my stored procedure also inserts and accesses a table in the database. Here's what I have it boiled down to: So, when I have CREATE PROCEDURE sp_DeleteMeOnlyForTesting @theInput varchar(50), @theOtherInput varchar(50), @theOutput varchar(100) OUTPUT AS SET @theOutput=@theInput+ at theOtherInput Then, I can run in python: >>> cursor = db.conn.cursor() >>> cursor.callproc('sp_DeleteMeOnlyForTesting', ('hello', 'bye', '')) [u'hello', u'bye', u'hellobye'] If I redefined the procedure as CREATE PROCEDURE sp_DeleteMeOnlyForTesting @theInput varchar(50), @theOtherInput varchar(50), @theOutput varchar(100) OUTPUT AS SELECT * From dbo.testtable SET @theOutput=@theInput+ at theOtherInput Then, the python comes out as : >>> cursor = db.conn.cursor() >>> cursor.callproc('sp_DeleteMeOnlyForTesting', ('hello', 'bye', '')) [u'hello', u'bye', u''] My search on the web found a couple of posts with similar problems, but no solutions. I am using SQLOLEDB.1 as Provider, connecting to SQL Server 2005. Any help appreciated. I just need one method of passing an output parameter back to python. Thanks, Li From castironpi at gmail.com Wed Nov 26 18:38:16 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 26 Nov 2008 15:38:16 -0800 (PST) Subject: Python C/API simple debugging References: <419117eb-1050-4b1f-8d3d-c1523e7bf803@h20g2000yqn.googlegroups.com> Message-ID: <11b655fa-cbd3-4e1d-9334-73368201705c@w35g2000yqm.googlegroups.com> On Nov 26, 5:27?am, k3xji wrote: > Hi all, > > I am new to Python C API and finding it difficult to debug C > extensions. So, basically I want to see the value of an integer value > during the C API. Here is the code: > > #define LAST_MIX_VAL 0xDEADBEEF > > static PyObject * > chash(PyObject *self, PyObject *args) > { > ? ? unsigned int key,result; //treat key like an usinged int. > ? ? ? ? unsigned char a,b,c,d; > > ? ? ? ? key = result = 0; > ? ? if (!PyArg_ParseTuple(args, "i", &key)) > ? ? ? ? return NULL; > > ? ? ? ? printf("Key:%i\n",Py_BuildValue("i", key)); > ? ? ? ? . > . > > So, I just want to see the contents of local variable key. If I call > printf(..) without Py_BuildValue(), the interpreter shuts down, because > (I am assuming) printf is allocating some value in heap that is not in > the interpreter's heap itself which is causing the corruption. > > This way it works, but this time I cannot see correct key content. > > So, questions are: > - What I am doing wrong here? > - What is the preffered approach for these kind simple-debugging > issue? I searched C/API ref but cannot see any help on that? > > Thanks, This works fine for me: static PyObject * methA(PyObject *self, PyObject *args) { int a; PyArg_ParseTuple( args, "i", &a ); printf( "%i\n", a ); Py_INCREF(Py_None); return Py_None; } Did you want capital-I for 'unsigned int'? From arnodel at googlemail.com Sun Nov 16 04:47:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 16 Nov 2008 09:47:19 +0000 Subject: Official definition of call-by-value (Re: Finding the instance reference...) References: <6nvts2F15nlmU1@mid.individual.net> <8fcccfa8-3bc9-454c-b898-dfc080f0dc1d@f37g2000pri.googlegroups.com> <012fb0ab$0$20662$c3e8da3@news.astraweb.com> Message-ID: Derek Martin writes: > I think he meant None... Or at least, I personally see a distinction > between zero and None (and so do the Python docs). Zero is a value, > whereas None is specifically intended to denote the lack of any value. None is an 'value' which is intended to denote the absence of any 'value' *other than None*. > I would, FWIW, only make such a distinction in the context of a > computer program... Clearly in mathematics and elsewhere, zero is the > lack of a value (it is the value of nothingness). I would like to have a word with your maths teacher! There are plenty of uses for 0, most of which are unrelated to 'nothingess'. E.g. 0 is *greater* than -1 so it must be something. -- Arnaud From bj_666 at gmx.net Mon Nov 10 12:33:40 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Nov 2008 17:33:40 GMT Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <4917295A.4040907@v.loewis.de> <49185275.8060800@chamonix.reportlab.co.uk> Message-ID: <6nr9jkF7p33U5@mid.uni-berlin.de> On Mon, 10 Nov 2008 16:32:47 +0000, Robin Becker wrote: > on the other hand I find it odd that > > cmp(None,None) fails in Python 3 when None==None returns True. That's because there is no order defined for `NoneType` but equality is. Ciao, Marc 'BlackJack' Rintsch From hubaghdadi at gmail.com Tue Nov 4 08:05:01 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Tue, 4 Nov 2008 05:05:01 -0800 (PST) Subject: Which PostgreSQL adapter to use? Message-ID: <87586a88-48f7-49c1-819e-27aa49f1036e@s1g2000prg.googlegroups.com> Hey, Which Adapter to use with PostgreSQL: PyPgSQL, psycopg or PyGreSQL? Thanks. From tjreedy at udel.edu Fri Nov 28 15:03:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Nov 2008 15:03:32 -0500 Subject: unicode and hashlib In-Reply-To: References: Message-ID: Jeff H wrote: > hashlib.md5 does not appear to like unicode, > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa6' in > position 1650: ordinal not in range(128) It is the (default) ascii encoder that does not like non-ascii chars. I suspect that is you encode to bytes first with an encoder that does work (latin-???), md5 will be happy. Reports like this should include Python version. > After googling, I've found BDFL and others on Py3K talking about the > problems of hashing non-bytes (i.e. buffers) > http://www.mail-archive.com/python-3000 at python.org/msg09824.html > > So what is the canonical way to hash unicode? > * convert unicode to local > * hash in current local > ??? > but what if local has ordinals outside of 128? > > Is this just a problem for md5 hashes that I would not encounter using > a different method? i.e. Should I just use the built-in hash function? > -- > http://mail.python.org/mailman/listinfo/python-list > From hoteljorba at gmail.com Sun Nov 2 01:27:01 2008 From: hoteljorba at gmail.com (morecowbell) Date: Sat, 1 Nov 2008 23:27:01 -0700 (PDT) Subject: remote unzip References: <490c30e6$0$31346$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <7f6466df-2af5-4aec-9952-863c1a91acc2@x16g2000prn.googlegroups.com> On Nov 1, 5:35?am, Stefan Behnel wrote: > morecowbell wrote: > > i got a bunch of zip files on a remote server and need to get to one > > of the files, an xml file, in each of the archives. fairly simple to > > do locally with zipfile but i don't seem to be able to combine that > > local code with the paramiko sftp client. a rather simplified code > > snippet to illustrate: > > > import os > > import paramiko > > import StringIO > > import zipfile > > > remote_file = 'remote.zip' > > ssh = paramiko.SSHClient() > > ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", > > "known_hosts"))) > > ssh.connect('www.xxx.com', username='root', password='it_aint') > > sftp = ssh.open_sftp() > > dirlist = sftp.listdir('.') > > zipfile = sftp.file('remote.zip', 'r') > > unzip = ZipFile(zfile) > > for f in unzip.namelist(): > > ? ? if f.endswith('.xml'): > > ? ? ? ? output.write(unzip.read(unzip)) > > ? ? ? ? xmlfiles.append(output.getvalue()) > > > sftp.close() > > ssh.close() > > I suppose this code doesn't work for you? What's the output you get? > > "don't seem to be able" is not a very helpful problem description. > > Stefan thanks for looking at this. problem is, code seems to get lost in in space.when the zipfile portion gets invoked: run this: import os import paramiko import StringIO import zipfile remote_file = 'remote.zip' xml_files = [] ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) try: ssh.connect('www.xxx.com', username='root', password='itaint') except Exception, e: print (e.__class__,e) sftp = ssh.open_sftp() dirlist = sftp.listdir('.') print dirlist #zfile = sftp.file(remote_file, 'r') #print zfile #unzip = ZipFile(zfile) #for f in unzip.namelist(): # if f.endswith('.xml'): # output.write(unzip.read(unzip)) # xmlfiles.append(output.getvalue()) sftp.close() ssh.close() and we get the dirlist output: PyMate r8111 running Python 2.5.1 (python) >>> untitled ['.bash_profile', 'remote.zip', '.zshrc', '.mozilla', '.bash_logout', '.emacs', '.bashrc'] Program exited. uncomment the zfile line, i get the paramiko file object: PyMate r8111 running Python 2.5.1 (python) >>> untitled ['.bash_profile', 'odb012007101.zip', '.zshrc', '.mozilla', '.bash_logout', '.emacs', '.bashrc'] Program exited. uncomment the next line, where the unzipping is done, and the program goes off to digital neverland. i don't seem to be able to do anything with the paramiko.STFPfile object. even print dir(zfile) ends up in the script not completing. thx From mattia.landoni at gmail.com Sun Nov 16 11:33:42 2008 From: mattia.landoni at gmail.com (The Web President) Date: Sun, 16 Nov 2008 08:33:42 -0800 (PST) Subject: re.match and non-alphanumeric characters Message-ID: <6cb11aa9-fc04-4fc7-9145-91dcefc135d6@v22g2000pro.googlegroups.com> Dear all, this is really driving me nuts and any help would be extremely appreciated. I have a string that contains some numeric data. I want to isolate these data using re.match, as follows. bogus = "IFC(35m)" data = re.match(r'(\d+)',bogus) print data.group(1) I would expect to have "35" printed out to screen, but instead I get an error that the regular expression did not match: Traceback (most recent call last): File "C:\Documents and Settings\Mattia\Desktop\Neeltje\read.py", line 20, in print data.group(1) AttributeError: 'NoneType' object has no attribute 'group' Note that the same holds if I look for "35" straight, instead of "\d +". If instead I look for "IFC" it works fine. That is, apparently re.match will match only up to the first non-alphanumeric character and ignore anything after a "(", "_", "[" and god knows what else. I am using Python 2.6 (r26:66721, latest stable version). Am I missing something very big and very important? From tekion at gmail.com Sun Nov 30 11:50:43 2008 From: tekion at gmail.com (tekion) Date: Sun, 30 Nov 2008 08:50:43 -0800 (PST) Subject: Help with capturing error References: <73731647-d177-4e80-9cca-0a95ed49199e@g38g2000yqd.googlegroups.com> Message-ID: <48feeef2-6c81-4f40-a81c-6b5cca11b743@s1g2000prg.googlegroups.com> Yes, you are absolutely right. I had open a file earlier and when it reach end of line with no new idea; it seems to have closed the file. I am not sure if this because I am using my own class to open and read a file or just a python behavior. I plan to test this out. On another note, is there a way for python to emulate a "tail -f" in Linux? Thanks. From tschork at gmail.com Tue Nov 11 15:18:26 2008 From: tschork at gmail.com (Thierry) Date: Tue, 11 Nov 2008 12:18:26 -0800 (PST) Subject: sys.stdout, urllib and unicode... I don't understand. Message-ID: Hello fellow pythonists, I'm a relatively new python developer, and I try to adjust my understanding about "how things works" to python, but I have hit a block, that I cannot understand. I needed to output unicode datas back from a web service, and could not get back unicode/multibyte text before applying an hack that I don't understand (thank you google) I have realized an wxPython simple application, that takes the input of a user, send it to a web service, and get back translations in several languages. The service itself is fully UTF-8. The "source" string is first encoded to "latin1" after a passage into unicode.normalize(), as urllib.quote() cannot work on unicode >>srcText=unicodedata.normalize('NFKD',srcText).encode('latin1','ignore') After that, an urllib request is sent with this encoded string to the web service >>con=urllib2.Request(self.url, headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'}, origin_req_host='http://translate.google.com') >>req=urllib2.urlopen(con) First problem, how to determine the encoding of the return ? If I inspect a request from firefox, I see that the server return header specify UTF-8 But if I use this code: >>ret=U'' >>for line in req: >> ret=ret+string.replace(line.strip(),'\n',chr(10)) I end up with an UnicodeDecodeError. I tried various line.decode(), line.normalize and such, but could not make this error disapear. I, until now, avoided that problem as the service always seems to return 1 line, but I am wondering. Second problem, if I try an >>print line into the loop, I too get the same error. I though that unicode() would force python to consider the given text as unicode, not to try to convert it to unicode. Here again, trying several normalize/decode combination did not helped at all. Then, looking for help through google, I have found this post: http://mail.python.org/pipermail/python-list/2007-October/462977.html and I gave it a try. What I did, though, was not to override sys.stdout, but to declare a new writer stream as a property of my main class: >>self.out=OutStreamEncoder(sys.stdout, 'utf-8') But what is strange, is that since I did that, even without using this self.out writer, the unicode translation are working as I was expecting them to. Except on the for loop, where a concatenation still triggers the UnicodeDecodeErro exception. I know the "explicit is better than implicit" python motto, and I really like it. But here, I don't understand what is going on. Does the fact that defining that writer object does a initialization of the standard sys.stdout object ? Does it is related to an internal usage of it, maybe in urllib ? I tried to find more on the subject, but felt short. Can someone explain to me what is happening ? The full script source can be found at http://www.webalis.com/translator/translator.pyw From MarkusJNZ at gmail.com Thu Nov 20 01:10:21 2008 From: MarkusJNZ at gmail.com (MarkusJ_NZ) Date: Wed, 19 Nov 2008 22:10:21 -0800 (PST) Subject: Moving file on remote server: How? References: Message-ID: <1ef10170-5406-4904-8b93-6f964c0cadd1@k1g2000prb.googlegroups.com> On Nov 20, 3:54?pm, alex23 wrote: > On Nov 20, 3:40?pm, MarkusJ_NZ wrote: > > > Can someone please tell me if / how I can move a file between folders > > on a remote server via FTP using Python. > > I'm assuming you're using ftplib? > > Try ftp.rename() (although I'm not in a position to test this...) Hi Alex, thanks for your help Markus From skip at pobox.com Thu Nov 20 18:58:52 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 20 Nov 2008 17:58:52 -0600 Subject: Python 3 __cmp__ semantic change? In-Reply-To: <9b9hv5x3fj.ln2@joeserver.homelan.net> References: <642a426a-74f4-460c-a274-8dc78c3c8611@d42g2000prb.googlegroups.com> <87bpwa59ap.fsf@benfinney.id.au> <9b9hv5x3fj.ln2@joeserver.homelan.net> Message-ID: <18725.63932.554595.199680@montanaro-dyndns-org.local> Johannes> Seems it was removed on purpose - I'm sure there was a good Johannes> reason for that, but may I ask why? Start here: http://www.mail-archive.com/python-3000 at python.org/msg11474.html Also, a comment to this blog post suggests creating a CmpMixin: http://oakwinter.com/code/porting-setuptools-to-py3k/ Skip From wkwang at cisco.com Thu Nov 13 16:45:39 2008 From: wkwang at cisco.com (Peter Wang) Date: Thu, 13 Nov 2008 16:45:39 -0500 Subject: Documenation for yum and rpmUtils modules Message-ID: <1226612740.367527@sj-nntpcache-2.cisco.com> Hi All, I'm new to Python. I troubleshoot a yum install error. so i'm studying yum and rmpUtils module and try to understand how yum works. Do you know where can I find the documenation for yum and rpmUtils module? Thanks, Peter From tjreedy at udel.edu Fri Nov 7 14:13:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Nov 2008 14:13:43 -0500 Subject: Finding the instance reference of an object [long and probably boring] In-Reply-To: <67E950AD-C574-466E-B97D-FE77F43769C5@strout.net> References: <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <01203bbd$0$20642$c3e8da3@news.astraweb.com> <3c4edf32-acda-4244-ba46-bad5ea623303@w39g2000prb.googlegroups.com> <0120cb30$0$20642$c3e8da3@n ews.astraweb.com> <00ec01c93eb7$8eab5460$0d00a8c0@hendrik> <01F40A1D-4368-48B6-AF13-C264DA5B40B6@strout. net> <67E950AD-C574-466E-B97D-FE77F43769C5@strout.net> Message-ID: Joe Strout wrote: > On Nov 6, 2008, at 10:35 PM, Steve Holden wrote: > Note: I tried to say "name" above instead of "variable" but I couldn't > bring myself to do it -- "name" seems to generic to do that job. Python has two types of names. Some complex objects -- modules, classes, and functions, and wrappers and subclasses thereof, have 'definition names' that are used instead of a 'value' to print a representation. Otherwise, names are identifiers, the term used in the grammar. But I agree even two meaning is one too many. Maybe 'label' would be a better short form for 'identifier'. 'Labeling' might be clearer for many beginners than 'name-binding'. > Lots > of things have names that are not variables: modules have names, classes > have names, methods have names, and so do variables. If I say "name," > an astute listener would reasonably say "name of what" Common nouns, when instantiated, become the name of whatever particular object they are associated with. > -- and I don't > want to have to say "name of some thing in a name space which can be > flexibly associated with an object" when the simple term "variable" > seems to work as well. 'Variable' has many more meanings than 'name' or 'label' and overall seems to be more confusing, not less. I say this as an empirical observation of c.l.p postings. You yourself switched back and forth between two different meanings. > I'm with you there. To me, the consistent simplicity is exactly this: > all variables are object references, and these are always passed by value. The me, this implies that the corresponding parameter should become a reference to that reference value. In any case, the last 10 years of this newsgroups shows that describing Python calling as 'by value' confuses people so that they are surprised that mutating a list inside a function results in the list being mutated outside the function. > But Python doesn't have those simple types, so there is a temptation to > try to skip this generalization and say that references are not values, The Python Language Reference uses the word 'reference' but does not define it. I take it to be 'whatever information an interpreter uses to associate a name or collection slot with an object and to retrieve the object (and possibly its value) when requested'. > Well of course. I'm pretty sure I've said repeatedly that Python > variables refer to objects on the heap. Built-in objects are not allocated on the heap. >(Please replace "heap" with "object space" if you prefer.) They are in abstract object space, although CPython occasionally leaks the abstraction in error messages about not being able to modify non-heap objects. > I'm only saying that Python variables > don't contain any other type of value than references. One problem with the word 'variable' is that variables are somethings thought of as 'containing', as you did above. So you switch back and forth between 'variables *are* references' and 'variables *contain* references'. Whereas a name (noun) definitely *is* a reference and not a container. > Ditto right back at you. :) So maybe here's the trouble: since all > Python variables are references, Back to *is*. > But continuing to attempt to gloss over that fact, when you come to > parameter passing, I believe most of us here try to follow Knuth's lead and use 'parameter' for the local names and 'argument' for the value/object that gets associated with the name. > not copied). You also have to describe the assignment operator as In Python, assignment is not an operator by intentional design. > different from all other languages, since clearly that's not copying the > object either. Python's assignment *statement* does what we routinely do in everyday life when we assign new labels to things, whether permanently or temporarily. > An assignment copies the RHS > reference into the LHS variable, nothing more or less. Back to variable as container. An assignment associates the RHS object(s) with the LHS target(s). > A parameter copies the argument reference into the formal parameter, A function call associates objects derived from the argument expressions and stored defaults with the function parameters. > Isn't that simple, clear, and far easier to explain? Applied to my version, I agree ;-). > I wonder if that could be tested systematically. Perhaps we could round > up 20 newbies, divide them into two groups of 10, give each one a 1-page > explanation either based on passing object references by-value, or > passing values sort-of-kind-of-by-reference, and then check their > comprehension by predicting the output of some code snippets. That'd be > very interesting. Except for your garbling of the alternative to your version, I agree. I suspect that different people might do better with different explanations, depending on background. > In my case, my understanding of Python became clear only once I stopped > listening to all the confusing descriptions here, and realized that > Python is no different from other OOP languages I already knew. Whereas I learned Python without any OOP experience but enough knowledge of C++ to know I did not want to go there. Terry Jan Reedy From jzakiya at mail.com Tue Nov 18 10:58:36 2008 From: jzakiya at mail.com (jzakiya) Date: Tue, 18 Nov 2008 07:58:36 -0800 (PST) Subject: Sieve of Zakiya References: <1992da9f-a844-4e2c-bab4-b930b1c938bd@q26g2000prq.googlegroups.com> <9fee2688-2fdb-4926-b235-d4d6026f993b@d42g2000prb.googlegroups.com> <86cbc999-befc-4427-9d9a-d8cf0b131aac@f40g2000pri.googlegroups.com> Message-ID: On Nov 18, 5:01?am, Mark Dickinson wrote: > On Nov 18, 7:53?am, jzakiya wrote: > > >www.4shared.com/account/dir/7467736/97bd7b71/sharing > > From the introduction to the paper: > > "Thus began a process that culminated in my developing a new class > of Number Theory Sieves (NTS) to generate prime numbers, and test > primality of numbers, that use minimum memory, are simple to code, > and are much faster than all previously known methods." > > That's quite a claim! ?You might consider toning this down > a little if you want to be taken seriously. ?:-) > > How does your prime-generating algorithm stack up against > Bernstein's primegen package? > > http://cr.yp.to/primegen.html > > Mark Hi Mark, Someone has done a multi-core C implementation (for AMD-X2 and Intel quad and 8-core systems using Intel and GCC compilers) and the SoZ prime generators are faster than the Sieve of Atkin (SoA) and Sieve of Eratosthenes (SoE). I think(?) he tried to run Bernstein's primegen, but its old code written before multi-core and widely used 64-bit systems, so he wrote his own multi-core/threaded version for his systems. The SoZs again, are faster. I've implemented the SoZ generators in Forth, Ruby, and Python, and all show the same results, to be faster than the SoA and SoE in those languages, along with C. Now that I've corrected the Python code (I am NOT a native Python programmer) it now beats the SoA implementation included in the code using psyco too (for 2.4.3, I don't have it for other versions). Run the code and see for yourself! :-) I am writing another paper explaining some of the mathematical basis for the SoZ, with complexity analysis, but I keep finding "interesting" features about the underlying math, which I hope real mathematicians will investigate and reveal what's going on here. I want to release at least a first version before December. But the proof is in the pudding, and the results speak for themselves. It's an amazingly simple algorithm, so tear it apart. Jabari From thudfoo at opensuse.us Thu Nov 13 18:02:58 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 13 Nov 2008 15:02:58 -0800 Subject: ctypes shared object FILE* In-Reply-To: <22c088140811081634j58a374c4p30b6905775ad55f7@mail.gmail.com> References: <22c088140811081634j58a374c4p30b6905775ad55f7@mail.gmail.com> Message-ID: <3d881a310811131502h7a658c38rd64321a7cfabe039@mail.gmail.com> On 11/8/08, Dog Walker wrote: > I need to call a function in a shared object with this signature: > init_dialog(FILE *input, FILE *output) > The FILE*'s are to stdin and stdout. > > The call from python is libdialog.init_dialog( x, y) > I need to define x and y so that they will have the structure of > sys.stdin and sys.stdout; the called function (init_dialog) is using a > (std?) function fileno to extract the fileno from the FILE* describing > stdin and stdout. > How can I do this? > I should have said "stderr" rather than "stdout". And the answer is: from ctypes import * from ctypes.util import find_library libc = CDLL(find_library("c")) libdialog = CDLL(find_library("dialog")) class FILE(Structure): pass libdialog.init_dialog(POINTER(FILE).in_dll(libc, "stdin"), POINTER(FILE).in_dll(libc, "stderr")) > -- > I have seen the future and I'm not in it! > > -- > http://mail.python.org/mailman/listinfo/python-list > From cbiarun123 at gmail.com Wed Nov 26 08:25:41 2008 From: cbiarun123 at gmail.com (alan wells) Date: Wed, 26 Nov 2008 05:25:41 -0800 (PST) Subject: ONLINE EARNINGS $$$ 500 - $$$ 1000 PER MONTH WITHOUT INVESTMENT... Message-ID: <03549f30-3438-4b5c-b1ff-ca9eaf4d2137@p2g2000prn.googlegroups.com> ONLINE EARNINGS $$$ 500 - $$$ 1000 PER MONTH WITHOUT INVESTMENT... projectpayday has been proven to a legit source of income that can be earned the same day you sign up.the best programme i found in online that it pays more than $100 perday to me. they provides you step by step guide untill than you made your first payment.You won't "get rich" but 1,000s of people have proven it's a realistic extra income system for the "Average Joe".. just have a look at this network.when i just join here i start earn within 15 minutes http://tinyurl.com/45twel The best opportunity to earn money. It is a free money making network. Mkke use it From bearophileHUGS at lycos.com Mon Nov 3 13:24:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 3 Nov 2008 10:24:30 -0800 (PST) Subject: length of a tuple or a list containing only one element References: <6bd670f7-89cd-4e27-80de-f82646a1658c@r37g2000prr.googlegroups.com> <79375523-8279-489f-a4df-d272ec6cd20c@q26g2000prq.googlegroups.com> Message-ID: Arnaud Delobelle: >And introduces some new inconsistencies for newcomers, e.g. > s = {1, 2, 3} # A set with 3 elements > s = {1} # A set with one element > s = {} # Surely, this should be an empty set!! Are you able to list other inconsistencies? Python3 introduces one or two warts, but removes many more inconsistencies, so for me it's a net gain. So far for me, beside the one you have shown, there's only another detail I don't like of Python3 (the removal of tuple unpaking in function calls). Bye, bearophile From saju.pillai at gmail.com Wed Nov 5 12:09:52 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Wed, 5 Nov 2008 09:09:52 -0800 (PST) Subject: How to build the pysqlite? Where to find the "sqlite3.h"? References: <5796cb61-28f0-48d7-bd67-e546dd1131f0@t39g2000prh.googlegroups.com> <59e6941f-73b4-4251-a45c-e73aece799e5@b38g2000prf.googlegroups.com> Message-ID: On Nov 5, 10:07?pm, "Shawn Milochik" wrote: > On Wed, Nov 5, 2008 at 11:58 AM, saju.pil... at gmail.com > > > > wrote: > > On Nov 5, 9:22 pm, "Shawn Milochik" wrote: > >> This is all useful and interesting stuff, but I don't think any of it > >> addresses the original poster's problem, which is that he has no root > >> access to a Linux or Unix box, and wants to get pysqlite2 working in > >> his home directory. I have exactly the same problem. I have tried the > >> "python setup.py install --home=~" method, and I get errors from GCC > >> that I have no permissions (and to be honest, nor the knowledge) to > >> overcome. > > >> Isn't there anyway to get a Linux binary that can just be put > >> somewhere in the Python path so we can use sqlite? Or are those of us > >> without admin/root control of our boxes screwed? > > > 1. Get sqlite3 fromhttp://www.sqlite.org/sqlite-3.6.4.tar.gz > > 2. build and install sqlite3 (./configure --prefix=/any/writeable/dir > > && make install) -- you may want to supply the --disable-tcl flag if > > you hit permission problems > > 3. get pysqlite3, edit setup.cfg libraries and include lines to point > > to the lib/ and include/ dir where you installed sqlite3 in the > > previous step > > 4. python setup.py install --home=somewhere > > 5. PYTHONPATH=somewhere ./python -- import pysqlite2 should work for > > you > > -- > > Thanks, but either I'm missing something or you're missing something. > I can't do any of what you describe on the machine I want to use > sqlite on. > > I have downloaded the binary sqlite3 file from sqlite's Web site, and The linux binary will not work. You need the headers and the libraries. Grab the src tar ball and build and install locally. -srp > I can use it with shell scripts and via the command line with no > problem. The issue is that I don't seem to have any way available to > me to use the pysqlite2 Python module. > > When I try the "python setup.py --install --home=somewhere" > installation, it blows up on GCC errors that I do not have the > permissions to even attempt to fix. ?What I was asking above was > whether there was a way do download the pysqlite2 module as files that > I can just copy into a directory that Python thinks is part of its > path so I can use it without having to compile or build it in any way > on that machine. > > Thanks, > Shawn From joe at strout.net Thu Nov 13 12:16:59 2008 From: joe at strout.net (Joe Strout) Date: Thu, 13 Nov 2008 10:16:59 -0700 Subject: using "private" parameters as static storage? Message-ID: <00A7304C-709D-4F94-8E72-B0C3FD791183@strout.net> One thing I miss as I move from REALbasic to Python is the ability to have static storage within a method -- i.e. storage that is persistent between calls, but not visible outside the method. I frequently use this for such things as caching, or for keeping track of how many objects a factory function has created, and so on. Today it occurred to me to use a mutable object as the default value of a parameter. A simple example: def spam(_count=[0]): _count[0] += 1 return "spam " * _count[0] >>> spam() 'spam ' >>> spam() 'spam spam ' This appears to work fine, but it feels a little unclean, having stuff in the method signature that is only meant for internal use. Naming the parameter with an underscore "_count" makes me feel a little better about it. But then, adding something to the module namespace just for use by one function seems unclean too. What are your opinions on this idiom? Is there another solution people generally prefer? Ooh, for a change I had another thought BEFORE hitting Send rather than after. Here's another trick: def spam2(): if not hasattr(spam2,'count'):spam2.count=0 spam2.count += 1 return "spam2 " * spam2.count This doesn't expose any uncleanliness outside the function at all. The drawback is that the name of the function has to appear several times within itself, so if I rename the function, I have to remember to change those references too. But then, if I renamed a function, I'd have to change all the callers anyway. So maybe this is better. What do y'all think? Best, - Joe From ldo at geek-central.gen.new_zealand Sun Nov 16 02:01:47 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 16 Nov 2008 20:01:47 +1300 Subject: Building musical chords starting from (a lot of) rules References: <6uSdnbjyCJqaWILUnZ2dnUVZ_qXinZ2d@earthlink.com> Message-ID: In message <6uSdnbjyCJqaWILUnZ2dnUVZ_qXinZ2d at earthlink.com>, Dennis Lee Bieber wrote: > On Sun, 16 Nov 2008 19:21:49 +1300, Lawrence D'Oliveiro > declaimed the following in > comp.lang.python: > >> In message , >> Mr.SpOOn wrote: >> >> > C 9 is a base chord plus a the ninth note, but this implies the >> > presence of the seventh too, so it results in: C E G B D >> >> I don't recall such meanings in the chord names I came across. If you >> wanted both a seventh and ninth, you had to say so: "C7+9" or "Cmaj7+9". > > My books on harmony and such do indicate that a Cx implies all the > intervening odd values up to x... But they also tend to indicate that > (especially for guitar) the intervening can be left out... Well, I did pick up chord notation mainly from guitar-playing friends. Myself I was learning classical piano, where we didn't have much need for such things. :) From joe at strout.net Mon Nov 24 15:36:32 2008 From: joe at strout.net (Joe Strout) Date: Mon, 24 Nov 2008 13:36:32 -0700 Subject: recommended __future__ imports for 2.5? Message-ID: OK, this will probably be placed into the "stupid question" category by some, but I really am in need of a bit of guidance here. I just rediscovered the "gotcha" of integer division in 2.5 and below, and found (to my delight) that this is fixed in 3.0, and fixable in older versions of Python with "from __future__ import division". Once I stumbled across that, I was able to find the relevant PEP (#238) and read more about it. So now that import has become part of our standard boilerplate at the top of each file, along with the path to Python and the UTF-8 encoding declaration. Now I'm wondering what other boilerplate I should be using. I'm not yet ready to upgrade to Python 2.6 -- parts of our business model rely on using the standard Python installed with Mac OS X (which is currently 2.5.1). But I would like our code to be as future-proof as possible, especially in cases like this where we're talking about changes to existing behavior, rather than the introduction of entirely new features (like the "with" statement). I found , which lists the available future imports, but doesn't link to any documentation on them. Searching for each one on google turns up some probably- relevant PEPs, but it's hard for a relative newbie to tell for sure exactly what was implemented when and which is merely a summary of discussion. So... besides "division", are there any other imports you would recommend as standard for any new code written in 2.5? And what else do you experienced gurus put at the top of every Python file? Thanks, - Joe From clp at rebertia.com Fri Nov 28 20:56:33 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 28 Nov 2008 17:56:33 -0800 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <92e687e9-f7e3-4a05-af88-4aff87145192@33g2000yqm.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <013fc09a$0$20626$c3e8da3@news.astraweb.com> <92e687e9-f7e3-4a05-af88-4aff87145192@33g2000yqm.googlegroups.com> Message-ID: <47c890dc0811281756k4578821bp6f700707ea1c942b@mail.gmail.com> On Fri, Nov 28, 2008 at 9:52 AM, r wrote: >> and we're not throwing ourselves at your pet project because most of us don't give a monkey's toss about Sketchup. > Why should we put our time and energy into a piece of software that we don't care about? > > AGAIN, I'm NOT asking you to support SKETCHUP I am asking for support > for PYTHON! Did you even read my entire OP?? Or did you just jump on > Chris's bandwagon? Do you think for yourself, or do you follow blindly > like a SHEEPLE?? > Since when do I have a bandwagon? I made one purely informational post and just said that I personally didn't really care one way or another about SketchUp. I'm not particularly pro- or anti- your idea, I just classified it as "personally irrelevant" but thought I'd point out one possibly relevant fact to you to be helpful. That's all. There Is No Cabal. Cheers, Chris From Tribulations at Paralleles.invalid Mon Nov 3 14:18:35 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 03 Nov 2008 20:18:35 +0100 Subject: script that parses command line, and execfile('') Message-ID: Hello, I have a script that uses the "optparse" package to parse the command line. For example: $ script.py --help # displays help about script.py Is this possible to call such a script with execfile('') once in the Python interactive shell? >>> execfile( 'script.py' ) I get errors because there is no argv dictionary when used with execfile. How to solve this problem, so that I am able to use script.py in command line as well as with execfile? Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z (55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From roy at panix.com Fri Nov 7 21:36:41 2008 From: roy at panix.com (Roy Smith) Date: Fri, 7 Nov 2008 18:36:41 -0800 (PST) Subject: Are .pyc files portable? Message-ID: <0a47b9e7-c07b-4a25-a7c1-0ee894803b74@x16g2000prn.googlegroups.com> I'm using Python as part of a test fixture for a large (mostly C++) software project. We build on a lot of different platforms, but Solaris is a special case -- we build on Solaris 8, and then run our test suite on Solaris 8, 9, and 10. The way the build system is set up (driven by Build Forge), the Sol 8, 9, and 10 test passes can happen in any order. The tests all run in a common directory, shared by NFS on all three machines. If (for example) the Sol 10 tests run first, and create .pyc files, will those .pyc files work correctly when the Sol 8 and Sol 9 test passes come along and run them in the same directories? The python binary is a build of 2.5.1 that we did on Solaris 8. The same binary is used on all Solaris platforms. Although we do separate 32-bit and 64-bit builds of our product, the python binary we use for the test driver is the same 32-bit build on all of them. A related question: is there any way to tell Python to put the .pyc files in some other directory, i.e. NOT the same directory where the .py sources are. That would make things cleaner, since we could just tell each system to put its .pyc's in a different place. We've also got some games we play with symlink farms (lndir), which may be part of the solution here, but I want to explore all the possibilities first. From arnodel at googlemail.com Mon Nov 3 12:20:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 03 Nov 2008 17:20:33 +0000 Subject: length of a tuple or a list containing only one element References: <6bd670f7-89cd-4e27-80de-f82646a1658c@r37g2000prr.googlegroups.com> <79375523-8279-489f-a4df-d272ec6cd20c@q26g2000prq.googlegroups.com> Message-ID: bearophileHUGS at lycos.com writes: > Steve Holden: >> While this kind of beginner >> mistake is common it isn't one that's frequently repeated once the >> learner understands the syntax. > > You may be right, but I don't have to like it. > When you teach programming to people that have never done it before, > and you use Python, they spot similar inconsistences in the blink of > an eye and often look annoyed. [...] You can teach them that the comma is a terminator rather than a separator (no more inconsistencies), but that the python parser is forgiving and understands when the last comma is missing if the expression is not already meaningful. I.e. one should write (1, 2, 3,) But python, being nice, understands when you write (1, 2, 3) Now consider this: 3 * (1 + 2) What interpretations should python take of the brackets? > The good thing is that Python3 fixes some of those things :-) And introduces some new inconsistencies for newcomers, e.g. s = {1, 2, 3} # A set with 3 elements s = {1} # A set with one element s = {} # Surely, this should be an empty set!! -- Arnaud -- Arnaud From grahn+nntp at snipabacken.se Mon Nov 10 17:22:29 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 10 Nov 2008 22:22:29 GMT Subject: disable ctrl-P in idle? References: <6g4hh49fabbu32k3e7p9j5n5186i5985re@4ax.com> <93eb5534-9185-4b48-ac46-fe504b0b3015@a29g2000pra.googlegroups.com> <5e427676-4ec8-4eb0-a44a-64ac33be14c7@g17g2000prg.googlegroups.com> Message-ID: On Mon, 10 Nov 2008 13:53:40 -0800 (PST), drobinow at gmail.com wrote: > On Nov 10, 3:27?pm, "timw.google" wrote: >> On Nov 10, 2:57?pm, Robert Singer wrote: ... >> > Or, you can just continue using emacs. I'm using vim, and can't think >> > of a single reason why I should change it for idle. >> Thanks. I on a XP box now, and it's a pain to get things installed >> here. That's why I'm not using emacs. When I'm on Linux, I use emacs. >> It's not worth the trouble to install something else for just this. > > It is not more difficult to install emacs on XP. What makes you think > that? Yeah. To me, it has just been a matter of unzipping emacs-x.y.z.zip somewhere, placing my .emacs somewhere where emacs searches for it, tell it to use the Lucida Console font and type away. As far as I can tell, there is no need to be local admin. (Of course, timw's employer might forbid Downloading Dangerous Unlicenced Freeware from the Internet -- but be got IDLE somehow, didn't he?) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From gslindstrom at gmail.com Wed Nov 19 07:47:07 2008 From: gslindstrom at gmail.com (greg) Date: Wed, 19 Nov 2008 04:47:07 -0800 (PST) Subject: Programming exercises/challenges References: Message-ID: On Nov 18, 6:39?pm, btk... at email.unc.edu wrote: > Hi guys, > > I'm learning Python by teaching myself, and after going through several > tutorials I feel like I've learned the basics. Since I'm not taking a > class or anything, I've been doing challenges/programs to reinforce the > material and improve my skills. I started out with stuff like "Guess my > number" games, hangman, etc. and moved on to making poker and card > games to work with classes. For GUIs I created games like minesweeper, > and a GUI stock portfolio tracker. I am out of ideas and am looking for > programming projects, challenges, or programs that have helped you'll > learn. I'm working on the project Euler problems, but I find that they > don't really help my programming skills; they are more math focused. > Suggestions? What has been useful or interesting to you? I'd also > welcome sources of textbook type problems, because the ones provided in > tutorials tend to be repetitive. > > Thanks, > Ben You night look at "Useless Python" (you'll have to Google for the site). It has tons of problems from trivial to complex. --greg From greg at cosc.canterbury.ac.nz Thu Nov 13 05:57:52 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 13 Nov 2008 23:57:52 +1300 Subject: Official definition of call-by-value (Re: Finding the instance reference...) In-Reply-To: References: <6nvts2F15nlmU1@mid.individual.net> Message-ID: <6o2fcaF1hu55U1@mid.individual.net> Fredrik Lundh wrote: > Python's definition of the word "value" can be found in the language > reference: > > http://docs.python.org/reference/datamodel.html#objects-values-and-types That whole passage is talking almost exclusively about the value of an *object*: Every object has an identity, a type and a value... ...possible values for objects of that type... The value of some objects can change... etc. etc. But we don't want to know about the value of an object, we want to know about the value of an *expression*. That section doesn't tell us. Nor does it tell us that expressions don't *have* values. It says nothing about expressions at all. > Using that definition, a Python expression yields an object, not an > object value. And as I've said before, that's a perfectly fine viewpoint. Because, An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. [http://docs.python.org/reference/simple_stmts.html#grammar-token-assignment_stmt] and what it says about binding makes it clear that assignment is a form of binding operation. So it doesn't matter *what* you call the result of an expression -- a value, an object, an object reference, or whatever -- the differences all cancel out when you define assignment in a corresponding way. -- Greg From alanbaljeu at yahoo.com Fri Nov 14 14:06:48 2008 From: alanbaljeu at yahoo.com (Alan Baljeu) Date: Fri, 14 Nov 2008 11:06:48 -0800 (PST) Subject: Fw: automatic reload Message-ID: <996300.25699.qm@web58306.mail.re3.yahoo.com> Alan Baljeu http://www.collaborative-systems.org Intelligent software that works _with_ you. ----- Forwarded Message ---- From: Alan Baljeu To: Mike Driscoll Sent: Friday, November 14, 2008 2:06:26 PM Subject: Re: automatic reload I thought I was reading something specific was made for unittest, although I can't find it now. TurboGears I don't know much about. I'm concerned its reload is specialized for a certain type of file (page generators?) and might not be suitable in general. The other option I was suggessting PyInitialize and Py_Finalize. Finalize comes with a scary list of issues, which basically say things may fail and memory may leak. I notice also Py_NewInterpreter/Py_EndInterpreter does about the same thing for me. Maybe that's the way to go. But these caveats scare me: Also note that the use of this functionality is incompatible with extension modules such as PyObjC and ctypes that use the PyGILState_* APIs (and this is inherent in the way the PyGILState_* functions work). Simple things may work, but confusing behavior will always be near.I'm not sure what these are, but they sound like what I would use in embedding the interpreter. But then again, this is a C function designed for embedding. How could this be a problem? Alan Baljeu ----- Original Message ---- From: Mike Driscoll To: python-list at python.org Sent: Friday, November 14, 2008 12:08:06 PM Subject: Re: automatic reload On Nov 14, 11:04 am, Alan Baljeu wrote: > I need a solution for automatically reloading files I edited. This is in a unit testing/fixing context, so there shouldn't be much problem with leftover data. I just need to be able to call a reload_changed() method of some sort before rerunning tests. Stopping and restarting the python interpreter (it's embedded) might be an option if (a) that's feasible within a process and (b) it's quick. > > Alan Baljeuhttp://www.collaborative-systems.org > Intelligent software that works _with_ you. > There's the "reload" builtin that you could use. In your method, just call reload on the modules you need reloaded. TurboGears somehow watches files for changes, so you might want to check out their source to see how it works. I'm sure it's something similar. Mike -- http://mail.python.org/mailman/listinfo/python-list __________________________________________________________________ Get a sneak peak at messages with a handy reading pane with All new Yahoo! Mail: http://ca.promos.yahoo.com/newmail/overview2/ __________________________________________________________________ Looking for the perfect gift? Give the gift of Flickr! http://www.flickr.com/gift/ From godson.g at gmail.com Wed Nov 12 05:40:43 2008 From: godson.g at gmail.com (Godson Gera) Date: Wed, 12 Nov 2008 16:10:43 +0530 Subject: How to navigate one window to another window through python scripts ? In-Reply-To: <002101c944a9$7bc15780$750ba8c0@patni.com> References: <002101c944a9$7bc15780$750ba8c0@patni.com> Message-ID: On Wed, Nov 12, 2008 at 3:01 PM, sambasivareddy wrote: > Hi all, > > > > How to navigate one window to another window through python scripts ? > > > > Basically I want to do Automatic testing one windows base c#.net > application through python scripts. > > > > I am Able to open the executable file with following scripts. > > Import os > > Os.system ('abc.exe') > > > > But how to navigate from one window to another window? > > How to set values in that window with python script? > > > > if any one have sample code and documents Plz share to me. > > Your inputs will really helpful and thanks in advance !!!!! > > > > *Regards**,* > > *Sambasivareddy.S* > You can use pywinauto http://pywinauto.openqa.org/ to automate desktop applications on windows. Thanks & Regards, Godson Gera http://godson.in -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrewpadilla1 at gmail.com Thu Nov 20 10:37:33 2008 From: andrewpadilla1 at gmail.com (Andrew) Date: Thu, 20 Nov 2008 07:37:33 -0800 (PST) Subject: imported method from module evaluates to None in some cases References: <873ahm1p2z.fsf@mulj.homelinux.net> Message-ID: <10880cd2-3933-46e8-b003-af7b3f7f0e90@o40g2000prn.googlegroups.com> On Nov 20, 6:53 am, Hrvoje Niksic wrote: > Andrew writes: > > I'm having a problem in some zope (2.10) code (HTTPResponse.py) where > > a method that gets imported somehow evaluates to None in certain cases > > which causes a TypeError exception to be raised (eg: TypeError: > > 'NoneType' object is not callable). The code excerpt is below where > > the exception is raised on the line with the comment 'TypeError IS > > RAISED HERE'. > > Could the "certain cases" involve automatic invocation of the close > method at interpreter shutdown? While the interpreter shuts down, > module-level variables are set to None. This is documented in some > detail inhttp://www.python.org/doc/essays/cleanup/, steps C1-C3. That's possible. I didn't know that. Now I guess the question for me is why and where did the interpreter shutdown? I don't see log entries relating to it. Is it possible for me to intercept an interpreter shutdown so I can find out the location and possibly the reason why the interpreter abruptly shuts down? From thebrasse at gmail.com Fri Nov 7 02:59:07 2008 From: thebrasse at gmail.com (brasse) Date: Thu, 6 Nov 2008 23:59:07 -0800 (PST) Subject: contextlib.nested() References: <4912ca4d$0$5462$9b622d9e@news.freenet.de> <6ngl90Fldsc3U1@mid.uni-berlin.de> Message-ID: <1a81beb4-23ab-4cb5-9161-e5db44e44171@u29g2000pro.googlegroups.com> On Nov 6, 5:45?pm, "Diez B. Roggisch" wrote: > > If you had a class that wanted to acquire some external resources that > > must be released at some point, how would you rewrite the code from my > > example? > > If you *can*, use a context. Use __enter__ and __exit__. Try really hard to > use it that way. > My case becomes something like this: from __future__ import with_statement from contextlib import nested class Foo(object): def __init__(self, tag, fail=False): print 'ctor', tag self.tag = tag self.fail = fail def __enter__(self): if self.fail: print 'fail', self.tag raise Exception() print '__enter__ acquire resource', self.tag return self def __exit__(self, *args): print '__exit__ release resource', self.tag with nested(Foo('a'), Foo('b', True)) as (a, b): print a.tag print b.tag When using Foo objects in a with statement this works good for me. But what if I want to use Foo objects as members in a class for example? Since we now must contruct an instance of Foo in two stages the code becomes less than ideal. def __init__(self): self.x = Foo() self.x.__enter__() Perhaps there is no way to write classes that fits neatly into all (or even these two) usage scenarios? > If not - create a specific finalize-method or some such, and try not to > forget to call that. Potentially with an atexit-handler or some such. > It seems to me that I have to use the with statement (or some try- finally construct) to be able to release all resources when my code throws exceptions(). Just remembering to call close/finalize/destroy will not be enough. :.:: mattias From george.sakkis at gmail.com Thu Nov 27 23:57:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 27 Nov 2008 20:57:53 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <082ed3fd-f194-4ddb-ace8-81c6a9d18a98@k41g2000yqn.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> Message-ID: <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> On Nov 27, 10:45?pm, r wrote: > I am still flabbergasted by the solid resistance to promoting Python. > Here of all places, NOT even one person(well Terry did kinda half > agree with me =), wants to support Python. I am completely perplexed. > I had to check and make sure this was comp.lang.python and NOT > comp.lang.ruby. > > (more inane rambling snipped) It's indeed comp.lang.python, a list which for whatever sociological reason attracts mainly moderate posters rather than rabid fanboys and script kiddies, unlike other communities you may be more familiar with. Perhaps you chose the wrong group for your new adopted religion. Why don't you go read a tutorial, write up some code, and come back with any real questions next time. George From deets at nospam.web.de Mon Nov 17 13:20:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Nov 2008 19:20:07 +0100 Subject: Suggestions for an education programming project References: <84320c16-089b-4286-b5d5-a3bd8891ed0d@a26g2000prf.googlegroups.com> Message-ID: <6odqt1F35ogiU2@mid.uni-berlin.de> Eric wrote: > Hi, > > I've been trying to get my son interested in learning some simple > programming for a while. While I understand that a structured tutorial > is best, I think if we can write something cool at least once, it will > encourage him to learn more. While I have a lot of experience with > MATLAB, I've just started playing with Python. It seems to me to be a > great language to learn with. My son has an idea for a program to > write. Basically he would like to present a window with a small circle > on it. The window title would have the instruction to click on the > circle. As the mouse approaches the circle, it moves away from the > spot. Being a kid, the visual and interactive aspect appeals. I think > this will be nice as he can add complexity incrementally such as what > direction to move, how to handle running into the edge of the window, > etc. > > What I'd like is a suggestion as to what GUI framework to use (Tk, wx > or something else). I can add modules if necessary. I'd just as soon > use something clean, understandable and not too complex. Certainly, > what ever we use needs to have good documentation. No code please, > that's for us to figure out. In case it matters, we are using are > programming in OS X. This sounds like the punching-monkey-example from pygame. While that won't teach about gui-programming on a toolkit level, it is extremely well suited to go about small games and such. Or even bigger ones, if the son grows up :) Diez From Auslieferator at gmx.net Wed Nov 5 10:53:12 2008 From: Auslieferator at gmx.net (Fabio) Date: Wed, 05 Nov 2008 16:53:12 +0100 Subject: Question concerning array.array and C++ Message-ID: <4911C168.5020107@gmx.net> Hi All, I have a question concerning the use of array.array inside of C++ code I wrote. I am working with _big_ data files but some entries in these files are usually bounded say between -5 to 40. Returning a Python list makes no sense. In Python I always work with the array.array module which does the trick. But now that I wrote my own C++ module for some preprocessing I need the return array.array objects. Consider the object array.array('c',[40,40,40]) Can I create such an object from within the C++ layer and pass it to the Python layer? I already looked at arraymodule.c and tried to link the arraymodule.o file to my code but then I have to mess around with extern "C" and the like and it gets really messy. Any help would be great! Fabio From steve at REMOVE-THIS-cybersource.com.au Thu Nov 27 21:25:52 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Nov 2008 02:25:52 GMT Subject: newbie question References: <724c1735-e7ff-459e-9cfa-79d5d9a659c6@s9g2000prg.googlegroups.com> <492e70e4$0$17309$426a74cc@news.free.fr> <936fb8cc-5b9a-4887-b781-18175eb34251@c36g2000prc.googlegroups.com> Message-ID: <013f4ea7$0$20626$c3e8da3@news.astraweb.com> On Thu, 27 Nov 2008 17:58:55 -0800, Asun Friere wrote: > if __name__ == '__main__' : > import sys > sys.exit(main(sys.argv)) > > Doesn't this just pollute the namespace with main()? Agreed. I don't see anything wrong with that. You have one function more than you otherwise would have had, and you get the benefit that after importing the module, you can say module.main(myargs) to run the code just as if you had run it from the command line. In other words... in my opinion, writing a non-trivial main() function is the right thing to do. -- Steven From gagsl-py2 at yahoo.com.ar Sat Nov 15 01:29:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Nov 2008 04:29:23 -0200 Subject: inspect.findsource problem with llinecache References: <94b2f6c9-8352-46e5-9dd7-43fbe3ef7b1b@o4g2000pra.googlegroups.com> Message-ID: En Wed, 12 Nov 2008 05:22:55 -0200, Rafe escribi?: > I think I have discovered two bugs with the inspect module and I would > like to know if anyone can spot any traps in my workaround. They look like real bugs - please report them at http://bugs.python.org else this will be forgotten. > I welcome comments on the bugs or optimization pointers for my code. I > am still quite new to Python. My primary question though is: will > linecache.clearcache() cause me any problems? I don't think so, apart from performance degradation (but good performance with bad results isn't good at all!) -- Gabriel Genellina From mdw at distorted.org.uk Fri Nov 14 13:08:51 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Fri, 14 Nov 2008 18:08:51 +0000 (UTC) Subject: Avoiding local variable declarations? References: <8d695469-348d-483d-8fcb-2ed43cfd2a75@s1g2000prg.googlegroups.com> Message-ID: Chris Mellon wrote: > Any time you port between languages, it's rarely a good idea to just > convert code verbatim. For example: > > import random, string > def random_char(): > return random.choice(string.ascii_letters + string.digits) Note that this code doesn't preserve the output distribution of the original, for which once expects half the characters to be numeric. I don't know if that's relevant; in fact I suspect that the original was buggy. -- [mdw] From mccredie at gmail.com Tue Nov 4 15:10:28 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 4 Nov 2008 12:10:28 -0800 (PST) Subject: Building loop with some exceptions? References: <0v71h4tsf30aodpjs46rfevgp3of8h73ps@4ax.com> Message-ID: <4dbe6ee0-2fb1-49e9-aa7d-2a283f1d9391@r15g2000prh.googlegroups.com> On Nov 4, 11:20?am, Gilles Ganault wrote: > Hello > > I need to call a URL through a loop that starts at 01 and ends at 99, > but some of the steps must be ignored: > > ===== > url = "http://www.acme.com/list?code=" > p = re.compile("^(\d+)\t(.+)$") > > for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89: > ? ? ? ? f = urllib.urlopen(url + i) > ? ? ? ? page = f.read() > ? ? ? ? f.close() > > ? ? ? ? for line in page: > ? ? ? ? ? ? ? ? m = p.search(line) > ? ? ? ? ? ? ? ? if m: > ? ? ? ? ? ? ? ? ? ? ? ? code = m.group(1) > ? ? ? ? ? ? ? ? ? ? ? ? label = m.group(2) > > ? ? ? ? ? ? ? ? ? ? ? ? print "Code=" + code + " # Label=" + label > ===== > > I'm clueless at what the Python way is to do this :-/ > > Thank you for any help. I would just do something like this (not tested): url_tmpl = "http://www.acme.com/list?code=%02d" p = re.compile("^(\d+)\t(.+)$") EXCLUDED_VALUES = 4, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89 for i in xrange(1,100): if i in EXCLUDED_VALUES: continue f = urllib.urlopen(url_tmpl % i) try: for line in f: m = p.search(line) if m: code = m.group(1) label = m.group(2) print "Code=", code, "# Label=", label finally: f.close() From stefaan.himpe at gmail.com Sat Nov 15 14:33:31 2008 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Sat, 15 Nov 2008 20:33:31 +0100 Subject: Building musical chords starting from (a lot of) rules In-Reply-To: References: Message-ID: > The costrunction of a chord is based on a root note and a structure, > so by default, giving just a note, it creates a major chord adding the > third and fifth note. Quite some time ago I wrote something to solve the reverse problem: given a list of note names, find out a chord name. (http://chordrecognizer.sourceforge.net/ ) I used a look-up table to made a correspondence between the chord-name and the notes from which the chord is built. The notes are expressed as a distance from the root note. E.g. starting from a chromatic scale built on C, the distances would be: C:0 C#:1 D:2 D#:3 E:4 F:5 F#:6 G:7 G#:8 A:9 A#:10 B:11 (and similar for flats, double sharps and double flats, ...) Any chord thus can be constructed from a root note + the distance information. example distance information: { 'm' : [ 0, 3, 7 ], # minor triad '' : [ 0, 4, 7 ], # major triad '7' : [ 0, 4, 7, 10] # etc... ... } How does one e.g. construct the E7 chord from this information? 1. generate the chromatic scale starting from E, and annotate with note distance to root note: E:0 F:1 F#:2 G:3 G#:4 A:5 A#:6 B:7 C:8 C#:9 D:10 D#:11 2. take the recipe for a '7' chord from the distance information: [0, 4, 7, 10] 3. map the numbers from step 2. to the note names from step 1.: E G# B D If you care about proper enharmonic spelling of the chord's note names (i.e. do not confuse F# and Gb), you will need to add some extra information in the look-up tables or you need to pass extra information to the chord construction recipe at the moment of creating a chord, but that is left as an excercise to you - the interested reader ;) HTH, Stefaan. From code at organisati.on Tue Nov 11 04:25:42 2008 From: code at organisati.on (Markus Mayer) Date: Tue, 11 Nov 2008 10:25:42 +0100 Subject: Project layout / Import files from different subdirectories In-Reply-To: <6nsu1rFnjd1U1@mid.uni-berlin.de> References: <6nsrjeFnksaU2@mid.uni-berlin.de> <6nsu1rFnjd1U1@mid.uni-berlin.de> Message-ID: <6nt1cmFp0dhU1@mid.uni-berlin.de> Diez B. Roggisch schrieb: > > By placing a __init__.py into project, and then > > import project.main > import project.gui.mainwindow > > > Diez Ouch. Thanks. Markus -- PGP/GPG key 0x2EB39BF9 From steve at holdenweb.com Wed Nov 5 14:11:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Nov 2008 14:11:26 -0500 Subject: [Python-Dev] Why don't range and xrange threat floats as floats? In-Reply-To: References: <502974.52539.qm@web45703.mail.sp1.yahoo.com> Message-ID: Matthieu Brucher wrote: > 2008/11/5 L V : >> Why don't range and xrange threat floats as floats? >> Is there any good reason range and xrange don't threat floats as floats but >> as integers? >> When I enter float arguments in a range, the floats are treated as integers. >> (+ some warning) >> >> This is how I think it should work: >>>>> range(0, 1, 0.1) >> [0.0, 0.10000000000000001, 0.20000000000000001, 0.29999999999999999, >> 0.40000000000000002, 0.5, 0.59999999999999998, 0.69999999999999996, >> 0.80000000000000004, 0.90000000000000002] >> >> I got these results by: >>>>> [x/10. for x in xrange(10)] >> I'm not looking for alternatives, just for the reason that it works this >> way. > It works this way because you can't be sure that you won't get an extra increment. When you repeatedly add fractions together, the desired final result might be just less or just more than the actual integral value. If it's just less you will get an extra increment. It just doesn't work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ptmcg at austin.rr.com Thu Nov 13 20:56:07 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 13 Nov 2008 17:56:07 -0800 (PST) Subject: Avoiding local variable declarations? References: <8d695469-348d-483d-8fcb-2ed43cfd2a75@s1g2000prg.googlegroups.com> <34c7c832-0f70-495d-b888-4acabb52387d@o4g2000pra.googlegroups.com> Message-ID: <326b8759-ce78-489e-a1ff-bdc290531241@c22g2000prc.googlegroups.com> On Nov 13, 6:47?pm, bearophileH... at lycos.com wrote: > Paul McGuire: > > > coinflip = lambda : int(random.random()*2) > > I warmly suggest you to use this instead: > randrange(2) > > Bye, > bearophile Really? Looking at randrange, it sure seems to do a lot of work in pursuit of handling all possible cases for specifying range boundaries, step values, etc. In fact, I think flipping a coin is a common enough task that it might even merit an addition to the random module API. It certainly would allow us to get rid of all of these variations on the theme, such as "if randrange(100) > 50", or "random.choice([True,False])". For that matter, my own obscure int (random.random() * 2) is better implemented using a direct comparison to random.random(), no need for multiplication, or int calls or anything else. Having an explicit method would also help prevent minor erroneous bugs like "if random.random() > 0.5", given that the range of random.random() is (0.0, 1.0] (that is, the lower half would be 0 inclusive to 0.5 exclusive, and the upper half 0.5 inclusive to 1.0 exclusive). If I would change anything, I think I prefer the name coin_toss over coinflip. So: coin_toss = lambda : random.random() >= 0.5 -- Paul From straton at lampsacos.demon.co.uk Mon Nov 17 06:42:22 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 17 Nov 2008 11:42:22 +0000 Subject: Midi manipulation In-Reply-To: <9DcUk.81217$Bk7.50124@newsfe29.ams2> References: <7671i4dvnudr4ssh4j54ummqa589r8tleb@4ax.com> <4f45a617-a969-4af0-b105-6bae06275d09@t39g2000prh.googlegroups.com> <9DcUk.81217$Bk7.50124@newsfe29.ams2> Message-ID: Ken Starks wrote: > Massi wrote: >> On 16 Nov, 23:23, Tim Roberts wrote: >>> Massi wrote: >>> >>>> Hi everyone, I'm searching for "something" which allows me to write >>>> scripts which handle midi files. I'm totally a newbie in audio >>>> manipulation, therefore any suggestion or link related to this field >>>> is welcome. Thanks in advance. >>> Google is much faster than this newsgroup. Search for "python midi >>> library" and the first page gives you a number of good hits. >>> >>> However, there's a lot to manipulating MIDI. What kinds of things >>> are you >>> hoping to accomplish? MIDI, for example, is not a particularly good >>> way to >>> store music for composition. >>> -- >>> Tim Roberts, t... at probo.com >>> Providenza & Boekelheide, Inc. >> >> I'm writing a script for didactic musical purpose. As first step I >> need something as simple as possible, for example a library of >> functions which are able to play a certain note, with a given >> instrument and a given length. I thought midi was good for this aim, >> am I wrong? > > Oh dear, I'm going to point you away from Python ... but I am not > intending to start a flame war... > > The Apache Cocoon project (NOT the latest version 2.2 though) might > appeal to you: > > http://cocoon.zones.apache.org/demos/release/samples/blocks/midi/ > > quote: > The MIDI block currently gives you an XMidiGenerator to generate an XML > representation of any MIDI file (called XMidi by its author Peter Loeb). > There is also the XMidiSerializer to render XMidi back as a MIDI file. I > have used XSLT to provide some basic musical manipulations such as > transposition, and inversion. Retrograde is harder, but I shall see what > I can come up with. Hopefully I shall also add some transformers to > generate SVG visualisations of the XMidi, starting with normal western > musical notation. > MIDI Documentation - Documentation available on the Cocoon Wiki. > The link to the wiki was dead when I tried it, so i expect it is dead. Try instead: http://wiki.apache.org/cocoon/MIDI From tjreedy at udel.edu Sun Nov 2 19:35:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Nov 2008 19:35:29 -0500 Subject: [ANN] Python 3 Symbol Glossary In-Reply-To: References: Message-ID: Terry Reedy wrote: > Over the years, people have complained about the difficulty of finding > the meaning of symbols used in Python syntax. So ... I wrote a > Python 3 Symbol Glossary > > http://code.google.com/p/xploro/downloads/list > There are .txt and .odt versions. Replaced with an updated .html version courtesy of help from Arnaud Delobelle. From clp at rebertia.com Mon Nov 3 04:58:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 3 Nov 2008 01:58:25 -0800 Subject: Efficient way to remove objects from a list In-Reply-To: References: Message-ID: <47c890dc0811030158i7593c9cft1e6e3c704768a66e@mail.gmail.com> On Mon, Nov 3, 2008 at 1:40 AM, ??? wrote: > Hi all, > > Today I wrote some code like this: > Build a new list as you go, then overwrite the old list with it. unfinished = [] > for m in self.messages: > if not m.finished: unfinished.append(m) > continue > > #process the message > Remove the following code > fini = [m for m in self.messages if m.finished] > for m in fini: > self.messages.remove(m) self.messages[:] = unfinished This way you aren't calling .remove() multiple times and only iterate through the list once. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > As you can, I want to find these finished messages in > "self.messages", > process them, and then remove them from the list. > > Because a list can not be modified while iterating it, I have to use > a list "fini" to accomplish the target. > > I found a smell of bad performance here. > Is there any faster ways? > -- > http://mail.python.org/mailman/listinfo/python-list > From esj at harvee.org Fri Nov 14 21:01:43 2008 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 14 Nov 2008 21:01:43 -0500 Subject: special editor support for indentation needed. In-Reply-To: <7bce0749-a13e-4100-8b6c-dc1dd6134690@h23g2000prf.googlegroups.com> References: <491DD44F.8010208@harvee.org> <7bce0749-a13e-4100-8b6c-dc1dd6134690@h23g2000prf.googlegroups.com> Message-ID: <491E2D87.50601@harvee.org> drobinow at gmail.com wrote: > I don't understand. If you don't want to terminate the "if", why do > you hit backspace? What is it that you would like to have happen? the goal is to make some aspects of indentation behave the same without context dependency. this goal exists for many features of programming assistance because it's a prerequisite for lowering the vocal load for this aspect of programming by voice I want three indentation adjustment tools. Indent to where a class should be, indent to where a method should be, and outdent n levels (close block (once|twice|thrice)). This is probably best shown by example although, I'm not guaranteeing my example will make it any clearer. :-) the current outdent capability conflates multiple outdent events. The outdent events are, at a minimum,: Close block close method close class Another way to look at these events are start method, start class and close block. Now using these events, let's compare a use case against the outdent mechanism. starting with an example of a previous message, class pet (object): """ """ def cat(self): """ """ if food in bowl: self.empty = True def dog(self): to start the dog method, after ending the Method, I would need to say something like: newline tab key Close block close block delta echo foxtrot dog left paren self close paren colon... But if the method ended like: ... def cat(self): """ """ self.empty = True def dog(self): I would only want to use a single "close block" to outdent. unfortunately, this context dependent behavior is frustratingly wrong when it comes to creating speech driven macros to enter templates. it requires user intervention to tell you how may times to outdent and that's counterproductive at best and physically damaging at worst for a disabled user. any clearer? From lepto.python at gmail.com Thu Nov 6 07:31:32 2008 From: lepto.python at gmail.com (oyster) Date: Thu, 6 Nov 2008 20:31:32 +0800 Subject: bind to HTMLayout or ubrowser Message-ID: <6a4f17690811060431t3a079750w5615f47f245aa1e2@mail.gmail.com> http://www.terrainformatica.com/htmlayout/ "uses its own lightweight HTML rendering engine", helps you to create applications with the "Web style" user interface http://ubrowser.com/ "is a library that makes it a little easier to embed the Mozilla Gecko rendering engine into your application" is there any python interface to it/them? thanx From steve at holdenweb.com Thu Nov 13 10:50:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Nov 2008 10:50:10 -0500 Subject: duck-type-checking? In-Reply-To: <6o233jF1dlfoU1@mid.individual.net> References: <9D538BAC-4C29-4DB5-8F33-5783B7359196@strout.net> <6o233jF1dlfoU1@mid.individual.net> Message-ID: <491C4CB2.5020709@holdenweb.com> greg wrote: > Joe Strout wrote: >> This is not hypothetical -- just last week I had a hard-to-track-down >> abend that ultimately turned out to be an NLTK.Tree object stored >> someplace that I expected to only contain strings. I found it by >> littering my code with assertions of the form >> isinstance(foo,basestring). > > But you have to ask yourself whether the time taken to > write and maintain all these assertions is really > cost-effective. In my experience, occurrences like this > are actually extremely rare -- the vast majority of the > time, you do get a failure very quickly, and it's fairly > obvious from the traceback where to look for the problem. > > It's as annoying as hell when something like this does > happen, but averaged over the lifetime of the project, > I find it doesn't cost all that much time. > This is particularly true since Joe is still proposing to check the objects when they are passed to functions and methods that use them. Unfortunately the assignment of the "wrong type of object" may well have taken place aeons ago, and it's the assignments you really need to catch (and it's also the assignments that static languages cause compile errors on). So it hardly matters whether the code blows up with Exception: my expensive type checks sounded an alarm or Attribute error: foo has no method bar() since both are equally informative when it comes to tracing the faulty assignment. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bearophileHUGS at lycos.com Sun Nov 16 15:05:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Nov 2008 12:05:48 -0800 (PST) Subject: Does python is suitable for enterprise cluster management? References: Message-ID: <5d66e9c1-a6c6-4b52-98e7-ba84d26e4479@a3g2000prm.googlegroups.com> Asaf Hayman: > We are currently pondering which programming language will best suite > us. The two major contenders are Python and Java. I think there is also Erlang for such kind of things. Bye, bearophile From boblatest at googlemail.com Mon Nov 10 06:11:06 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Mon, 10 Nov 2008 03:11:06 -0800 (PST) Subject: C Module question Message-ID: <20d7d226-3971-45bf-8636-5010f9219028@35g2000pry.googlegroups.com> Hello, I'm trying to write a Python extension module in C for the first time. I have two questions: 1. How can I pass a file-like object into the C part? The PyArg_* functions can convert objects to all sort of types, but not FILE*. 2. How can I preserve information needed in the C part between calls to my module functions? The way I've thought of is: - put this information in a dynamically allocated struct - pass it out of and into the C module as CObject into/from an intermediate Python wrapper module where it gets stored in a Python object Is this the way to do it? Thanks. robert From gstaniak at wp.pl Sat Nov 8 14:57:53 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Sat, 8 Nov 2008 19:57:53 +0000 (UTC) Subject: Workflow engine? References: Message-ID: On 08.11.2008, Tino Wildenhain wroted: >> In a couple of weeks I'm starting a medium-size project (using a web >> framework) involving a workflow implementation. Are you aware of any >> open source workflow engines/libraries that I could base the project >> on? Google returns hist for GoFlow (Django only, from what I can tell), >> itools.workflow, spiff (AFAIK tied to a CMS), but not much else. I don't >> think I'll have enough time to get acquinted with Plone and its offer >> of products. Has anyone here tried any such code? What would you recommend? > > I would recommend to start with a problem, rather then with a solution. > There is not so much magic in workflows as you might seem to think. > > After all its "just" maintaining a state and rules for possible transitions. Sure, and I know more or less how I'd do it if I had to code from scratch. On the other hand, I don't want to code from scratch - if there are other viable options. I'm not a genius, but I think I'd manage to write a web framework too - do you really think it would be a good idea to start writing another one? I'd much prefer an existing workflow project that I could use, test, and contribute to, just as I decided on TG for the web thing. GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From bob at mellowood.ca Fri Nov 14 13:35:48 2008 From: bob at mellowood.ca (bvdp) Date: Fri, 14 Nov 2008 11:35:48 -0700 Subject: Building musical chords starting from (a lot of) rules In-Reply-To: References: Message-ID: <491DC504.4070209@mellowood.ca> Mr.SpOOn wrote: > Hi, > I'm writing a method to create musical chords. > > This method must follow a specific set of syntax rules. At least, this > is my idea, but maybe there's a better way. > Anyway, in the code I have class Chord which is a set. > > The costrunction of a chord is based on a root note and a structure, > so by default, giving just a note, it creates a major chord adding the > third and fifth note. > > So, in pseudo-code: Chord(C) -> [C, E, G] > > And this is the base case. All the other rules must specify what kind > of note to add or which one should be modified. > > For example: C min, means to add the third minor note: C Eb G > > C 9 is a base chord plus a the ninth note, but this implies the > presence of the seventh too, so it results in: C E G B D > > But I can also say: C 9 no7, so it should just be: C E G D, without the seventh. > > There are also more complex rules. For the eleventh, for example, it > should add also the ninth and seventh note. In the normal case it adds > their major version, but I can specify to add an augmented nine, so > this modification must have precedence over the base case. > > Anyway, I think I can use a chain of if-clauses, one per rule and at > the end remove the notes marked with "no". But this seems to me a very > bad solution, not so pythonic. Before I proceed for this way, do you > have any suggestion? Hope the problem is not too complicated. > > Thanks, > Carlo Have a look at my program MMA which does just what I think you want. Well, probably for different purposes, but same end result with the chords. All table based, BTW. http://www.mellowood.ca/mma From aioe.org at technicalbloke.com Fri Nov 21 02:00:31 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 21 Nov 2008 02:00:31 -0500 Subject: Sending username password to a webpage References: <02f1ad4b-8925-42a6-8682-39ce77b7b622@j39g2000yqn.googlegroups.com> Message-ID: KDawg44 wrote: > Hi, > > Is there a way to essentially simulate populating a text box and > calling a submit button on a webpage? I want to write an app that > gets a users information from a website and then uses that to get > information from another site. The first site requires a log in. > > Thanks for any advice that gets me in the right direction. > > Thanks. > > Kevin I dread to think why you want to do that but you probably need urllib or urllib2. You basically need to figure out if the webpage is using GET or POST to send the form data and then URLencode and send your data as a request. Most forms these days will use POST. e.g. postvars = urlencode( { "name":"john", "tel":"2384792389" } ) result = urllib.urlopen("http://www.example.com/form1",postvars) Roger. From alessio.pace at gmail.com Sun Nov 30 07:22:23 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Sun, 30 Nov 2008 04:22:23 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? Message-ID: Hi, I have to distribute a Python application which relies on an external library, and I'm not very fluent in this kind of stuff with Python (I come from the Java world where I would have used the Maven build tool to create an "assembly with dependencies" of all it is needed to run the app), so I was wondering if someone here could give me some suggestions :-) The external library is generally not present on the machines where I have to distribute my app, and the set of machines on which I have to distribute this application is not known a priori (it is just known they are Unix systems). In fact by means of SSH I will have to copy (and install) the app+library and make it runnable onto the specified destination(s). My question is: how would you do that? At the moment my current solution is to make a tarball of the sources of my app + the "distutils" archive of the external library, copy all into the target machine, decompress and install via distutils(*) the external library, setup some PYTHONPATH stuff on the destination machine, and finally be able to launch the application. (*) specifying a prefix into the user home, as I'm not root there So in the end I was wondering if there is a more elegant way of doing this because, as I said before, I'm not very experienced in these kind of tasks in Python. Thanks in advance for any suggestion or comment. Alessio Pace. From mal at egenix.com Tue Nov 4 13:50:11 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 04 Nov 2008 19:50:11 +0100 Subject: PEP 249 - DB API question In-Reply-To: References: Message-ID: <49109963.5060000@egenix.com> On 2008-11-04 18:52, k3xji wrote: > Hi all, > > As development goes on for a server project, it turns out that I am > using the MySQLDB and DB interactions excessively. One questions is > just bothering me, why don't we have a timeout for queries in PEP 249 > (DB API)? > > Is it really safe to wait for a query to finish, means, is it always > returning, even if the DB server goes down? > > And, also from my point view, it may be a good feature. We may use > long/non-critical DB queries with a timeout and slow/critical without > a timeout. This will give us a little chance to prioritize/consume > queries on their criticality? And, I don't see so much effort in > implementing this. One has to change the socket logic in the related > DB's API source code? > > What do you think? This would be a question for the Python DB-SIG mailing list. Things like timeouts and handling of these is generally something that is very database specific. It is difficult to provide a reliable way of configuring this and may very well not even be within the scope of a database API (e.g. because the timeout has to be configured in the database server using some config file). I'd suggest you check whether MySQL provides a way to set timeouts and you then just use that for your project. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 04 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 stef.mientki at gmail.com Thu Nov 13 19:08:09 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 14 Nov 2008 01:08:09 +0100 Subject: What is the best Python GUI API? In-Reply-To: References: <3719fa8e-379a-4b0a-83a9-0af3e0daa3a9@c36g2000prc.googlegroups.com> Message-ID: <491CC169.6080007@gmail.com> rm wrote: > On Nov 13, 2:23 pm, James Harris > wrote: > >> On 13 Nov, 18:59, Stef Mientki wrote: >> >> >>> Abah Joseph wrote: >>> >>>> What is the best Python GUI API? I am planning to start my first GUI >>>> application and I need something easy and cross platform. Qt >>>> applications look beautiful but I hate the license. What do you advice? >>>> >>> I agree about the Qt-license, >>> and I'm now a happy wxPython user. >>> >> I too have had good results with wxwidgets when developing a GUI. The >> cross-platform native look and feel was a major benefit from my point >> of view allowing screens to "look native" under different OSs with no >> code changes. >> >> -- >> James >> > > Not so good if your native Linux look is KDE. ;) I also hate the fact > that the GTK File Save/Open dialog box does not allow file/folder > renames. On Windows, however, wxPython is great. I guess it depends > on how big your application is and what is the target audience/ > clientele. > Ok you only guess, but ... .. you're suggesting - that if the application is too big, wxPython is not a good choice. What's big ? - if the target is ... ??? ... it's not a good choice, for what audience is wxPython not suited ? thanks, Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at v.loewis.de Thu Nov 6 18:18:08 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 07 Nov 2008 00:18:08 +0100 Subject: Python25\Tools\checkversions.py In-Reply-To: References: Message-ID: <49137B30.7090207@v.loewis.de> Colin J. Williams wrote: > Is _checkversion.py used at all currently? I don't think so. Regards, Martin From donnyf at gmail.com Sat Nov 22 10:53:53 2008 From: donnyf at gmail.com (Chuck Connors) Date: Sat, 22 Nov 2008 07:53:53 -0800 (PST) Subject: Need help converting text to csv format References: <6e21bcdc-a5e6-4b1e-8658-05a47df0d076@l42g2000yqe.googlegroups.com> <33ec332e-1cdc-4c06-8660-8b061bc8d816@l39g2000yqn.googlegroups.com> <67f50a2d-98f3-47aa-9e1e-51e7171112eb@q9g2000yqc.googlegroups.com> <313f7129-1a9d-442b-b616-80a5bbfc0d45@g17g2000prg.googlegroups.com> Message-ID: Firstly, I would like to thank those that offered help. I was able to get my data into the database and also have connectivity with the mysql and can pull the data in/out at will. Hooray and thanks again. Secondly, perhaps I overstated my abilities. I have written a couple of websites from scratch that pull data in/out of databases and have formatted their outputs for user consumption. I am by no means a php expert and have never had occasion to use regular expressions for the type of data I've been manipulating. My sarcastic reply was only in response to the 'go google it' answer I received to what I thought was a fair question. It's usually easiest to google something if you know what you are looking for. At no point did I expect anyone to spend a great deal of time working out my specific problem but I am most grateful for those who did provide more than what could have been expected. From darren.mansell at opengi.co.uk Mon Nov 17 10:55:42 2008 From: darren.mansell at opengi.co.uk (Darren Mansell) Date: Mon, 17 Nov 2008 15:55:42 +0000 Subject: Problems Writing =?ISO-8859-1?Q?=A3?= (pound sterling) To MS SQL Server using pymssql In-Reply-To: <49218CBC.7030509@timgolden.me.uk> References: <1226933534.29181.25.camel@darrenm-desktop> <49218CBC.7030509@timgolden.me.uk> Message-ID: <1226937342.29181.31.camel@darrenm-desktop> On Mon, 2008-11-17 at 15:24 +0000, Tim Golden wrote: > Darren Mansell wrote: > > Hi. > > > > I'm relatively new to python so please be gentle :) > > > > I'm trying to write a ? symbol to an MS SQL server using pymsssql . This > > works but when selecting the data back (e.g. using SQL management > > studio) the ? symbol is replaced with ?? (latin capital letter A with > > circumflex). > > > This is a bit of a non-answer but... use pyodbc[*], > use NVARCHAR cols, and use unicode values on insert: > Thanks for the help. Unfortunately pyodbc seems to only work on Windows. I need to connect to the SQL server from a Linux box. The db schema is very set in stone, I can't do anything with it. I'm currently opening autogenerated SQL scripts, decoding them from utf-16 and then back into utf-8 for pymssql to run them. It's been working great for ages until someone noticed the ? symbols had this extra character in there.. -- Darren Mansell From alex.gaynor at gmail.com Fri Nov 14 19:19:13 2008 From: alex.gaynor at gmail.com (Alex_Gaynor) Date: Fri, 14 Nov 2008 16:19:13 -0800 (PST) Subject: Code generation architecture question References: <66179052-40cf-42ed-b33b-864979b4defa@d42g2000prb.googlegroups.com> Message-ID: <53b131f5-50ae-454e-8963-756cf03c2b93@u18g2000pro.googlegroups.com> On Nov 14, 3:04?am, Aaron Brady wrote: > On Nov 13, 7:16?pm, Alex_Gaynor wrote: > > > I'm trying to figure out what the best architecture for doing code > > generation would be. ?I have a set of ASTs that define a program, so > > what should I do to for code generation. ?As I see it the 2 choices > > are to have the ASTs have a generate code method that returns the > > correct code for themselves, or to have a seperate class that > > generates code for a given AST. ?The problem with the first is that it > > isn't very flexible if I want to generate code for a new language/ > > platform, as well as the fact that it is very tightly coupled. > > However the issue with the other approach is that I can't think of a > > good way to write it without have a ton of if isinstance() calls. ?Any > > thoughts on what the best appraoch would be? > > I think you are seeking the Visitor Pattern. > > class A: > ? def meth( self, visitor ): > ? ? visitor.visit_classA( self ) > > class B: > ? def meth( self, visitor ): > ? ? visitor.visit_classB( self ) > > class Visitor: > ? def visit_classA( self, objinst ): > ? ? #handle classA > ? def visit_classB( self, objinst ): > ? ? #handle classB > > then A().meth( v ) gets around to getting v.visit_classA called. ?The > code is moderately repetitive. ?I believe the Transformer class in the > 'ast' module uses the visitor pattern, possibly called NodeWalker or > something. Ah this is great, the Visitor class knows how to transform everything into code, and each AST knows which method it is on the Visitor, thanks a ton! From ldo at geek-central.gen.new_zealand Mon Nov 17 03:10:38 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 17 Nov 2008 21:10:38 +1300 Subject: end child process when parent dies (on Unix) References: Message-ID: ?????? ??????????? wrote: >>> I'm starting a Unix tool with subprocess.Popen() from a python script >>> and I want the child to be killed when the parent (my script) ends >>> for whatever reason *including* if it gets killed by SIGKILL. >> >> A Linux-specific solution is prctl(2). > > I've tried this in a test C program... exactly what I need. Now if I > could slip this between the fork and exec in subprocess.Popen() An obvious way, if you're trying to hack something without the source, is to substitute your own executable which does the prctl before execing the real executable. From wuwei23 at gmail.com Sat Nov 29 21:53:14 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 29 Nov 2008 18:53:14 -0800 (PST) Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> Message-ID: <2a7664b4-668c-4269-8feb-cb35e23260dd@o4g2000pra.googlegroups.com> On Nov 30, 7:31?am, Lie wrote: > Python's learning > curve shouldn't raise with time, it should get lower so more people > can join in the board. I understand the altruistic urge present in such a desire. At the risk of being considered an elitist, as a professional programmer using Python in several large projects I think that nothing will brand Python a toy-language more than favouring ease-of-uninitiated-use requirements over those of long term developers. Bear them in mind, yes; provide lower-level documentation explaining the underlying model/ reason behind aspects of the language, yes; make it the new LOGO, no. From wuwei23 at gmail.com Fri Nov 28 00:25:28 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 27 Nov 2008 21:25:28 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <082ed3fd-f194-4ddb-ace8-81c6a9d18a98@k41g2000yqn.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8ecf853e-c71d-4c65-ba48-45287e0bb2de@w1g2000prk.googlegroups.com> <4c43e6d6-c834-4134-af9e-7839679bd741@g38g2000yqn.googlegroups.com> Message-ID: <4e1d743b-b785-4c2c-bfa6-37331f46a462@k1g2000prb.googlegroups.com> On Nov 28, 2:08?pm, r wrote: > Did you even read my OP, I mean the whole thing... not just the title? > I am working on the problem, I am trying to garner support for a > Python intergration. Grass Roots kinda thing. Jesus wept. Of course I did. It's why I actually made suggestions on how you could achieve this rather than trying to offload the effort to others. Pissing off potential supporters -within- the Python community is hardly what I'd consider a successful grass roots approach. > Why can't Google change the API now? Developing a 2nd API -costs in time and effort-. It doesn't happen for free. > Why can't there be 2 API's? Because the reward has to be worth the cost, and it has to be be more rewarding than shutting up every single idiot who wants their language of choice to be supported. You sound like the endless drones who proclaimed Google App Engine to be pointless because it didn't support PHP/Ruby/Perl/Erlang/Brainfuck from the very beginning. > A kinda 60 free love thing. Hippie idealism aside, nothing is "free". You're asking -other- people to shoulder the effort for something -you- want. How much is this API -worth- to you? How much time are -you- willing to commit to developing it? If you lack the ability, how much -money- are you willing to spend on hiring the people with that ability? > And why are you SO violently against it? Please point out exactly where I said I was opposed to SketchUp growing a Python API. While doing so, try and pay attention to how I repeatedly stated that it was your -approach- that was the issue. > Is this a sin? This isn't about morality at all; your evangelicalism aside, Python isn't a religion. If anything, this is about respect, understanding and the sheer lack of either you seem to demonstrate. From tengounplanb at gmail.com Thu Nov 27 10:23:00 2008 From: tengounplanb at gmail.com (tengounplanb at gmail.com) Date: Thu, 27 Nov 2008 07:23:00 -0800 (PST) Subject: Apache & mod_python: I don't receive anything with POST method References: <92451074-0e43-4bf7-92a4-099cbf2d8d75@e12g2000yqm.googlegroups.com> <2592268c-9f4d-463e-88bb-865d96a5f182@f40g2000pri.googlegroups.com> <2c6bdb81-0a77-41ab-8c9f-6d0d6a36b369@g38g2000yqd.googlegroups.com> Message-ID: On 27 nov, 15:13, tengounpl... at gmail.com wrote: > On 26 nov, 23:22, Graham Dumpleton wrote: > > > > > On Nov 27, 12:21?am, tengounpl... at gmail.com wrote: > > > > Hi, > > > > I'm using a simple form to make possible the users of our site upload > > > files. > > > > > > > ? ? > > > ? ? > > > ? ?
> > > ? ? ? ?
> > > ? ? ? ? > > > ? ?
> > > ? ? > > > > > > > The "upload.py" looks like this: > > > > from mod_python import apache, util; > > > > def index(req): > > > ? ? form = util.FieldStorage(req, keep_blank_values=1) > > > ? ? try: > > > ? ? ? ? # form is empty here > > > ? ? ? ? # return form --> I get "{}" > > > ? ? ? ? ufile = form.get('upfile', None) > > > > ? ? ? ? if not form.has_key('upfile'): > > > ? ? ? ? ? ? return ":( No 'upfile' key" > > > > ? ? ? ? # some checks. I never get beyond here > > > > ? ? ? ? ufile = form['upfile'] > > > ? ? ? ? if ufile.file: > > > ? ? ? ? ? ? return ufile.file.name > > > ? ? ? ? else: > > > ? ? ? ? ? ? return ":( It's not a file" > > > ? ? except Exception, e: > > > ? ? ? ? return 'Fail: ' + str(e) > > > > I'm getting an empty 'form'. No 'upfile' key at all. I've tried to add > > > some other text fields but the result is the same: empty. If I use GET > > > method with text fields, it works properly. > > > > Currently I'm using: > > > Apache 2.2.9 (initially I used Apache 2.2.3 too) > > > mod_python 3.3.1 (initially I used mod_python 3.2.10 too) > > > Python 2.5.2 > > > Which is the correct result for the code you are using. > > > The problem is that you appear to be using mod_python.publisher which > > does its own form handling before you are even getting a chance, thus > > it is consuming the request content. > > > For how to handle forms in mod_python.publisher see: > > >http://webpython.codepoint.net/mod_python_publisher_forms > > > Graham > > Hi, > > I should get a non-empty "form". > > With the following html > > > ? ? > ? ? > ? ?
> ? ? ? ?
> ? ? ? ? > ? ?
> ? ? > > > ...and the following "upload.py": > > from mod_python import util, apache > > def index(req): > ? ? form = util.FieldStorage(req, keep_blank_values=1) > ? ? try: > ? ? ? ? some_text = form.get('some_text', None); > ? ? ? ? return form.items > ? ? except Exception, e: > ? ? ? ? return 'Fail: ' + str(e) > > ...I get (writting "Python" in the text box) > > [('some_text', Field('some_text', 'Python'))] > > So, I have a "form" with a non-empty structure of (key, value), and > I'm able to get the value I'm looking for: > > ... > some_text = form.get('some_text', None) # It's not empty anymore > ... > > Thanks > > Le?n I got an alternative solution here http://codepoint.net/index.php/topic,118.msg507.html#msg507 Regards From kyosohma at gmail.com Thu Nov 6 10:56:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Nov 2008 07:56:54 -0800 (PST) Subject: Error importing wxPython References: <85a56112-02f3-4936-9acf-488f01eb79b8@s9g2000prm.googlegroups.com> Message-ID: <6a95929d-b63e-433e-8864-e5871d1da36c@d42g2000prb.googlegroups.com> On Nov 6, 8:09?am, ron.re... at gmail.com wrote: > Hi, > > I just installed wxPython fromhttp://wxpython.org/download.php. ?When > I import (import wx), I get this error: > > ImportError: DLL load failed: The application has failed to start > because its side-by-side configuration is incorrect. Please see the > application event log for more detail. > > Has anyone had this problem and how can I resolve it? > > Thanks in advance. > > -- > Ron Reidy I haven't seen that one before. What OS are you using? Did you install the latest wxPython? Is there a previous version of wxPython already installed? If so, was that intentional? Mike From rafesacks at gmail.com Fri Nov 21 05:02:03 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 21 Nov 2008 02:02:03 -0800 (PST) Subject: strange pythoncom.com_error - it only happens once References: <434b5ce7-fe9f-42ef-986f-b23c5852d538@r15g2000prh.googlegroups.com> Message-ID: On Nov 21, 4:50?pm, Rafe wrote: > Hi, > > I'm getting this error: > # ? File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", > line 491, in __getattr__ > # ? ? raise pythoncom.com_error, details > # COM Error: Unspecified failure - [line 52] > > ...when my program hits a line of code which I know should work. The > strange thing is, when I run it again in the same python session, it > DOES work (no error is thrown and the expected results occur). Then it > happens again on a later line which also works. If I run the program > again without restarting python, it works all the way through and > forever after. > > Any ideas as to what might cause this? An error that is not an error > and only happens once? > > I would show examples, but it is application-specific and wouldn't > help. I have been using this application for about 10 years, so i know > my usage is correct (especially since it works most times) > > Cheers, > > - Rafe Forgot to mention I am using win32com.client.dynamic. I'm not sure if makepy will solve this or not. I need to ask around and find out how to run it for this application. I tried using pyWin's tool but it failed. There are 5 or 6 libraries though, so maybe I tried an invalid one? - Rafe From benjamin.kaplan at case.edu Wed Nov 19 14:01:34 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 19 Nov 2008 14:01:34 -0500 Subject: wxPython Crashes with basic example In-Reply-To: <65c3648d0811190951n52c8b9ddkae7b88877c338050@mail.gmail.com> References: <65c3648d0811190951n52c8b9ddkae7b88877c338050@mail.gmail.com> Message-ID: On Wed, Nov 19, 2008 at 12:51 PM, Samuel Morhaim wrote: > Hi, I am trying to run the basic wxpython example as seen here > http://www.zetcode.com/wxpython/firststeps/ and everytime i run it, it > crashes python/wxpython .. meaning it doesnt close gracefully. > The error I get is > > Problem signature: > Problem Event Name: APPCRASH > Application Name: pythonw.exe > Application Version: 0.0.0.0 > Application Timestamp: 48e49638 > Fault Module Name: comctl32.dll_unloaded > Fault Module Version: 0.0.0.0 > Fault Module Timestamp: 4791a629 > Exception Code: c0000005 > Exception Offset: 72b35a6e > OS Version: 6.0.6001.2.1.0.256.1 > Locale ID: 1033 > Additional Information 1: fd00 > Additional Information 2: ea6f5fe8924aaa756324d57f87834160 > Additional Information 3: fd00 > Additional Information 4: ea6f5fe8924aaa756324d57f87834160 > > Read our privacy statement: > http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409 > > > > Any ideas? it is just a basic example.. running python 2.6, wxpython, > executing via IDLE or eric or any other.. > I don't have any idea what caused your problem since I don't use Windows, but you shouldn't run wxPython apps from IDLE because of conflicting event loops. I think you might also have problems with Eric. Try running the script from the command line and see if that solves your problem. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alphadogg at gmail.com Thu Nov 6 11:28:49 2008 From: alphadogg at gmail.com (alphadog) Date: Thu, 6 Nov 2008 08:28:49 -0800 (PST) Subject: Python 2.6, GUI not working on vista? References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> Message-ID: <79353ac5-8eb3-446a-8fda-0a1f8b3087df@b31g2000prb.googlegroups.com> On Oct 5, 4:13?am, Lawrence D'Oliveiro wrote: > In message <48e75d94$0$25303$426a7... at news.free.fr>, Michel Claveau - NoSpam > > SVP ; merci wrote: > > Another way is to de-activate UAC. > > Please don't be stupid! How about a compromise: Disable UAC. Install Python "for all". Re- enable UAC. Why do people have to be so black-and-white? From saju.pillai at gmail.com Fri Nov 7 00:03:05 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 6 Nov 2008 21:03:05 -0800 (PST) Subject: Can read() be non-blocking? References: Message-ID: On Nov 7, 9:09?am, Lawrence D'Oliveiro wrote: > In message , Lawrence D'Oliveiro wrote: > > > In message , Thomas > > Christensen wrote: > > >> ? ? ? r = select.select([proc.stdout.fileno()], [], [], 5)[0] > >> ? ? ? if r: > >> ? ? ? ? ? # NOTE: This will block since it reads until EOF > >> ? ? ? ? ? data = proc.stdout.read() > > > No, it will read what data is available. > > Sorry, maybe not. But you can set O_NOBLOCK on the fd. Set O_NONBLOCK on proc.fileno() and try using os.read() on that descriptor. -srp From dickinsm at gmail.com Tue Nov 25 12:34:34 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 25 Nov 2008 09:34:34 -0800 (PST) Subject: Enumerating k-segmentations of a sequence References: Message-ID: <3d50f962-b057-4323-930a-1e53c02d794e@w35g2000yqm.googlegroups.com> On Nov 25, 4:56?pm, bullockbefriending bard wrote: > I'm not sure if my terminology is precise enough, but what I want to > do is: > [snip problem description] > Structural Recursion not being my strong point, any ideas on how to go > about this would be much appreciated! If you have Python 2.6 available, itertools.combination might be useful. Here's an example: from itertools import combinations def partitions(l, k): """generate all partitions of a list l into k nonempty pieces""" n = len(l) for c in combinations(range(1, n), k-1): c = [0] + list(c) + [n] yield [l[c[i]:c[i+1]] for i in xrange(k)] for p in partitions(range(1, 6), 3): print p Mark From arnodel at googlemail.com Tue Nov 25 11:03:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 25 Nov 2008 16:03:46 +0000 Subject: initialized list: strange behavior References: <660df740-4381-46b7-8571-76b0d2eeae98@k41g2000yqn.googlegroups.com> Message-ID: Steve Holden writes: > Arnaud Delobelle wrote: >> Jason Scheirer writes: >>> Python is pass-by-reference, not pass-by-value. >> >> It's certainly not pass-by-reference, nor is it pass-by-value IMHO. >> > Since no lists are being passed as arguments in these examples it's not > pass-by-anything. Jump off that horse right now! You're right that Python's calling semantics have nothing to do with the question asked. I just thought best not to leave the OP under any misapprehension. -- Arnaud From simone.dalmasso at gmail.com Fri Nov 7 04:37:18 2008 From: simone.dalmasso at gmail.com (Simo D) Date: Fri, 7 Nov 2008 01:37:18 -0800 (PST) Subject: Mod_python permission denied Message-ID: <20377387.post@talk.nabble.com> Hi, I'm using a script.py to write a file in a dir on the server. Mod_python work but i get: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib64/python2.4/site-packages/mod_python/publisher.py", line 204, in handler module = page_cache[req] File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 82, in __getitem__ return self._checkitem(name)[2] File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 124, in _checkitem value = self.build(key, name, opened, entry) File "/usr/lib64/python2.4/site-packages/mod_python/publisher.py", line 77, in build return ModuleCache.build(self, key, req, opened, entry) File "/usr/lib64/python2.4/site-packages/mod_python/cache.py", line 371, in build exec opened in module.__dict__ File "/var/www/html/flood/py/flood_pdf.py", line 18, in ? c.save() File "/usr/lib64/python2.4/site-packages/reportlab/pdfgen/canvas.py", line 881, in save self._doc.SaveToFile(self._filename, self) File "/usr/lib64/python2.4/site-packages/reportlab/pdfbase/pdfdoc.py", line 218, in SaveToFile f = open(filename, "wb") IOError: [Errno 13] Permission denied: 'wms.pdf' The dir has the read, write and execute permissions and SELinux is disabled. Can you help me? Thanks in advance. Simone -- View this message in context: http://www.nabble.com/Mod_python-permission-denied-tp20377387p20377387.html Sent from the Python - python-list mailing list archive at Nabble.com. From skip at pobox.com Tue Nov 11 07:09:01 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 11 Nov 2008 06:09:01 -0600 Subject: Final Python Class of 2009 In-Reply-To: References: Message-ID: <18713.30173.390417.782758@montanaro-dyndns-org.local> >> Steve, have you been in Guido's time machine again? Steve> No, honest (hides hands behind back). Well then what's that red stuff on your face that looks like strawberry jam? Could it be the special grease we store next to the keys to the time machine? Skip From deets at nospam.web.de Tue Nov 4 20:03:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Nov 2008 02:03:59 +0100 Subject: What's your choice when handle complicated C structures. In-Reply-To: References: Message-ID: <6nc9o0Fl0b7oU1@mid.uni-berlin.de> ??? schrieb: > Hi all, > > Recently I am writing a small network application with python. > > The protocol is binary based and defined in c header files. > > Now I'm using the upack function of 'struct' module, but it's really > annoying to write fmt strings for complicated structures. > > What will be your choice when handling binary structures? You can try gccxml + ctypes instead. Diez From luke.leighton at googlemail.com Mon Nov 17 11:06:55 2008 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 17 Nov 2008 08:06:55 -0800 (PST) Subject: Django or TurboGears or Pylons? for python web framework. References: Message-ID: <9b5007db-1b8d-40d7-8633-c35e746d63d8@e1g2000pra.googlegroups.com> > On Wed, 05 Nov 2008 08:35:23 +0200, 3000 billg > > Just from my preferences, I want to useDjangobut the AJAX support will > > be > > a problem. Also I need to select a JavaScriptframeworkand lean it, > > maybe > > JQuery, mootools or other. And I can not writepythonas it is written in > > general javascript. I need to learn a different syntax. yes, you can write python - and have it compiled to AJAX: http://pyjs.org > > Could everybody give me a hand for your select?Djangoor Turbegears or > >Pylons? and Why? > > IfDjango, how to do Ajax support for you? and why? pyjamas. then you get to write the front-end in python _and_ the back-end in python. see http://pyjs.org/book/output/Bookreader.html#Rest%20of%20the%20World which will help you to choose at least between django and web.py for AJAX-based frameworks, as there are four example techniques illustrated to do JSONRPC. l. From thorsten at thorstenkampe.de Tue Nov 11 15:06:38 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 11 Nov 2008 21:06:38 +0100 Subject: [ANN] sqlite 0.8.3 References: Message-ID: * sandro (Tue, 11 Nov 2008 11:42:00 GMT) > ANNOUNCE: sqlkit 0.8.3 > > November, 10 2008 > > I'm happy to announce release 0.8.3 of sqlkit package for python - the > first public release. Are you aware that you announced "sqlite 0.8.3" in the subject??!! Thorsten From stef.mientki at gmail.com Sun Nov 9 06:58:43 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 09 Nov 2008 12:58:43 +0100 Subject: is there really no good gui builder In-Reply-To: <8f67b6f80811090133s7c9a60d6oc46258104e46f58e@mail.gmail.com> References: <27953e31-c924-42b4-9c90-e169719733c6@k1g2000prb.googlegroups.com> <491620F6.9000508@gmail.com> <8f67b6f80811090133s7c9a60d6oc46258104e46f58e@mail.gmail.com> Message-ID: <4916D073.6060106@gmail.com> Mr.SpOOn wrote: > On Sun, Nov 9, 2008 at 12:29 AM, Stef Mientki wrote: > >> Qt seems to be good, but I don't like their licence. >> > > > What's the problem with qt licence? > I can't change a commercial application into an open application and vice-versa. (And therefor I also have to maintain 2 versions) cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sun Nov 9 13:16:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 09 Nov 2008 13:16:47 -0500 Subject: sorting list of complex numbers In-Reply-To: <18710.65078.447635.784757@montanaro-dyndns-org.local> References: <6nobt3Fmg32fU1@mid.individual.net> <18710.65078.447635.784757@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > Duncan> If you don't like the tuple then just do the two sorts separately: > > >>>> lst.sort(key=lambda x: x.imag) > >>>> lst.sort(key=lambda x: x.real) > ... > > I tried that. I could have sworn when I read through the output it hadn't > retained the order of the real parts. Wait a minute... I sorted by real > them by imag. So the trick is to sort by primary sort key last. This is called radix sorting. It requires that the sort be order preserving, that it preserve the order of items with equal keys. It is an old technique. It was used, for instance, to sort punched cards on a card sorter that sorted cards on one columm at a time. One had to be careful to properly remove and combine the cards after each pass; make one mistake and start over. I once helped someone sort 1000s of student record cards by 6- or 7-digit id. Terry Jan Reedy From castironpi at gmail.com Sat Nov 22 06:08:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 22 Nov 2008 03:08:21 -0800 (PST) Subject: Official definition of call-by-value (Re: Finding the instance reference...) References: <0124739f$0$20668$c3e8da3@news.astraweb.com> <6dd2bf03-54fa-4d42-9392-659a8e972598@b38g2000prf.googlegroups.com> <6nsbskFib5vU1@mid.individual.net> <6nul1qF100urU1@mid.individual.net> <6oh3adF3ikb9U1@mid.individual.net> <6ojsa3F41nfsU1@mid.individual.net> <2bc58c17-1b13-494d-a4fa-6b2a3ff4eb9d@t2g2000yqm.googlegroups.com> <6op44aF4n4lgU1@mid.individual.net> <956fb0fa-85c9-4906-9388-718ad1d71564@d32g2000yqe.googlegroups.com> <6opac1F4qm0rU1@mid.individual.net> Message-ID: <742c4b2d-62ce-4397-8d6b-196fdaa5485a@c1g2000yqg.googlegroups.com> On Nov 21, 8:53?pm, greg wrote: > Aaron Brady wrote: > > Call-by-value has other characteristics that Python does not > > meet. > > The designers of most other dynamic languages don't > seem to share that opinion, since they use the term > call-by-value just as though it *does* mean call- > by-assignment and nothing more. The experts are divided. There is no science that tells you how to extrapolate a term, such as say, the Japanese equivalent of meat & potatoes or apple pie, or c-b-v into a language that doesn't have a copy constructor. Furthermore, to apply c-b-v to Python, you have to introduce the concept of pointers, which is ostensibly non-native for human programmers. You'd have a pretty hard time making the case that c-b-v is 'round peg, round hole' for Python. Just describe it and give it a name. From mr.spoon21 at gmail.com Wed Nov 5 13:56:48 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Wed, 5 Nov 2008 19:56:48 +0100 Subject: Inheritance problem In-Reply-To: <6ne56tFl2n38U1@mid.uni-berlin.de> References: <6ne56tFl2n38U1@mid.uni-berlin.de> Message-ID: <8f67b6f80811051056q458c7ee8k1842ee91355adc49@mail.gmail.com> On Wed, Nov 5, 2008 at 6:59 PM, Diez B. Roggisch wrote: > You need to call the __init__ of NoteSet inside Scale, as otherwise the > instance isn't properly initialized. Thanks, solved. From anton.vredegoor at gmail.com Fri Nov 21 18:38:39 2008 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 22 Nov 2008 00:38:39 +0100 Subject: Best strategy for finding a pattern in a sequence of integers References: <84d521eb-9e5f-40e1-9bbe-9a2713d37ce8@13g2000yql.googlegroups.com> Message-ID: <20081122003839.3b10796f@outerspace> On Fri, 21 Nov 2008 18:10:02 +0100 Gerard flanagan wrote: > data = ''' > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1''' > > data = [int(x) for x in data.split()] > > from itertools import groupby But groupby needs sorted data? Suppose the rules do not conflict or overlap and between them divide all the values, then maybe this would work: class StateMachine: def __init__(self,*rules): self.rules = rules self.state = len(rules) #deliberately unreachable self.first = True def change(self,x): #check and/or change state for i,rule in enumerate(self.rules): if rule(x): if i == self.state: #no state change return False else: #maybe state change self.state = i if self.first: #set initial state, no change self.first = False return False else: return True #state is changed raise ValueError def test(): data = ''' 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1''' data = map(int, data.split()) def rule1(x): return x in set((0, 3, 9)) def rule2(x): return x in set((6, 1, 10)) state = StateMachine(rule1,rule2) L = [] res = [] for x in data: if state.change(x): res.append(list(L)) L =[] L.append(x) res.append(list(L)) print res if __name__=='__main__': test() From arnodel at googlemail.com Sun Nov 9 03:19:26 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Nov 2008 08:19:26 +0000 Subject: Python 3.0 - is this true? References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> <01267674$0$20668$c3e8da3@news.astraweb.com> Message-ID: Kay Schluehr writes: > On 9 Nov., 07:06, Steven D'Aprano > In any case, the above doesn't work now, since either L1 or L2 might >> contain complex numbers. >> The sorted() trick only works because you're >> making an assumption about the kinds of things in the lists. If you want >> to be completely general, the above solution isn't guaranteed to work. > > You are right. I never used complex numbers in Python so problems were > not visible. Otherwise the following comp function in Python 2.X does > the job: > > def comp(x1, x2): > try: > if x1 return -1 > else: > return 1 > except TypeError: > if str(x1) return -1 > else: > return 1 > Sadly it fails on transitivity: >>> comp(2, 3j) -1 >>> comp(3j, True) -1 >>> comp(True, 2) -1 -- Arnaud From timotoole at gmail.com Thu Nov 6 10:08:09 2008 From: timotoole at gmail.com (timotoole at gmail.com) Date: Thu, 6 Nov 2008 07:08:09 -0800 (PST) Subject: CGI Python problem Message-ID: <3ac37279-f233-4342-84a5-284831904d3a@x16g2000prn.googlegroups.com> Hi all, I'm trying to get python to work with cgi for a small intranet site, however even a simply "hello world test isn't working". Here is the test file: #!/usr/bin/python # -*- coding: UTF-8 -*- # enable debugging import cgitb; cgitb.enable() print "Content-Type: text/plain;charset=utf-8" print print "Hello World!" I've placed this file in both public_html and as a test in public_html/ cgi-bin directories in my local user account (I dont have root access - its a corparate network). The file definitely has read and execute permission (744) as have the assoicated directories. However when I navigate to the file with my browser I get a 500 page?! The code was written fully in linux, so its not some odd windows/linux line termination issue. As a test I tried a perl cgi hello world test, and this worked correctly. The apache server appears to be locked down tightly, as allowOverwrite is None, so I can't do anything in .htaccess files. Any thoughts on how I might debug this or where the problem is From jcd at sdf.lonestar.org Mon Nov 17 12:05:43 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 17 Nov 2008 12:05:43 -0500 Subject: Problems Writing =?ISO-8859-1?Q?=A3?= (pound sterling) To MS SQL Server using pymssql In-Reply-To: <1226937342.29181.31.camel@darrenm-desktop> References: <1226933534.29181.25.camel@darrenm-desktop> <49218CBC.7030509@timgolden.me.uk> <1226937342.29181.31.camel@darrenm-desktop> Message-ID: <1226941543.29485.13.camel@aalcdl07.lib.unc.edu> On Mon, 2008-11-17 at 15:55 +0000, Darren Mansell wrote: > On Mon, 2008-11-17 at 15:24 +0000, Tim Golden wrote: > > Darren Mansell wrote: > > > Hi. > > > > > > I'm relatively new to python so please be gentle :) > > > > > > I'm trying to write a ? symbol to an MS SQL server using pymsssql . This > > > works but when selecting the data back (e.g. using SQL management > > > studio) the ? symbol is replaced with ?? (latin capital letter A with > > > circumflex). > > > > > > This is a bit of a non-answer but... use pyodbc[*], > > use NVARCHAR cols, and use unicode values on insert: > > > > Thanks for the help. Unfortunately pyodbc seems to only work on Windows. > I need to connect to the SQL server from a Linux box. > > The db schema is very set in stone, I can't do anything with it. I'm > currently opening autogenerated SQL scripts, decoding them from utf-16 > and then back into utf-8 for pymssql to run them. > > It's been working great for ages until someone noticed the ? symbols had > this extra character in there.. > As I was trying to explain in my other email, the ? does *not* have an "extra symbol" attached to it. It is being encoded at UTF-8 and then decoded as Latin-1 (ISO-8859-1). If you had other higher-order (> ASCII) characters in your text, they would also be mis-decoded, but would probably not show the original character in the output. That was just a coincidence. For example, if you had the character u'\xe6' (?) in your input, which has the binary representation 1110 0110, it would be encoded in UTF-8 as follows: mask: 110x xxxx 10xx xxxx byte: 11 10 0110 encoding: 1100 0011 1010 0110 hex: c 3 a 6 bytestring: '\xc3\xa6' If you decode it as UTF-8, you get u'?', but if you decode it as latin-1, you get u'??'. Note that the latin-1 decoding here does not include ?. So what you are seeing is best thought of as two garbage characters, one of which happens (by coincidence only) to be the same as your original character. If you decode the bytes returned properly (as UTF-8), you will get the bytes you put in, for all characters. Cheers, Cliff From martin at v.loewis.de Mon Nov 3 15:32:26 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Nov 2008 21:32:26 +0100 Subject: How do I find the memory used by a python process In-Reply-To: <31324fb8-964d-4fc9-96c2-61190e940ef7@e1g2000pra.googlegroups.com> References: <31324fb8-964d-4fc9-96c2-61190e940ef7@e1g2000pra.googlegroups.com> Message-ID: <490f5fda$0$5381$9b622d9e@news.freenet.de> > So each test would check the amount of memory available, call the > function N times and then check the amount of memory available > afterwards. If the amount of memory before and after changes by a > certain amount then the test is failed. Please take a look at the muppy package: http://pypi.python.org/pypi/muppy Regards, Martin From ldo at geek-central.gen.new_zealand Tue Nov 4 23:42:43 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 05 Nov 2008 17:42:43 +1300 Subject: Rewriting a bash script in python References: Message-ID: In message , Chris Jones wrote: > I wrote this in bash and although it's worked w/o a glitch for the last > couple of months .. I'm not comfortable with .. "the look & feel of it". Engineering rule #1: if it works, don't fix it. From claird at lairds.us Mon Nov 3 14:36:06 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 3 Nov 2008 19:36:06 +0000 Subject: SQL is many things, but "mini" had never occurred to me as one of them (was: push-style templating - an xml-like way to process xhtml) References: <8c5b70a9-29bd-4341-9200-edc05631647c@n1g2000prb.googlegroups.com> <490DB3E5.7080506@wildenhain.de> <490DB86F.9030300@gmail.com> Message-ID: <6e04u5-8uf.ln1@lairds.us> In article , Tino Wildenhain wrote: . . . >Mini languages is the correct term. And yes they have their >purpose. (Think of SQL for example). . . . I am, incidentally, among those who finds templating languages in general and TAL in particular more "perplexing annoyance" than "solution". I certainly use TAL, though ... From arnodel at googlemail.com Sat Nov 15 09:22:38 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Nov 2008 14:22:38 +0000 Subject: Comparing value in two dictionaries? References: Message-ID: Gilles Ganault writes: > Hello > > I fill two dictionaries with the same number of keys, and then need to > compare the value for each key, eg. > > #Pour chaque APE, comparaison societe.ape.nombre et verif.ape.nombre > import apsw > > #============ > dic1={} > [...] > rows=list(cursor.execute(sql)) > for id in rows: > dic1[id[0]] = id[1] > #============ > dic2={} > [...] > rows=list(cursor.execute(sql)) > for id in rows: > dic2[id[0]] = id[1] > #============ > #Here, compare each key/value to find values that differ > for i in dic1.items(): > [...] > > What would be a good way to do this in Python? > > Thank you. I think you would be better off writing some SQL query that does it. If you want to do this in Python, I suppose it depends whether you know that the two dictionaries have the same set of keys. If they do you can simply write something like: diff = [key for key, val1 in dic1.iteritems() if val1 != dic2[key]] -- Arnaud From robie at justgohome.co.uk Tue Nov 25 04:32:26 2008 From: robie at justgohome.co.uk (Robie Basak) Date: 25 Nov 2008 09:32:26 GMT Subject: Python/C API: using from a shared library Message-ID: Hi, If I use dlopen() to open a shared library that I've written, and that shared library tries to use the Python/C API, then it fails. I've reduced the problem to the test case below. The error is: ImportError: /usr/lib/python2.5/lib-dynload/time.so: undefined symbol: PyExc_ValueError It appears that time.so tries to resolve PyExc_ValueError out of my program instead of libpython.so. I'm using Ubuntu 8.04, so that's Python 2.5.2. How do I go about getting this to work? Is this a bug in lib-dynload, or am I using the wrong linker flags? Would this be better asked in python-dev? Thanks, Robie /* Start of mylib.c */ /* Compile with: gcc -I/usr/include/python2.5 -fno-strict-aliasing -g -fwrapv -Wall -Wstrict-prototypes -L/usr/lib/python2.5/config -fPIC -shared -l:libpython2.5.so.1 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions -o mylib.so mylib.c */ #include #include int init(void) { PyObject *module; module = PyImport_ImportModule("time"); if(!module) { fprintf(stderr, "python module load failed\n"); PyErr_Print(); return -1; } Py_DECREF(module); return 0; } void init_module(void) { fprintf(stderr, "python initalizing\n"); Py_Initialize(); fprintf(stderr, "python initialized\n"); } /* vim: set ts=8 sts=4 sw=4 ai : */ /* End of mylib.c */ /* Start of myprog.c */ /* Compile with: gcc -o myprog -ldl myprog.c */ #include #include int main(int argc, char **argv) { void *lib; int (*init)(void); void (*init_module)(void); char *error; lib = dlopen("./mylib.so", RTLD_LAZY); if(!lib) { fprintf(stderr, "%s\n", dlerror()); return 1; } dlerror(); *(void **) (&init_module) = dlsym(lib, "init_module"); if((error=dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return 1; } (*init_module)(); *(void **) (&init) = dlsym(lib, "init"); if((error=dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return 1; } (*init)(); dlclose(lib); return 0; } /* vim: set ts=8 sw=4 sts=4 ai : */ /* End of myprog.c */ From mr.spoon21 at gmail.com Fri Nov 7 11:23:21 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Fri, 7 Nov 2008 17:23:21 +0100 Subject: More __init__ methods In-Reply-To: References: <6ngijnFlbequU3@mid.uni-berlin.de> <8f67b6f80811061029j30671d3v293935069c1ebdf2@mail.gmail.com> <49133AF4.4070509@timgolden.me.uk> Message-ID: <8f67b6f80811070823u57233a78y91a4e897b2637100@mail.gmail.com> On Fri, Nov 7, 2008 at 4:16 PM, Duncan Booth wrote: > There is a really big advantage to being explicit in this situation: you no > longer have to make sure that all your constructors use a unique set of > types. Consider: > > class Location(object): > def __init__(self, lat, long): ... > > @classmethod > def from_city(name): ... > > @classmethod > def from_postcode(name): ... > > 'from_string' is a bad name here for your factory method: you should try to > make it clear what sort of string is expected. Yes, that's what I was going to do. But, for example, I have a parse method to create such object from a string. So I need to call this method to actually create the object. Now I must put the code of the parse method into the @classmethod constructor. What if I need the parse method to be called in other parts of the program? From sjmachin at lexicon.net Tue Nov 25 19:37:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Nov 2008 16:37:33 -0800 (PST) Subject: checking for mis-spelled variable names / function names References: <492c8754$0$8400$426a74cc@news.free.fr> Message-ID: <2b1e9d3c-b707-4db9-b33e-2dbfaf6aacb0@q26g2000prq.googlegroups.com> On Nov 26, 10:16?am, News123 wrote: > Hi, > > Let's imagine following code > > def specialfunc(): > ? ? ? ? print "very special function" > > name= getuserinput() > if name == 'one_name_out_of_a_million': > ? ? ? ? print "Hey your name '%s' is really rare" % namee > ? ? ? ? specialfunk() > > my python script could survive thousands of runs before falling into > the mis-spelled code section. ('namee' instead of 'name' and > 'specialfunck()' instead of 'specialfunc()' > I know that good designers should always test their code and have > complete code coverage, before releasing their beasts into the wild, but > in my experience this is not always what happens. > > I fell already over quite of my own sins, but also over typoes of other > python authors. > > Is there any way in python to check for mis-spelled variable / function > names? > > In perl for example 'use strict;' would detect bad variable names, > though it wouldn't detect calls to undeclared functions. > > I am aware, that there is absolutely valid (and useful) python code with > ?undefined functions / variable names. > > However for the scripts that I write I would prefer to identify as many > typoes as possibe already when trying to run the script the first (and > not the millionth) time. > > Do you have ideas suggestions? > Are there any 'lint' like tools trying to analyze python code for > potential stupidities? > > If yes, what would be 'the' way to add these tools / modules at )least > during the development cycle) to the scripts. > C:\junk>type typo.py def specialfunc(): print "very special function" ### name= getuserinput() ### won't even compile; gets NameError def get_check_name(name): if name == 'one_name_out_of_a_million': print "Hey your name '%s' is really rare" % namee specialfunk() C:\junk>pychecker typo.py C:\junk>c:\python25\python.exe c:\python25\Lib\site-packages\pychecker \checker.py typo.py Processing typo... Warnings... typo.py:7: No global (namee) found typo.py:8: No global (specialfunk) found From kurdayon at yahoo.com Wed Nov 5 20:36:07 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Wed, 5 Nov 2008 17:36:07 -0800 (PST) Subject: How to re-import a function from a module? Message-ID: Hi, I have the following small problem. I run Python interactively. In the beginning of the run I import many functions from many modules. Than I execute some commands and notice that one of the imported functions contains a mistake. I open another terminal in which I open the file with the problematic function and correct the function. However, the Python does not see my changes. It still uses the old version of the function. In principle I could close the Python session and reopen it again and import all functions agane. But it does not seem to be a convenient solution. Is there a way to force Python to re-import the function, i.e. to force it to use the new version of the function? Thank you in advance. From david.lyon at preisshare.net Tue Nov 25 00:57:20 2008 From: david.lyon at preisshare.net (david.lyon at preisshare.net) Date: Tue, 25 Nov 2008 00:57:20 -0500 Subject: Python surpasses Perl in popularity? In-Reply-To: <77450bcf-ec47-44ac-820b-c214b300ee68@a3g2000prm.googlegroups.com> References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <77450bcf-ec47-44ac-820b-c214b300ee68@a3g2000prm.googlegroups.com> Message-ID: <20081125005720.tg95zwijq8coogss@syd-srv02.ezyreg.com> Quoting John Machin : > I'll try again: On what grounds do you assert that "Many libraries, > aren't as sophisticated - ie spreadsheet reading and writing."? What > Python spreadsheet reading and writing libraries have you used? In > what way are they less sophisticated than their perl counterparts? Do > you have any particular enhancement requests? Hi John, Since you asked a second time and appear genuinely interested - I will answer properly. :-) pyExcelorator - Setting column widths. Doesn't seem to work. Nor setting attrributes in sheets. Things seem to be only half done when compared to what I have seen in Perl. Perl was much easier to get the same functionality working. Here is my particular complaint: .. from pyExcelerator import * .. .. # -- Adjust the column width if dbf1.fieldDefinitions()[f].fieldInfo()[1] == 'C': ws.col(f).width = 0x0d00 + (f * 600) in perl.... $sheet1->set_column(0, 0, 20); perl works nicely... I couldn't find a way to so easily set a column width... plus.. colours are all broken... If you can shed any light on it for me, I would be thankful. Regards David From steve at holdenweb.com Thu Nov 13 10:41:47 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Nov 2008 10:41:47 -0500 Subject: multiple breaks In-Reply-To: <47c890dc0811130216n3afb46d4gdee1d066b16d86a7@mail.gmail.com> References: <47c890dc0811130216n3afb46d4gdee1d066b16d86a7@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Thu, Nov 13, 2008 at 2:07 AM, TP wrote: >> Hi everybody, >> >> Several means to escape a nested loop are given here: >> >> http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python >> >> According to this page, the best way is to modify the loop by affecting the >> variables that are tested in the loops. Otherwise, use exception: >> >> "If, for some reason, the terminating conditions can't be worked out, >> exceptions are a fall-back plan." >> >> In the following example, is this possible to affect the two iterators to >> escape the two loops once one "j" has been printed: >> > > Non-exception alternative: > > done = False >> for i in range(5): >> for j in range(i): >> print j > done = True > break >> # I would type "break 2" in shell bash >> # In C, I would set j=i-1 and i=4 >> # In Python, is this possible to affect the two iterators? > if done: > break >> Or the only means is to use exception? > > No, you could add a boolean variable and a break condition like above. > Though I would have to ask why you would want to. An exception seems rather cleaner, though of course tastes vary. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From pdorange at pas-de-pub-merci.mac.com Thu Nov 20 10:38:10 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 20 Nov 2008 16:38:10 +0100 Subject: Air Force1 and Air Jordan shoes PAYPAL wholesale References: <3eda264a-6981-44e4-bfb8-8453496e2700@r10g2000prf.googlegroups.com> Message-ID: <1iqpq6p.163ykykbxd3mkN%pdorange@pas-de-pub-merci.mac.com> air force1 shoes wrote: >>> air force1 shoes. air force1 high shoes. air force1 light shoes File "", line 1 air force1 shoes. air force1 high shoes. air force1 light shoes ^ SyntaxError: invalid syntax >>> -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From manu3d at gmail.com Tue Nov 18 20:16:55 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Tue, 18 Nov 2008 17:16:55 -0800 (PST) Subject: Restricted Execution of untrusted code References: <87y701obgz.fsf@benfinney.id.au> Message-ID: <0780ca94-f434-4405-9578-ec4b4c1dab63@v22g2000pro.googlegroups.com> Thanks to those who replied and sorry for not having replied sooner. Ok, got the message: chroot jail. I understand chroot is available for unix-like OS as a kernel-provided facility. If I was developing for, say, Linux or maybe even MacOSX, it might even be easy. My target OS however are XP and Vista. I did find chroot-like features in various virtualization platforms for those OS, but it would definitely be overkill to request the user that he installs a virtualization software to run a small application. I was reading this page http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20(i.e.%20Sandbox) and it seems to me my only two options are pypy-c and Jython. Would you agree or are there more avenues to explore given my OS requirements? Manu From stefan_ml at behnel.de Fri Nov 7 01:46:31 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 07 Nov 2008 07:46:31 +0100 Subject: convert to XMLRPC In-Reply-To: References: Message-ID: <4913e447$0$31339$9b4e6d93@newsspool4.arcor-online.net> Michel Perez wrote: > [db connection] > In the stdlib xmlrpclib handles this in a common way, but i use a > customized GatewayHandler that give me the posibility to serialize my > objects and send them to my clients Doesn't XML-RPC do that for you already? What's the protocol you use for client communication? > but my real need is to convert this > object to XML -or something like it- to send it in a way i can use them > in every presentation a suggest like GUI, WEB or anything i like. > There's any thing i can do to convert them. You can recursively copy the attributes of your objects into the E factory of lxml, either with generic code, or with specialised code for each (sub-)object. http://codespeak.net/lxml/tutorial.html#the-e-factory There's also a separate implementation for plain ElementTree (the xml.etree package) by Fredrik Lundh. Stefan From kinch1967 at gmail.com Tue Nov 25 11:56:24 2008 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Tue, 25 Nov 2008 08:56:24 -0800 (PST) Subject: Enumerating k-segmentations of a sequence Message-ID: I'm not sure if my terminology is precise enough, but what I want to do is: Given an ordered sequence of n items, enumerate all its possible k- segmentations. This is *not* the same as enumerating the k set partitions of the n items because I am only interested in those set partitions which preserve the order of the items. i.e. if the input sequence is (1 2 3 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4 5)) is acceptable. Hence use of term 'segmentations'. e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function which enumerates the following 3-segmentations: ((1 2 3) (4) (5)) ((1 2) (3 4) (5)) ((1 2) (3) (4 5)) ((1) (2 3 4) (5)) ((1) (2 3) (4 5)) ((1) (2) (3 4 5)) The reason I want to do this is to use it in some simple one- dimensional clustering, i.e. each set item (won't be just integers as above) will have a value of interest, and i'll select the particular set partition which minimises Sigma SSD (sum of squared differences from mean) of these values. It seems overkill to generate the full list of set partitions [including e.g. ((1 4) (2) (3 5))] because I intend to begin by sorting the input sequence such that element 1 < element 2 < ... < element n. Structural Recursion not being my strong point, any ideas on how to go about this would be much appreciated! From bartweber at gmail.com Sat Nov 29 19:35:09 2008 From: bartweber at gmail.com (Bart) Date: Sat, 29 Nov 2008 16:35:09 -0800 (PST) Subject: Embedded Program Icon (wxPython) References: <7da831f7-ff7d-4029-aea1-713bf36d15b1@33g2000yqm.googlegroups.com> <25133a35-0650-4883-b2eb-52c01e113e53@j39g2000yqn.googlegroups.com> Message-ID: <62b61fdb-3d3b-4470-8b26-d25fe7624f4f@c1g2000yqg.googlegroups.com> On Nov 29, 10:14?pm, Mike Driscoll wrote: > On Nov 29, 2:30?pm, Bart wrote: > > > > > Dear members, > > It's not (yet) easy to find my way through the bunch of info scattered > > over the internet to find out how to embed an icon. It could be that > > I?m looking at the wrong places, I'm new to Python and wxPython. > > Nevertheless, I would like to share this little script with the rest > > of the world. Any suggestions are welcome! > > > Regards, > > Bart > > > import wx > > import cStringIO > > import base64 > > > def getImageStream(): > > ? ? img_b64 = \ > > > """iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAATlJ REFUWIXNl2FyhCAMhV > > +0B/NmCzfrHkxff+zSik0gCI77ZhwdCckHQoIi04w7Nd0a/ > > WMBuK0cHcjyKdYa4LZSplmanBXsrTYTQOvonZljHys4AHx5HWVgTBx5syjWpeBVgN+A75H/ > > BTbsmEBe9rXgQNcuqPp2qQqgj74cPJl61sxn5oGyxkx9B8BYZQDcVqbL7kLEGP691d55fGfb0LN tzsr0LdNcvQAQAPcKIZAESWTP5MsWAD2+b18DxVqwl5YPYowAgMcj7By > > +787P2T0D+ > > +Bn5AZIIxKt4iSbxtE3AVylywFq9cBdjADf1B5tZJqlBFEEsE4zaR0sy4Ln8xsxBvUw4oEwAWpH qVZZEOap > > +Iq0rPlUAa6sCS6AkrR8EELI2pr8nfk3bP0vGA5wBOn5ZF0AI3R7Kv4BLsO1PPzEcJMAAAAASUV ORK5CYII=""" > > ? ? img = base64.b64decode(img_b64) > > ? ? return img > > > class MyFrame(wx.Frame): > > ? ? def __init__(self, parent, id, caption): > > ? ? ? ? wx.Frame.__init__(self, parent, id, caption) > > > ? ? ? ? myStream = cStringIO.StringIO(getImageStream()) > > ? ? ? ? myImage = wx.ImageFromStream(myStream) > > ? ? ? ? myBitmap = wx.BitmapFromImage(myImage) > > > ? ? ? ? myIcon = wx.EmptyIcon() > > ? ? ? ? myIcon.CopyFromBitmap(myBitmap) > > ? ? ? ? self.SetIcon(myIcon) > > > app = wx.PySimpleApp() > > frame = MyFrame(None, -1, "Embedded Programm Icon Sample") > > frame.Show(True) > > app.MainLoop() > > wxPython provides the img2py utility for this sort of thing. On my > Windows box, it was here: > > L:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\tools > > You can read up on how to use it here: > > http://www.blog.pythonlibrary.org/?p=34 > > Unfortunately, that article is a little dated. The newest version of > wxPython includes an updated img2py utility that I'm told supports the > previous API, but I haven't tested it. One of these days, I'll have to > update that post to reflect the new way though... > > Glad you found an alternate way to do it though. I recommend > subscribing to the wxPython group. They can give you additional > pointers, should you need them:http://wxpython.org/maillist.php > > Mike Thanks a lot Mike! In Dutch we would say 'handig'! (Translated as 'handy') Your fine example was what I was looking for the whole day :) I tried this thing for my self but my 'img2py.py' gives indeed an other script (see below). To make this new version of 'myIcon.py' work with your sample script 'embed_icons3.py', you've to change the last line of 'myIcon.py': getpyIcon = py.GetIcon ,into getIcon = py.GetIcon That piece of code in my previous post was a collection of code snippets I found in all different kind of examples. Your way, I think, is much more elegant. Actually, simple. Regards, Bart Script of myIcon.py generated with the new version of img2py.py (Version: wxPython 2.8.9.1 for Python 2.5) # myIcon.py # #---------------------------------------------------------------------- # This file was generated by C:\Python25\Lib\site-packages\wx-2.8-msw- unicode\wx\tools\img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage py = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAvxJ" "REFUWIXtl0tPU0EUgL+5baHQlncpBKkPMGpYIKiJKw1xoysXGk1cGLf+Bv +CS6Mr3ZoYNHFh" "ohuMcYWYBowkClYaCG0pD9vS0td9uJhCH/TSFhaYyEkm9845nXO +mXt6ZkYIxcJhinKo0QEB" "jwww6hzmRyjjolhj6LcNGKgbwAo2GHXDqAcsovoIgMV2+DBeqrtxEbyn5Hs0Db4IzMdkv8kC" "Fzww1Cn7mgG+FfBFsAJwqQceDkNjjfnwqRMj9NhgOiT753vh5ghcPS77/ igk1QKAwwZj/XDv" "rOxnNHg2UwRgt0Jro3zWIuc8cGcEjnvgaxCsdnDYoc0u7a4GaCiajCKgyVqwp9WdWDVGLJOB" "djjdA4NdsJqErLovN+YAPzdgdg1SWqm +3wlDXeB2gF0BpwWsArL7jm8C8G0VXnyH9XSpfqwf" "upuhww6plGyaVtHFwQASOQgmIZIq1a+lIKeDEGAYoOsHCg7/ QCGqvAJeF1zzQixTqh/thpaG" "6l4dNhh2y2wH+Q/zuuoAGHZDrxPUsiVuaQB3c3WADjtcPwGXe/ NRFOhuqgOgq1k2M1ndgkBc" "VrONNOQMmI6A0wYnW8HjAK8NvGXjshoEYrJQLcT2AKgmgRi8moMvYQglQAfe+mFxE +6ekQCV" "JKvB52V4Mw +h5B4AwU1Y2oSsSZb7IjL4XBCIAgb8apOfzOsCuwWOuQogGVX680dhMgS+cH5c" "zARgZg1ez0E0U9HMn3R+BlGE8lwAGPoDg9VWeLcASwm4NVgASObg41LetgkYCOWpMF +BcBKm" "ViASAeKAWbEJFr0vQtIKP1rkbnelr2DK6fA7BpPLeX/ RHVOVHFhBKC9r2qOFMiFgAkO/b0Cf" "ya9UhPKkxF+VQhSvJXaZJPew7c6pQ6+ERwBHAEcAshClVbn3b+/ fKRX0ei8rRaLpsJWT9wOA" "eEYexU0BpsKyfG5fTGbXZf3er2yk4X0A/Pl7wVZOnjMrA +TAtyzb7qnsI7oG0QRMJGCi3Lb7" "+C7++9vxX9DXCWOvj7llAAAAAElFTkSuQmCC") getpyData = py.GetData getpyImage = py.GetImage getpyBitmap = py.GetBitmap getIcon = py.GetIcon From wuwei23 at gmail.com Wed Nov 26 19:35:04 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 Nov 2008 16:35:04 -0800 (PST) Subject: what's so difficult about namespace? References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> <20081211231321.223@gmail.com> Message-ID: On Nov 27, 9:28?am, Xah Lee wrote: > Hi Stefan, try not to be a moron. Hi Xah, try not to be an asshole. [and in a separate post] > your post is too much verbiage and enthusiasm. The hypocrisy here would be funny if I didn't think you were serious. From aspersieman at gmail.com Mon Nov 3 09:13:35 2008 From: aspersieman at gmail.com (Aspersieman) Date: Mon, 03 Nov 2008 16:13:35 +0200 Subject: damn street venders In-Reply-To: <9a2ed6e0-91b2-4ca6-ae7f-6e77cb753e2e@o4g2000pra.googlegroups.com> References: <9a2ed6e0-91b2-4ca6-ae7f-6e77cb753e2e@o4g2000pra.googlegroups.com> Message-ID: +1 -- Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo On Mon, 03 Nov 2008 16:05:13 +0200, r wrote: > Hey, go sell your stupid watch somewhere else. > i am tired of the message boards clogged with these stupid ads. > Nobody here cares about your cheap rolex watches or porn or anything > else. > This is python, and that is all we care about. > If we want those things we *know* how to find them. > good day! > > > -- > http://mail.python.org/mailman/listinfo/python-list From tengounplanb at gmail.com Thu Nov 27 09:13:23 2008 From: tengounplanb at gmail.com (tengounplanb at gmail.com) Date: Thu, 27 Nov 2008 06:13:23 -0800 (PST) Subject: Apache & mod_python: I don't receive anything with POST method References: <92451074-0e43-4bf7-92a4-099cbf2d8d75@e12g2000yqm.googlegroups.com> <2592268c-9f4d-463e-88bb-865d96a5f182@f40g2000pri.googlegroups.com> Message-ID: <2c6bdb81-0a77-41ab-8c9f-6d0d6a36b369@g38g2000yqd.googlegroups.com> On 26 nov, 23:22, Graham Dumpleton wrote: > On Nov 27, 12:21?am, tengounpl... at gmail.com wrote: > > > > > Hi, > > > I'm using a simple form to make possible the users of our site upload > > files. > > > > > ? ? > > ? ? > > ? ?
> > ? ? ? ?
> > ? ? ? ? > > ? ?
> > ? ? > > > > > The "upload.py" looks like this: > > > from mod_python import apache, util; > > > def index(req): > > ? ? form = util.FieldStorage(req, keep_blank_values=1) > > ? ? try: > > ? ? ? ? # form is empty here > > ? ? ? ? # return form --> I get "{}" > > ? ? ? ? ufile = form.get('upfile', None) > > > ? ? ? ? if not form.has_key('upfile'): > > ? ? ? ? ? ? return ":( No 'upfile' key" > > > ? ? ? ? # some checks. I never get beyond here > > > ? ? ? ? ufile = form['upfile'] > > ? ? ? ? if ufile.file: > > ? ? ? ? ? ? return ufile.file.name > > ? ? ? ? else: > > ? ? ? ? ? ? return ":( It's not a file" > > ? ? except Exception, e: > > ? ? ? ? return 'Fail: ' + str(e) > > > I'm getting an empty 'form'. No 'upfile' key at all. I've tried to add > > some other text fields but the result is the same: empty. If I use GET > > method with text fields, it works properly. > > > Currently I'm using: > > Apache 2.2.9 (initially I used Apache 2.2.3 too) > > mod_python 3.3.1 (initially I used mod_python 3.2.10 too) > > Python 2.5.2 > > Which is the correct result for the code you are using. > > The problem is that you appear to be using mod_python.publisher which > does its own form handling before you are even getting a chance, thus > it is consuming the request content. > > For how to handle forms in mod_python.publisher see: > > http://webpython.codepoint.net/mod_python_publisher_forms > > Graham Hi, I should get a non-empty "form". With the following html

...and the following "upload.py": from mod_python import util, apache def index(req): form = util.FieldStorage(req, keep_blank_values=1) try: some_text = form.get('some_text', None); return form.items except Exception, e: return 'Fail: ' + str(e) ...I get (writting "Python" in the text box) [('some_text', Field('some_text', 'Python'))] So, I have a "form" with a non-empty structure of (key, value), and I'm able to get the value I'm looking for: ... some_text = form.get('some_text', None) # It's not empty anymore ... Thanks Le?n From joe at strout.net Fri Nov 14 15:28:27 2008 From: joe at strout.net (Joe Strout) Date: Fri, 14 Nov 2008 13:28:27 -0700 Subject: duck-type-checking? In-Reply-To: <39d83435-5304-4be2-9dfe-c50f70eb4b6a@d10g2000pra.googlegroups.com> References: <2b6000bf-fd9a-4330-be33-3a798a7ca387@z6g2000pre.googlegroups.com> <012ceefc$0$20662$c3e8da3@news.astraweb.com> <5828ef60-66df-4bb0-9a7d-aa08490f9e49@40g2000prx.googlegroups.com> <39d83435-5304-4be2-9dfe-c50f70eb4b6a@d10g2000pra.googlegroups.com> Message-ID: <7444C15D-D65C-4C5C-A936-1D3C15A46691@strout.net> On Nov 14, 2008, at 12:27 PM, pruebauno at latinmail.com wrote: > What would be actually interesting would be an switch to the python > interpreter that internally annotated function parameters with how > they are used in the function and raised an exception as soon as the > function is called instead of later. Failing earlier rather than > later. That would be interesting, but it wouldn't have helped in the case I had last week, where the method being called does little more than stuff the argument into a container inside the class -- only to blow up much later, when that data was accessed in a certain way. The basic problem was that the data being stored was violating the assumptions of the class itself. Sometimes in the past I've used a "check invariants" method on a class with complex data, and call this after mutating operations to ensure that all the class invariants are still true. But this class wasn't really that complex; it's just that it assumed all the stuff it's being fed were strings (or could be treated as strings), and I inadvertently fed it an NLTK.Tree node instead (not realizing that a library method I was calling could return such a thing sometimes). So, in this case, the simplest solution was to have the method that initially accepts and stores the data check to make sure that data satisfies the assumptions of the class. Best, - Joe From joe at strout.net Mon Nov 17 13:09:47 2008 From: joe at strout.net (Joe Strout) Date: Mon, 17 Nov 2008 11:09:47 -0700 Subject: compressed serialization module In-Reply-To: <5aad6da2-e025-4524-a616-14197c3e3ef0@s9g2000prg.googlegroups.com> References: <5aad6da2-e025-4524-a616-14197c3e3ef0@s9g2000prg.googlegroups.com> Message-ID: <1A172A1E-43DA-4C0D-93FF-13305191276E@strout.net> On Nov 17, 2008, at 10:47 AM, Mark wrote: > I used pickle and found the file was saved in text format. I wonder > whether anyone is familiar with a good compact off-the-shelf module > available that will save in compressed format... or maybe an opinion > on a smart approach for making a custom one? Well, here's a thought: create a zip file (using the standard zipfile module), and pickle your data into that. HTH, - Joe From martin at v.loewis.de Sun Nov 9 15:10:32 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Nov 2008 21:10:32 +0100 Subject: Installing Python 2.6 on Vista In-Reply-To: <7327c96b-ddae-45bb-a619-84cccf5a2408@r36g2000prf.googlegroups.com> References: <12a4784e-dfaa-4a73-a3d2-a743664ecc1d@d10g2000pra.googlegroups.com> <49173c5a$0$28043$9b622d9e@news.freenet.de> <7327c96b-ddae-45bb-a619-84cccf5a2408@r36g2000prf.googlegroups.com> Message-ID: <491743b8$0$28011$9b622d9e@news.freenet.de> > It installs fine for 'just me', so no problem. It installs for 'just me', but it doesn't work. Just try starting IDLE, or import the socket module. Regards, Martin From Charlie.Xia.FDU at gmail.com Tue Nov 18 14:59:03 2008 From: Charlie.Xia.FDU at gmail.com (Charlie) Date: Tue, 18 Nov 2008 11:59:03 -0800 (PST) Subject: C Function Pointer Wrapping Example not working References: <5e766d7f-ad2f-4e7c-883f-120e214e1472@40g2000prx.googlegroups.com> Message-ID: <0c6a0520-72e5-4a56-9532-54bfcec873f4@d36g2000prf.googlegroups.com> > Nowhere in your code is the definition of binary_op - that is why you > get a linker error. > > Is it defined in another C file? ?If so you need to link it with the > swig wrapper before you make the .so > Thanks for pointing out. I sorted the code out finally! Charlie From castironpi at gmail.com Sun Nov 30 18:36:17 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 30 Nov 2008 15:36:17 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <734145eb-9625-4f34-9308-7ac6652c3562@3g2000yqs.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> Message-ID: <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> > > r, i am with you! i will back Python!!!?we MUST spread > > Python throughout the world! sketchup is the first step, > > only the first step. > > First step? Really? AFAIK, Python is already used in: OpenOffice.Org, > Blender, GIMP, Inkscape, Scribus, etc. I've never used these tools, > but I heard they also have python interface: AbiWord, Gnumeric. > > Definitely not first step. On Nov 30, 10:45 am, r wrote: > The "first step" simply meant..."within this movement"...Not that > there exist no "other" Python API's. That's circular: Sketchup is the first step within the Sketchup movement. From mail at microcorp.co.za Mon Nov 3 15:57:56 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 3 Nov 2008 22:57:56 +0200 Subject: Finding the instance reference of an object References: <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <6mv3bnFj2qd8U1@mid.individual.net><011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> <011ac754$0$20643$c3e8da3@news.astraweb.com><8862f5ae-c482-4f53-a020-629eb45a5c3f@c22g2000prc.googlegroups.com> Message-ID: <001401c93e03$9bd01860$0d00a8c0@hendrik> "Aaron Brady" wrote: >I think we can conclude that Python passes by reference, since a >function can modify objects that were passed in to it. Sort of - if the modification is by "side effect" - so you can append to a list, for instance. However, if you use the passed param name on the left of an assignment statement, you get a new local object. I think it is this that lies at the root of the confusion. - Hendrik From tjreedy at udel.edu Sun Nov 23 13:03:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Nov 2008 13:03:14 -0500 Subject: initialization in argument definitions In-Reply-To: <6orlblF5455sU1@mid.individual.net> References: <7005ea9f-f803-4c06-831c-7f221a5fd598@r15g2000prh.googlegroups.com> <09787f36-0846-41a5-9075-7d3d80588389@o2g2000yqd.googlegroups.com> <6orlblF5455sU1@mid.individual.net> Message-ID: greg wrote: > George Sakkis wrote: > >> Don't worry, it's not obvious to *anyone* new to Python (and many not- >> so-new for that matter). > > That's by no means certain, because we only hear from the > people who guessed the wrong way. We have no way of knowing > how many people guessed the right way. I did not guess. I started by reading through the tutorial in about three hours. Then I did some work with Python. Within a couple of weeks, I read through the ref manual. I am really weird, it seems. From george.sakkis at gmail.com Mon Nov 10 10:50:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 10 Nov 2008 07:50:26 -0800 (PST) Subject: using exec() to instantiate a new object. References: <6cffedba-b69e-4029-ad4d-aa50d7e8af9c@q26g2000prq.googlegroups.com> <4e1e0900-787e-4bc4-9889-c35f27b64c93@u29g2000pro.googlegroups.com> Message-ID: <14d98bff-7328-4adc-a4f5-0d97a7a14ea6@35g2000pry.googlegroups.com> On Nov 10, 10:37?am, RyanN wrote: > On Nov 10, 7:47?am, RyanN wrote: > > > Thank you both, I knew there had to be a good way of doing this. > > > -Ryan > > Just an update. I used dictionaries to hold objects and their names. > I'm beginning to understand better. Now to apply this to my actual > problem. Here's the code I ended up with: That's fine, but unless you add functionality that *does* actually something with all these data, there's not much value going with an OO approach compared to using plain old data structures (e.g. [default]dicts and [named]tuples). George From nopsidy at gmail.com Mon Nov 3 00:33:05 2008 From: nopsidy at gmail.com (nopsidy) Date: Sun, 02 Nov 2008 23:33:05 -0600 Subject: CAD.py In-Reply-To: <4dcd31f0-81de-4dbe-b8f8-96640b3d1e54@40g2000prx.googlegroups.com> References: <9cacbd90-c6b4-414b-b4c5-75751bbb2091@v13g2000pro.googlegroups.com> <4dcd31f0-81de-4dbe-b8f8-96640b3d1e54@40g2000prx.googlegroups.com> Message-ID: r wrote: > On Nov 1, 7:13 pm, infixum wrote: >> s... at pobox.com wrote: >>> r> I am currently looking to create a small CAD program with python. >>> Instead of starting from scratch how about extending PythonCAD instead: >>> http://www.pythoncad.org/ >>> Skip >> ThanCAD might have a few ideas too. >> Carl T. > > Thanks for the replies: > I tried pythoncad but all links to source are broken > I even contacted devoloper and he gave me a link that also is > broken...hmm > I also tried thancad, did get it to download but cant run it yet... > but anyway thanks again i will keep trying. you can use git to get the source of pythoncad git clone git://repo.or.cz/pythoncad.git -nop From sjmachin at lexicon.net Sun Nov 23 15:48:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Nov 2008 12:48:27 -0800 (PST) Subject: Using dictionary to hold regex patterns? References: Message-ID: <0fadb9b3-3321-4f19-940b-f757e696d232@r24g2000prr.googlegroups.com> On Nov 24, 5:36?am, Terry Reedy wrote: > Gilles Ganault wrote: > > Hello > > > After downloading a web page, I need to search for several patterns, > > and if found, extract information and put them into a database. > > > To avoid a bunch of "if m", I figured maybe I could use a dictionary > > to hold the patterns, and loop through it: > > Good idea. > > import re > > > pattern = {} > > pattern["pattern1"] = ">.+?.+?>(.+?)" > > ... = re.compile("...") > > > for key,value in pattern.items(): > > for name, regex in ... > > > ? ?response = ">whatever.+?>Blababla" > > > ? ?#AttributeError: 'str' object has no attribute 'search' > > Correct, only compiled re patterns have search, better naming would make > error obvious. > > > ? ?m = key.search(response) > > m = regex.search(response) > > > ? ?if m: > > ? ? ? ? ? ?print key + "#" + value > > print name + '#' + regex Perhaps you meant: print key + "#" + regex.pattern From steve at REMOVE-THIS-cybersource.com.au Sat Nov 29 00:21:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Nov 2008 05:21:30 GMT Subject: Two attributes! Why? References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> Message-ID: <0140c948$0$20670$c3e8da3@news.astraweb.com> On Fri, 28 Nov 2008 19:22:42 -0800, Emanuele D'Arrigo wrote: > Hi everybody, > > I'm having a naming/scoping/mangling issue. I have a class like this: > > class MyClass(object): > __init__(self): > self.__myAttribute = None > > def myMethod(self, aValue): > attributeName = "__myAttribute" > setattr(self, attributeName, aValue) > > It all looks good to me but when I use a debugger I find that > > - myClass._MyClass__myAttribute = None > > and > > - myClass.__myAttribute = aValue > > I can't quite understand why. This is a side-effect of name-mangling. Double-underscore names are only mangled when they are referred to directly as attributes, not when they are passed to setattr, getattr etc. Those functions don't do any name mangling. -- Steven From ndbecker2 at gmail.com Thu Nov 6 07:17:21 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 06 Nov 2008 07:17:21 -0500 Subject: email for gpg encrypted? Message-ID: I know we have 'email' module. Is there something I could use to produce properly mime-encoded gpg encrypted messages? From jeff.tchang at gmail.com Tue Nov 18 13:45:50 2008 From: jeff.tchang at gmail.com (Jeff Tchang) Date: Tue, 18 Nov 2008 10:45:50 -0800 Subject: Class instantiation fails when passed in a file but work via line by line interpreter Message-ID: <63f9d2650811181045y64453c9j4cb6c9a14456710a@mail.gmail.com> Odd issue I am having with class instantiation on Python 2.5.2 (Windows). I have a custom module with a few classes in it. The module is named SAML.py. There is a copy of it in C:\Python25\Lib\site-packages\SAML.py. Basically when I try to run a python file that tries to create an instance of the class Subject I get this error: AttributeError: type object 'SAML' has no attribute 'Subject' In SAML.py I have the class... class Subject(object): ... ... etc However, when I run the same line by line by starting up python it works. >> import SAML >> subject = SAML.Subject("JohnDoe at example.com","EMailAddress") >>> print subject >>> I've double checked I am loading the correct module by the usage of the -v flag. What else should I be checking? -Jeff From steve at REMOVE-THIS-cybersource.com.au Fri Nov 21 21:02:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Nov 2008 02:02:12 GMT Subject: how to dynamically instantiate an object inheriting from several classes? References: Message-ID: <01376047$0$20662$c3e8da3@news.astraweb.com> On Fri, 21 Nov 2008 15:11:20 -0700, Joe Strout wrote: > I have a function that takes a reference to a class, Hmmm... how do you do that from Python code? The simplest way I can think of is to extract the name of the class, and then pass the name as a reference to the class, and hope it hasn't been renamed in the meantime: def foo(cls_name, item_args): # Won't necessarily work for nested scopes. cls = globals()[cls_name] item = cls(**itemArgs) return item instance = foo(Myclass.__name__, {'a':1}) Seems awfully complicated. If I were you, I'd forget the extra layer of indirection and just pass the class itself, rather than trying to generate some sort of reference to it. Let the Python virtual machine worry about what is the most efficient mechanism to use behind the scenes. [...] > But now I want to generalize this to handle a set of mix-in classes. > Normally you use mixins by creating a class that derives from two or > more other classes, and then instantiate that custom class. But in my > situation, I don't know ahead of time which mixins might be used and in > what combination. So I'd like to take a list of class references, and > instantiate an object that derives from all of them, dynamically. > > Is this possible? If so, how? It sounds like you need to generate a new class on the fly. Here's one way: # untested def foo(cls, item_args, mixins=None): superclasses = [cls] + (mixins or []) class MixedClass(*superclasses): pass item = MixedClass(**itemArgs) return item instance = foo(MyClass, {'a':1}, [Aclass, Bclass, Cclass]) -- Steven From kyosohma at gmail.com Thu Nov 20 09:19:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 20 Nov 2008 06:19:59 -0800 (PST) Subject: Hooking windowsmessages with python References: Message-ID: <31cdaf94-e11b-4586-a715-2ae8047a4abb@u14g2000yqg.googlegroups.com> On Nov 20, 3:52?am, Kevin Osthoff wrote: > Hi! > > I'm trying to set a message hook with python to catch WM_DROPFILES. > The guiframework is Tkinter. > Here a code snippet: > > > hwnd = eval(self.wm_frame()) > > win32gui.DragAcceptFiles(hwnd,1) > > wnd = win32ui.CreateWindowFromHandle(hwnd) > > wnd.HookMessage(self.test,w32con.WM_DROPFILES) > > def test(self): > > ? ?print "blala" > > The DragAcceptFiles-Call seems to be alright. When i drag a file over > the gui there is this drag-and-drop icon. But the problem is, that the > callback-function (test) is never executed. > I also try different messages like Mousemove or Buttondown. So i think > there is a problem with the HookMessage function. > I read that you must compile Python with PYWIN_WITH_WINDOWPROC option > enabled. Is this the problem? > > Can someone give me a short working code to hook a message so i can try > it on my workstation? > > Thx in advance! I recommend re-posting to the PyWin32 mailing list where the creators of this package lurk. They'll probably be able to give you some advice: http://mail.python.org/mailman/listinfo/python-win32 Mike From nick at craig-wood.com Fri Nov 14 08:29:58 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 14 Nov 2008 07:29:58 -0600 Subject: How to use a contiguous memory location of n bytes in python References: <6cdf28cc-1174-4c24-9f1a-123c89baa983@f40g2000pri.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > chachi: > > I want to know how to instantiate a data structure which has n bytes > > (given by me) and is internally stored in a contiguous fashion. > > array.array("B", ...) may be fit for you. You can also use a numpy > array of bytes. The mmap module is useful also for larger amounts (>4k say). mmap's are individually free-able so they don't fragment your memory. http://docs.python.org/library/mmap.html Eg create a 1 GB anonymous mmap, access it and then delete it >>> from mmap import mmap >>> a = mmap(-1, 1000000000) >>> a[0] '\x00' >>> a[0] = 'z' >>> a[999999999] '\x00' >>> a[999999999]='q' >>> a[999999999] 'q' >>> del a -- Nick Craig-Wood -- http://www.craig-wood.com/nick From simone.dalmasso at gmail.com Mon Nov 10 05:59:13 2008 From: simone.dalmasso at gmail.com (Simo D) Date: Mon, 10 Nov 2008 02:59:13 -0800 (PST) Subject: mod_python and file not found Message-ID: <20417611.post@talk.nabble.com> Hello, I'm trying to configure the apache to handle the python scripts. My platform is a CentOs server. I wrote these directives in the conf.d/python.conf: Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On The results are that if the script writes something on the server it works fine but if the script contains only html like this: print "Content-type: text/html\n" print "" print "" print "

ok

" print "" print "" it returns url not found on this server. It seems that I can't send info back to the browser. Can you help me? Thanks a lot. Simone -- View this message in context: http://www.nabble.com/mod_python-and-file-not-found-tp20417611p20417611.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Fri Nov 14 08:24:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 14 Nov 2008 05:24:49 -0800 (PST) Subject: Clustering the keys of a dict according to its values References: <491d6b57$0$32671$9b4e6d93@newsspool2.arcor-online.net> <323e1137-de0f-453d-ba73-41cc028c4da7@l33g2000pri.googlegroups.com> Message-ID: Alternative version: def cluster(data): d = defaultdict(list) pairs = enumerate(data) if isinstance(data, list) else data.iteritems() for k, v in pairs: d[v].append(k) return d Bye, bearophile From greg at cosc.canterbury.ac.nz Thu Nov 13 00:49:10 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 13 Nov 2008 18:49:10 +1300 Subject: cannot pickle object returned by urllib2.urlopen() In-Reply-To: References: Message-ID: <6o1t9gF1eligU1@mid.individual.net> > On Wed, 12 Nov 2008 11:00:26 +0800, scsoce wrote: > >>got a exception: "a class that defines __slots__ without defining >>__getstate__ cannot be pickled " >>why? Because in the absence of any other information, the default way of pickling an object is to save the contents of its __dict__. But an object with __slots__ doesn't necessarily have a __dict__, and even if it does, it doesn't include the contents of the slots. So you need to tell pickle how to deal with it by defining __getstate__ and __setstate__ methods. -- Greg From mr.spoon21 at gmail.com Wed Nov 19 07:44:20 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Wed, 19 Nov 2008 13:44:20 +0100 Subject: Programming exercises/challenges In-Reply-To: <12cbbbfc0811190435x3f2e3296kbdcab67883253ce8@mail.gmail.com> References: <8f67b6f80811190412p33ba6af0wb3c7e959bce72041@mail.gmail.com> <12cbbbfc0811190435x3f2e3296kbdcab67883253ce8@mail.gmail.com> Message-ID: <8f67b6f80811190444r1ed74041r8f0fe81621881507@mail.gmail.com> On Wed, Nov 19, 2008 at 1:35 PM, Jeremiah Dodds wrote: > > Personally, I prefer a host that gives me root on a box (or virtual > machine). I've had a great time with slicehost (http://slicehost.com). Yes, I knew about slicehost, but it is expensive for what I need to do, that is just experimentin a bit. > There are a few hosts that specialize in, or explicitly offer python > hosting, http://wiki.python.org/moin/PythonHosting has an overview of them. Thanks for the link, seems useful. From jeff_barish at earthlink.net Fri Nov 14 15:58:53 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Fri, 14 Nov 2008 13:58:53 -0700 Subject: Multiprocessing vs. [Pyro, RPyC] References: <18717.58823.533948.327676@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > > Jeffrey> With the release of multiprocessing in Python 2.6, is there > any Jeffrey> reason to use Pyro or RPyC? > > As far as I know the multiprocessing module only works on one machine > (multi-cpu or multi-core), not across machines. So I thought at first, but then I saw this statement in the documentation: It is possible to run a manager server on one machine and have clients use it from other machines (assuming that the firewalls involved allow it). -- Jeffrey Barish From luke.leighton at googlemail.com Thu Nov 27 14:33:17 2008 From: luke.leighton at googlemail.com (lkcl) Date: Thu, 27 Nov 2008 11:33:17 -0800 (PST) Subject: Applying a decorator to a module Message-ID: <6f276eee-ebbf-485c-9e67-d2d29a78f58e@v38g2000yqb.googlegroups.com> Very simple question: how do you apply a decorator to an entire module? an idea whose time has properly arrived is to merge pyjamas (http://pyjs.org) into web2py (http://web2py.com), and to do that, it's necessary to "identify" functions, classes, global variables and modules that should be compiled into javascript, rather than executed server-side. i figured that the best pythonic way would be to put a decorator on an entire module, if the entire module was to be compiled to javascript. ... however, i don't know how to do that! @decorate(module) ? @decorator() import modulename ? should this work? many thanks, l. From deets at nospam.web.de Wed Nov 26 10:52:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Nov 2008 16:52:39 +0100 Subject: Is the behavior expected? References: <2ab44767-cfd0-44b1-b790-cb90830babb4@y1g2000pra.googlegroups.com> <6p4uotF6cr74U1@mid.uni-berlin.de> <1d5b07a2-5e4d-4af1-8f33-69f7ab0502cd@l42g2000yqe.googlegroups.com> Message-ID: <6p59j4F6f0knU1@mid.uni-berlin.de> Alphones wrote: > On 11?26?, ??9?28?, bearophileH... at lycos.com wrote: >> Alphones: >> >> > it is a little deferent from other script language. >> >> See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping >> >> Python doesn't have such automatic closures, probably for performance >> reasons and/or maybe to keep its C implementation simpler (maybe other >> people here can give you an explanation of this, I too am curious). >> >> Bye, >> bearophile > > i encountered this problem when i'm writing a program for packaging > files. > the program generates tasks according to description file. > and tasks are deferent from each other, and should be excuted at the > last of program. > > i have experience on Lua and have learned about scheme and haskell, so > i wrote the wrong code in python. > > now my solution is, using class taskCreator to create tasks and put > them into tasklist. > class taskCreator: > def __init__(self, proc, input, output): > self.proc = proc > self.input = input > self.output = output > def call(self): > return self.proc.call(self.input, self.output) > 'proc' is generated by procCreators, it's specified. > > it looks more complex than lambda one. > > is there any other simple way to implement it? > and does the taskCreator mean 'create a new scope'? Not exactly, but there is a saying: "Closures are a poor man's objects. And objects are a poor man's closures." What you did creating a class and instantiating was to capture the parameters you needed at a time, and using them within call at another time. A similar thing happens when you create a lambda with arguments assigned, as I showed you - as then as part of the closure of the lambda there are the names in it's parameter list, assigned to the values the right hand sides had at the time being. Depending on what you want to do, both approaches - classes or closures - are valid. The more complex a problem gets, the more explicit & powerful a class becomes, where it might be a bit of an overhead for really simple problems. One thing for example classes allow - which is interesting for you - is that it is easy to look into them, for debugging/tracing. You can take a taskCreator (BTW, read PEP 8 about naming conventions in python) and see what is in there, e.g. logging it before executing the task or some such. OTOH, a lambda (or function) is an opaque thing you can't ask such things, making life a bit harder sometimes. Diez From Krzysztof.Retel at googlemail.com Thu Nov 20 10:03:46 2008 From: Krzysztof.Retel at googlemail.com (Krzysztof Retel) Date: Thu, 20 Nov 2008 07:03:46 -0800 (PST) Subject: Problem with writing fast UDP server Message-ID: Hi guys, I am struggling writing fast UDP server. It has to handle around 10000 UDP packets per second. I started building that with non blocking socket and threads. Unfortunately my approach does not work at all. I wrote a simple case test: client and server. The client sends 2200 packets within 0.137447118759 secs. The tcpdump received 2189 packets, which is not bad at all. But the server only handles 700 -- 870 packets, when it is non- blocking, and only 670 ? 700 received with blocking sockets. The client and the server are working within the same local network and tcpdump shows pretty correct amount of packets received. I included a bit of the code of the UDP server. class PacketReceive(threading.Thread): def __init__(self, tname, socket, queue): self._tname = tname self._socket = socket self._queue = queue threading.Thread.__init__(self, name=self._tname) def run(self): print 'Started thread: ', self.getName() cnt = 1 cnt_msgs = 0 while True: try: data = self._socket.recv(512) msg = data cnt_msgs += 1 total += 1 # self._queue.put(msg) print 'thread: %s, cnt_msgs: %d' % (self.getName(), cnt_msgs) except: pass I was also using Queue, but this didn't help neither. Any idea what I am doing wrong? I was reading that Python socket modules was causing some delays with TCP server. They recomended to set up socket option for nondelays: "sock.setsockopt(SOL_TCP, TCP_NODELAY, 1) ". I couldn't find any similar option for UDP type sockets. Is there anything I have to change in socket options to make it working faster? Why the server can't process all incomming packets? Is there a bug in the socket layer? btw. I am using Python 2.5 on Ubuntu 8.10. Cheers K From __peter__ at web.de Sat Nov 1 08:44:41 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Nov 2008 13:44:41 +0100 Subject: Simplifying anonymous inner classes? References: Message-ID: Tim Chase wrote: > I've got code similar to the following > > class Action: > def __init__(self, ...): pass > def __call__(self, ...): pass > def get_help(self, ...): pass > > class Backend: > class _Load(Action): > def __init__(self, ...): pass # override1 > def __call__(self, ...): pass # override1 > def get_help(self, ...): pass # override1 > load = _Load(...) > class _Run(Action): > def __call__(self, ...): pass # override2 > def get_help(self, ...): pass # override2 > run = _Run(...) > > class DatabaseBackend(Backend): > class _Frob(Action): > def __init__(self, ...): pass # override3 > def __call__(self, ...): pass # override3 > def get_help(self, ...): pass # override3 > frob = _Frob(...) > > In certain other languages, I might reach for an anonymous inner > class -- however, I don't see any way to do something like > > class Backend: > load = (class Action: > def __init__(self, ...): pass # override1 > def __call__(self, ...): pass # override1 > def get_help(self, ...): pass # override1 > )(...args to __init__...) > run = ... > > It seems silly to define the inner classes _Load and _Run just to > create a single instance of them (and for all it matters the > _Load and _Run could be promptly deleted from the containing > namespace immediately after instantiation). Method > implementations are sufficiently complex that a lambda won't > suffice (or if they would, they're beyond my know-how). > > Is there a more Pythonic way to instantiate sub-classes and > provide instance-specific implementations without the overhead of > an unused "anonymous" class cluttering my code/namespace? Python 2.6 has class decorators: >>> class instantiate(object): ... def __init__(self, *args): ... self.args = args ... def __call__(self, class_): ... return class_(*self.args) ... >>> class Backend: ... @instantiate(1,2) ... class load: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def __str__(self): ... return "load(%s, %s)" % (self.x, self.y) ... >>> print Backend.load load(1, 2) For older Pythons you can put the class into a function: >>> class instantiate: ... def __init__(self, *args): ... self.args = args ... def __call__(self, make_class): ... return make_class()(*self.args) ... >>> class Backend: ... @instantiate(1,2) ... def load(): ... class Load: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def __str__(self): ... return "load(%s, %s)" % (self.x, self.y) ... return Load ... >>> print Backend.load load(1, 2) While the class namespace isn't "cluttered" it's all a bit too complex to be truly pythonic. Peter From anthra.norell at bluewin.ch Thu Nov 27 07:25:33 2008 From: anthra.norell at bluewin.ch (F. Rentsch) Date: Thu, 27 Nov 2008 13:25:33 +0100 Subject: Requesting direction for installation problem In-Reply-To: <492d3907$0$9076$426a74cc@news.free.fr> References: <492d3907$0$9076$426a74cc@news.free.fr> Message-ID: <492E91BD.9020601@bluewin.ch> Bruno Desthuilliers wrote: > Frederic Rentsch a ?crit : >> Hi, >> >> Where can one get assistance if a Windows installation service fails >> to install an msi installer? I used to download zip files, but they >> seem to have been replaced with msi files. I know this issue is off >> topic here. So my question simply is: where is it not off topic? > > I'd have a look at the comp.os.ms-windows* hierarchy... > -- > http://mail.python.org/mailman/listinfo/python-list > Thank you for the hint. A preliminary peek looks promising. Frederic From bearophileHUGS at lycos.com Fri Nov 21 04:17:36 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Nov 2008 01:17:36 -0800 (PST) Subject: Dynamic features used Message-ID: <0404d520-554a-4356-bfd2-0f44b9a4053a@y18g2000yqn.googlegroups.com> I often use Python to write small programs, in the range of 50-500 lines of code. For example to process some bioinformatics data, perform some data munging, to apply a randomized optimization algorithm to solve a certain messy problem, and many different things. For that I often use several general modules that I have written, like implementation of certain data structures, and small general "utility" functions/classes, plus of course several external modules that I keep updated. Compared to other languages Python generally allows me to write a correctly working program in the shorter time (probably because of the Python shell, the built-in safeties, the doctests, the clean and short and handy syntax, the quick write-run-test cycle, the logical design, its uniformity, the availability of standard data structures and many standard or external modules, and the low number (compared to other languages) of corner cases and tricky semantic corners). Today Python is defined a dynamic language (and not a scripting language, a term that few languages today seem to want attached to them) but being dynamic isn't a binary thing, it's an analog quality, a language can be less or be more dynamic. For example I think Ruby is more dynamic than Python, Python is more dynamic than CLisp, CLips seems more dynamic than C#/Java, Java is more dynamic than D, and D is more dynamic than C++. Often such differences aren't sharp, and you can find ways to things more dynamically, even with a less nice syntax (or creating less idiomatic code). (In C#4 they have even added a dynamic feature that may make languages like IronPython/Boo faster and simpler to write on the dotnet). In the last two years I have seen many answers in the Python newsgroups, and I have seen that some of the dynamic features of Python aren't much used/appreciated: - Metaclasses tricks - exec and eval - monkey patching done on classes - arbitrary cmp among different types removed from Python 3 While some new static-looking/related features are being introduced: - ABCs and function signatures added - More tidy exception tree So it seems that while C#/D are becoming more dynamic, Python/ JavaScript are becoming a little less dynamic looking (and this I think this is positive, because too much dynamism turns code into a swamp, and too much rigid systems lead to bloat and other problems. Note that there are another orthogonal solution: to use an advanced flexible and handy static type system, as in Haskell). I have seen that in lot of those little programs of mine, or in a significant percentage of their lines, I often don't use the dynamic features of Python (this means that the same code can be written with static types, especially if you can use templates like in C++/D, or a flexible type system like in Haskell, and it also means that lot of those small programs can be compiled by ShedSkin/Cython, with usually a sharp decrease of running time). What are the dynamic features of Python more used in your programs? (From this set try to remove the things that can be done with a flexible static template system, like the D one, that for some things is more handy and powerful than the C++ template system, and for other things less powerful). If very little or no dynamic features are used in a program it may seem a "waste" to use Python to write the code, because the final program may be quite slow with no gain from the other features of Python. (I think in such situations Python can be a good choice anyway, because it's good to write working prototypes in a short time). (The large number of solution of this page shows how a certain class of Python programmers want more speed from their programs: http://scipy.org/PerformancePython and note that page misses many other solutions, like SIP, Boost Python, ShedSkin, Cinpy, Cython, RPython, and so on). In the last year I have found two situations where exec/eval is a way to reduce a lot of the complexity of the code, so if used with care the dynamic features can be quite useful. Before ending this partially incoherent post, I'd also like to briefly remind how the dynamic features are used in the Boo language: Boo programs are generally statically typed, but duck types are used once in a while to reduce the "pressure" of the static type system. You can find more info on this on the Boo site. (Note that I have never seen a good set of speed benchmarks to compare the performance of CPython to Boo). Bye, bearophile From drobinow at gmail.com Mon Nov 10 16:53:40 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Mon, 10 Nov 2008 13:53:40 -0800 (PST) Subject: disable ctrl-P in idle? References: <6g4hh49fabbu32k3e7p9j5n5186i5985re@4ax.com> <93eb5534-9185-4b48-ac46-fe504b0b3015@a29g2000pra.googlegroups.com> Message-ID: <5e427676-4ec8-4eb0-a44a-64ac33be14c7@g17g2000prg.googlegroups.com> On Nov 10, 3:27?pm, "timw.google" wrote: > On Nov 10, 2:57?pm, Robert Singer wrote: > > > > > On Mon, 10 Nov 2008 20:56:46 +0100, Robert Singer > > wrote: > > > >On Mon, 10 Nov 2008 10:40:28 -0800 (PST), "timw.google" > > > wrote: > > > >>Is there a way to disable ctrl-P (print window) in IDLE? I'm editing > > >>some python code in IDLE and I keep hitting this by mistake from my > > >>years of emacs editing. > > > >>Thanks in advance. > > > >Try autohotkey and map it to something else. Like, nothing :-) > > > >Internally, I don't think so, it's part of CUI. > > > >-- Bob > > > ... continue: > > Or, you can just continue using emacs. I'm using vim, and can't think > > of a single reason why I should change it for idle. > > > -- Bob > > Thanks. I on a XP box now, and it's a pain to get things installed > here. That's why I'm not using emacs. When I'm on Linux, I use emacs. > It's not worth the trouble to install something else for just this. It is not more difficult to install emacs on XP. What makes you think that? From bignose+hates-spam at benfinney.id.au Tue Nov 4 21:18:27 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Nov 2008 13:18:27 +1100 Subject: Is there a better/simpler way to filter blank lines? References: <6fa8c5d5-0dee-4f35-a0b5-59cb0d8f7f97@b31g2000prb.googlegroups.com> <87vdv3htgd.fsf@benfinney.id.au> <6ncbevFkre17U3@mid.uni-berlin.de> Message-ID: <87k5bij4p8.fsf@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > On Wed, 05 Nov 2008 12:06:42 +1100, Ben Finney wrote: > > > Falcolas writes: > > > >> Using the surrounding parentheses creates a generator object > > > > No. Using the generator expression syntax creates a generator > > object. > > > > Parentheses are irrelevant to whether the expression is a > > generator expression. The parentheses merely group the expression > > from surrounding syntax. > > No they are important: Your example shows only that they're important for grouping the expression from surrounding syntax. As I said. They are *not* important for making the expresison be a generator expression in the first place. Parentheses are irrelevant for the generator expression syntax. -- \ ?Today, I was ? no, that wasn't me.? ?Steven Wright | `\ | _o__) | Ben Finney From michele.simionato at gmail.com Tue Nov 4 02:10:10 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 3 Nov 2008 23:10:10 -0800 (PST) Subject: Structures References: <87d4hcmql2.fsf@benfinney.id.au> <11b141710811031538q37f8a1eauef846700da7c82e1@mail.gmail.com> Message-ID: <17ddd2d1-7a6b-422c-b491-627791ab8db9@v39g2000pro.googlegroups.com> On Nov 4, 2:57?am, Glenn Linderman wrote: > Note that classes, by default, are based on a contained dict! ?There are > games to be played with slots that can apparently improve that. ?I am > not yet experienced enough with Python to know if a slot is as fast as a > C struct, but perhaps it is. ? No, slots have nothing to do with speed, they are a memory optimization. IMO slots fall in the category of premature optimization and it was a mistake to include them in the language (the functionality should have been made available only at the C- level). As of now, lots of people abuse slots without realizing their disadvantages (for instance, they break multiple inheritance). From castironpi at gmail.com Sat Nov 8 15:44:48 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 8 Nov 2008 12:44:48 -0800 (PST) Subject: Finding the instance reference of an object References: <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <01203bbd$0$20642$c3e8da3@news.astraweb.com> <6ncanuFkre17U1@mid.uni-berlin.de> <6nkmcqFm081nU1@mid.individual.net> <01253391$0$20668$c3e8da3@news.astraweb.com> Message-ID: On Nov 8, 1:08?am, Steven D'Aprano wrote: > On Sat, 08 Nov 2008 18:31:47 +1300, greg wrote: > There's no "obviously" about it. To anyone who has learned that "call-by- > value" means that a copy is made, "obviously" it does mean copying the > value. If you have learned a different meaning, then you will believe > differently. I don't think it's obvious to everyone what a copy constructor is and when it's called. That's ok, it's something you can learn. I think Joe's idea is that you can think of every variable in Python as a pointer, and that clears up some confusions about its variable model. What happens when a pointer is copied? What is an example of copying a pointer in spoken language? >>> a= [ 1, 2, 3 ] Are the following true? The value of 'a' is an object. The value of that object is [ 1, 2, 3 ]. The value of 'a' is [ 1, 2, 3 ]. If so, 'value' is ambiguous and therefore not very useful as a term. From steve at holdenweb.com Mon Nov 24 18:10:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Nov 2008 18:10:42 -0500 Subject: Using dictionary to hold regex patterns? In-Reply-To: <6f127406-7450-4506-95d1-961ce9256b4d@i20g2000prf.googlegroups.com> References: <47dji4p2impcujt0disjqtjh6d00i8q2g8@4ax.com> <7ddb3ced-ddce-4d78-95d1-8028dd4d74b2@s9g2000prm.googlegroups.com> <6680d36e-7029-4156-9210-f74de70d5e73@s1g2000prg.googlegroups.com> <6f127406-7450-4506-95d1-961ce9256b4d@i20g2000prf.googlegroups.com> Message-ID: John Machin wrote: > On Nov 25, 4:38 am, Thomas Mlynarczyk [...] >>> Judging which of two structures is "simpler" should not be independent >>> of those requirements. I don't see a role for intuition in this >>> process. >> Maybe I should have said "upon first sight" / "judging from the outer >> appearance" instead of "intuition". > > I don't see a role for "upon first sight" or "judging from the outer > appearance" either. > They are all potentially (inadequate) substitutes for the knowledge and experience you bring to the problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at holdenweb.com Tue Nov 11 06:32:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Nov 2008 06:32:35 -0500 Subject: Final Python Class of 2009 In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Mon, 10 Nov 2008 22:14:16 -0500, Steve Holden wrote: > > Subject: Final Python Class of 2009 > > Steve, have you been in Guido's time machine again? > :-) > > No, honest (hides hands behind back). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From thedsadude at gmail.com Fri Nov 21 10:23:21 2008 From: thedsadude at gmail.com (thedsadude at gmail.com) Date: Fri, 21 Nov 2008 07:23:21 -0800 (PST) Subject: Custom Formatting The Output Of subprocess.Popen Message-ID: <1fa5b276-cd38-44b4-ac79-0d85775a67e0@a12g2000yqm.googlegroups.com> Hello, I'm launching a script as follows: p = subprocess.Popen(['./p.py', 'aa']) p.wait() If p.py writes to sys.stdout, then it is shown on the console. Looking at the console, then, it is hard to distinguish the output of p.py from that of the script launching it. I'd like to do it so the output looks like this: output of launcher p: output of launchee p: more output of launchee more output of launcher i.e., that each output line of p.py will be formatted so that it is preceded by 'p:'. How should this be done, then? Should I write a file class, and pass on object like so: custom_f = custom_file(sys.stdout, line_prefix = 'p') p = subprocess.Popen(['./p.py', 'aa'], stdout = custom_f) p.wait() or is a different option easier? Are there any links for writing custom file classes? Thanks & Bye, TD From jowillia at gmail.com Sat Nov 22 10:14:54 2008 From: jowillia at gmail.com (jowillia at gmail.com) Date: Sat, 22 Nov 2008 07:14:54 -0800 (PST) Subject: Modification of a urllib2 object ? References: <67360ab7-2679-4cac-9841-767f797778ad@8g2000hse.googlegroups.com> <355b358b-6a35-4cae-a7dc-5c22016cd959@l62g2000hse.googlegroups.com> <3b4392ae-fd35-4748-9456-8376b429b0de@34g2000hsh.googlegroups.com> Message-ID: On Oct 10, 10:57?pm, George Sakkis wrote: > On Oct 10, 6:12?pm, vincehofmeis... at gmail.com wrote: > > > > > On Oct 10, 1:02 pm, George Sakkis wrote: > > > > On Oct 10, 2:32 pm, vincehofmeis... at gmail.com wrote: > > > > > I have several ways to the following problem. > > > > > This is what I have: > > > > > ... > > > > import ClientForm > > > > import BeautifulSoup from BeautifulSoup > > > > > request = urllib2.Request('http://form.com/) > > > > > self.first_object = urllib2.open(request) > > > > > soup = BeautifulSoup(self.first_object) > > > > > forms = ClienForm.ParseResponse(self.first_object) > > > > > Now, when I do this, forms returns an index errror because no forms > > > > are returned, but the BeautifulSoup registers fine. > > > > First off, please copy and paste working code; the above has several > > > syntax errors, so it can't raise IndexError (or anything else for that > > > matter). > > > > > Now, when I switch the order to this: > > > > > import ClientForm > > > > import BeautifulSoup from BeautifulSoup > > > > > request = urllib2.Request('http://form.com/) > > > > > self.first_object = urllib2.open(request) > > > > > forms = ClienForm.ParseResponse(self.first_object) > > > > > soup = BeautifulSoup(self.first_object) > > > > > Now, the form is returned correctly, but the BeautifulSoup objects > > > > returns empty. > > > > > So what I can draw from this is both methods erase the properties of > > > > the object, > > > > No, that's not the case. What happens is that the http response object > > > returned by urllib2.open() is read by the ClienForm.ParseResponse or > > > BeautifulSoup - whatever happens first - and the second call has > > > nothing to read. > > > > The easiest solution is to save the request object and call > > > urllib2.open twice. Alternatively check if ClientForm has a parse > > > method that accepts strings instead of urllib2 requests and then read > > > and save the html text explicitly: > > > > >>> text = urllib2.open(request).read() > > > >>> soup = BeautifulSoup(text) > > > >>> forms = ClientForm.ParseString(text) > > > > HTH, > > > George > > > request = urllib2.Request(settings.register_page) > > > ? ? ? ? ? ? ? ? self.url_obj = urllib2.urlopen(request).read() > > > ? ? ? ? ? ? ? ? soup = BeautifulSoup(self.url_obj); > > > ? ? ? ? ? ? ? ? forms = ClientForm.ParseResponse(self.url_obj, > > backwards_compat=False) > > > Now I am getting this error: > > > Traceback (most recent call last): > > ? File "C:\Python25\Lib\site-packages\PyQt4\POS Pounder\Oct7\oct.py", > > line 1251, in createAccounts > > ? ? forms = ClientForm.ParseResponse(self.url_obj, > > backwards_compat=False) > > ? File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg > > \ClientForm.py", line 1054, in ParseResponse > > AttributeError: 'str' object has no attribute 'geturl' > > Did you read what I wrote ? ClientForm.ParseResponse() expects a > response object, not a string. Browsing through its docs, it seems > there is an alternative parsing fuction, ClienForm.ParseFile(file, > base_uri, ...). > > The following should work (untested): > > from cStringIO import StringIO > > request = urllib2.Request(settings.register_page) > response = urllib2.urlopen(request) > text = response.read() > soup = BeautifulSoup(text) > forms = ClientForm.ParseFile(StringIO(text), response.geturl(), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?backwards_compat=False) > > HTH, > George Hello George, I seem to be running into the same problem as Vince. Your solution seems very good, but ClientForm gets a little bit more from the handle than just the text. > The following should work (untested): > > from cStringIO import StringIO > > request = urllib2.Request(settings.register_page) > response = urllib2.urlopen(request) > text = response.read() > soup = BeautifulSoup(text) > forms = ClientForm.ParseFile(StringIO(text), response.geturl(), > backwards_compat=False) Hello George, When running your code in my program, which is doing something very similar to Vince, I get: AttributeError: 'cStringIO.StringI' object has no attribute 'geturl' This makes perfect sense in regards to the way ClientForms handles requests. It seems that short of figuring out how to deepcopy the handle, your going to be stuck making the request twice. But this is going to hit the URL (server) twice, which I would say is a bad idea. I've been struggling with this issue for some time now, and this is the first place I've found a solid discussion about it. -Josh From martin at v.loewis.de Sun Nov 9 13:18:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Nov 2008 19:18:02 +0100 Subject: Python 3.0 - is this true? In-Reply-To: <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> References: <64fee417-96d0-458a-8f5c-c71147a2c3bb@w1g2000prk.googlegroups.com> <7edee5cc-a98e-4a72-880a-7e20339f9697@i20g2000prf.googlegroups.com> <65e693aa-81ad-4de2-82ee-8bb99a89384e@x16g2000prn.googlegroups.com> Message-ID: <4917295A.4040907@v.loewis.de> > Sure: > > if len(L1) == len(L2): > return sorted(L1) == sorted(L2) # check whether two lists contain > the same elements > else: > return False > > It doesn't really matter here what the result of the sorts actually is > as long as the algorithm leads to the same result for all permutations > on L1 ( and L2 ). Unfortunately, for many releases, the list's sort algorithm would not provide that property. Release for release, new cases where found where the builtin ordering was not transitive (i.e. you get a < b and b < c, but not a < c). With funny definitions of __cmp__ in some classes, you can still get this today. Regards, Martin From alif016 at gmail.com Mon Nov 10 21:02:39 2008 From: alif016 at gmail.com (Andrew) Date: Mon, 10 Nov 2008 20:02:39 -0600 Subject: [Newbie] Strange output from list In-Reply-To: <87wsfbca4p.fsf@benfinney.id.au> References: <87wsfbca4p.fsf@benfinney.id.au> Message-ID: <4918E7BF.1000007@gmail.com> Ben Finney wrote: > Gilles Ganault writes: > > >> Hello >> >> I'm getting some unwanted result when SELECTing data from an SQLite >> database: >> >> ====== >> sql = 'SELECT id FROM master' >> rows=list(cursor.execute(sql)) >> for id in rows: >> sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0] >> result = list(cursor.execute(sql)) >> print "Code=%s, number=%s" % (id[0],result[0]) >> ====== >> Code=0111Z, number=(47,) >> ====== >> >> I expected to see "number=47". Why does Python return "(47,)"? >> > > The result of an SQL SELECT is a sequence of tuples, where each item > in the tuple is a value for a column as specified in the SELECT > clause. > > SQLAlchemy represents this with a sequence of ResultProxy objects. > When you convert a ResultProxy object to a string, it displays like a > tuple. See the documentation for other ways of accessing various > attributes of a ResultProxy object. > (47,) is the python representation of a one item tuple If you want: Code=0111Z, number=47 Just change your code to: sql = 'SELECT id FROM master' rows=list(cursor.execute(sql)) for id in rows: sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0] result = list(cursor.execute(sql)) print "Code=%s, number=%s" % (id[0],result[0][0]) Notice the extra [0] index on the "result" In English: Item zero of the tuple that is item zero of result E.g. >>> result = [(47,)] >>> result = result[0] >>> result (47,) >>> result[0] 47 -- Andrew From gregturn at mindspring.com Thu Nov 6 13:12:05 2008 From: gregturn at mindspring.com (Goldfish) Date: Thu, 6 Nov 2008 10:12:05 -0800 (PST) Subject: Spring Python 0.8.0 has been released/Spring Python goes green References: Message-ID: <2efdcc3f-6881-439d-812c-6cb6804b21b6@x16g2000prn.googlegroups.com> The Links section has some faults in it. Here is a corrected copy: Links: For more information, please visit the website at http://springpython.webfactional.com Framework download at http://s3browse.com/getObject/dist.springframework.org/release/EXT/se-springpython-py/springpython-0.8.0-RELEASE.tar.gz Sample applications at http://s3browse.com/getObject/dist.springframework.org/release/EXT/se-springpython-py/springpython-samples-0.8.0-RELEASE.tar.gz For general browsing of Spring Python releases, visit http://s3browse.com/explore/dist.springframework.org/release/EXT/se-springpython-py/ From george.sakkis at gmail.com Wed Nov 19 20:16:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 19 Nov 2008 17:16:55 -0800 (PST) Subject: Using eval, or something like it... References: Message-ID: <86be857a-c237-42b3-9fe2-5e0267e21591@v42g2000yqv.googlegroups.com> On Nov 19, 7:44?pm, r0g wrote: > Hi There, > > I know you can use eval to dynamically generate the name of a function > you may want to call. Can it (or some equivalent method) also be used to > do the same thing for the variables of a class e.g. > > class Foo(): > ? bar = 1 > ? gum = 2 > > mylist = ['bar','gum'] > > a = Foo() > for each in mylist: > ? a.eval(each) = 999 > > If so, what is the proper syntax/method for this. for each in mylist: setattr(a, each, 999) HTH, George From castironpi at gmail.com Thu Nov 20 19:07:31 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 20 Nov 2008 16:07:31 -0800 (PST) Subject: Optional parameter object re-used when instantiating multiple objects References: <5df8e227-1977-48eb-80ec-c905b7701bba@f37g2000pri.googlegroups.com> <0fbf3fca-2615-47de-989f-97ba6aa15bf1@w1g2000prk.googlegroups.com> <131f3d2b-af48-4657-8d12-5fb9f682390b@35g2000pry.googlegroups.com> <39422951-995d-4577-bc19-814215ce8806@p35g2000prm.googlegroups.com> <59mdnSY8fY7_yLnUnZ2dnUVZ_qXinZ2d@earthlink.com> <0283873b-0f35-4d05-8760-f2fceaef19c2@k19g2000yqg.googlegroups.com> <5763330a-2498-44d1-9c77-074076a2c4e1@j39g2000yqn.googlegroups.com> <61b66781-27c8-41cd-9799-6e8469795451@i20g2000prf.googlegroups.com> Message-ID: On Nov 20, 5:54?pm, alex23 wrote: > On Nov 20, 10:42?pm, Aaron Brady wrote: > > > At first, I would expect it to define them at compile-time. ?Then, > > when I learned there was no such thing, I would expect it to define > > them at execute-time. ?What does that have to do with evaluating a > > default argument? > > It has -everything- to do with it when we're talking about the > defining of functions, and certainly a lot more relevance than straw > man arguments on the behaviour of browser buttons. > > You said that you "would expect it to define them at execute-time". So > is that when the interpreter first hits the def or when the > interpreter hits every single function call? Because I personally > consider it to clearly occur at the point of definition and not at the > point of calling. Why, I would expect the interpreter to define the functions when it first hits the def, that is, at the point of definition. From duncan.booth at invalid.invalid Sun Nov 9 05:46:53 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Nov 2008 10:46:53 GMT Subject: is there really no good gui builder References: <27953e31-c924-42b4-9c90-e169719733c6@k1g2000prb.googlegroups.com> <491620F6.9000508@gmail.com> Message-ID: <6nntctFmbi6vU1@mid.individual.net> Mr.SpOOn wrote: > On Sun, Nov 9, 2008 at 12:29 AM, Stef Mientki wrote: >> Qt seems to be good, but I don't like their licence. > > > What's the problem with qt licence? "You must purchase a Qt Commercial License from Qt Software or from one of its authorized resellers before you start developing commercial software. The Commercial license does not allow the incorporation of code developed with the Open Source Edition of Qt into a commercial product." In effect this means that if you want to develop any commercial software with Qt you have to buy the license in advance (even if all you want is to knock together some proof-of-concept) and you are also permanently locked out from including any previously developed Qt code which the wider community may have produced. With other GPL licensed software you have the option of approaching the original author and negotiating with them for their code to be relicensed for use within your proprietary product (or the author could simply distribute their code under a less restrictive license to begin with), but the Qt license restricts you from using anything publicly available *except for Qt itself*. It is a novel interpretation of the GPL. Qt Software have every right to impose this sort of condition, but it makes me want to avoid them. From mh at pixar.com Thu Nov 6 17:13:50 2008 From: mh at pixar.com (mh at pixar.com) Date: Thu, 06 Nov 2008 22:13:50 GMT Subject: etymology of "list comprehension"? References: Message-ID: Chris Rebert wrote: > the term > "comprehension" for the concept was first used in the NPL programming > language (Wikipedia again). Ah, thanks... and does "comprehension" have any special computer science meaning? -- Mark Harrison Pixar Animation Studios From tjreedy at udel.edu Sun Nov 16 23:34:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Nov 2008 23:34:58 -0500 Subject: Official definition of call-by-value (Re: Finding the instance reference...) In-Reply-To: <012fd44f$0$20662$c3e8da3@news.astraweb.com> References: <6nul1qF100urU1@mid.individual.net> <6nvts2F15nlmU1@mid.individual.net> <012e69d6$0$20662$c3e8da3@news.astraweb.com> <4ee9ead6-c228-45cd-a717-22dcf9358327@v39g2000pro.googlegroups.com> <012fd44f$0$20662$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >> Because of >> Python's interpreted nature, names can't be compiled away as in C, they >> need a concrete runtime existence, but does the language definition need >> to assume that? > > Of course. It wouldn't be Python if they didn't. However, remember that > objects don't have names. Actually, Python pretty much does compile away names for function bodies. (They are replaced by array indexes.) It only needs to manifest them for locals(). CPython Dis.dis also accesses them, but that is obviously implementation specific. I suspect that the names are stored as C char sequences rather than as Python string objects unless and until the latter are needed for locals(). ... >>>> class EqualsAll(object): > ... def __eq__(self, other): > ... return True > ... >>>> 5 == EqualsAll() > True > > > The methods of 5 don't even get called. Why do you say that? As I read the manual, type(left-operand).__eq__ is called first. > This of course is a special case, because 5 is a built-in, If true, this would be CPython-specific optimization, not language definition. > but in general, the result of x==y depends on *both* x and y. True. But type(x) gets first crack at the answer. ... > You're assuming that == compares values, which is often a safe > assumption, but not always. The default is to compare by identity, so assuming otherwise is only safe when one knows the classes of x and y to over-ride the default. Terry Jan Reedy From opsbat at infomed.sld.cu Wed Nov 12 09:33:41 2008 From: opsbat at infomed.sld.cu (Michel Perez) Date: Wed, 12 Nov 2008 09:33:41 -0500 Subject: problem with JSON-RPC Message-ID: <1226500421.8416.6.camel@cerebellum> Hi everybody: I'm trying to use JSON-RPC to provide my services but produce this exception: Traceback (most recent call last): File "", line 1, in File "jsonrpc/proxy.py", line 43, in __call__ resp = loads(respdata) File "jsonrpc/json.py", line 211, in loads raise JSONDecodeException('Expected []{}," or Number, Null, False or True') jsonrpc.json.JSONDecodeException: Expected []{}," or Number, Null, False or True This is what am doing ==== configuration file for apache ==== Alias /services/ //home/mperez/Desktop/test_jsonrpc/ Options Indexes MultiViews FollowSymLinks Order deny,allow Allow from All AddHandler mod_python .py PythonHandler jsonrpc ==== service for jsonrpc test.py ==== from jsonrpc import ServiceMethod class MyService(object): @ServiceMethod def echo(self, msg): return msg service = MyService() ==== service client ==== ? #!/usr/bin/env python from jsonrpc import ServiceProxy s = ServiceProxy("http://localhost/services/test.py") print s.echo("foobar") Regards -- ?Michel Perez )\._.,--....,'``. Ulrico Software Group /, _.. \ _\ ;`._ ,. Nihil est tam arduo et difficile human ?`._.-(,_..'--(,_..'`-.;.' ?mens vincat. S?neca. ============================= --------------------------------------- Red Telematica de Salud - Cuba CNICM - Infomed From saju.pillai at gmail.com Thu Nov 6 14:26:40 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 6 Nov 2008 11:26:40 -0800 (PST) Subject: Weird behavior with lexical scope References: Message-ID: On Nov 6, 9:57?pm, mrstevegross wrote: > I ran into a weird behavior with lexical scope in Python. I'm hoping > someone on this forum can explain it to me. > > Here's the situation: I have an Outer class. In the Outer class, I > define a nested class 'Inner' with a simple constructor. Outer's > constructor creates an instance of Inner. The code looks like this: > > ========= > class Outer: > ? class Inner: > ? ? def __init__(self): > ? ? ? pass > ? def __init__ (self): > ? ? a = Inner() > Outer() > ========= > > However, the above code doesn't work. The creation of Inner() fails. > The error message looks like this: > > ? File "/tmp/foo.py", line 12, in > ? ? Outer() > ? File "/tmp/foo.py", line 10, in __init__ > ? ? a = Inner() > NameError: global name 'Inner' is not defined > > This surprises me! Since the construction of Inner takes place within > the lexical scope 'Outer', I assumed the interpreter would search the > Outer scope and find the 'Inner' symbol. But it doesn't! If I change: > ? a = Inner() > to > ? a = Outer.Inner() > > it works fine, though. AFAIK, when 'Outer.__init__' executes, 'Inner' is first searched for within 'Outer.__init__()'s local namespace. Since 'Inner' is defined outside the function namespace, the search will fail. Python then looks at the module level namespace - where Inner is again not defined (only 'Outer' is available in the module namespace), the final search will be in the interpreter global namespace which will fail too. When you change your code from 'Inner' to 'Outer.Inner', the module level namespace search will match ( or atleast that's how i think it should all work :) ) Try this .. class Outer: def __init__(self): class Inner: def __init__(self): pass a = Inner() Outer() This should work, because the Outer.__init__ namespace (first namespace being searched) has Inner defined within it -srp > > So, can anyone explain to me how Python looks up symbols? It doesn't > seem to be searching the scopes I expected... > > Thanks, > --Steve From steve at REMOVE-THIS-cybersource.com.au Sat Nov 8 02:12:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Nov 2008 07:12:40 GMT Subject: Finding the instance reference of an object References: <6mv3bnFj2qd8U1@mid.individual.net> <011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> <011ac754$0$20643$c3e8da3@news.astraweb.com> <8862f5ae-c482-4f53-a020-629eb45a5c3f@c22g2000prc.googlegroups.com> <6029a24d-bc25-455a-95f3-f25290cecbe6@u18g2000pro.googlegroups.com> <6n9j7jFk8mutU7@mid.uni-berlin.de> <99574ae4-2019-4e79-9865-a4a6d8ed76dc@w39g2000prb.googlegroups.com> <6nkpqgFm53f6U1@mid.individual.net> Message-ID: <01253474$0$20668$c3e8da3@news.astraweb.com> On Sat, 08 Nov 2008 19:30:17 +1300, greg wrote: > Something has just occurred to me. If you take the view that the value > of an expression is an object, then the terms "value" and "object" are > synonymous. So far so good. > So if you then insist that Python uses "call by object", you're actually > saying it uses call by value! Fail! The terms "guy" and "man" are synonymous, but a wise guy and a wise man are not. -- Steven From prologic at shortcircuit.net.au Mon Nov 10 17:33:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 11 Nov 2008 08:33:06 +1000 Subject: Memory error due to the huge/huge input file size In-Reply-To: <5f12daa1-b777-4653-bdc8-6c1f8787c2f7@a29g2000pra.googlegroups.com> References: <5f12daa1-b777-4653-bdc8-6c1f8787c2f7@a29g2000pra.googlegroups.com> Message-ID: On Tue, Nov 11, 2008 at 7:47 AM, wrote: > refSeqIDsinTransPro = [] > promoterSequencesinTransPro = [] > reader2 = csv.reader(open(sys.argv[2],"rb")) > reader2_list = [] > reader2_list.extend(reader2) Without testing, this looks like you're reading the _ENTIRE_ input stream into memory! Try this: def readCSV(file): if type(file) == str: fd = open(file, "rU") else: fd = file sniffer = csv.Sniffer() dialect = sniffer.sniff(fd.readline()) fd.seek(0) reader = csv.reader(fd, dialect) for line in reader: yield line for line in readCSV(open("foo.csv", "r")): ... --JamesMills -- -- -- "Problems are solved by method" From ldo at geek-central.gen.new_zealand Tue Nov 25 00:51:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Nov 2008 18:51:10 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: Cameron Laird wrote: > I've been trying to decide if there's any sober reason to advocate > the one-liner > > map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024]) Are lambdas like the Dark Side of Python? :) From iqbaltalaat at gmail.com Mon Nov 24 03:01:01 2008 From: iqbaltalaat at gmail.com (I-T) Date: Mon, 24 Nov 2008 00:01:01 -0800 (PST) Subject: Python Django Latex Permissions Problem Message-ID: I have a python/django webapp running with apache2. It executes system commands for getting a pdf generated by pdflatex from a .tex file and a couple of image files which it also generates. The permssions from ls-l for all the created files is:- -rw-r--r-- 1 www-data www-data The files are being created in /tmp/pdfscratch{id} created from the script and so is the directory. pdflatex fails with the following error message:- This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) %&-line parsing enabled. entering extended mode ! I can't write on file `uber.log'. Please type another transcript file name: ! Emergency stop ! ==> Fatal error occurred, no output PDF file produced! Its supposed to write to this directory. I have a feeling that pdflatex is trying to generate files using some weird access credentials that dont have access to /tmp/pdfscratch{id} What do you guys think could be the problem/solution Thanks in advance From steve at holdenweb.com Fri Nov 21 07:57:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Nov 2008 07:57:50 -0500 Subject: call an exturnal program in python In-Reply-To: <77A613A6E0834D309F0CA92057B67D4B@Familyroom2> References: <77A613A6E0834D309F0CA92057B67D4B@Familyroom2> Message-ID: Adam wrote: > I am trying to run an external program in my code using > os.system('exename -exearg') but the exe has an "&" in it so windows > thinks it's two commands any way around this? > Have you tries quoting the exename: os.system('"exename" -exearg') That might help. How do you run it from the command line? You might be better using subprocess.call(), since that allows you to run subprocesses without the shell interpreting the command line. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From thudfoo at opensuse.us Thu Nov 13 15:57:40 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 13 Nov 2008 12:57:40 -0800 Subject: Where can I get Lucid Toolkit? In-Reply-To: References: Message-ID: <3d881a310811131257sc04877fj9130d9abf1996b2e@mail.gmail.com> On 11/11/08, est wrote: > Hi guys, > > I tried to grab source code for Lucid Toolkit http://www.clarographics.org/svn_details > which was mentioned http://wiki.python.org/moin/GuiProgramming > > So is this project abandoned? Is there any backup that I can get the > code? > > Any other recommands for simple GUI development, with out large > library runtime(qt, gtk, wx) ? > easygui? > -- > http://mail.python.org/mailman/listinfo/python-list > From Shawn at milochik.com Wed Nov 5 11:39:02 2008 From: Shawn at milochik.com (Shawn Milochik) Date: Wed, 5 Nov 2008 11:39:02 -0500 Subject: Parse each line by character location In-Reply-To: References: Message-ID: <2dc0c81b0811050839r682c03dcj7e9c423b03d05ffe@mail.gmail.com> I work with tab-delimited files for a living. Because of the same need you have, I created a Python script to do this. It has usage information that is easy to follow (just run it without any arguments). I hope someone else finds this useful. I have, and use it every month. It can be easily modified to create comma-delimited files, but that's something I never use, so it does tabs. http://milochik.com/shawn/fwconvert.zip Usage: fwconvert -r rulesFile fileName [-t|-f] or cat filename | fwconvert -r rulesFile" (-t|-f) -t (to tab) or -f (to fixed-width) required when piping input to script. Otherwise, it will be auto-determined. Rules file format: fieldStart:fieldLength,fieldStart:fieldLength... Example: 1:3,4:20,24:5 From rupole at hotmail.com Fri Nov 7 13:18:43 2008 From: rupole at hotmail.com (Roger Upole) Date: Fri, 7 Nov 2008 13:18:43 -0500 Subject: adodbapi and output parameters in stored procedures References: Message-ID: wrote in message news:b100b7ac-44e5-407b-8c78-d60f87211945 at p35g2000prm.googlegroups.com... > Hello, > > I need some help getting output values from my stored procedures when > using adodbapi. There's an example > testVariableReturningStoredProcedure in adodbapitest.py, and that > works for my system. But my stored procedure also inserts and > accesses a table in the database. Here's what I have it boiled down > to: > > So, when I have > CREATE PROCEDURE sp_DeleteMeOnlyForTesting > @theInput varchar(50), > @theOtherInput varchar(50), > @theOutput varchar(100) OUTPUT > AS > SET @theOutput=@theInput+ at theOtherInput > > Then, I can run in python: >>>> cursor = db.conn.cursor() >>>> cursor.callproc('sp_DeleteMeOnlyForTesting', ('hello', 'bye', '')) > [u'hello', u'bye', u'hellobye'] > > > If I redefined the procedure as > CREATE PROCEDURE sp_DeleteMeOnlyForTesting > @theInput varchar(50), > @theOtherInput varchar(50), > @theOutput varchar(100) OUTPUT > AS > SELECT * From dbo.testtable > SET @theOutput=@theInput+ at theOtherInput > > Then, the python comes out as : >>>> cursor = db.conn.cursor() >>>> cursor.callproc('sp_DeleteMeOnlyForTesting', ('hello', 'bye', '')) > [u'hello', u'bye', u''] > > My search on the web found a couple of posts with similar problems, > but no solutions. I am using SQLOLEDB.1 as Provider, connecting to > SQL Server 2005. > > Any help appreciated. I just need one method of passing an output > parameter back to python. > > Thanks, > Li > -- > http://mail.python.org/mailman/listinfo/python-list Output parameters aren't actually retrieved until you've iterated thru all record sets. The below works using ADO objects directly, not sure how it would translate into adodbapi. import win32com.client conn_str="Driver={SQL Server};Server=.\\SqlExpress;Trusted_Connection=yes;" sp_name="sp_DeleteMeOnlyForTesting" c=win32com.client.gencache.EnsureDispatch('adodb.connection',0) c.Open(conn_str) cmd=win32com.client.Dispatch('ADODB.Command') cmd.ActiveConnection=c cmd.CommandType = win32com.client.constants.adCmdStoredProc cmd.CommandText = sp_name cmd.Parameters('@theInput').Value = 'bork' cmd.Parameters('@theOtherInput').Value = 'borkbork' rs, rc = cmd.Execute() rs.NextRecordset() print (cmd.Parameters('@theOutput').Value) If the NextRecordset line is commented out, the output parm is None. Roger From jarausch at skynet.be Sat Nov 29 07:43:45 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Sat, 29 Nov 2008 13:43:45 +0100 Subject: double import protection - how to ? Message-ID: <49313901$0$2854$ba620e4c@news.skynet.be> Hi, sorry if this is a FAQ (I couldn't find an answer) I have a module which gets imported at several different places not all of which are under my control. How can I achieve that all/some statements within that module get executed only at the very first import? (the statement which must be executed only once, initializes another OS-thread (java in my case)) Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From clp at rebertia.com Sun Nov 9 00:39:50 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 8 Nov 2008 21:39:50 -0800 Subject: replacing characters within a string In-Reply-To: References: Message-ID: <47c890dc0811082139y7ab8eecr641b51e1b3b5c969@mail.gmail.com> On Sat, Nov 8, 2008 at 9:16 PM, John Smith wrote: > Hi, > > I coded a python script that lets me parse a csv file into html code with a > certain format, but I would like to replace every "<" and ">" character that > appears within each column entry of the csv file (they are parsed as > strings) with the html equivalents of "<" and ">". You want the cgi.escape() function - http://docs.python.org/library/cgi.html#cgi.escape Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > example csv file row: > "FIXED","All","Enable