[ANN] Twisted 8.0
http://twistedmatrix.com/ MASSACHUSETTS (DP) -- Version 8.0 of the Twisted networking framework has been released, Twisted Matrix Laboratories announced Wednesday. Enslaved by his new robotic overloads, Master of the Release Christopher Armstrong presented the new package to the Internet on March 26th. Armstrong was unable to comment, because of a device worn around his neck preventing him from doing so, scientists say. Secretary of Defense Jean-Paul Calderone was asked about concerns that French interference may have played a role in the delay of this release. I find such speculation preposterous. Thomas Hervé is an upstanding member of the Labs and his loyalties lie with us. He is a fine addition to our team. Rumors in the community allege that Secretary Calderone is holding Hervé's cat ransom until the release is successfully distributed. Hervé was unavailable for comment. This release comes shortly after the announcement by Chief of Public Affairs Duncan McGreggor that Twisted had joined the Software Freedom Conservancy. We're happy to join the SFC, and we are now accepting sponsorship. The fact that we are now ruled by a cabal of robots should not put off potential donors. Our robotic overlords are running us at peak efficiency, so we can most effectively distribute The Love. Asked about the version number jump in this release, Commander-in-Chief Glyph Lefkowitz had the following to say: Our benefactors have found our previous dice-rolling version number scheme to be inadequate, and have deigned to propose to us a more... logical system of versioning. = Twisted is an event-based framework for Internet applications which works on Python 2.3, 2.4, and 2.5. It can be downloaded from http://twistedmatrix.com/ Twisted 8.0 is a major feature release, with several new features and a great number of bug fixes. Some of the highlights follow. - The IOCP reactor is now much improved and many bugs have been resolved. - Twisted is now easy_installable. - Many improvements were made to Trial, Twisted's unit testing system. - A new memcache client protocol implementation was added. - So much more[1]! To see the full list of changes in its fifteen kilobytes of glory, see the release notes[1]. We welcome you to download and enjoy, and please file any bugs you find[2] and send comments to the mailing list[3]. Why the large version number bump? We've decided to switch to a time-based versioning scheme. 8.0 means the first release in 2008. [1] http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.0.1/NEWS?format=raw [2] Register: http://twistedmatrix.com/trac/register New ticket: http://twistedmatrix.com/trac/newticket [3] http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python Thanks! -- Christopher Armstrong International Man of Twistery http://radix.twistedmatrix.com/ http://twistedmatrix.com/ http://canonical.com/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: subprocess.popen function with quotes
En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk [EMAIL PROTECTED] escribió: On Mar 25, 9:25 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk [EMAIL PROTECTED] escribió: i'm trying to call subprocess.popen on the 'rename' function in linux. When I run the command from the shell, like so: rename -vn 's/\.htm$/\.html/' *.htm it works fine... however when I try to do it in python like so: p = subprocess.Popen([rename,-vn,'s/\.htm$/ \.html/',*.htm],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] nothing gets printed out (even for p.communicate()[1]) I'd try with: p = subprocess.Popen([rename, -vn, r's/\.htm$/\.html/', *.htm], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (note that I added shell=True and I'm using a raw string to specify the reg.expr.) Thanks Gabriel, I tried the new command and one with the raw string and single quotes, but it is still giving me the same results (no output). any other suggestions? My next try would be without the single quotes... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Decent 2D animation with Windows.Forms GUI
Hi folks, I'm running a simple 2D game using Pygame but really would like a decent GUI and am currently testing out wxPython. As it turns out, I can't get Pygame working in a wxPython canvas and instead turned to openGL - which is painfully slow at reading through an array of points. Can anyone advise on a combination of a good GUI (wxPython really takes the cake here, plugging into the OSes GUI - does anything else do that?) and some form of 2D animation package that has a fair bit of horsepower behind it, that can fit into said GUI? Failing that, any advice on speeding up PyopenGL? I appreciate your assistance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Graham Dumpleton wrote: Yes that is a viable option, as still are existing fastcgi solutions for Apache, lighttpd and nginx. Fast cgi is a good technology, but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It's more reliable than using things like mod_python, where you have application code running in the web server's address space. That creates both security problems and robustness problems. If an fcgi process crashes, it is automatically replaced by a fresh copy of the program at the next request. Other activity in progress is not affected. Also, fcgi processes are reloaded after some number of requests, so minor memory leaks won't choke the system over time. The main problem is that the documentation is terrible, and the monitoring and administrative tools are absent. Little problems include the fact that if you put an .fcgi file in the CGI directory, it's run silently, and inefficiently, in CGI mode. This is because Apache has CGI built into it at a level below the level at which it recognizes other files. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Computer Shop center
Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 -- http://mail.python.org/mailman/listinfo/python-list
Computer Shop center
Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
John Nagle [EMAIL PROTECTED] writes: Fast cgi is a good technology, but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It seems to be coming back into favor. See: http://cryp.to/publications/fastcgi/ I've thought for a long time that the right way to do it is with the SCM_RIGHTS ancillary message on unix domain sockets, that lets you pass file descriptors around between processes. One of these days... -- http://mail.python.org/mailman/listinfo/python-list
Re: how to dynamically create class methods ?
On Mar 25, 10:55 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: As per your suggestion, I tried looking at include/code.h and include/funcobject.h (my MS Windows distribution does not appear to contain .c files). However, since I'm not a C programmer, I did not find the .h files all that helpful. I'm hardly surprised. The naivety of those who insist that the best way to understand how new.function and new.code work is to look at the C source code for object is amusing. Since 'those who insist...' are just one person, me, you might as well name them. Firstly I didn't 'insist', I stated it once. Secondly I'm glad that I provided you with a few chuckles, but to proclaim that one is 'amused by the naivety of others' doesn't make one automatically right. Do you know how these functions behave? Have you looked at their documentation? new.function and new.code (implemented as Objects/ funcobject.c:func_new and Objects/codeobject.c:new_code) are not really documented (new.code.__doc__ is 'Create a code object. Not for the faint of heart.'). If you can't read the source then I don't think you should use the functions. Not everybody reads C. This is a Python group, and surely the best way would be to see some good examples using *Python*. And this is what I did in the second part of my post. I gave an example which was in essence trying to illustrate the same aspect of Python as your example, quoted below (namely that you can use 'def' to create functions on the fly). Here's an example that might help. class MyClass(object): pass records = [spam, ham] for record in records: # define a new function def f(n): return (record + )*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instance.execute(5) Amusingly naive'ly yours -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: how to dynamically create class methods ?
On Mar 25, 10:55 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: [...] In my haste I forgot to finish my post: Here's an example that might help. class MyClass(object): pass records = [spam, ham] for record in records: # define a new function def f(n): return (record + )*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instance.execute(5) Except it only *appears* to work. What happens if were store the instances in a list and then execute them all in one go? class MyClass(object): pass records = [spam, ham] instances = [] for record in records: # define a new function def f(n): return (record + )*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instances.append(instance) # ONLY THIS LINE CHANGED for instance in instances: instance.execute(5) Outputs: 'ham ham ham ham ham ' 'ham ham ham ham ham ' Because the name 'record' in f is bound to 'ham' after the loop. To fix this, you can for example change def f(n): ... to def f(n, record=record): ... This way, 'record' is local to f and won't change at the next iteration of the loop. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering a Python list to uniques
On Mar 25, 4:30 pm, kellygreer1 [EMAIL PROTECTED] wrote: What is the best way to filter a Python list to its unique members? I tried some method using Set but got some unhashable error. lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] # how do i reduce this to lsttwo = [ 1, 2, 3, 4, 5, 6 ] If the elements are hashable, try this: lsttwo = sorted(set(lstone)) If not hashable, try: lsttwo = [k for k,v in itertools.groupby(sorted(lstone))] Raymond -- http://mail.python.org/mailman/listinfo/python-list
Strange loop behavior
Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. -- Arimaz SA Av. du 24 Janvier 11 Ateliers de la Ville de Renens, Atelier 5 1020 Renens, Switzerland www.mydeskfriend.com Mob: +41-(0)79-539-0069 -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
Gabriel Rossetti schrieb: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. But you used a superfluous repr. Look at this: repr() '' repr() == False So - get rid of the useless repr, then things should work. Regarding the behavior in the debugger: that's an artifact of the debugger that it doesn't step into that line, it doesn't change the way the code works. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Prototype OO
On Mar 26, 3:14 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: On Wed, 26 Mar 2008 02:03:24 -0300, Gabriel Genellina [EMAIL PROTECTED] declaimed the following in comp.lang.python: No:http://en.wikipedia.org/wiki/Saruman Ask him any time over. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
Gabriel Rossetti wrote: I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) And yes I checked, the d variable is en empty string at some point, so the looping should stop. d may be an empty string, but repr(d) isn't: d = print repr(d) '' print d Remove the two repr() calls and you should be OK. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: SoC project: Python-Haskell bridge - request for feedback
A few thoughts. The envisioned Python-Haskell bridge would have two directions: 1) calling Haskell code from Python; 2) calling Python code from Haskell. The proposal spends more space on #1 but I think #1 is both more difficult and less interesting. By Haskell I presume you mean GHC. I think that the GHC runtime doesn't embed very well, despite the example on the Python wiki (http://wiki.python.org/moin/PythonVsHaskell near the bottom). This is especially if you want to use the concurrency stuff. The GHC runtime wants to trap the timer interrupt and do select based i/o among other things. And I'm not sure that wanting to call large Haskell components under a Python top-level is that compelling: why not write the top level in Haskell too? The idea of making the critical components statically typed for safety is less convincing if the top level is untyped. There is something to be said for porting some functional data structures to Python, but I think that's mostly limited to the simpler ones like Data.Map (which I've wanted several times). And I think this porting is most easily done by simply reimplementing those structures in a Python-friendly style using Python's C API. The type signatures (among other things) on the Haskell libraries for this stuff tend to be a little too weird for Python; for example, Data.Map.lookup runs in an arbitrary monad which controls the error handling for a missing key. The Python version should be like a dict, where you give it a key and a default value to return if the key is not found. Plus, do you really want Python pointers into Haskell data structures to be enrolled with both systems' garbage collectors? (Actually (sidetrack that I just thought of), a Cyclone API would be pretty useful for writing safe Python extensions. Cyclone is a type-safe C dialect, see cyclone.thelanguage.org ). The Haskell to Python direction sounds more useful, given Haskell's weirdness and difficulty. Python is easy to learn and well-packaged for embedding, so it's a natural extension language for Haskell applications. If you wrote a database in Haskell, you could let people write stored procedures in Python if they didn't want to deal with Haskell's learning curve. Haskell would call Python through its safe FFI (which runs the extension in a separate OS thread) and not have to worry much about the Python side doing IO or whatever. Of course this would also let Python call back into the Haskell system, perhaps passing Python values as Data.Dynamic, or else using something like COM interface specifications. Anyway I'm babbling now, I may think about this more later. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
On Mar 26, 8:35 am, Gabriel Rossetti [EMAIL PROTECTED] wrote: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. No, it isn't the empty string, it is the printable representation of the empty string (because you wrap your f.read() calls in repr()), which is the string '': print '' '' Why do you wrap f.read(...) in the repr() function? If you remove the two repr() I suspect your code will work. OTOH do you know that the read() method of file objects does what you want? You could simply write: file_str = f.read() Or are there some other factors that prevent you from doing this? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
Gabriel Rossetti wrote: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. Ok, I get it, the repr() function actually returns a string with quote characters around it, thus the length is never 0, but 2. The reason I began using the repr() function is that the str() and unicode() constructors didn't accept the data read, because it was bigger than ord(128) (or something like that. I'm trying to read a binary file and put it's contents in an xml message to send via the network, so that I can re-create it on the other side. I do need to keep the xml aspect though. Is there a better way of doing this? Thanks, Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
On Mar 26, 8:51 am, Gabriel Rossetti [EMAIL PROTECTED] wrote: Gabriel Rossetti wrote: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. Ok, I get it, the repr() function actually returns a string with quote characters around it, thus the length is never 0, but 2. The reason I began using the repr() function is that the str() and unicode() constructors didn't accept the data read, because it was bigger than ord(128) (or something like that. I'm trying to read a binary file and put it's contents in an xml message to send via the network, so that I can re-create it on the other side. I do need to keep the xml aspect though. Is there a better way of doing this? Thanks, Gabriel Have a look at the uu and base64 modules: http://docs.python.org/lib/module-uu.html http://docs.python.org/lib/module-base64.html -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
Gabriel Rossetti wrote: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) FWIW, you could do it like this to avoid duplicating that line of code: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) Some people would also compress the whitespace a bit: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) snip (I'll comment on your Unicode issues in a minute.) -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange loop behavior
Arnaud Delobelle wrote: On Mar 26, 8:35 am, Gabriel Rossetti [EMAIL PROTECTED] wrote: Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != : file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the d variable is en empty string at some point, so the looping should stop. No, it isn't the empty string, it is the printable representation of the empty string (because you wrap your f.read() calls in repr()), which is the string '': print '' '' Why do you wrap f.read(...) in the repr() function? If you remove the two repr() I suspect your code will work. OTOH do you know that the read() method of file objects does what you want? You could simply write: file_str = f.read() Or are there some other factors that prevent you from doing this? -- Arnaud Ok, like I mentioned in my second msg, I had put repr() there because I was getting errors because the ascii range (128) was exceeded, I tried cheating and telling it it was unicode but that didn't work, so I tried repr() and it gave me a string rep. of my data, that was ok. After that I tried using StringIO instead of what I had before, a list of strings that I later joined with an empty string. I just re-tried removing the repr() and it works with the StringIO version. Thanks for all your answers, Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Circular references not being cleaned up by Py_Finalize()
blackpawn [EMAIL PROTECTED] writes: I know the garbage collector is tracking the object because it properly calls the traverse function but for whatever reason it never calls the clear function. Does anyone have experience with circular references and had success with it or the example in the docs? I've now tried it, and it seems to work. Modifying Nody_dealloc with printf(collecting %p\n, self), it works like this: import noddy4 n = noddy4.Noddy() n.first = n del n # n would be dealloced here without the cycle ^D collecting 0xb7d3bf2c So the garbage-collector is invoked at least once before shutdown. However, it doesn't work without del n line, so it would appear that the gc is not invoked after the module cleanup and therefore doesn't explicitly dealloc global objects that contain cycles. You can work around that by using the atexit module to register a cleanup function that removes your global objects from the module namespace(s) and, if necessary, invokes gc.collect() manually. That way your objects end up as reclaimable garbage. This won't work if your cycle-containing objects are indirectly reachable from the module namespace through other containers not under your control. In that case, you should really rethink your strategy of depending on finalizers to run and perhaps use atexit to do your exit processing or, as others pointed out, use scope tools (try/finally, with) at the entry point of your code. -- http://mail.python.org/mailman/listinfo/python-list
GUI toolkits with Tkinter's .pack() alternative
Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) Could anyone with experience in different toolkits help, please Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering a Python list to uniques
On 26 мар, 02:30, kellygreer1 [EMAIL PROTECTED] wrote: What is the best way to filter a Python list to its unique members? I tried some method using Set but got some unhashable error. lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] # how do i reduce this to lsttwo = [ 1, 2, 3, 4, 5, 6 ] Is there a page on this in the Python in a Nutshell or the Python Cookbook? Did I miss something? Kelly Greer [EMAIL PROTECTED] change nospam to yahoo or just look this thread for a fastest solution http://groups.google.com/group/comp.lang.python/browse_frm/thread/709189841310/af8961f1ed91ccea?lnk=gstq=duplicates#af8961f1ed91ccea -- http://mail.python.org/mailman/listinfo/python-list
Re: Time module is not behaving.
Yep that does it. Thanks Gary. - Original Message From: Gary Herron [EMAIL PROTECTED] To: jjlofaro [EMAIL PROTECTED] Cc: python-list@python.org Sent: Wednesday, 26 March, 2008 2:49:55 AM Subject: Re: Time module is not behaving. jjlofaro wrote: Hi I'm just getting myself going again on Python and would appreciate any help. My install of Python seems to have some difficulty loading and using the time module in a script. Strange thing is that if I start another instance of Python I can type in my program manually/interactively and it works. The version of Python I am using is... * Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2* Installed on a Ubuntu 7.10 workstation. Here's my little program [EMAIL PROTECTED]:~/tmp$ more time.py import time * Right there is the problem. Your program, named time.py, is hiding the Python supplied module. So that import of time is finding and re-importing itself. Rename your script to something that won't shadow a Python library module. Gary Herron *print time.time()* And this is what happens when I run it [EMAIL PROTECTED]:~/tmp$ python time.py Traceback (most recent call last): File time.py, line 1, in module import time File /home/jeff/tmp/time.py, line 2, in module print time.time() TypeError: 'module' object is not callable Error in sys.excepthook: Traceback (most recent call last): File /var/lib/python-support/python2.5/apport_python_hook.py, line 38, in apport_excepthook from apport.fileutils import likely_packaged File /var/lib/python-support/python2.5/apport/__init__.py, line 1, in module from apport.report import Report File /var/lib/python-support/python2.5/apport/report.py, line 14, in module import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys File /usr/lib/python2.5/urllib.py, line 28, in module import time File /home/jeff/tmp/time.py, line 2, in module print time.time() TypeError: 'module' object is not callable Original exception was: Traceback (most recent call last): File time.py, line 1, in module import time File /home/jeff/tmp/time.py, line 2, in module print time.time() TypeError: 'module' object is not callable [EMAIL PROTECTED]:~/tmp$ * Any hints or tips appreciated. Jeff. Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/y7mail -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. You sure can, but differently. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. Could anyone with experience in different toolkits help, please Thanks -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Minor Gordon a écrit : (snip otherwise intersting stuff) Background: I'm in this to help write a story for Python and web applications. Everyone likes to go on about Ruby on Rails, and as far as I can tell there's nothing that approaches Rails in Python. You may have missed Django and Pylons then. Beta testers: should be intermediate to advanced Python programmers with demanding applications, particularly web applications with databases and AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory libraries beyond python-dev. Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. I can only second Graham here: setup a project page with source code downloads, install instructions and (at least minimal) software documentation, and if possible a tracker. -- http://mail.python.org/mailman/listinfo/python-list
Socialsoft Startup Jobs
http://www.thesocialsoft.com/jobs.html We - Build stuff that people love and use everyday - have a healthy disregard for the impossible - are not a conventional company and do not intend to be one - Think big, think fast and think ahead - set our goals high and work to exceed them, then we set our sights even higher - love our users more than anything else - launch early launch often - work on Web scale projects - believe that velocity matters - Care about interaction and user interface - grow by systematically removing bottlenecks - easy to know when something is a win - are experts in building scalable high performance clusters - scale horizontally - are scientific - collect data and understand it - start with good enough and iterate rapidly to reach perfection and critical mass - truly love the internet - see the elegance in simplicity - know what the user wants but listen to feedback - love to experiment with new fun viral ideas - are a really high energy team, it is not surprising for traffic to double overnight - aim to be better than the best - believe that we can change the world - This is a great company and we are moving quickly to make it even better - love fresh home made frozen yogurt across the street Cutting edge Tools We use - we love love Python - cheetah - memcached - postgresql - berkeley db - starling - jquery - subversion - git - nginx - haproxy - php We are the Most fun team in Silicon valley - beanbag plushies - Be in the driving seat of your project - Herman miller chairs - believe in developer productivity and happiness - live in downtown Palo Alto You (exceptional) - are a brilliant web software hacker who can design, build, and ship interesting web products - are among the best at what you do and routinely solve hard technical problems - have an understanding of successful web properties - have some insight into what makes them resonate with users - want to reach millions if not billions of people through your code - Are pragmatic and flexible - Care deeply about users and the user experience - should be available to work full-time or more Start your incredibly fun journey with the Socialsoft Team! - Join the Socialsoft dream, email [EMAIL PROTECTED] now -- http://mail.python.org/mailman/listinfo/python-list
matplotlib / legend of x-axis
Hi everybody, I've got a problem concerning matplotlib/pylab. I use it to represent curves. I will use these pictures in a report. However, it writes me a string 'date' on the bottom of my x-axis. I use this to produce my date axis (x-axis): mondays = WeekdayLocator(MONDAY)# every monday months= MonthLocator(range(1,13), bymonthday=1) # every month monthsFmt = DateFormatter(%b %d '%y) years= YearLocator() # every month yearsFmt = DateFormatter(%y) #subplot.xaxis.set_major_locator(months) #subplot.xaxis.set_major_formatter(monthsFmt) #subplot.xaxis.set_minor_locator(mondays) subplot.xaxis.set_major_locator(years) subplot.xaxis.set_major_formatter(yearsFmt) #subplot.autoscale_view() setp(subplot.get_xticklabels(), 'rotation', 45, fontsize=10) Can you help me to remove this 'date'? thank you! Frédéric -- http://mail.python.org/mailman/listinfo/python-list
Re: _tkinter fails when installing Python 2.4.4
jgelfand wrote: On Mar 25, 5:52 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: jgelfand schrieb: I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat Enterprise Linux 4.6] 64-bit machine. Running ./configure --prefix=/ usr/local/yosi/ciao-4.0/ots --enable-shared appears to be fine, but I get the following error message when I run make: building '_tkinter' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/_tkinter.o gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so *** WARNING: renaming _tkinter since importing it failed: build/ lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents Any suggestions / ideas as to what is going wrong? I don't get any other warnings or errors on the other modules. Thanks -- Yosi You are aware that the above shows python 2.5 as the version that is being used for compilation? Diez Sorry. I get the same error messages for Python 2.4.4, Python 2.4.5, and Python 2.5. The software package I'm trying to build from source requests that I install Python 2.4.4, so I'm interesting in solutions for that particular distribution. I think the actual problem is that the linking doesn't find the XftGlyphExtends. I can only guess, but it might be related to 64-bit-problems. Make sure you have the library that contains the XftGlyphExtends is available in the lib64 dirs and so forth. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: embedded python pythonpath
On Wed, Mar 26, 2008 at 3:49 AM, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 25 Mar 2008 22:22:41 -0300, Furkan Kuru [EMAIL PROTECTED] escribió: On 3/26/08, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru [EMAIL PROTECTED] escribió: Actually, I do not want any .py or .pyc files around my executable. (including userdict, sys, site etc) I want to have just single zip file for all python files. Putting all of them into pythonNN.zip (NN depending on the Python version in use) should be enough, but I've never tried it. I had already tried putting all of them into pythonNN.zip but I had to copy it to the place where sys.path points in my case it was windows\system32\python25.zip It should be in the same directory as python25.dll; you don't have to use windows\system32 if you copy python25.dll to your application directory. I did not know that. Ok, I tried and it works! Thank you, -- Furkan Kuru -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 26, 12:24 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: On Tue, 25 Mar 2008 08:24:13 -0700 (PDT), Craig [EMAIL PROTECTED] declaimed the following in comp.lang.python: 41 0 0 0 7 0 0 0 Which makes sense for two reasons: 1. It would only return the non-space-filled part of the returned key. 2. At least from VB6, the variable does not even have to be used before the call. Hmmm... I wonder what the library would have done if you just passed a 0 to it... Rather than even doing that SysAlloc...() mess... PriKey = ctypes.int32(0)#or whatever the syntax was ... byref(PriKey) May with an effective null pointer the library would just allocate directly rather than trying to determine the length field of the one passed in. Something for the future, maybe... printDistID = \x22%s\x22 % DCOD.DistID You realize you can avoid those \x22 literals by changing the outer quotes? print ' DistID = %s ' % or using triples print DistID = %s % ... In other files, some of those fields are VB6 currency types, which have been described as 8-byte integers with an implied 4 decimal places (which I guess would be __int64 or c_longlong and then divide by 10,000, or simply put a decimal point 4 away from the end). Don't divide directly; you might lose significance as the result is converted to double-precision float. You could possibly convert to string, splice in that . and then pass the result to the Decimal module/type... -- WulfraedDennis Lee Bieber KD6MOG [EMAIL PROTECTED] [EMAIL PROTECTED] HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: [EMAIL PROTECTED]) HTTP://www.bestiaria.com/ I made these changes: # SecKey = windll.oleaut32.SysAllocStringByteLen(1234567890123456789012345678901234567890\x00, 41) SecKey = c_int32(0) ci_SecKey = c_int32(SecKey) # PriKey = windll.oleaut32.SysAllocStringByteLen(ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00, 41) PriKey = c_int32(0) ci_PriKey = c_int32(PriKey) And got: Traceback (most recent call last): File C:\temp\vbisam_test_2.py, line 123, in module ci_SecKey = c_int32(SecKey) TypeError: an integer is required Creating 2 dummy BSTR's isn't too bad of an option anyway. No, being somewhat new I didn't realize I could use (') in place if () if I wanted to use a () as a literal, but it seems to make a lot of sense now. I don't understand why I never tried it. As for the division vs. string manipulation, I agree - the string seems to be the simplest way to insure no loss of data. Thanks for all the input. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter menus from keyboard
Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with f). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? -- http://mail.python.org/mailman/listinfo/python-list
Re: Prototype OO
sam a écrit : Bruno Desthuilliers napisał(a): In dynamically typed language when you create object A that is inherited from another object B, than object A knows that B is his predecessor. So when you reference A.prop, then prop is looked in A first, then in B, then in predecessors of B, and so on. What you're describing here is the inheritance mechanism of Python. And could apply just as well to javascript prototype mechanism. A javascript object has a reference to it's prototype object - that you can customize, rebind etc -, a Python object has a reference to it's class object - that you can customise, rebind etc... I can see that Python and Javascript inheritance model is almost the same. Both languages are dynamically typed. And it seems that using classes in Python makes some things more complicated then it is necessary I have to disagree here. (eg functions, methods and lambdas are differen beeing in Python concept). The lambda statement creates an ordinary function object, so no difference here - and it has nothing to do with classes vs prototypes. wrt/ functions and methods, what you declare with a def statement within a class statement is actually a plain function (and FWIW, you can add dynamically add methods to classes or instances). Python 'methods' are only thin callable wrappers around the function/class/instance set, wrappers that are dynamically generated by the function object itself when it's looked up on a class or instance, thanks to the descriptor protocol. Don't be fooled by the term class itself - it's meaning is totally different in a language like Python. Probably I'm not alone. Many people who think dymanic types are Rhight Thing in programming will also prefer prototype-based programming to class-based. Chapter and verse, please ? Ok, I repeat (please read more carefully): Don't be fooled by the term class itself - it's meaning is totally different in a language like Python. suspect you don't have a serious knowledge of Python's object model. Yes -- I'm new to Python. So may I suggest you actually *learn* how Python's object model works ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
2008/3/26, [EMAIL PROTECTED] [EMAIL PROTECTED]: Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with f). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? Set the underline option to the index of the desired letter -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
memory allocation for Python list
hi all, I have a python list of unknown length, that sequentially grows up via adding single elements. Each element has same size in memory (numpy.array of shape 1 x N, N is known from the very beginning). As I have mentioned, I don't know final length of the list, but usually I know a good approximation, for example 400. So, how can I optimize a code for the sake of calculations speedup? Currently I just use myList = [] for i in some_range: ... myList.append(element) ... Thank you in advance, Dmitrey -- http://mail.python.org/mailman/listinfo/python-list
Dimensions of Arrays, Matrices
Hi, Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: Dimensions[A] = {3,3} TensorRank[A] = 2 Are there exact functions for these two in Python? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Dimensions of Arrays, Matrices
Google - matrix python 1st response: http://www.python.org/community/sigs/retired/matrix-sig/ The purpose of this SIG was to continue development of a Python matrix type. This effort succeeded and resulted in Numerical Pythonhttp://numpy.sf.net/, a high-speed array language for Python by following the magic hyperlink I arrive at http://scipy.org/ which might be too embellished, so I then returned to the retired-sig and found http://sourceforge.net/projects/numpy I'm sure if you dig around in either of those places you'll find more than you are looking for =) 2008/3/26, Dark Wind [EMAIL PROTECTED]: Hi, Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: Dimensions[A] = {3,3} TensorRank[A] = 2 Are there exact functions for these two in Python? Thank you -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: memory allocation for Python list
dmitrey: As I have mentioned, I don't know final length of the list, but usually I know a good approximation, for example 400. There is no reserve()-like method, but this is a fast enough operation you can do at the beginning: l = [None] * 400 It may speed up your code, but the final resizing may kill your performance anyway. You can try it. Just using Psyco is probably better. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: memory allocation for Python list
Just write it in C and compile it into a file.so/pyd =) 2008/3/26, [EMAIL PROTECTED] [EMAIL PROTECTED]: dmitrey: As I have mentioned, I don't know final length of the list, but usually I know a good approximation, for example 400. There is no reserve()-like method, but this is a fast enough operation you can do at the beginning: l = [None] * 400 It may speed up your code, but the final resizing may kill your performance anyway. You can try it. Just using Psyco is probably better. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Why not just put it on the net somewhere and tell us where it is? People aren't generally going to want to help or even look at it if you treat it like a proprietary application. So, put the documentation and code up somewhere for all to see. http://www.yieldserver.com:8081/ -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.popen function with quotes
On Mar 25, 11:04 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk [EMAIL PROTECTED] escribió: On Mar 25, 9:25 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk [EMAIL PROTECTED] escribió: i'm trying to call subprocess.popen on the 'rename' function in linux. When I run the command from the shell, like so: rename -vn 's/\.htm$/\.html/' *.htm it works fine... however when I try to do it in python like so: p = subprocess.Popen([rename,-vn,'s/\.htm$/ \.html/',*.htm],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] nothing gets printed out (even for p.communicate()[1]) I'd try with: p = subprocess.Popen([rename, -vn, r's/\.htm$/\.html/', *.htm], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (note that I added shell=True and I'm using a raw string to specify the reg.expr.) Thanks Gabriel, I tried the new command and one with the raw string and single quotes, but it is still giving me the same results (no output). any other suggestions? My next try would be without the single quotes... -- Gabriel Genellina thanks for the input guys, I've tried the suggestions but can't get it to work. I have a file named test.htm in my directory, and when I run the following command: rename -vn 's/(.*)\.htm$/model.html/' *.htm from the shell in that directory I get the following output: test.htm renamed as model.html now my python script is called test.py, is located in the same directory, and is called from the shell with 'python test.py' the contents of test.py: import subprocess p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as model.html when I add shell=True to the subprocess command, I get the following output: Usage: rename [-v] [-n] [-f] perlexpr [filenames] am i doing something wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: Do any of you recommend Python as a first programming language?
On Sun, Mar 23, 2008 at 4:29 AM, Steven D'Aprano [EMAIL PROTECTED] wrote: Python is a programming language. It can be used for scripting, but that's not all it can do. Describing it as a scripting language is like describing a fully-equipped professional kitchen as a left-over warming room. +1 QOTW. -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.popen function with quotes
On Mar 26, 6:44 am, skunkwerk [EMAIL PROTECTED] wrote: On Mar 25, 11:04 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk [EMAIL PROTECTED] escribió: On Mar 25, 9:25 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk [EMAIL PROTECTED] escribió: i'm trying to call subprocess.popen on the 'rename' function in linux. When I run the command from the shell, like so: rename -vn 's/\.htm$/\.html/' *.htm it works fine... however when I try to do it in python like so: p = subprocess.Popen([rename,-vn,'s/\.htm$/ \.html/',*.htm],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] nothing gets printed out (even for p.communicate()[1]) I'd try with: p = subprocess.Popen([rename, -vn, r's/\.htm$/\.html/', *.htm], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (note that I added shell=True and I'm using a raw string to specify the reg.expr.) Thanks Gabriel, I tried the new command and one with the raw string and single quotes, but it is still giving me the same results (no output). any other suggestions? My next try would be without the single quotes... -- Gabriel Genellina thanks for the input guys, I've tried the suggestions but can't get it to work. I have a file named test.htm in my directory, and when I run the following command: rename -vn 's/(.*)\.htm$/model.html/' *.htm from the shell in that directory I get the following output: test.htm renamed as model.html now my python script is called test.py, is located in the same directory, and is called from the shell with 'python test.py' the contents of test.py: import subprocess p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as model.html when I add shell=True to the subprocess command, I get the following output: Usage: rename [-v] [-n] [-f] perlexpr [filenames] am i doing something wrong? in addition, when I use Popen without any quotes, or without quotes for the regular expression, I get an exception. I'm running ubuntu linux 7.10 with python 2.5.1 thanks -- http://mail.python.org/mailman/listinfo/python-list
Running a python program as main...
Stumbling through Mark Lutz's Programming Python 3rd, he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3ELauncher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3Epython Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). -- http://mail.python.org/mailman/listinfo/python-list
PyQT / QDate / QTableWidget
Hi, new at PyQT but not coding.. I'm stumbling with QDate and QTableWidget using PyQT and would appreciate some guidance: My server gives me a string y[0]: 20080327, which I convert to a QDateTime object using: x=QDateTime.fromString(y[0],mmdd) Printing x.toString(dd-mm-) gives me what I would expect - 27-03-2008 What I'm trying to do though is add this to a QTableWidget item to create a date sortable column; I'm using this: if type(y)==QDateTime: item=QTableWidgetItem() item.setData(Qt.DisplayRole,QVariant(y)) BUT.. I'm adding 90 dates going back from today and getting values that look like this: 27/01/2007 00:12 28/01/2007 00:12 29/01/2007 00:12 30/01/2007 00:12 31/01/2007 00:12 01/01/2008 00:01 01/01/2008 00:02 01/01/2008 00:03 etc I tried using QDate but couldn't seem to be able to get QDate.fromString to create an object at all. Could someone please advise where I'm going wrong, the end result should be a column in my QTableWidget formatted dd/mm/ that can be sorted as dates, not strings, and originate from data formatted MMDD Thank you very much in advance! -- http://mail.python.org/mailman/listinfo/python-list
py2exe socket.gaierror (10093)
Hi, I have encountered a problem which I can not figure out a solution to. Tried Googeling it, but to no help unfortunately. The problem is running smtplib in a py2exe compiled exe file. When it tries to establish a socket to the mail server it fails. Just wondering someone has encountered this before, and if someone might be able to point me in the right direction. Unhandled exception in thread started by Traceback (most recent call last): File AutomationThread.pyc, line 152, in Run File mail.pyc, line 11, in sendMail File smtplib.pyc, line 244, in __init__ File smtplib.pyc, line 296, in connect socket.gaierror: (10093, 'getaddrinfo failed') Thank you ! -- http://mail.python.org/mailman/listinfo/python-list
Re: last mouse movment or keyboard hit
Gabriel Genellina wrote: En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler [EMAIL PROTECTED] escribió: I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? Which platform? On non-ancient Windows versions, you can periodically check GetLastInputInfo http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp No, it would be for Linux and preferrably it would work on MacOS Windows as wellis there anything? Thanks! -- chEErs roN -- http://mail.python.org/mailman/listinfo/python-list
ANN: python-ldap-2.3.2
Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Released 2.3.2 2008-03-26 Changes since 2.3.1: Lib/ * ldap.dn.escape_dn_chars() now really adheres to RFC 4514 section 2.4 by escaping null characters and a space occurring at the beginning of the string * New method ldap.cidict.cidict.__contains__() * ldap.dn.explode_dn() and ldap.dn.explode_rdn() have a new optional key-word argument flags which is passed to ldap.dn.str2dn(). Modules/ * Removed unused OPT_PRIVATE_EXTENSION_BASE from constants.c Doc/ * Various additions, updates, polishing (thanks to James). -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.popen function with quotes
skunkwerk wrote: p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as model.html Without shell=True, your glob characters will not be expanded. Hence, the command looks for a file actually named *.htm when I add shell=True to the subprocess command, I get the following output: Usage: rename [-v] [-n] [-f] perlexpr [filenames] Here the use of the shell may be confounding the arguments passed. Your command will probably work better if you avoid using shell=True. However, you will need to perform your own globbing: # Untested (no perl-rename here): command = ['rename','-vn', 's/(.*)\.htm$/model.html/'] files = glob.glob('*.htm') command.extend(files) p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) Jeffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: _tkinter fails when installing Python 2.4.4
On Mar 26, 7:02 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: I think the actual problem is that the linking doesn't find the XftGlyphExtends. I can only guess, but it might be related to 64-bit-problems. Make sure you have the library that contains the XftGlyphExtends is available in the lib64 dirs and so forth. I tried running configure with --x-include=/usr/X11R6/include --x- libraries=/usr/X11R6/lib (in addition to the flags above) and got the same error. I believe XftGlyphExtends is defined in Xft.h which is located in the directory /usr/X11R6/include/X11/Xft. Based on the output below, python looks in /usr/X11R6/include but not in this directory: building '_tkinter' extension gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/_tkinter.c - o build/temp.linux-x86_64-2.4/_tkinter.o gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/tkappinit.c - o build/temp.linux-x86_64-2.4/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.4/_tkinter.o build/ temp.linux-x86_64-2.4/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib - L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 - lX11 -o build/lib.linux-x86_64-2.4/_tkinter.so When I try setting CFLAGS=-I/usr/X11R6/include/X11/Xft and re- running configure, I get the same error message regardless if I tell python to it to use the 32 bit of 64 bit X-Windows libraries. How should I force python to look in this directory? Thanks a lot -- Yosi -- http://mail.python.org/mailman/listinfo/python-list
Sr. Architect - NYC - Opportunity
Senior Developer Must be proficient in Python, expert preferred Must have one large scale public web project in their portfolio, preferably startup experience Must be able to develop with certain architectural considerations in mind at all times, such as: multilingual text, runtime efficiency in a very high load environment, file mgmt in a clustered environment, etc Must be self-motivated and eager to utilize the existing team's business knowledge to advance their own knowledge. We don't want anyone who wants to squirrel themselves away and read code alone all day. We need to be as efficient as possible in knowledge sharing in order to keep the code generation rate high. Must be able to manage time efficiently among multiple projects. These tech requirements should be implicit in the criteria above, but nonetheless are imperative: OO design SQL including indexing and query tuning AJAX, including APIs like Google Maps RSS and XML feeds in general. We deal with a lot of third party feeds that love to use XML. DHTML with CSS and Javascript Working knowledge of subversion, including branching and merging Must be able to configure a LAMP development environment (If you can do one, you can do them all. In our case LAMP means FreeBSD, Apache, MySQL, Webware for Python) Please contact: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Paul Rubin wrote: John Nagle [EMAIL PROTECTED] writes: Fast cgi is a good technology, but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It seems to be coming back into favor. See: http://cryp.to/publications/fastcgi/ That paper is from 2002. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
Guilherme Polo wrote: Set the underline option to the index of the desired letter Elegant simplicity in the dropdowns. Thanks! Now, how about main menu underscores? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
On Wed, 26 Mar 2008 13:45:29 +0100, Guilherme Polo [EMAIL PROTECTED] wrote: 2008/3/26, [EMAIL PROTECTED] [EMAIL PROTECTED]: Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with f). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? Set the underline option to the index of the desired letter BTW, this standard is not universal at all: e.g, there is no such convention on Macs. Not (only...) nitpicking: if your application has to run on a Mac, it may look weird if you use this option... But I never tested how it was handled on Macs. My $0.02... -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python program as main...
En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad [EMAIL PROTECTED] escribió: Stumbling through Mark Lutz's Programming Python 3rd, he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3ELauncher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3Epython Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). I think it is an option in the installer, to associate or not Python to the .py extension. You could reinstall Python paying attention to the options, or repair the association as described in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d0fd05b3615057/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Problem with write binary data to OLE field in Access
Hi~ I would like to save images in OLE field in Microsoft Access. It writes the binary data which read from an JPEG/BMP file. But seems I meet an encoding problem. The following code demos that. Any sugguestion? --- import win32com.client as wc conn = wc.Dispatch(r'ADODB.Connection') recordset = wc.Dispatch(r'ADODB.RecordSet') dsn = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;' conn.Open(dsn) print conn k = recordset.Open('[tblImageDataTypes]', conn, 1, 3) #recordset.AddNew() #recordset.Fields('Field3_GENERAL').AppendChunk(open('tt.jpg', 'rb').read()) #recordset.Update() #print Actual Size: , recordset.Fields('Field3_GENERAL').ActualSize recordset.MoveFirst() kk = recordset.Fields('Field3_GENERAL').GetChunk( recordset.Fields('Field3_GENERAL').ActualSize) print len(str(kk).decode('utf-16')) print len(open('tt.jpg', 'rb').read()) recordset.Close conn.Close() ### One of the results: the length of original file is : 2598 the actual size of the field is: 3658 the length decode from the chunk is: 1829 I try to write some text files into the filed and read it out, it is OK. Windows XP sp2; Python 2.4.4; Pywin32 210; Microsoft Access 2002 --- Regards, lialie -- http://mail.python.org/mailman/listinfo/python-list
Some notes on a high-performance Python application.
I run SiteTruth (sitetruth.com), which rates web sites for legitimacy, based on what information it can find out about the business behind the web site. I'm going to describe here how the machinery behind this is organized, because I had to solve some problems in Python that I haven't seen solved before. The site is intended mainly to support AJAX applications which query the site for every ad they see. You can download the AdRater client (http://www.sitetruth.com/downloads/adrater.html;) and use the site, if you like. It's an extension for Firefox, written in Javascript. For every web page you visit, it looks for URLs that link to ad sites, and queries the server for a rating, then puts up icons on top of each ad indicating the rating of the advertiser. The client makes the query by sending a URL to an .fcgi program in Python, and gets XML back. So that's the interface. At the server end, there's an Linux/Apache/mod_fcgi/Python server. Requests come in via FCGI, and are assigned to an FCGI server process by Apache. The initial processing is straightforward; there's a MySQL database and a table of domains and ratings. If the site is known, a rating is returned immediately. This is all standard FCGI. If the domain hasn't been rated yet, things get interesting. The server returns an XML reply with a status code that tells the client to display a busy icon and retry in five seconds. Then the process of rating a site has to be started. This takes more resources and needs from 15 seconds to a minute, as pages from the site are read and processed. So we don't want to do rating inside the FCGI processes. We want FCGI processing to remain fast even during periods of heavy rating load. And we may need to spread the processing over multiple computers. So the FCGI program puts a rating request into the database, in a MySQL table of type ENGINE=MEMORY. This is just an in-memory table, something that MySQL supports but isn't used much. Each rating server has a rating scheduler process, which repeatedly reads from that table, looking for work to do. When it finds work, it marks the task as in process. The rating scheduler launches multiple subprocesses to do ratings, all of which run at a lower priority than the rest of the system. The rating scheduler communicates with its subprocesses via pipes and Pickle. Launching a new subprocess for each rating is too slow; it adds several seconds as CPython loads code and starts up. So the subprocesses are reusable, like FCGI tasks. Every 100 uses or so, we terminate each subprocess and start another one, in case of memory leaks. (There seems to be a leak we can't find in M2Crypto. Guido couldn't find it either when he used M2Crypto, as he wrote in his blog.) Each rating process only rates one site at a time, but is multithreaded so it can read multiple pages from the site, and other remote data sources like BBBonline, at one time. This allows us to get a rating within 15 seconds or so. When the site is rated, the database is updated, and the next request back at the FCGI program level will return the rating. We won't have to look at that domain for another month. The system components can run on multiple machines. One can add rating capacity by adding another rating server and pointing it at the same database. FCGI capacity can be added by adding more FCGI servers and a load balancer. Adding database capacity is harder, because that means going to MySQL replication, which creates coordination problems we haven't dealt with yet. Also, since multiple processes are running on each CPU, multicore CPUs help. Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put fair queueing in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. Another useful property of using MySQL for coordination is that we can have internal web pages that make queries and display the system and queue status. This is easy to do from the outside when the queues are in MySQL. It's tough to do that when they're inside some process. We log errors in a database table, not text files, for the same reason. In addition to specific problem logging, all programs have a final try block around the whole program that does a stack backtrace and puts that in a log entry in MySQL. All servers log to the same database. Looking at this architecture, it was put together from off the shelf parts, but not the parts that have big fan bases. FCGI isn't used much. The MySQL memory engine isn't used much. MySQL advisory locking (SELECT GET LOCK(lockname,timeout)) isn't used much. Pickle isn't used much over pipes. M2Crypto isn't used much. We've spent much time finding
Re: py2exe socket.gaierror (10093)
En Wed, 26 Mar 2008 11:17:15 -0300, Python Programming on Win32 [EMAIL PROTECTED] escribió: The problem is running smtplib in a py2exe compiled exe file. When it tries to establish a socket to the mail server it fails. Just wondering someone has encountered this before, and if someone might be able to point me in the right direction. Unhandled exception in thread started by Traceback (most recent call last): File AutomationThread.pyc, line 152, in Run File mail.pyc, line 11, in sendMail File smtplib.pyc, line 244, in __init__ File smtplib.pyc, line 296, in connect socket.gaierror: (10093, 'getaddrinfo failed') The script can't resolve the server name. Try to do it by hand using nslookup or even ping (you may want to add a few print statements inside the script to see the exact host name it is trying to connect to, in case it isn't what you expect) If you can't resolve the host name using nslookup, there is a network problem, not in your script. If you can resolve it, try your script without py2exe if possible. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: last mouse movment or keyboard hit
You can use wxPython. Take a look on the DemoFiles that you can download also from the site. I remember that there has been a demo of capturing mouse coordinates and also one example about capturing Which key has been pressed at which time. Just start the time, count the interactions of key strokes and mouse gestures. Apply some statistics and voila. there it is. On Mar 26, 3:28 pm, Ron Eggler [EMAIL PROTECTED] wrote: Gabriel Genellina wrote: En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler [EMAIL PROTECTED] escribió: I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? Which platform? On non-ancient Windows versions, you can periodically check GetLastInputInfo http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winu... No, it would be for Linux and preferrably it would work on MacOS Windows as wellis there anything? Thanks! -- chEErs roN -- http://mail.python.org/mailman/listinfo/python-list
naive packaging question
Hello all, I've read a number of the python books, and several online tutorials about modules and packaging, but not one addresses this issue, so I thought I'd ask here... I am building a library for use in an internal project. This library is the client side interface to a REST-ful service that provides access to parts of our accounting database. BUT, we are pretty sure that the accounting database and hence the service implementation will change in the future. So, I want to design a generic (abstract) api for fetching various info from the accounting db, but I want to isolate the specific details into a module/package that can be changed in future (and co-exist with the old one). I've designed a generic api class, with functions to fetch the various info into python data structures (mostly lists of dictionaries, some just single values). And I've got an interface-specific version that follows that same api, and which is derived from the generic api. I'm a bit unclear on the best way to implement the module and package. Here's the directory structure that I've got so far: project dir top level directory setup.py company direventually, we'll have other modules __init__.py error.py some classes that will be used in all log.py modules acctdb dir the acct db interface directory __init__.py api.py the abstract class def (derived from object) specific.py the specific implementation, derived from the api base class For arguments sake, let's call the base class (defined in api.py) 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' So, in the acctdb/__init__.py, do I do something like this: if SPECIFIC_CLASS: from company.acctdb.specific import SpecificClass as BaseClass with the idea that at some point in the future I'd designate a different class in some other way? Hopefully this is enough info for you to see what I'm trying to accomplish. It's a bit like the DB interfaces, where there is a generic DB API, and then the different drivers to implement that API (MySQL, etc). Thanks for any suggestions! -scott -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python program as main...
On Wed, 26 Mar 2008 13:05:55 -0300, Gabriel Genellina wrote: En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad [EMAIL PROTECTED] escribió: Stumbling through Mark Lutz's Programming Python 3rd, he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3ELauncher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3Epython Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). I think it is an option in the installer, to associate or not Python to the .py extension. You could reinstall Python paying attention to the options, or repair the association as described in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ b1d0fd05b3615057/ See also the official (development version of the) documentation with the new section Using Python. Using Python on Windows covers exactly this topic: http://docs.python.org/dev/using/windows.html#executing-scripts HTH, -- Robert Stargaming Lehmann -- http://mail.python.org/mailman/listinfo/python-list
Re: last mouse movment or keyboard hit
En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler [EMAIL PROTECTED] escribió: I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? En Wed, 26 Mar 2008 13:59:15 -0300, azrael [EMAIL PROTECTED] escribió: You can use wxPython. Take a look on the DemoFiles that you can download also from the site. I remember that there has been a demo of capturing mouse coordinates and also one example about capturing Which key has been pressed at which time. (Please don't top post) Does wx catch all events in all other applications? My understanding is that the OP wants a global detection, not restricted to a single application. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Some notes on a high-performance Python application.
Am Mittwoch, 26. März 2008 17:33:43 schrieb John Nagle: ... Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put fair queueing in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. ... Does anyone else architect their systems like this? A Xen(tm) management system I've written at least shares this aspect in that the RPC subsystem for communication between the frontend and the backends is basically a (MySQL) database table which is regularily queried by all backends that work on VHosts to change the state (in the form of a command) according to what the user specifies in the (Web-)UI. FWIW, the system is based on SQLObject and CherryPy, doing most of the parallel tasks threaded from a main process (because the largest part of the backends is dealing with I/O from subprocesses [waiting for them to complete]), which is different from what you do. CherryPy is also deployed with the threading server. -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python program as main...
On Mar 26, 8:12 pm, waltbrad [EMAIL PROTECTED] wrote: Stumbling through Mark Lutz's Programming Python 3rd, he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3ELauncher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3Epython Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). You have to set the path in your run time environment. regards, Subeen. http://love-python.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Some notes on a high-performance Python application.
Heiko Wundram wrote: Am Mittwoch, 26. März 2008 17:33:43 schrieb John Nagle: ... Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put fair queueing in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. ... Does anyone else architect their systems like this? A Xen(tm) management system I've written at least shares this aspect in that the RPC subsystem for communication between the frontend and the backends is basically a (MySQL) database table which is regularily queried by all backends that work on VHosts to change the state (in the form of a command) according to what the user specifies in the (Web-)UI. I see nothing unusual with this: I vaguely remember that this database approach was teached at my former university as a basic mechanism for distributed systems at least since 1992, but I'd guess much longer... And in one of my projects a RDBMS-based queue was used for a PKI registration server (e.g. for handling the outbound CMP queue). IIRC Microsoft's Biztalk Server also stores inbound and outbound queues in its internal MS-SQL database (which then can be the bottleneck). Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Py2exe embed my modules to libary.zip
Hello, Does anybody have any idea how can I embed my modules to libary.zip and use it from my application.For example if user write this code in my TextEntry ( or something like that, textentry is created with wxpython ) : import d3dx # directpython module frame=d3dx.Frame(uMy frame) # create frame frame.Mainloop() # run it and then when my application execute code how can I set path to d3dx module to library.zip/d3dx.py. I'm not sure is this properly set question. Regards, Vedran -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
HOw can we use express pointers as in C or python? On Tue, Mar 25, 2008 at 7:36 PM, Tim Chase [EMAIL PROTECTED] wrote: In most of the languages ^ is used for 'to the power of'. No, not in most languages. In most languages (C, C++, Java, C#, Python, Fortran, ...), ^ is the xor operator ;) ...and in Pascal it's the pointer-dereferencing operator... -tkc -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
Eric Brunel wrote: BTW, this standard is not universal at all: e.g, there is no such convention on Macs. Thanks for the info. It's standard on Windows and Linux/KDE. GNOME, anyone? -- http://mail.python.org/mailman/listinfo/python-list
Re: naive packaging question
On Mar 26, 12:33 pm, Scott Sharkey [EMAIL PROTECTED] wrote: Here's the directory structure that I've got so far: project dir top level directory setup.py company dir eventually, we'll have other modules __init__.py error.py some classes that will be used in all log.py modules acctdb dir the acct db interface directory __init__.py api.py the abstract class def (derived from object) specific.py the specific implementation, derived from the api base class For arguments sake, let's call the base class (defined in api.py) 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' So, in the acctdb/__init__.py, do I do something like this: if SPECIFIC_CLASS: from company.acctdb.specific import SpecificClass as BaseClass Seems pretty reasonable to me. Do you have any specific reasons for being concerned about this organization? (My only minor suggestion would be not to import the SpecificClass as BaseClass, but instead with a name that's different from both, for example, PublicClass. All that does is to avoid a tiny bit of potential confusion down the road.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Some notes on a high-performance Python application.
Am Mittwoch, 26. März 2008 18:54:29 schrieb Michael Ströder: Heiko Wundram wrote: Am Mittwoch, 26. März 2008 17:33:43 schrieb John Nagle: ... Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put fair queueing in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. ... Does anyone else architect their systems like this? A Xen(tm) management system I've written at least shares this aspect in that the RPC subsystem for communication between the frontend and the backends is basically a (MySQL) database table which is regularily queried by all backends that work on VHosts to change the state (in the form of a command) according to what the user specifies in the (Web-)UI. I vaguely remember that this database approach was teached at my former university as a basic mechanism for distributed systems at least since 1992, but I'd guess much longer... I didn't say it was unusual or frowned upon (and I was also taught this at uni IIRC as a means to easily distribute systems which don't have specific requirements for response time to RPC requests), but anyway, as you noted for Biztalk, it's much easier to hit bottlenecks with a polling-style RPC than with a true RPC system, as I've come to experience when the number of nodes (i.e., backends) grew over the last year and a half. That's what's basically causing a re-consideration to move from DB-style RPC to socket-based RPC, which is going to happen at some point in time for the system noted above (but I've sinced changed jobs and am now only a consulting developer for that anyway, so it won't be my job to do the dirty migration and the redesign ;-)). -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
En Wed, 26 Mar 2008 14:55:43 -0300, [EMAIL PROTECTED] escribió: Does anybody have any idea how can I embed my modules to libary.zip and use it from my application.For example if user write this code in my TextEntry ( or something like that, textentry is created with wxpython ) : import d3dx # directpython module frame=d3dx.Frame(uMy frame) # create frame frame.Mainloop() # run it and then when my application execute code how can I set path to d3dx module to library.zip/d3dx.py. I'm not sure is this properly set question. If d3dx.py is in library.zip (top level), and the path to library.zip is in sys.path, Python will find the module. A .zip in sys.path acts as it were a directory itself. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson [EMAIL PROTECTED] escribió: HOw can we use express pointers as in C or python? Traceback (most recent call last): File stdin, line 1, in module File parser.py, line 123, in parse_text tree = language.parse_text(text) File english.py, line 456, in parse_text tree = self.parse_sentence(sentence) File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
and then when my application execute code how can I set path to d3dx module to library.zip/d3dx.py. I'm not sure is this properly set question. use the module zipimport http://docs.python.org/lib/module-zipimport.html -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
Am Mittwoch, 26. März 2008 19:04:44 schrieb David Anderson: HOw can we use express pointers as in C or python? There's no such thing as a pointer in Python, so you can't express them either. Was this what you were trying to ask? -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
On Wed, Mar 26, 2008 at 1:36 PM, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson [EMAIL PROTECTED] escribió: HOw can we use express pointers as in C or python? File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' string = How can we use express pointers as in C or python? import advancedParser advancedParser.translate(string) LogicError: indication that we are not outside of python, recursive self-definition requested. (segmentation fault) all sarcasm aside if you actually meant to ask how to pass by value or pass by reference in Python, then the simple answer is don't worry about it, Python handle's things in a natural and intuitive way. If you have a specific question regarding python's handling of this concept, ask it, as some instances can be confusing and have gotchyas. -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
HOw can we use express pointers as in C or python? Traceback (most recent call last): File stdin, line 1, in module File parser.py, line 123, in parse_text tree = language.parse_text(text) File english.py, line 456, in parse_text tree = self.parse_sentence(sentence) File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' Possible express pointers: http://www.geocities.com/derwin_b/sr91sign.jpg http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg If those meet the OP's need, I recommend urllib2 and PIL. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering a Python list to uniques
On Mar 26, 5:45 am, hellt [EMAIL PROTECTED] wrote: On 26 ÍÁÒ, 02:30,kellygreer1[EMAIL PROTECTED] wrote: What is the best way to filter a Python list to its unique members? I tried some method using Set but got some unhashable error. lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] # how do i reduce this to lsttwo = [ 1, 2, 3, 4, 5, 6 ] Is there a page on this in the Python in a Nutshell or the Python Cookbook? Did I miss something? Kelly Greer [EMAIL PROTECTED] change nospam to yahoo or just look this thread for a fastest solutionhttp://groups.google.com/group/comp.lang.python/browse_frm/thread/709... How come the Set() thing seems to work for some people and I get the 'unhashable' error? How do you test for 'membership' on a dictionary? # where tmp is the non-unique list # dct is a dictionary where each unique key will be tied to a count (the value) # for testing I was setting the count to 0 for v in tmp: if not v in dct: dct[v] = 0 # I get unhashable error here. # Even if I write it. for v in tmp: if not v in dct.keys(): dct[v] = 0 What am I missing? Thanks, Kelly -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Il Tue, 25 Mar 2008 20:31:39 +, Minor Gordon ha scritto: Hello all, I'm looking for beta testers for a high performance, event-driven Python application server I've developed. About the server: the front end and other speed-critical parts of the server are written in portable, multithreaded C++. The back end is an embedded CPython interpreter. The server is much faster than anything in pure Python, and it can compete with C servers (including e.g. lighttpd for file workloads) or outdo them (e.g. anything behind Apache) until CPython consumes a single processor. Have you tried my WSGI implementation for Nginx? http://hg.mperillo.ath.cx/nginx/mod_wsgi/ Its not a general purpose solution, but it can be of interest. On the Python side it supports WSGI (the server can handle the static and dynamic requests of MoinMoin with a handful of lines), the DB API with blocking calls offloaded to a connection in a separate thread (MySQL, SQLite supported), Google's ctemplate, gzipping responses, file caching, reading and writing to URIs as a client, AJAX integration, debugging as a Python extension, and a lot of other features. The core Python API is event-driven, using continuations like Twisted but much cleaner (continuations are any callables, there are no special objects anywhere). The Python back end also supports Stackless Python so all of the continuation machinery can be hidden behind tasklet switching. I have recently added support for asynchronous application. There are two examples: an application that execute a query to PostgreSQL and an application that execute an HTTP request with pycurl: http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-postgres- async.py http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-curl.py Note that ngx.poll extension is still experimental. [...] Manlio Perillo -- http://mail.python.org/mailman/listinfo/python-list
Re: Beta testers needed for a high performance Python application server
Il Wed, 26 Mar 2008 00:22:38 -0700, John Nagle ha scritto: Graham Dumpleton wrote: Yes that is a viable option, as still are existing fastcgi solutions for Apache, lighttpd and nginx. Fast cgi is a good technology, Well, not really so good: http://twistedmatrix.com/pipermail/twisted-web/2006-April/002598.html but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It's more reliable than using things like mod_python, where you have application code running in the web server's address space. That creates both security problems and robustness problems. If an fcgi process crashes, it is automatically replaced by a fresh copy of the program at the next request. Other activity in progress is not affected. Also, fcgi processes are reloaded after some number of requests, so minor memory leaks won't choke the system over time. The problem is simple: why put an extra server layer between an HTTP client and an HTTP server? Moreover, you should not use mod_python as an example. The WSGI module for Apache has a lot of feature for reducing these problems; and as an alternative you can use the WSGI implementation for Nginx. [...] Manlio Perillo -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay [EMAIL PROTECTED] escribió: and then when my application execute code how can I set path to d3dx module to library.zip/d3dx.py. I'm not sure is this properly set question. use the module zipimport http://docs.python.org/lib/module-zipimport.html You don't have to do anything special to use zipimport; from http://docs.python.org/lib/module-zipimport.html : It is usually not needed to use the zipimport module explicitly; it is automatically used by the builtin import mechanism -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
Err even I cant understand what I wrote... The right question was:HOw can we use/express pointers python as in C or Pascal? But thx to Heiko, He got what I mean =) On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase [EMAIL PROTECTED] wrote: HOw can we use express pointers as in C or python? Traceback (most recent call last): File stdin, line 1, in module File parser.py, line 123, in parse_text tree = language.parse_text(text) File english.py, line 456, in parse_text tree = self.parse_sentence(sentence) File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' Possible express pointers: http://www.geocities.com/derwin_b/sr91sign.jpg http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg If those meet the OP's need, I recommend urllib2 and PIL. -tkc -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
A question on decorators
Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2pickled_data1 pickled_data2 0woeif aposf (bin) (bin) 1ofime powe(bin) (bin) ... noiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, let me demonstrate t.data.update({'new key':'new value'}) print t.data {... 'new key':'new value' ...} which makes it appear that the database has been updated as well, but in fact it hasn't to update the database with this scheme you actually have to do this. t.data.update({'new key':'new value'}) t.data = t.data this is not ideal so I subclassed the built in dict type like this: class _my_dict(dict): def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) self.update_db() def __delitem__(self, key): if self.write_access: dict.__delitem__(self, key) self.update_db() def __setitem__(self, key, value): if self.write_access: dict.__setitem__(self, key, value) self.update_db() def clear(self): if self.write_access: dict.clear(self) self.update_db() ... more methods which are simliar ... def update_db(self): if self.write_access: con = get_dbConnection() cur = con.cursor() table = self.experiment.TABLE row_index_name = self.row_index_name row_index = self.row_index column_name = self.column_name column_value = MySQLdb.escape_string(pickle.dumps(self)) q1 = '''UPDATE %(table)s SET %(column_name)s = '%(column_value)s' WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() cur.execute(q1) con.close() Now while this works, it is a lot of work. What I want to be able to do is something where I write one decorator function that automatically updates the database for me. So let us pretend I have this function. let: dec_update_db() be my decorator which updates the dictionary. to use this function it seems I would probably still have to subclass dict like this: class _my_dict2(dict): @dec_update_db def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) @dec_update_db def __delitem__(self, key): dict.__delitem__(self, key) @dec_update_db def __setitem__(self, key, value): dict.__setitem__(self, key, value) @dec_update_db def clear(self): dict.clear(self) ... and so on ... this is also not ideal. because I still have to apply the decorator to every function which changes the dictionary. What I really want is a way to have the decorator applied automatically every time a method in dict or a sub class is called. I feel like this must be possible. Has any one here done anything like this before? Thank you for reading my long post, I hope you understand what I am asking especially since the code in it is not very good. cheers Tim Henderson -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
ANd... By express I mean... Dereferencing... Habits from my native language where the verb express also means this On Wed, Mar 26, 2008 at 4:14 PM, David Anderson [EMAIL PROTECTED] wrote: Err even I cant understand what I wrote... The right question was:HOw can we use/express pointers python as in C or Pascal? But thx to Heiko, He got what I mean =) On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase [EMAIL PROTECTED] wrote: HOw can we use express pointers as in C or python? Traceback (most recent call last): File stdin, line 1, in module File parser.py, line 123, in parse_text tree = language.parse_text(text) File english.py, line 456, in parse_text tree = self.parse_sentence(sentence) File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' Possible express pointers: http://www.geocities.com/derwin_b/sr91sign.jpg http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg If those meet the OP's need, I recommend urllib2 and PIL. -tkc -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: A question on decorators
On Mar 26, 2:10 pm, Tim Henderson [EMAIL PROTECTED] wrote: Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2pickled_data1 pickled_data2 0woeif aposf (bin) (bin) 1ofime powe(bin) (bin) ... noiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, let me demonstrate t.data.update({'new key':'new value'}) print t.data {... 'new key':'new value' ...} which makes it appear that the database has been updated as well, but in fact it hasn't to update the database with this scheme you actually have to do this. t.data.update({'new key':'new value'}) t.data = t.data this is not ideal so I subclassed the built in dict type like this: class _my_dict(dict): def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) self.update_db() def __delitem__(self, key): if self.write_access: dict.__delitem__(self, key) self.update_db() def __setitem__(self, key, value): if self.write_access: dict.__setitem__(self, key, value) self.update_db() def clear(self): if self.write_access: dict.clear(self) self.update_db() ... more methods which are simliar ... def update_db(self): if self.write_access: con = get_dbConnection() cur = con.cursor() table = self.experiment.TABLE row_index_name = self.row_index_name row_index = self.row_index column_name = self.column_name column_value = MySQLdb.escape_string(pickle.dumps(self)) q1 = '''UPDATE %(table)s SET %(column_name)s = '%(column_value)s' WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() cur.execute(q1) con.close() Now while this works, it is a lot of work. What I want to be able to do is something where I write one decorator function that automatically updates the database for me. So let us pretend I have this function. let: dec_update_db() be my decorator which updates the dictionary. to use this function it seems I would probably still have to subclass dict like this: class _my_dict2(dict): @dec_update_db def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) @dec_update_db def __delitem__(self, key): dict.__delitem__(self, key) @dec_update_db def __setitem__(self, key, value): dict.__setitem__(self, key, value) @dec_update_db def clear(self): dict.clear(self) ... and so on ... this is also not ideal. because I still have to apply the decorator to every function which changes the dictionary. What I really want is a way to have the decorator applied automatically every time a method in dict or a sub class is called. I feel like this must be possible. Has any one here done anything like this before? Thank you for reading my long post, I hope you understand what I am asking especially since the code in it is not very good. cheers Tim Henderson Why aren't you using SQLAlchemy or SQLObject? I think they would work better than this and give you a lot more flexibility. Besides, you should use sqlite rather than pickle databases. It's especially easy since sqlite is included with Python 2.5. Mike -- http://mail.python.org/mailman/listinfo/python-list
distutils crashing: $MACOSX_DEPLOYMENT_TARGET mismatch
Hi group, When starting a distutils script (which I mostly consider as a black box) distutils crashes with the following traceback: Traceback (most recent call last): File pyrexcompile.py, line 50, in module cmdclass = {'build_ext': build_ext}) File /sw/lib/python2.5/distutils/core.py, line 125, in setup dist.parse_config_files() File /sw/lib/python2.5/distutils/dist.py, line 366, in parse_config_files filenames = self.find_config_files() File /sw/lib/python2.5/distutils/dist.py, line 329, in find_config_files check_environ() File /sw/lib/python2.5/distutils/util.py, line 208, in check_environ os.environ['PLAT'] = get_platform() File /sw/lib/python2.5/distutils/util.py, line 78, in get_platform cfgvars = get_config_vars() File /sw/lib/python2.5/distutils/sysconfig.py, line 493, in get_config_vars func() File /sw/lib/python2.5/distutils/sysconfig.py, line 378, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now 10.3 but 10.5 during configure The script is used to trigger pyrex compilation. I am using Pyrex 0.9.6.4. I set the environment variable to 10.5 manually from the bash. I also hacked the distutils script and manually set it in os.environ to 10.5. Googling for the error message did not help a lot, either. I am running Mac OS X 10.5 on an Intel processor. I have distutils verison 2.5.1 running on a Python 2.5.2 installed via fink. Any help would be greatly appreciated! Regards, -Justin -- http://mail.python.org/mailman/listinfo/python-list
Daylight savings time problem
Hi, I'm trying to execute some operations based on a file's time. The file's time is actually the file's name (e.g. FILE1_20080326170558). So I do this: fileTimeInSecs = time.mktime(time.strptime(timeString, %Y%m%d%H%M)) timeString contains the date part of the file's name. Function strptime returns a time_struct, but my problem is that tm_isdst is set to 0, and when we enter daylight savings time the file's time is off by 1 hour. This time_struct is also read only so I can't change tm_isdst to -1. Anyone knows how to fix it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering a Python list to uniques
On Wed, Mar 26, 2008 at 2:50 PM, kellygreer1 [EMAIL PROTECTED] wrote: How come the Set() thing seems to work for some people and I get the 'unhashable' error? How do you test for 'membership' on a dictionary? # where tmp is the non-unique list # dct is a dictionary where each unique key will be tied to a count (the value) # for testing I was setting the count to 0 for v in tmp: if not v in dct: dct[v] = 0 # I get unhashable error here. # Even if I write it. for v in tmp: if not v in dct.keys(): dct[v] = 0 What am I missing? Some of the elements of tmp are unhashable. Unhashable items can't be the keys of a dictionary or members of a set. I don't think you've said anywhere in the thread what these items are, you just started out with an example of a list of integers. Do you believe the elements in tmp are integers? If so, try the following - for v in tmp: print type(v), repr(v), hash(v) and let us know what it spits out. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: A question on decorators
Mike Driscoll said: Besides, you should use sqlite rather than pickle databases. It's especially easy since sqlite is included with Python 2.5. I am using mysql, and sqlite is not appropriate for my situation since some of the databases and tables I access are being accessed by other applications which are already written and live. I am not using the SQLAlchemy or SQLObject, because I didn't want too (although in the future I may consider using them). This question actually has nothing to do with the database, I simply put the information on the database in to give it some context. cheers Tim Henderson -- http://mail.python.org/mailman/listinfo/python-list
How to convert latex-based docs written with Python 2.5 to 2.6 framework
HI! I had a look on how Doc/ is organized with Python 2.6. There are files with suffix .rst. Hmm... I'm maintaing existing docs for python-ldap which I might have to convert to the new concept in the long run. What's the recommended procedure for doing so? Any pointer? Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python program as main...
On Mar 26, 9:12 am, waltbrad [EMAIL PROTECTED] wrote: On his command line he types: C:\...\PP3ELauncher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3Epython Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). Browse this thread on clp: http://tinyurl.com/2wbnde RD -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: Am Mittwoch, 26. März 2008 19:04:44 schrieb David Anderson: HOw can we use express pointers as in C or python? There's no such thing as a pointer in Python, so you can't express them either. Was this what you were trying to ask? Strictly speaking, many objects are passed by reference, which is kind of pointer-like, even though it doesn't expose the true messiness of a true pointer. Also strictly speaking, if you use SWIG, it can wrap up pointers from other languages as a python object to be passed around within a python program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Daylight savings time problem
On Wed, 26 Mar 2008 19:37:16 - Fabio Durieux Lopes [EMAIL PROTECTED] wrote: I'm trying to execute some operations based on a file's time. The file's time is actually the file's name (e.g. FILE1_20080326170558). So I do this: fileTimeInSecs = time.mktime(time.strptime(timeString, %Y%m%d%H%M)) timeString contains the date part of the file's name. Function strptime returns a time_struct, but my problem is that tm_isdst is set to 0, and when we enter daylight savings time the file's time is off by 1 hour. This time_struct is also read only so I can't change tm_isdst to -1. Anyone knows how to fix it? Use UTC. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
PyODBC Stored proc calling
This is probably pretty late to be replying but I had the same problem. As it turns out, you just need to be sure you use the correct syntax to call the sproc: db_cur.execute( {call test_bed(?)}, ('test data string') ) -- Teleoperate a roving mobile robot from the web: http://www.swampgas.com/robotics/rover.html -- http://mail.python.org/mailman/listinfo/python-list
first interactive app
hi, I want to write a tiny interactive app for the following situation: I have books of many chapters that must be split into volumes before going to the printer. A volume can have up to 600 pages. We obviously break the book into volumes only at chapter breaks. Since some chapters make a natural grouping, we want some human interaction for where the volume breaks occur. Not having experience with interactive apps, I'm asking for advice about how to go about it. The data I start with is just a dictionary with chapter name = ending page number. I figured I would first show where the volumes would break with no human interaction, with the begin and ending chapter names/pagenumbers for each volume. From here I thought about having a slider for each volume, but the number of volumes could change during the session. Or maybe I should just ask 'enter the ending chapter for the first volume' and recalculate, etc until all volumes are defined. Any ideas on a simple interface for this? thanks, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: A question on decorators
Tim Henderson schrieb: Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2pickled_data1 pickled_data2 0woeif aposf (bin) (bin) 1ofime powe(bin) (bin) ... noiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, let me demonstrate t.data.update({'new key':'new value'}) print t.data {... 'new key':'new value' ...} which makes it appear that the database has been updated as well, but in fact it hasn't to update the database with this scheme you actually have to do this. t.data.update({'new key':'new value'}) t.data = t.data this is not ideal so I subclassed the built in dict type like this: class _my_dict(dict): def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) self.update_db() def __delitem__(self, key): if self.write_access: dict.__delitem__(self, key) self.update_db() def __setitem__(self, key, value): if self.write_access: dict.__setitem__(self, key, value) self.update_db() def clear(self): if self.write_access: dict.clear(self) self.update_db() ... more methods which are simliar ... def update_db(self): if self.write_access: con = get_dbConnection() cur = con.cursor() table = self.experiment.TABLE row_index_name = self.row_index_name row_index = self.row_index column_name = self.column_name column_value = MySQLdb.escape_string(pickle.dumps(self)) q1 = '''UPDATE %(table)s SET %(column_name)s = '%(column_value)s' WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() cur.execute(q1) con.close() Now while this works, it is a lot of work. What I want to be able to do is something where I write one decorator function that automatically updates the database for me. So let us pretend I have this function. let: dec_update_db() be my decorator which updates the dictionary. to use this function it seems I would probably still have to subclass dict like this: class _my_dict2(dict): @dec_update_db def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) @dec_update_db def __delitem__(self, key): dict.__delitem__(self, key) @dec_update_db def __setitem__(self, key, value): dict.__setitem__(self, key, value) @dec_update_db def clear(self): dict.clear(self) ... and so on ... this is also not ideal. because I still have to apply the decorator to every function which changes the dictionary. What I really want is a way to have the decorator applied automatically every time a method in dict or a sub class is called. I feel like this must be possible. Has any one here done anything like this before? There are a few possibilities - one of them is using a metaclass to apply the decorator to alle methods. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Daylight savings time problem
I'm sorry, but could you be more specific? How exactly should I use UTC? -- Fabio Durieux Lopes - Salsa - Original Message From: D'Arcy J.M. Cain [EMAIL PROTECTED] To: Fabio Durieux Lopes [EMAIL PROTECTED] Cc: python-list@python.org Sent: Wednesday, March 26, 2008 4:49:57 PM Subject: Re: Daylight savings time problem On Wed, 26 Mar 2008 19:37:16 - Fabio Durieux Lopes [EMAIL PROTECTED] wrote: I'm trying to execute some operations based on a file's time. The file's time is actually the file's name (e.g. FILE1_20080326170558). So I do this: fileTimeInSecs = time.mktime(time.strptime(timeString, %Y%m%d%H%M)) timeString contains the date part of the file's name. Function strptime returns a time_struct, but my problem is that tm_isdst is set to 0, and when we enter daylight savings time the file's time is off by 1 hour. This time_struct is also read only so I can't change tm_isdst to -1. Anyone knows how to fix it? Use UTC. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Python / C++ embed halfway working - question about constructors
I am running my C++ / Python App on a MacBook Pro with 2.5 installed I have had some success in that I can load a module, get the class, get the reference, but when the python class calls another python class I don't ever seem to get the object back from the constructor. I am doing the following in the C++ file: Py_Initialize() PyObject* module = PyImport_Import(moduleName); PyObject* class = PyObject_GetAttrString(module, className); Py_DECREF(module); Py_DECREF(class); // Create the TSAFE object constructor arguments: // a file, and an int PyObject* tsafeOutputFile = PyFile_FromString(TsafeOutput, a); PyObject* resolveValue = PyInt_FromLong(0); PyObject* classArgumentTuple = PyTuple_New(2); PyTuple_SetItem(classArgumentTuple, 0, tsafeOutputFile); PyTuple_SetItem(classArgumentTuple, 1, resolveValue); classReference = PyEval_CallObject(class, classArgumentTuple); Py_MY_INCREF(classReference); Py_MY_DECREF(class); PyObject* pythonMethod = PyObject_GetAttrString(classReference, registerFlight); registerReturn = PyEval_CallObject(pythonMethod, argumentTuple); Py_MY_DECREF(pythonMethod); Py_MY_DECREF(argumentTuple); Essentially the code above should: call class constructor call registerFlight() calls registerFlight_() calls _flightPointer() - where I never get by the section of code where the Flight.py Constructor get called Each flight should be added to my class object to build up a dictionary of flights. The python class methods getting called are detailed below and I never get by the call to _flightPointer(). I have opened a file and write to it at each step of code and I never get all the way through the _flightPointer() method Is there something I am missing here I cannot print the data out of the __init__ method in the Flight.py file? I did not include all of the code here because I am hoping the issue is I have got something wrong and it's not the python code but me. Ant help will be greatly appreciated. def registerFlight(self, ID, ACtype=?, IFR=1, RVSM=0, ATCcat=?, filedAlt=0, filedSpeed=0): register flight (unitless args for outside client) filedAlt *= FL # FL = Flight Level = 100 ft filedSpeed *= kn # kn = knots self.registerFlight_(ID, ACtype, IFR, RVSM, ATCcat, filedAlt,filedSpeed) def registerFlight_(self, ID, ACtype=?, IFR=1, RVSM=0, ATCcat=?, filedAlt=0, filedSpeed=0): register flight (accepts arguments with units) flight = self._flightPointer(ID) flight.registerFlight(ACtype, IFR, RVSM, ATCcat, filedAlt, filedSpeed) def _flightPointer(self, ID, track=0, Flight=Flight): manage tracked and untracked flight lists fltPointerFile = open('TSAFE_flightPointerOut', 'a') fltPointerFile.write(In the _flightPointer function\n) flights = self.flights unflights = self.untrackedFlights if ID in flights: fltPointerFile.write(in first IF\n) return flights[ID] if track: # new data record is a track update - start tracking if ID in unflights: # move flight to tracked status flights[ID] = unflights[ID] del unflights[ID] else: flights[ID] = Flight(ID) # new Flight object return flights[ID] ## THIS IS THE SECTION OF CODE NOT RETURNING A REFERENCE TO THE Flight object if ID not in unflights: fltPointerFile.write(ID) fltPointerFile.write( In if ID not in unflights\n\n) unflights[ID] = Flight(ID) fltPointerFile.write(BACK FROM CALLING Flight(ID)\n) unflightsValue = (unflights[ID], unflights[ID]) unflightsString = str(unflightsValue) fltPointerFile.write(Return value is ) fltPointerFile.write(unflightsString) fltPointerFile.write('\n') return unflights[ID] -- http://mail.python.org/mailman/listinfo/python-list
RE: Do any of you recommend Python as a first programming language?
Steven D'Aprano wrote: On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: Yes. And because Python is a scripting language Python is a programming language. It can be used for scripting, but that's not all it can do. Describing it as a scripting language is like describing a fully-equipped professional kitchen as a left-over warming room. I'm putting words in sturlamolden's mouth here, but I think he was implying that Python has all the advantages of a scripting language, hence has a much gentler introduction than many fully-fledged programming languages (and indeed, many scripting languages). Cheers, Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: Daylight savings time problem
On 2008-03-26, Salsa [EMAIL PROTECTED] wrote: I'm sorry, but could you be more specific? How exactly should I use UTC? In my experience, using local time for timestamps is always a big mistake, so I presume he meant don't use local time in the file names -- put the UTC date/time in the filenames. If that's not an option, I'd try to figure out how to convert from whatever _is_ in the filename to UTC. -- Grant Edwards grante Yow! Half a mind is a at terrible thing to waste! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Not understanding lamdas and scoping
I am trying to use lamdba to generate some functions, and it is not working the way I'd expect. The code is below, followed by the results I'm getting. More comments below that. patterns = ( ('[sxz]$', '$','es'), ('[^aeioudgkprt]h$', '$', 'es'), ('[^aeiou]y$', 'y$', 'ies'), ('$', '$', 's'), ) def z(*a): print a def make_pattern(pattern, search, replace): def compare(word): z(pattern, search, replace) return compare rules = [make_pattern(pattern, search, replace) for (pattern, search, replace) in patterns] print 'make pattern' for rule in rules: rule('noun') rules = [lambda word: z(pattern, search, replace) for (pattern, search, replace) in patterns] print 'lambda/list comprehension' for rule in rules: rule('noun') rules = [] for pattern, search, replace in patterns: rules.append(lambda word: z(pattern, search, replace)) print 'lamda/for loop' for rule in rules: rule('noun') Ouptut: make pattern ('[sxz]$', '$', 'es') ('[^aeioudgkprt]h$', '$', 'es') ('[^aeiou]y$', 'y$', 'ies') ('$', '$', 's') lambda/list comprehension ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') lamda/for loop ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') Of course, in my real code, I'm not calling z(), but a couple of RE search/replace functions (yes, I'm working on the Dive Into Python pluralizer). The first result is obviously the correct one. But the next two don't make sense. Why do all the functions returned by lamda have the last input values? What am I missing? OK, I figured out if I did this: def make_pattern(pattern, search, replace): return lambda word: z(pattern, search, replace) it would give correct results. So, is there some scoping issue with lambda that I'm not seeing? Thanks! j -- http://mail.python.org/mailman/listinfo/python-list