Volume id
Hi, I have a problem, which may be trivial, but I could not find an answer. I have to write a Python script, which does a directory tree walking on given mounted disk. But I do need to extract the volume id, somehow. And that's the problem. An additional issue, the script will be used on unix type systems, and on MS XP or Vista, too Any ideas are wellcome. Gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking Python Developer
[EMAIL PROTECTED] wrote: Hi, I work for an IT company in Phoenix, AZ and am trying to find an experienced python developer in the area. Can anyone help? Hi, There's a Python job board at http://www.python.org/community/jobs/ The first link on the page documents how to get your ad listed. j. -- http://mail.python.org/mailman/listinfo/python-list
Re: no __len__ attribute in NodeList or the list base?
[EMAIL PROTECTED] writes: i extract class object from an instance of NodeList (minicompat.py) like so PyObject *pclass = PyObject_GetAttrString( nodelistinsance, __class__); but PyObject_GetAttrString(pclass, __len__) returns NULL. Are you sure about that? import xml.dom.minicompat xml.dom.minicompat.NodeList class 'xml.dom.minicompat.NodeList' xml.dom.minicompat.NodeList.__len__ slot wrapper '__len__' of 'list' objects xml.dom.minicompat.NodeList() [] _.__class__ class 'xml.dom.minicompat.NodeList' _.__len__ slot wrapper '__len__' of 'list' objects to explain that endless loop i have to assume __len__ is defined in the NodeList base(list that is) but i don't see __len__ anywhere in listobject.c!!! The list object has __len__: list.__len__ slot wrapper '__len__' of 'list' objects It just gets defined in a different way, through a C structure of function pointers defining sequence operations. (See where list_length is defined and used.) -- http://mail.python.org/mailman/listinfo/python-list
What is the function to evaluate code object returned by PyParser _SimpleParseString function?
Hi, Thanks for this information Py_CompileString takes the source code from file, isn't it? As can be seen from the syntax of this function: PyObject* Py_CompileString(char *str, char *filename, int start) I want to parse the code which is in memory - loaded from database. In that case, may I know, how to use the Py_CompileString? Is it mandatory to read from file for this function? Reading from file increases startup time of my application. So, I was thinking of using PyParser_SimpleParseString, which takes the code to be parsed in the char* format. Quit suitable to my need. Can I use the output of the function PyParser_SimpleParseString as input to PyEval_EvalCode? Please guide. Thanks in advance for your time guidance. Warm Regards, Ganesh -Original Message- From: Gabriel Genellina [mailto:[EMAIL PROTECTED] Sent: 15 November 2007 07:51 To: python-list@python.org Subject: Re: How to use the evaluate the code object returned by PyParser_Simp leParseString function? En Wed, 14 Nov 2007 06:48:41 -0300, Borse, Ganesh [EMAIL PROTECTED] escribió: `struct _node* PyParser_SimpleParseString(char *str, int start)' Parse Python source code from STR using the start token START. The result can be used to create a code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated many times. I have exactly same requirement. I have dynamic expressions loaded from database at startup in my C++ application. I want to parse these expressions at startup keep the parsed (compiled) code in memory of this application. Then at runtime, I want to evaluate all this parsed code. This has to be very efficient. parsed != compiled. Use Py_CompileString instead. The resulting code object may be executed with PyEval_EvalCode. BTW, instead of looking at some random web site, it's better to read the official documentation at http://docs.python.org. You should have a copy of it in the Doc subdirectory inside your Python installation. -- Gabriel Genellina == Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html == -- http://mail.python.org/mailman/listinfo/python-list
Memory problem
Hi, I have a strange (for me) memory problem. When running a loop in a Python program memory usage increases from about 4% up to 100%. I do a gc.collect() every loop cycle but this doesn't help. There are about 67000 objects that are tracked by the garbage collector. This number does vary a little bit but does not increase on average whereas the memory usage does. The number of garbage objects (len(gc.garbage()) is zero. This is a very severe problem for my application, so I would be very appreciative for any help. With kind regards Rolf -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory problem
Rolf Wester wrote: Hi, I have a strange (for me) memory problem. When running a loop in a Python program memory usage increases from about 4% up to 100%. I do a gc.collect() every loop cycle but this doesn't help. There are about 67000 objects that are tracked by the garbage collector. This number does vary a little bit but does not increase on average whereas the memory usage does. The number of garbage objects (len(gc.garbage()) is zero. This is a very severe problem for my application, so I would be very appreciative for any help. well, it might be that the relative moon humidity resonates with the loop-cycle, creating quantum-flux in the main memory banks. Or not. Seriously - what help do you expect without showing us _any_ code or at least getting into details like usage of libs, python-version, possible C-extensions, platform, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory problem
Sorry, of course your are wright. I'm running Python2.5 on Linux, my program imports numpy, matplotlib, sys and a python module of my own. This module uses numpy and scipy.weave for imbedded C-code but no extension modules. I though the code to be to large to show, I hoped you could give me hint on what I could try. Thank you in advance Rolf Diez B. Roggisch wrote: Rolf Wester wrote: Hi, I have a strange (for me) memory problem. When running a loop in a Python program memory usage increases from about 4% up to 100%. I do a gc.collect() every loop cycle but this doesn't help. There are about 67000 objects that are tracked by the garbage collector. This number does vary a little bit but does not increase on average whereas the memory usage does. The number of garbage objects (len(gc.garbage()) is zero. This is a very severe problem for my application, so I would be very appreciative for any help. well, it might be that the relative moon humidity resonates with the loop-cycle, creating quantum-flux in the main memory banks. Or not. Seriously - what help do you expect without showing us _any_ code or at least getting into details like usage of libs, python-version, possible C-extensions, platform, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGilState_Ensure interrupts python critical sections
Many thanks for the clarification. Also good idea to focus on lock ownership rather that thread activity in your diagram. To be honest I was not actually experiencing deadlock issues. I had just deduced (incorrectly) that I might do so if I started using locks in my py code called from c-land. As I was suffering some horrible race-condtions that had suddenly appeared in code that had been perfectly stable for the past 6 months I didn't want to go down that route given my misconceptions; Even if introducing the locks worked I'd always feel it was a deadlock waiting to happen. Misunderstanding arose as for some reason I had decided that python code called from C did not allow any other python threads to run until control had returned to C and the gil had been released from C-land. I.e. once the gil was given to the C thread then python had to wait until it was given back. I have to say the docs could be a little more explicit on the mechanisms involved. They tend to be better at stating what individual functions do rather that giving overall explanations. Maybe I'll get around to submitting a chapter on it ;) On Nov 12, 4:54 pm, Chris Mellon [EMAIL PROTECTED] wrote: On Nov 12, 2007 6:56 AM, [EMAIL PROTECTED] wrote: Hi, I have a native windows thread in a c python module which calls into python code and adds an item to a data structure (a home-grown circular buffer). At the same time my main python application is removing items from this data structure. Unlike native python containers adding and removing items from the circular buffer is not atomic. So I need to put access to it in a critical section. Using threading.Lock will work for native python threads competing for access. But when access is from a windows thread this will not work. That is because my call to PyGilState_ensure will preempt my native python thread ***even when it is inside the critical section***. What is going on looks something like this (I think). Py Python Windows Py threading.Lock resource SchedThread Thread Code| | | || | | |Go (GIL)#|| | | |#|| | | |#|| | | |#...Doit.|...| | | |#||. acquire...| | |-PyGILState_Ensure--|| | | | ... ... ... ... |Stop# |---`| | |Ensure rtns-# PyObject_ || | :|CallMethod | | | | :|.(Doit)... |. acquire...| DEADLOCK | : : :.how does python thread tell PyScheduler not to give away Gil until we are done with critical section?? So my question is how in python do I tell the scheduler not to prempt the current python thread. Especially how to tell it not to give the GIL to any calls to PyGILState_ensure until further notice (i.e. until I am outside my critical section?? It sounds like a reasonable request - surely this exists already but I can't find it. It took me some time to understand the problem you were describing because you've got some terms backward - there's no Python scheduler, and calling PyGILState_ensure doesn't preempt anything. The Python interpreter *releases* the GIL every so often to allow other threads looking for it to run, but calling the python GIL functions has no effect on preemption. The problem is that the GIL is being released while your object lock is held, a second thread (started from C) acquires the GIL and then blocks on the object lock. What you seem to be seeing is that it blocking on the object lock is preventing it from releasing the GIL, which prevents the python thread from running and releasing the lock. This shouldn't happen - blocking on a lock releases the GIL, so the python thread should run, release the GIL, and eventually your C thread should be able to acquire both locks at the same time. Are you sure that you're correctly acquiring the GIL in your C code? The data flow you *should* be seeing should look something like this: GIL object lock (P=Python, C=C, *=released) --- P P Python holds both locks * P Python releases the GIL, inside critical section C P C thread acquires the GIL and starts executing Python code * P C thread tries to acquire object lock and blocks, releasing the GIL P P Python thread re-acquires
Resolving declaring class of a method at runtime
Hello, Is there a simple way to resolve declaring class of a method at runtime ? Consider this simple example: $ python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type help, copyright, credits or license for more information. class X: ... def x(self): ...pass ... class Y(X): ... def y(self): ...pass ... y = Y() y.x.im_class class __main__.Y at 0x7ff24bfc y.y.im_class class __main__.Y at 0x7ff24bfc What I would like to find out is the declaring class of method x, ie. class X How to do this ? -- __janne -- http://mail.python.org/mailman/listinfo/python-list
Re: Volume id
Gabor Urban wrote: Hi, I have a problem, which may be trivial, but I could not find an answer. I have to write a Python script, which does a directory tree walking on given mounted disk. But I do need to extract the volume id, somehow. And that's the problem. An additional issue, the script will be used on unix type systems, and on MS XP or Vista, too Any ideas are wellcome. I believe (although not 100% sure) that volume id always belongs to a FAT partition (maybe an NTFS partition?). When you format a partition, it will give you a - hopefully unique - volume identifier. I don't think that unix partitions (like reiserfs, ext2, ext3, ufs2 etc.) has that identifier. I may be wrong, others will probably correct me. Do you want to know the identifier (serial number?) of the disk device instead? E.g. not the partition but the hard disk? Can you list the platforms/operating systems where you want to use your program? It might help to look at the documentation/source code or the various hardware diagnostic utilities. Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
how to figure out if python was used as a cgi script
hi, is there a way to figure out which scripting language was used in a cgi. I used to watch extensions (i.e. py, pl, asp or php) nowadays i hardly see any extensions and really it is hard to find out anything from the generated HTML or even the HTML being sent out through the FORM tag .. is there another way to find out which scripting language was used in website!!! ce Sorry I couldn't resist -- http://mail.python.org/mailman/listinfo/python-list
Re: how to figure out if python was used as a cgi script
ce wrote: hi, is there a way to figure out which scripting language was used in a cgi. I used to watch extensions (i.e. py, pl, asp or php) nowadays i hardly see any extensions and really it is hard to find out anything from the generated HTML or even the HTML being sent out through the FORM tag .. is there another way to find out which scripting language was used in website!!! No. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: how to figure out if python was used as a cgi script
ce wrote: hi, is there a way to figure out which scripting language was used in a cgi. I used to watch extensions (i.e. py, pl, asp or php) nowadays i hardly see any extensions and really it is hard to find out anything from the generated HTML or even the HTML being sent out through the FORM tag .. is there another way to find out which scripting language was used in website!!! You can of course examine the HTTP headers but for example, one can easily hide this information: ServerSignature Off ServerTokens Prod Production sites usually do this because it is easier to attack the site if you know the platform, used extensions etc. The best thing you can do is to call the maintainer of the site and ask. :-) Regards, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory problem
Rolf Wester wrote: Diez B. Roggisch wrote: Rolf Wester wrote: I have a strange (for me) memory problem. When running a loop in a Python program memory usage increases from about 4% up to 100%. I do a gc.collect() every loop cycle but this doesn't help. There are about 67000 objects that are tracked by the garbage collector. This number does vary a little bit but does not increase on average whereas the memory usage does. The number of garbage objects (len(gc.garbage()) is zero. This is a very severe problem for my application, so I would be very appreciative for any help. well, it might be that the relative moon humidity resonates with the loop-cycle, creating quantum-flux in the main memory banks. Sorry, of course your are wright. I'm running Python2.5 on Linux, my program imports numpy, matplotlib, sys and a python module of my own. This module uses numpy and scipy.weave for imbedded C-code but no extension modules. I though the code to be to large to show, I hoped you could give me hint on what I could try. I think it is now safe to say that the embedded C code is a more likely culprit than the relative humidity of the moon... If you have python prototypes for the C chunks you could temporarily put them back in. Otherwise it is time to start stripping down the code until you can isolate the problem -- or at least have something you can post here. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: how to figure out if python was used as a cgi script
ce wrote: is there a way to figure out which scripting language was used in a cgi. I used to watch extensions (i.e. py, pl, asp or php) I'd say that ASP and PHP are rather rarely used for CGI scripts. Also, extensions are essentially meaningless. nowadays i hardly see any extensions and really it is hard to find out anything from the generated HTML or even the HTML being sent out through the FORM tag .. is there another way to find out which scripting language was used in website!!! Since this is a Python NG I suspect you have something you'd like to achieve using Python regarding this topic. What is it? Sorry I couldn't resist ? Regards, Björn -- BOFH excuse #413: Cow-tippers tipped a cow onto the server. -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyInkblot - Creating Rorschach Inkblots using Genetic Algorithms
Hi All, I've been working on a 'toy' application for the past month or so called PyInkblot. Simply mirroring a random plotting of half of a grid onto the second half, you can create pictures that look 'organic' like Rorschach Inkblot's. PyInkblot uses pygene for the Genetic Algorithm backend and pygame to draw the 'organisms' onto the screen. The user selects 0 or more (up to 6) of the organisms to go into a new population, more organism's will be added until there is 6 in the new population. Then a new generation is created using this population. To be able to try out PyInkblot you need the following packages * pygame1.8.0 * pygene0.2.1 * python2.4 and PyInkblot can be downloaded from http://code.google.com/p/pyinkblot/ Please provide feedback/criticism/tips ! Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Resolving declaring class of a method at runtime
Janne Härkönen [EMAIL PROTECTED] wrote: $ python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type help, copyright, credits or license for more information. class X: ... def x(self): ...pass ... class Y(X): ... def y(self): ...pass ... y = Y() y.x.im_class class __main__.Y at 0x7ff24bfc y.y.im_class class __main__.Y at 0x7ff24bfc What I would like to find out is the declaring class of method x, ie. class X How to do this ? For what it is worth, this should work for simple cases: def searchclass(K, name): for base in getattr(K, '__mro__', (K,)+K.__bases__): if name in base.__dict__: return base searchclass(Y, 'y') class __main__.Y at 0x00C4FE40 searchclass(Y, 'x') class __main__.X at 0x00C4FE70 -- http://mail.python.org/mailman/listinfo/python-list
Movement recognition in video file
Hi, I am looking for a python tool or module that helps me build a script that can perceive object moves in a video file captured by a (web) camera. My main goal is to be able to count people entering a store using the store's surveillance camera. I know of some packages like Eyesweb (gestural recognition package) or Pure Data's module called GEM, but I don't know any written in python. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: why there is no pythonscript insine web browsers?
Piet == Piet van Oostrum [EMAIL PROTECTED] writes: Piet CGI is server-side. The OP was asking for client-side Piet embedding of Python. FireFox 3 aka Gran Paradiso can be compiled to have python scripting but for security reasons it can be used only on crome:// urls, which load local content. there is an xpi package that can be installed on Gran Paradiso alphas: http://vamposdecampos.googlepages.com/pyxpcom -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyInkblot - Creating Rorschach Inkblots using Genetic Algorithms
I suspect you could make it visually far more interesting if you replaced the colored pixels with colorful images, and mapped the images on a grid using Flash. -- http://mail.python.org/mailman/listinfo/python-list
Re: Resolving declaring class of a method at runtime
Janne Härkönen wrote: class X: ... def x(self): ...pass ... class Y(X): ... def y(self): ...pass ... y = Y() y.x.im_class class __main__.Y at 0x7ff24bfc y.y.im_class class __main__.Y at 0x7ff24bfc What I would like to find out is the declaring class of method x, ie. class X How to do this ? The general idea of OOP is to not have to do this. I suspect you have a problematic design. What's the problem you try to solve? Regards, Björn -- BOFH excuse #105: UPS interrupted the server's power -- http://mail.python.org/mailman/listinfo/python-list
Re: Movement recognition in video file
[EMAIL PROTECTED] wrote: Hi, I am looking for a python tool or module that helps me build a script that can perceive object moves in a video file captured by a (web) camera. My main goal is to be able to count people entering a store using the store's surveillance camera. I know of some packages like Eyesweb (gestural recognition package) or Pure Data's module called GEM, but I don't know any written in python. These kinds of tasks require massive computational efforts and thus usually are the domain of more performant languages - like C. A great library for that is Intel's OpenCV. And incidentially Gary Bishop has some nice ctypes-bindings for OpenCV. http://wwwx.cs.unc.edu/~gb/wp/blog/2007/02/04/python-opencv-wrapper-using-ctypes/ Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 14, 6:26 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: Someone please summarize. Yes, that would be good. On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Turning garbage collection off doesn't help. -- Steven. criminy... Any root cause? patch? btw, I think I've seen this, but I think you need to get into 10s of megs or more before it becomes critical. Note: I know someone will say don't scare off the newbies but in my experience most Python programmers are highly experienced professionals who need to know this sort of thing. The bulk of the newbies are either off in VB land or struggling with java. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=silly+walk -- http://mail.python.org/mailman/listinfo/python-list
logging.SocketHandler connections
Hi folks, I'm writing some fairly simple logging code that makes use of the SocketHandler. The example server code works fine, as expected. (http:// docs.python.org/lib/network-logging.html) However, initially, I had tried it with a server that closed the connection after receiving each record, and the SocketHandler doesn't seem to behave as advertised. My test script was simply this: #!/usr/bin/python import logging import logging.handlers import time import sys port = 12345 handler = logging.handlers.SocketHandler('localhost', port) l = logging.getLogger(my-logger) l.addHandler(handler) l.addHandler(logging.StreamHandler(sys.stdout)) l.setLevel(logging.DEBUG) for i in xrange(10): l.info(Log message %i, i) time.sleep(1) My test server received messages 0, 3, 6 and 9. Doing a packet capture with wireshark confirmed that it only made 4 connections. The SocketHandler documentation says that it will re-establish the connection if it has been closed. After a bit of digging, I found a patch had been submitted and accepted that made it back off exponentially. However, this should be time based. Even if I make my sleep here 30 seconds, my server still only receives messages 0, 3, 6 and 9. I'm concerned that if a connection is lost at some point, I will always lose at least 2 log messages. Is there some reason for this that I am not aware of? Have I misunderstood something, or is this a bug? -Oliver -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Tkinter scrollbar
On Wednesday 14 November 2007 18:22, [EMAIL PROTECTED] wrote: I want to create a custom scrollbar using particular images, which will then be placed on a canvas to control another window on the canvas. Right now I am inheriting from scrollbar, but I do the movement with custom functions. When I create it and put in into the canvas with canvas.create_window a standard scrollbar shows in the correct spot and my custom one is outside of the canvas. All I have right now is something that moves like a scrollbar but has no effect on other objects. Can anyone give me some advice or point me to a guide for this? Is it even possible? Can I create a widget that mimics a scrollbar, or would that be more difficult? I have been unable to find anything online and would appreciate any help. Sounds to me that you want a navigation window for a chosen image. Gimp imaging program has such a window. Check out how gimp works with multiple images. You might want to work with a toolbar that opens a navigation window for each image. For an explanation on how scrolling works check out a book by O'Reilly written by Mark Lutz, Programming Python, look up programming scrollbars. jim-on-linux http://www.inqvista.com -- http://mail.python.org/mailman/listinfo/python-list
formated local time
I have been trying to find appropriate way to do get local time in -mm-dd hh:mm:ss format, but the best I got is this: datetime.datetime.fromtimestamp(time.mktime(time.localtime())) It seems to me I'm missing a much simpler method, am I? -- Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams -- http://mail.python.org/mailman/listinfo/python-list
Re: Volume id
OK, you are right... Problem was not precise enough. I need to process CDs to create a list. Does it ring a bell for you? Thanks 2007/11/15, Laszlo Nagy [EMAIL PROTECTED]: Gabor Urban wrote: Hi, I have a problem, which may be trivial, but I could not find an answer. I have to write a Python script, which does a directory tree walking on given mounted disk. But I do need to extract the volume id, somehow. And that's the problem. An additional issue, the script will be used on unix type systems, and on MS XP or Vista, too Any ideas are wellcome. I believe (although not 100% sure) that volume id always belongs to a FAT partition (maybe an NTFS partition?). When you format a partition, it will give you a - hopefully unique - volume identifier. I don't think that unix partitions (like reiserfs, ext2, ext3, ufs2 etc.) has that identifier. I may be wrong, others will probably correct me. Do you want to know the identifier (serial number?) of the disk device instead? E.g. not the partition but the hard disk? Can you list the platforms/operating systems where you want to use your program? It might help to look at the documentation/source code or the various hardware diagnostic utilities. Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
RE: formated local time
datetime also has the strftime method: import datetime datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') - Adam -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Thursday, November 15, 2007 9:56 AM To: python-list@python.org Subject: Re: formated local time On Nov 15, 7:19 am, Nikola Skoric [EMAIL PROTECTED] wrote: I have been trying to find appropriate way to do get local time in -mm-dd hh:mm:ss format, but the best I got is this: datetime.datetime.fromtimestamp(time.mktime(time.localtime())) It seems to me I'm missing a much simpler method, am I? If you want the formatted string, you can use strftime: time.strftime(%Y-%m-%d %H:%M:%S) '2007-11-15 07:51:12' -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: why there is no pythonscript insine web browsers?
On Nov 14, 9:42 am, Piet van Oostrum [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] (k) wrote: k On Nov 12, 12:07 pm, Timuçin K z lay [EMAIL PROTECTED] wrote: I'm an old programmer coming from a cobol background and started to learn python. I'm using javasript for web based applications but after I started to learn python, the javascript language started to seem ugly to me. Now I'm wondering why there is java support on web browsers but no python support? there is even a vbscript support inside MS-IE but there is no python support. it would be really nice and easy for me to use python instead of javascript to write those ajax scripts. Please tell me, is there a python substitude for JRE ? k You can also use Python's cgi module. It's pretty cool, from what I've k read: CGI is server-side. The OP was asking for client-side embedding of Python. -- Piet van Oostrum [EMAIL PROTECTED] URL:http://www.cs.uu.nl/~piet[PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] Oh...oops...mis-read again. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGilState_Ensure interrupts python critical sections
On Nov 15, 2007 4:50 AM, [EMAIL PROTECTED] wrote: Many thanks for the clarification. Also good idea to focus on lock ownership rather that thread activity in your diagram. To be honest I was not actually experiencing deadlock issues. I had just deduced (incorrectly) that I might do so if I started using locks in my py code called from c-land. As I was suffering some horrible race-condtions that had suddenly appeared in code that had been perfectly stable for the past 6 months I didn't want to go down that route given my misconceptions; Even if introducing the locks worked I'd always feel it was a deadlock waiting to happen. A good reason to avoid the threading metaphor for concurrency entirely ;) Misunderstanding arose as for some reason I had decided that python code called from C did not allow any other python threads to run until control had returned to C and the gil had been released from C-land. I.e. once the gil was given to the C thread then python had to wait until it was given back. This is essentially true. The part you're missing is that some Python functions themselves release the GIL and call into C - in this case, it's blocking on a lock. Some other functions that do this including blocking on file or (especially) socket IO. If this didn't happen, it'd be pretty much impossible to mix Python threads and C threads in any safe manner - the deadlock situation you envisioned would be a very common reality. I have to say the docs could be a little more explicit on the mechanisms involved. They tend to be better at stating what individual functions do rather that giving overall explanations. Maybe I'll get around to submitting a chapter on it ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: formated local time
On Nov 15, 7:19 am, Nikola Skoric [EMAIL PROTECTED] wrote: I have been trying to find appropriate way to do get local time in -mm-dd hh:mm:ss format, but the best I got is this: datetime.datetime.fromtimestamp(time.mktime(time.localtime())) It seems to me I'm missing a much simpler method, am I? If you want the formatted string, you can use strftime: time.strftime(%Y-%m-%d %H:%M:%S) '2007-11-15 07:51:12' -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedded Python - Blocking Python Function
On Nov 14, 4:20 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: Not forcibly - you need some cooperation from the Main function. Maybe setting a global variable that Main checks periodically. Thanks. I'll give that a try! Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 14, 6:26 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Turning garbage collection off doesn't help. Fwiw, Testing on a 2 cpu 64 bit machine with 1gb real memory I consistently run out of real memory before I see this effect, so I guess it kicks in for dicts that consume beyond that.That's better than I feared at any rate... -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=especially+nasty+windows -- http://mail.python.org/mailman/listinfo/python-list
Re: Volume id
On Nov 15, 10:21 am, Tim Golden [EMAIL PROTECTED] wrote: Gabor Urban wrote: OK, you are right... Problem was not precise enough. I need to process CDs to create a list. Does it ring a bell for you? On Windows, at least, you can do this with WMI: code import win32com.client wmi = win32com.client.GetObject (winmgmts:) for result in wmi.ExecQuery ( SELECT VolumeSerialNumber FROM Win32_LogicalDisk WHERE DriveType=5 ): print result.Properties_ (VolumeSerialNumber) /code If you do anything non-trivial with WMI, I cough recommend my WMI module: http://timgolden.me.uk/python/wmi.html TJG I recommend Tim's module too. Using the win32 module's directly is usually much more complicated. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 14, 2007 5:26 PM, Steven D'Aprano [EMAIL PROTECTED] wrote: On Wed, 14 Nov 2007 18:16:25 +0100, Hrvoje Niksic wrote: Aaron Watters [EMAIL PROTECTED] writes: On Nov 12, 12:46 pm, Michael Bacarella [EMAIL PROTECTED] wrote: It takes about 20 seconds for me. It's possible it's related to int/long unification - try using Python 2.5. If you can't switch to 2.5, try using string keys instead of longs. Yes, this was it. It ran *very* fast on Python v2.5. Um. Is this the take away from this thread? Longs as dictionary keys are bad? Only for older versions of Python? It sounds like Python 2.4 (and previous versions) had a bug when populating large dicts on 64-bit architectures. No, I found very similar behaviour with Python 2.5. Someone please summarize. Yes, that would be good. On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Turning garbage collection off doesn't help. I can't duplicate this in a dual CPU (64 bit, but running in 32 bit mode with a 32 bit OS) system. I added keys to a dict until I ran out of memory (a bit over 22 million keys) and deleting the dict took about 8 seconds (with a stopwatch, so not very precise, but obviously less than 30 minutes). d = {} idx = 0 while idx 1e10: ... d[idx] = idx ... idx += 1 ... Traceback (most recent call last): File stdin, line 2, in module MemoryError len(d) 22369622 del d -- http://mail.python.org/mailman/listinfo/python-list
Re: Movement recognition in video file
On Nov 15, 8:29 am, [EMAIL PROTECTED] wrote: Hi, I am looking for a python tool or module that helps me build a script that can perceive object moves in a video file captured by a (web) camera. My main goal is to be able to count people entering a store using the store's surveillance camera. I know of some packages like Eyesweb (gestural recognition package) or Pure Data's module called GEM, but I don't know any written in python. Thanks You could use something like PyMedia to iterate the frames in the video, then process the image using something like PIL or numpy. Other possibilities might include gstreamer, or any other multimedia library that has python bindings. Depending on your exact needs, python may be too slow for the guts of the algorithm, but certainly could be used for prototyping and/or glue code. I've used PyMedia with both PIL and numpy to do some video processing in the past. If you need help getting started, just ask. --Nathan Davis -- http://mail.python.org/mailman/listinfo/python-list
Printing user input?
Hi, I'm v.new to Python, so please don't be too harsh :) I get a NameError with the code below - All I want to do is store some input taken from the user in a variable called name, then print name # START CODE == # Print name demo def PersonsDetails(): name = input(What's your name?) PersonsDetails() print(name) # END CODE == Thanks for reading any help on this -- http://mail.python.org/mailman/listinfo/python-list
Re: Volume id
Gabor Urban wrote: OK, you are right... Problem was not precise enough. I need to process CDs to create a list. Does it ring a bell for you? On Windows, at least, you can do this with WMI: code import win32com.client wmi = win32com.client.GetObject (winmgmts:) for result in wmi.ExecQuery ( SELECT VolumeSerialNumber FROM Win32_LogicalDisk WHERE DriveType=5 ): print result.Properties_ (VolumeSerialNumber) /code If you do anything non-trivial with WMI, I cough recommend my WMI module: http://timgolden.me.uk/python/wmi.html TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: SPAM
Lew [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] just bob wrote: John Bean [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Wed, 14 Nov 2007 11:04:35 -0800, just bob [EMAIL PROTECTED] wrote: Your SPAM appears to be non-existent. Vapourware. Not real. Shame, I fancied a Spam fritter. The guy gets Google dollars when people view the site or click on links, me thinks. It's spam. Yes, but it's not SPAM. SPAM is a registered trademark of Hormel Foods Corporation for a canned pork product. Spam is unwanted messages or email. Or SPAM , is me shouting an alert for spam. -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing user input?
On Nov 15, 11:03 am, Mohammed_M [EMAIL PROTECTED] wrote: Hi, I'm v.new to Python, so please don't be too harsh :) I get a NameError with the code below - All I want to do is store some input taken from the user in a variable called name, then print name # START CODE == # Print name demo def PersonsDetails(): name = input(What's your name?) PersonsDetails() print(name) # END CODE == Thanks for reading any help on this It's a scope issue. You have the variable, name, inside a function and then you try to reference it outside the function, where it is not defined. Thus, Python gives an error. To fix this, put the print statement in the function itself...and when you use print, you don't usually put the object to be printed in parentheses. def PersonsDetails(): name = input(What's your name?) print name PersonsDetails() See also this article on scopes and namespaces: http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html or http://www.diveintopython.org/html_processing/locals_and_globals.html Hope that helps some. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing user input?
On Thu, 2007-11-15 at 09:03 -0800, Mohammed_M wrote: Hi, I'm v.new to Python, so please don't be too harsh :) I get a NameError with the code below - All I want to do is store some input taken from the user in a variable called name, then print name # START CODE == # Print name demo def PersonsDetails(): name = input(What's your name?) PersonsDetails() print(name) # END CODE == Thanks for reading any help on this You will need to return the input from the function. def PersonsDetails(): return raw_input(What is your name? ) name = PersonsDetails() print name Notice that in your code the variable name is created inside the function PersonsDetails(), so it is scoped to the function. This means that the variable is not accessible outside of PersonsDetails() and the attempt to print it with print(name) will fail. Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
RE: formated local time
You could use: import time time.strftime( %Y-%m-%d %H:%M:%S ) or time.strftime( %Y-%m-%d %H:%M:%S, time.localtime() ) Output: '2007-11-15 11:02:34' Both strftime calls are equivalent, in this case. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] ] On Behalf Of Nikola Skoric Sent: Thursday, November 15, 2007 8:20 AM To: python-list@python.org Subject: formated local time I have been trying to find appropriate way to do get local time in -mm-dd hh:mm:ss format, but the best I got is this: datetime.datetime.fromtimestamp(time.mktime(time.localtime())) It seems to me I'm missing a much simpler method, am I? -- Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
google earth / pythoncom
Hi, I'd like to write a python script to control Google Earth, and I've read that Google Earth provides a COM api, and that Python has a COM module 'pythoncom'. Anyone know where to get pythoncom from - as a separate module, because I'm using the Python application that comes with my GPS chip, from Telit :- http://www.telital.com/toru/TelitPy1_5_2+_v4_1.zip NB. this (I'm told) is a reduced version of Python that allows me to run 'EZPython' scripts on the GPS chip. The Python script I want to run to control Google Earth will be on the PC (WinXP) - so maybe I should install the 'normal/full' Python on the PC too - if that can be done ? Have 2 Pythons installed on one PC ? Any advice welcome. Thanks, john. -- http://mail.python.org/mailman/listinfo/python-list
Which uses less memory?
I'm not sure if this is as easy a question as I'd like it to be, but here goes I'm working on an application that is very memory intensive, so we're trying to reduce the memory footprint of classes wherever possible. I have a need for a class which is able to have a type identifier which can be examined at run-time to determine whether that class (called Domain) contains data I care about or not. I've thought of two ways to implement this: 1. Add a type attribute and set it to a descriptive string. 2. Create marker classes and use multiple inheritance to attach these markers to specific Domains. Here's the kicker: I need to serialize these Domains and send them to/ from Java code as well as work on them using Python. We're looking to use Hessian and pyactivemq to handle the Java/Python interfaces. Which, I guess, leads to the following group of questions: 1. Which method has the smaller footprint within the Python engine? 2. Do these protocols (Hessian and Stomp) preserve the class information when the class is serialized? Any input would be most welcome. Thanks! Bret Wortman -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Installer or Executable in Python
Shane Geiger [EMAIL PROTECTED] wrote: DanielJohnson wrote: I have a small project which has around 10 .py files and I run this project using command line arguments. I have to distribute this project to somebody. I was wondering how can I make an executable or some kind of installer, so that end user doesn't need to compile and worry if he/ she has Python installed or not ? A few candidate solutions: http://nsis.sourceforge.net/Main_Page http://www.jrsoftware.org/isinfo.php I've used py2exe and nsis quite a few times - works well. Note that py2exe can bundle your app into a single exe which you can just run which may be good enough (no need for an installer). -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing user input?
On Thu, Nov 15, 2007 at 09:03:26AM -0800, Mohammed_M wrote regarding Printing user input?: Hi, I'm v.new to Python, so please don't be too harsh :) I get a NameError with the code below - All I want to do is store some input taken from the user in a variable called name, then print name # START CODE == # Print name demo def PersonsDetails(): name = input(What's your name?) PersonsDetails() print(name) # END CODE == Thanks for reading any help on this -- http://mail.python.org/mailman/listinfo/python-list Also, you'll want to use raw_input() instead of input. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: Movement recognition in video file
Thanks guys, I will give those solutions a try! [EMAIL PROTECTED] escreveu: On Nov 15, 8:29 am, [EMAIL PROTECTED] wrote: Hi, I am looking for a python tool or module that helps me build a script that can perceive object moves in a video file captured by a (web) camera. My main goal is to be able to count people entering a store using the store's surveillance camera. I know of some packages like Eyesweb (gestural recognition package) or Pure Data's module called GEM, but I don't know any written in python. Thanks You could use something like PyMedia to iterate the frames in the video, then process the image using something like PIL or numpy. Other possibilities might include gstreamer, or any other multimedia library that has python bindings. Depending on your exact needs, python may be too slow for the guts of the algorithm, but certainly could be used for prototyping and/or glue code. I've used PyMedia with both PIL and numpy to do some video processing in the past. If you need help getting started, just ask. --Nathan Davis -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 14, 6:26 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Please don't propagate this nonsense. If you see this then the problem exists between the chair and monitor. There is nothing wrong with neither creating nor deleting dictionaries. i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedded Python - Blocking Python Function
On Nov 15, 9:43 am, [EMAIL PROTECTED] wrote: On Nov 14, 4:20 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: Not forcibly - you need some cooperation from the Main function. Maybe setting a global variable that Main checks periodically. Thanks. I'll give that a try! Andy It works but the problem is that the script will be written by the end user. If they make a mistake and the cancel flag isn't perodically checked then it seems I have no way of cleanly ending the interpreter. If I wait for a specific time after requesting the Main function stop I need to be able to kill the interpreter without a runtime error. Any ideas? Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: google earth / pythoncom
On Thu, 2007-11-15 at 18:09 +, John Walsh wrote: Hi, I'd like to write a python script to control Google Earth, and I've read that Google Earth provides a COM api, and that Python has a COM module 'pythoncom'. I think what you are looking for you can download from here: http://sourceforge.net/project/showfiles.php?group_id=78018 The main page is here: http://starship.python.net/crew/mhammond/win32/Downloads.html The Python script I want to run to control Google Earth will be on the PC (WinXP) - so maybe I should install the 'normal/full' Python on the PC too - if that can be done ? Have 2 Pythons installed on one PC ? You can have two python installations on one pc. You have to use the full path to the interpreter to get the one you want. Or, the first one it finds in your path will be used. HTH, Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 15, 2:11 pm, Istvan Albert [EMAIL PROTECTED] wrote: There is nothing wrong with neither creating nor deleting dictionaries. I suspect what happened is this: on 64 bit machines the data structures for creating dictionaries are larger (because pointers take twice as much space), so you run into memory contention issues sooner than on 32 bit machines, for similar memory sizes. If there is something deeper going on please correct me, I would very much like to know. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=alien+friend -- http://mail.python.org/mailman/listinfo/python-list
Python Design Patterns - composition vs. inheritance
In learning about design patterns, I've seen discussion about using inheritance when an object's relationship to another object is 'is-a' and composition when the relationship is 'has-a'. Since this is all new and I'm still learning, I was hoping someone can give me some pointers on best practices on applying these ideas. If my logic is incorrect on anything, please don't hesitate to tell me where I'm wrong - I'm completely open to any help offered. As a very simplified example, if I had two classes, Pet and Owner, it seems that I would not have Pet inherit from Owner, since a pet 'has an' owner, but not 'is an' owner. If this is correct, does my code below reflect this? I passed the owner object into the pet object's constructor - is this the right way to do it? Also, I've seen talk that ideally you shouldn't have too many dots in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? Thanks in advance to anyone who can share their experience with me - it's very appreciated. class Owner(object): def __init__(self): self.address = '123 Fake Street' def get_foo(self): return 'bar' class Pet(object): def __init__(self, owner): self.owner = owner def __getattr__(self, name): if name == 'address': return self.owner.address else: raise AttributeError, name def get_foo(self): return self.owner.get_foo() owner = Owner() pet = Pet(owner) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
As a very simplified example, if I had two classes, Pet and Owner, it seems that I would not have Pet inherit from Owner, since a pet 'has an' owner, but not 'is an' owner. If this is correct, does my code below reflect this? I passed the owner object into the pet object's constructor - is this the right way to do it? Yes. Of course there are other ways, establishing the connection later, and of course making the Owner know her pets. But your unidirectional, ctor-passed implementation is sensible. Also, I've seen talk that ideally you shouldn't have too many dots in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? No, that's certainly not a good idea. And I'm under the impression you misunderstood something there in the original lecture/explanation. The reason is simple: by adding these methods, you essentially extend Pet's knowledge as a class to what only its owner has to know. Which makes no sense. Why should pets know about addresses? Or cars? Or anything else that belongs to the owner only. Of course there are just reasons to create such delegation methods - if for example the property/method is of general interest to the Pet, but implemented by means of the owner. But I've got difficulties even to imagine such thing, at least in your actual example. Diez -- http://mail.python.org/mailman/listinfo/python-list
Python beginner!
Could someone please paste some program in wxPython that uses inharitance. I would be very thankfull. -- http://mail.python.org/mailman/listinfo/python-list
extension to idle to clear screen - but how to write to screen?
and here I thought I was going to finally be able to change the world AND contribute back to python with my amazing clear screen extension - but I can't get it to work. ;( Copying from ZoomHeight.py and someone else's clever print suggestion: - # My Clear extension: clear a window class Clear: menudefs = [ ('windows', [ ('_Clear', 'clear'), ]) ] def __init__(self, editwin): self.editwin = editwin def clear_event(self, event): for i in range(60): print -- It shows up as a menu item, but does not do anything. No output, nuffin. I did get some sort of 'no connection msg' playing around which leads me to believe that I can't really write to the window (at least not this simplistically)... Pointers? -- http://mail.python.org/mailman/listinfo/python-list
Insert image to a List box
I run the following code and got the error (I put a .gif file on the desktop) Traceback (most recent call last): File 11.py, line 25, in module for gifname in os.listdir(dirpath): OSError: [Errno 2] No such file or directory: '.\\Desktop\\' import os import Tkinter root = Tkinter.Tk() L = Tkinter.Listbox(selectmode=Tkinter.SINGLE) gifsdict = {} dirpath = '.\\Desktop\\' for gifname in os.listdir(dirpath): if not gifname[0].isdigit(): continue gifpath = os.path.join(dirpath, gifname) gif = Tkinter.PhotoImage(file=gifpath) gifsdict[gifname] = gif L.insert(Tkinter.END, gifname) L.pack() img = Tkinter.Label() img.pack() def list_entry_clicked(*ignore): imgname = L.get(L.curselection()[0]) img.config(image=gifsdict[imgname]) L.bind('ButtonRelease-1', list_entry_clicked) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
SMALLp wrote: Could someone please paste some program in wxPython that uses inharitance. I would be very thankfull. Please read this: URL:http://www.catb.org/~esr/faqs/smart-questions.html Then ask again. /W -- http://mail.python.org/mailman/listinfo/python-list
RE: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 15, 2:11 pm, Istvan Albert [EMAIL PROTECTED] wrote: There is nothing wrong with neither creating nor deleting dictionaries. I suspect what happened is this: on 64 bit machines the data structures for creating dictionaries are larger (because pointers take twice as much space), so you run into memory contention issues sooner than on 32 bit machines, for similar memory sizes. If there is something deeper going on please correct me, I would very much like to know. Since some people missed the EUREKA!, here's the executive summary: Python2.3: about 45 minutes Python2.4: about 45 minutes Python2.5: about _30 seconds_ The cut/paste of the EUREKA MOMENT from earlier in this thread: You can download the list of keys from here, it's 43M gzipped: http://www.sendspace.com/file/9530i7 and see it take about 45 minutes with this: $ cat cache-keys.py #!/usr/bin/python v = {} for line in open('keys.txt'): v[long(line.strip())] = True It takes about 20 seconds for me. It's possible it's related to int/long unification - try using Python 2.5. If you can't switch to 2.5, try using string keys instead of longs. Yes, this was it. It ran *very* fast on Python v2.5. Terribly on v2.4, v2.3. (I thought I had already evaluated v2.5 but I see now that the server With 2.5 on it invokes 2.3 for 'python'.) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Thu, 15 Nov 2007 11:11:57 -0800, Istvan Albert wrote: On Nov 14, 6:26 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Please don't propagate this nonsense. If you see this then the problem exists between the chair and monitor. There is nothing wrong with neither creating nor deleting dictionaries. Please read the whole thread before making unsupported statements like that. You should consider that this behaviour has been observed by multiple people, before making insulting statements. Both myself and the original poster have given code that demonstrates this problem. We've given concrete evidence of a problem which is replicable across different versions of Python and different versions of the Linux operating system. Unless you're accusing both myself and the original poster of outright lying, of faking our results, what's your explanation? Have you tried running our code on a 64-bit or multi-CPU system to see for yourself, or are you just being closed-minded and arrogant? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Thu, 15 Nov 2007 10:51:08 -0600, Chris Mellon wrote: I can't duplicate this in a dual CPU (64 bit, but running in 32 bit mode with a 32 bit OS) system. Can you try it running in 64-bit mode? What Python version are you running? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
Steven D'Aprano [EMAIL PROTECTED] writes: Someone please summarize. Yes, that would be good. On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Can you post minimal code that exhibits this behavior on Python 2.5.1? The OP posted a lot of different versions, most of which worked just fine for most people. -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Thu, 15 Nov 2007 15:51:25 -0500, Michael Bacarella wrote: Since some people missed the EUREKA!, here's the executive summary: Python2.3: about 45 minutes Python2.4: about 45 minutes Python2.5: about _30 seconds_ I'm really happy that upgrading to 2.5 solved the issue for you, but I get similar behaviour and I'm running 2.5, so it isn't as simple as that. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
On Nov 15, 8:57 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Please read this: URL:http://www.catb.org/~esr/faqs/smart-questions.html Then ask again. /W Give me back the old comp.lang.python, where anyone could ask anything and be sure of a range of replies, instead of this sort of pedanticism. Sorry, nothing personal, maybe Python users have become too professional and geeky to remember that Python's main objective is fun, that is why it is called Python. Telling the asker to go and learn how to ask properly is not fun, it reeks of arrogance, high handedness and rejection of newcomers. Nothing personal Wildemar, I have seen lots of others reply in a similar fashion. Am I alone in thinking this group has changed in these ways? Tony -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 15, 2007 2:57 PM, Steven D'Aprano [EMAIL PROTECTED] wrote: On Thu, 15 Nov 2007 10:51:08 -0600, Chris Mellon wrote: I can't duplicate this in a dual CPU (64 bit, but running in 32 bit mode with a 32 bit OS) system. Can you try it running in 64-bit mode? What Python version are you running? C:\python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. I can't switch to 64 bit right now. This is a dual Core 2 Duo machine (2 CPUs, 2 cores each). I've looked at the deallocation code for dict objects and I can't see anything that should be affected by 64 bitness, at least not nearly the degree described - it DECREFs all the keys and values in the dict, calls PyMem_Free on its memory pool (if it was large enough to be malloced, which this certainly was, and either adds itself back to the dict object pool or deallocs itself (if its a subclass of dict). -- http://mail.python.org/mailman/listinfo/python-list
Re: Resolving declaring class of a method at runtime
On Thu, 15 Nov 2007 13:01:27 +0200, Janne Härkönen wrote: Hello, Is there a simple way to resolve declaring class of a method at runtime ? Have you tried looking at dir(TheClass) to see what it lists? Also helpful is TheClass.__dict__.keys(). Python has powerful introspection abilities. Learn to use them, and you too will be able to impress your friends with your Python knowledge. class X: ... def x(self): ...pass ... X is an old style class. Most people probably shouldn't use old style classes, for various reasons. To use new style classes, you inherit from object: class X(object) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
RE: Populating a dictionary, fast [SOLVED SOLVED]
On Thu, 15 Nov 2007 15:51:25 -0500, Michael Bacarella wrote: Since some people missed the EUREKA!, here's the executive summary: Python2.3: about 45 minutes Python2.4: about 45 minutes Python2.5: about _30 seconds_ I'm really happy that upgrading to 2.5 solved the issue for you, but I get similar behaviour and I'm running 2.5, so it isn't as simple as that. Maybe some more details about my environment will help. Our fast Python is 2.5, built from source. Our slow Python is 2.3, default installed with the OS, from rpm. # python Python 2.5.1 (r251:54863, May 11 2007, 14:17:21) [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 Type help, copyright, credits or license for more information. # which python /usr/local/bin/python # ls -la /usr/local/bin/python -rwxr-xr-x 2 root root 5312572 Nov 12 12:54 /usr/local/bin/python # md5sum /usr/local/bin/python 5c24e54a6cf5a556e9371325d18bc1fb /usr/local/bin/python # ls -la /usr/bin/python* lrwxrwxrwx 1 root root9 Nov 12 12:57 /usr/bin/python - python2 lrwxrwxrwx 1 root root6 Nov 12 12:57 /usr/bin/python2 - python2.5 -rwxr-xr-x 1 root root 8344 May 2 2007 /usr/bin/python2.3 lrwxrwxrwx 1 root root 21 Nov 12 12:57 /usr/bin/python2.5 - /usr/local/bin/python # ls -la /usr/local/src/ | grep Python drwxr-xr-x 191000 1000 4096 Nov 12 12:54 Python-2.5.1 -rw-r--r-- 1 rootroot 9383651 Nov 12 12:51 Python-2.5.1.tar.bz2 # gcc -v Reading specs from /usr/lib/gcc/x86_64-redhat-linux/3.4.4/specs Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=x86_64-redhat-linux Thread model: posix gcc version 3.4.4 20050721 (Red Hat 3.4.4-2) # cat /etc/redhat-release CentOS release 4.2 (Final) # uname -a Linux xxx 2.6.9-22.ELsmp #1 SMP Sat Oct 8 21:32:36 BST 2005 x86_64 x86_64 x86_64 GNU/Linux # free total used free sharedbuffers cached Mem: 73902446961440 428804 0 155202549732 -/+ buffers/cache:43961882994056 Swap: 2096472 102802086192 # cat /proc/cpuinfo processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 5 model name : AMD Opteron(tm) Processor 246 stepping: 10 cpu MHz : 2009.305 cache size : 1024 KB fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext lm 3dnowext 3dnow bogomips: 3981.31 TLB size: 1088 4K pages clflush size: 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp processor : 1 vendor_id : AuthenticAMD cpu family : 15 model : 5 model name : AMD Opteron(tm) Processor 246 stepping: 10 cpu MHz : 2009.305 cache size : 1024 KB fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext lm 3dnowext 3dnow bogomips: 4014.08 TLB size: 1088 4K pages clflush size: 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp * information about Python 2.3 * # rpm -qi python Name: python Relocations: (not relocatable) Version : 2.3.4 Vendor: CentOS Release : 14.4 Build Date: Wed 02 May 2007 07:20:29 PM EDT Install Date: Mon 04 Jun 2007 05:48:29 PM EDT Build Host: builder6 Group : Development/Languages Source RPM: python-2.3.4-14.4.src.rpm Size: 21137194 License: PSF - see LICENSE Signature : DSA/SHA1, Sat 05 May 2007 09:33:49 AM EDT, Key ID a53d0bab443e1821 URL : http://www.python.org/ Summary : An interpreted, interactive, object-oriented programming language. Description : Python is an interpreted, interactive, object-oriented programming language often compared to Tcl, Perl, Scheme or Java. Python includes modules, classes, exceptions, very high level dynamic data types and dynamic typing. Python supports interfaces to many system calls and libraries, as well as to various windowing systems (X11, Motif, Tk, Mac and MFC). Programmers can write new built-in modules for Python in C or C++. Python can be used as an extension language for applications that need a programmable interface. This package contains most of the standard Python modules, as well as modules for interfacing to the Tix widget set for Tk and RPM. Note that documentation for Python is provided in the python-docs
Re: Python beginner!
On Nov 15, 2:38 pm, SMALLp [EMAIL PROTECTED] wrote: Could someone please paste some program in wxPython that uses inharitance. I would be very thankfull. Most examples of wxPython use inheritance. I would recommend going to their website and downloading the demo as it has lots of code to learn from. www.wxpython.org They also have a mostly helpful wiki here: http://wiki.wxpython.org/ Also see: http://zetcode.com/wxpython/ http://showmedo.com/videos/series?name=PythonWxPythonBeginnersSeries http://www.onlamp.com/pub/a/python/excerpts/chpt20/wxpython.html http://www.linuxjournal.com/article/3776 Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Insert image to a List box
On Nov 15, 12:45 pm, linda.s [EMAIL PROTECTED] wrote: I run the following code and got the error (I put a .gif file on the desktop) Traceback (most recent call last): File 11.py, line 25, in module for gifname in os.listdir(dirpath): OSError: [Errno 2] No such file or directory: '.\\Desktop\\' import os import Tkinter root = Tkinter.Tk() L = Tkinter.Listbox(selectmode=Tkinter.SINGLE) gifsdict = {} dirpath = '.\\Desktop\\' for gifname in os.listdir(dirpath): if not gifname[0].isdigit(): continue gifpath = os.path.join(dirpath, gifname) gif = Tkinter.PhotoImage(file=gifpath) gifsdict[gifname] = gif L.insert(Tkinter.END, gifname) L.pack() img = Tkinter.Label() img.pack() def list_entry_clicked(*ignore): imgname = L.get(L.curselection()[0]) img.config(image=gifsdict[imgname]) L.bind('ButtonRelease-1', list_entry_clicked) root.mainloop() The exception points to this line as being the issue: for gifname in os.listdir(dirpath): and the error says `No such file or directory: '.\\Desktop\\'' So, there must be no directory named '.\\Desktop\\' in your current working directory. To find out your current working directory use `os.getcwd()'. Make sure that `os.getcwd()' returns the path to a directory with a Desktop folder in it. This is usually something like 'C:\\Documents and Settings\\username'. Matt Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
On Nov 15, 8:38 pm, SMALLp [EMAIL PROTECTED] wrote: Could someone please paste some program in wxPython that uses inharitance. I would be very thankfull. HI SMALLp: welcome to Python! Here is a link that shows some basics of inheritance in Wx, try other searches on Google:) http://www.ibiblio.org/obp/py4fun/gui/wxPhone.html Hope this helps Tony -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
On Nov 15, 3:37 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Also, I've seen talk that ideally you shouldn't have too many dots in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? No, that's certainly not a good idea. And I'm under the impression you misunderstood something there in the original lecture/explanation. Having read lots of perspectives on OO style, it wouldn't surprise me if the OP understood the point perfectly. I.e., there probably are people out there who suggest that when you have something like this: mypet.owner.get_attributes() you should reverse-refactor it into something like this: mypet.get_owner_attributes() I would agree that the former is preferable, especially in cases like this one where the classes aren't really closely related. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
Yes. Of course there are other ways, establishing the connection later, and of course making the Owner know her pets. But your unidirectional, ctor-passed implementation is sensible. I think my main concern while getting my toes wet on this was to not reference the owner object out of thin air but to pass it in when pet is instantiated. I'm not sure what 'actor-passed' is yet, but it gives me something to search for and learn about. I'd love to see other/better/different implementations if anyone wants to enlighten me. What would a non-unidirectional (bidirectional?) look like or accomplish? Does that mean that in the example I provided, you could make the owner aware of their pets? That's something that is not available using inheritance, if I understand correctly. No, that's certainly not a good idea. And I'm under the impression you misunderstood something there in the original lecture/explanation. That wouldn't surprise me if I misunderstood it :) I've watched Alex Martelli's Google Tech talk a half-dozen times and it's only now starting to make sense. It's hard to apply some of the available material's examples to Python since a lot of the documentation I find is specific to implementations in lower-level languages and don't apply to Python. (such as the Strategy pattern?) My understanding was that using __getattr__ was either called delegation or a Command pattern, and this was hiding/encapsulating the specifics of the implementation. I'd like to be corrected if I'm wrong, or if I'm two blocks off Main Street with this. The reason is simple: by adding these methods, you essentially extend Pet's knowledge as a class to what only its owner has to know. Which makes no sense. Why should pets know about addresses? Or cars? Or anything else that belongs to the owner only. Of course there are just reasons to create such delegation methods - if for example the property/method is of general interest to the Pet, but implemented by means of the owner. But I've got difficulties even to imagine such thing, at least in your actual example. Yeah, I was struggling to come up with a decent example - a pet's address was about the best example of a delegated property I could think of. If someone has a better set of objects that make sense, let me know and I'll probably feel less foolish asking. Thanks for your help! It's truly appreciated. Scott -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Thu, 15 Nov 2007 21:51:21 +0100, Hrvoje Niksic wrote: Steven D'Aprano [EMAIL PROTECTED] writes: Someone please summarize. Yes, that would be good. On systems with multiple CPUs or 64-bit systems, or both, creating and/or deleting a multi-megabyte dictionary in recent versions of Python (2.3, 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, compared to seconds if the system only has a single CPU. Can you post minimal code that exhibits this behavior on Python 2.5.1? The OP posted a lot of different versions, most of which worked just fine for most people. Who were testing it on single-CPU, 32 bit systems. The plot thickens... I wrote another version of my test code, reading the data into a list of tuples rather than a dict: $ python slurp_dict4.py # actually slurp a list, despite the name Starting at Fri Nov 16 08:55:26 2007 Line 0 Line 100 Line 200 Line 300 Line 400 Line 500 Line 600 Line 700 Line 800 Items in list: 8191180 Completed import at Fri Nov 16 08:56:26 2007 Starting to delete list... Completed deletion at Fri Nov 16 08:57:04 2007 Finishing at Fri Nov 16 08:57:04 2007 Quite a reasonable speed, considering my limited memory. What do we know so far? (1) The problem occurs whether or not gc is enabled. (2) It only occurs on some architectures. 64 bit CPU seems to be common factor. (3) I don't think we've seen it demonstrated under Windows, but we've seen it under at least two different Linux distros. (4) It affects very large dicts, but not very large lists. (5) I've done tests where instead of one really big dict, the data is put into lots of smaller dicts. The problem still occurs. (6) It was suggested the problem is related to long/int unification, but I've done tests that kept the dict keys as strings, and the problem still occurs. (7) It occurs in Python 2.3, 2.4 and 2.5, but not 2.5.1. Do we treat this as a solved problem and move on? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
Steven D'Aprano [EMAIL PROTECTED] writes: (7) It occurs in Python 2.3, 2.4 and 2.5, but not 2.5.1. Do we treat this as a solved problem and move on? I'm not comfortable with this. Better to identify the cause for certain. I'll look at it sometime if I get a chance. I have some 64-bit multi-cpu machines I can try it on. -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Python Design Patterns - composition vs. inheritance
Sorry for the double post -- Forwarded message -- From: Matthieu Brucher [EMAIL PROTECTED] Date: 15 nov. 2007 23:38 Subject: Re: Python Design Patterns - composition vs. inheritance To: [EMAIL PROTECTED] [EMAIL PROTECTED] 2007/11/15, [EMAIL PROTECTED] [EMAIL PROTECTED]: In learning about design patterns, I've seen discussion about using inheritance when an object's relationship to another object is 'is-a' and composition when the relationship is 'has-a'. Another way to express this is to say : - inheritance when you want to reuse an interface - compositon when you want to reuse the implementation IIRC this is the approach of Bruce Eckel. Matthieu -- French PhD student Website : http://miles.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -- French PhD student Website : http://miles.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
On Nov 15, 2007 2:37 PM, Diez B. Roggisch [EMAIL PROTECTED] wrote: As a very simplified example, if I had two classes, Pet and Owner, it seems that I would not have Pet inherit from Owner, since a pet 'has an' owner, but not 'is an' owner. If this is correct, does my code below reflect this? I passed the owner object into the pet object's constructor - is this the right way to do it? Yes. Of course there are other ways, establishing the connection later, and of course making the Owner know her pets. But your unidirectional, ctor-passed implementation is sensible. Also, I've seen talk that ideally you shouldn't have too many dots in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? No, that's certainly not a good idea. And I'm under the impression you misunderstood something there in the original lecture/explanation. The reason is simple: by adding these methods, you essentially extend Pet's knowledge as a class to what only its owner has to know. Which makes no sense. Why should pets know about addresses? Or cars? Or anything else that belongs to the owner only. Of course there are just reasons to create such delegation methods - if for example the property/method is of general interest to the Pet, but implemented by means of the owner. But I've got difficulties even to imagine such thing, at least in your actual example. An example might be something like pet.has_foodbowl, which is implemented as self.owner.has_foodbowl_for(self). If you've got pets with more than one owner, it might be any(owner.has_foodbowl_for(self) for owner in self.owners) - certainly a candidate for an easy accessor in the Pet class. This is more an example of API convenience than it is any sort of general OO or type theory concept. Note that any time you do this sort of reverse binding you're codifying assumptions about your object model (by which I mean domain objects, rather than your inheritance hierarchy) into your code. I don't worry to much about is-a or has-a or any sort of strict class hierarchy or type system. I view inheritance, in Python, as a way of inheriting implementation and I do it when I want some other classes implementation and not otherwise. In other languages (not C++ family, but ML family) I think much more in terms of types and type systems, but in Python I stay pragmatic and flexible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
I think my main concern while getting my toes wet on this was to not reference the owner object out of thin air but to pass it in when pet is instantiated. I'm not sure what 'actor-passed' is yet, but it gives me something to search for and learn about. I meant ctor, short-hand for constructor. I'd love to see other/better/different implementations if anyone wants to enlighten me. What would a non-unidirectional (bidirectional?) look like or accomplish? Does that mean that in the example I provided, you could make the owner aware of their pets? That's something that is not available using inheritance, if I understand correctly. Its simple. class Owner(object): def __init__(self): self.pets = [] class Pet(object): def __init__(self, owner): self.owner = owner owner.pets.append(self) No, that's certainly not a good idea. And I'm under the impression you misunderstood something there in the original lecture/explanation. That wouldn't surprise me if I misunderstood it :) I've watched Alex Martelli's Google Tech talk a half-dozen times and it's only now starting to make sense. It's hard to apply some of the available material's examples to Python since a lot of the documentation I find is specific to implementations in lower-level languages and don't apply to Python. (such as the Strategy pattern?) My understanding was that using __getattr__ was either called delegation or a Command pattern, and this was hiding/encapsulating the specifics of the implementation. I'd like to be corrected if I'm wrong, or if I'm two blocks off Main Street with this. I don't know that talk. Maybe you can give us the link, so we can see for ourselves? There is no doubt about Alex' being a profound teacher of software design. But yet I think your example doesn't capture what you think he wanted to present. Delegation of course is a well-known pattern. It applies at circumstances that are manyfold, e.g. wehn you try create a proxy for purposes of tracking or filtering calls. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the function to evaluate code object returned byPyParser _SimpleParseString function?
Borse, Ganesh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Py_CompileString takes the source code from file, isn't it? No. | As can be seen from the syntax of this function: PyObject* Py_CompileString(char *str, char *filename, int start) I am rather sure that the filename param is the same as for the Python-level builtin function compile: compile( string, filename, kind[, flags[, dont_inherit]]) Compile the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('string' is commonly used). The filename is used for exception traceback messages. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyInkblot - Creating Rorschach Inkblots using Genetic Algorithms
On Nov 16, 1:47 am, SamFeltus [EMAIL PROTECTED] wrote: I suspect you could make it visually far more interesting if you replaced the colored pixels with colorful images, and mapped the I'm already planning of using images instead of coloured blocks. But first i want to try using a gradient from the left half of the grid to the middle, then from the middle to the right. images on a grid using Flash. I don't know about Flash. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
Steven D'Aprano [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | (7) It occurs in Python 2.3, 2.4 and 2.5, but not 2.5.1. | | Do we treat this as a solved problem and move on? If the problem was fixed accidentally as an undocumented by product of a patch aimed at something else, it might get similarly unfixed without triggering a test failure. So if someone pins down the problem source well enough to warn future maintainers in a comment or commit note, all the better. Otherwise, wait until a reversion happens, if ever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode: matching a word and unaccenting characters
On Nov 15, 12:21 am, Jeremie Le Hen [EMAIL PROTECTED] wrote: (Mail resent with the proper subject. Hi list, (Please Cc: me when replying, as I'm not subscribed to this list.) I'm working with Unicode strings to handle accented characters but I'm experiencing a few problem. The first one is with regular expression. If I want to match a word composed of characters only. One can easily use '[a-zA-Z]+' when working in ascii, but unfortunately there is no equivalent when working with unicode strings: the latter doesn't match accented characters. The only mean the re package provides is '\w' along with the re.UNICODE flag, but unfortunately it also matches digits and underscore. It appears there is no suitable solution for this currently. Am I right? [snip] You can match a single character with '\w' and then ensure that it isn't a digit or underscore with a negative lookbehind '(?![\d_])', so to match only words consisting of characters (in the sense you mean), use '\w(?![\d_]))+'. -- http://mail.python.org/mailman/listinfo/python-list
Redirecting sys.stdin
Can anyone tell me what I am doing wrong with the following code? When python 2.4 is embedded it crashes because of the assignment to stdin. import sys; class RedirectB: def readline(self): return bar; sys.stdin = RedirectB(); Thanks! Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedded Python - Blocking Python Function
En Thu, 15 Nov 2007 16:18:45 -0300, [EMAIL PROTECTED] escribió: On Nov 15, 9:43 am, [EMAIL PROTECTED] wrote: On Nov 14, 4:20 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: Not forcibly - you need some cooperation from the Main function. Maybe setting a global variable that Main checks periodically. It works but the problem is that the script will be written by the end user. If they make a mistake and the cancel flag isn't perodically checked then it seems I have no way of cleanly ending the interpreter. If I wait for a specific time after requesting the Main function stop I need to be able to kill the interpreter without a runtime error. Any ideas? You could use PyThreadState_SetAsyncExc - it's supposed to raise an exception in another thread. There is a Cookbook recipe using it here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 I've never actually used it, but I want to try it some day, so please report back your findings if you decide to use this function. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting sys.stdin
On Nov 15, 4:09 pm, [EMAIL PROTECTED] wrote: Can anyone tell me what I am doing wrong with the following code? When python 2.4 is embedded it crashes because of the assignment to stdin. import sys; class RedirectB: def readline(self): return bar; sys.stdin = RedirectB(); Seems the interpreter didn't like me using one class to redirect stdout and stderr and another class to redirect stdin. Sigh. Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: pyopenglcontext binaries for 2.5 on win32
On Nov 14, 7:42 pm, [EMAIL PROTECTED] wrote: On Nov 13, 12:03 am, gz [EMAIL PROTECTED] wrote: no, I don't have them... I need them :) I'd like to thank Giovanni Bajo for providing binaries for the various package dependencies, and geting me going with pyopengl. Unfortunately I only menaged to run a basic example, where there's no animation. The glwindow only get's redrawn when it's resized, moved... well generally redrawed as a window. I would greatly appreciate some hints, about how to process the gui events in the gl portion, and how to run a continous animation in wx + pyopengl? I suspect the whole thing would be way easier with pyopenglcontext, but I can't seem to find a binary for python 2.5 I can't get it to install with mingw and don't have vc currently installed. If someone has successfully built it, plesase share. Although, I think, an example of a running opengl spinning cube, embedded in some wx menu + buttons, capable of handling, say, mouse clicks in the glwindow, would work best for me. I'm not even that keen on wx. I choose it, purely, on the basis that wx is generaly brought up here frequenter than qt. (Didn't qt have some licensing change in the last few months that could potentially change that?) OK. I got OpenGLContext to compile on my home machine after some tinkering with numpy. I uploaded the resulting .exe to my web page at: http://www.pythonlibrary.org/python_modules.htm Let me know if it works for you. Mike Somehow I didn't get this uploaded correctly. It is now on the website and I also made note that it is approx. 2 MB in size. Sorry for the confusion. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing user input?
Thanks Mike, Lorenzo Cliff for your replies. I definately will be reading up on namespaces scopes. Thanks again guys :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Populating a dictionary, fast [SOLVED SOLVED]
On Nov 15, 4:11 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: Unless you're accusing both myself and the original poster of outright lying, of faking our results, what's your explanation? I don't attribute it to malice, I think you're simply measuring something else. You both must be having some some system setting that forces your application to swap disk. Do you really believe that you cannot create or delete a large dictionary with python versions less than 2.5 (on a 64 bit or multi- cpu system)? That a bug of this magnitude has not been noticed until someone posted on clp? Have you tried running our code on a 64-bit or multi-CPU system to see for yourself, the answer is: yes and yes, I see nothing out of the ordinary. i. -- http://mail.python.org/mailman/listinfo/python-list
PDF library
hi, I am looking for a python PDF library that starts with 'Q' ... I just found them somewhere in the internet but I can't find them now that I need it. Does someone knows this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
On Nov 15, 3:28 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: My response ended up being pretty long and heavy for a beginner, but you sound pretty smart. In learning about design patterns, I've seen discussion about using inheritance when an object's relationship to another object is 'is-a' and composition when the relationship is 'has-a'. I've never been a big fan of this rule, for two reasons. First of all, is a and has a aren't always used in the sense intended by this rule's inventor. To illustrate the confusion, take your Pet-Owner example. When you say A Pet has an Owner, the verb to have has the sense of to possess. But possession alone is *not* the right sense of to have to suggest using containment. (Note: I'm using containment to mean object X owns object Y. Referencing the object without owning it is not containment; it's just referencing.) The reciprocal relationship to has a is is a part of, and I rather prefer that way of putting it. The Pet has an Owner, but the Owner is not part of the Pet, so has a is being used in the wrong sense. OTOH, a Car has an Engine, and an Engine is part of a Car, so has a is being used in the right sense there. This is not to say containment is not the appropriate way to implement Pet-Owner in any case. If this program is Pet-centric, and the Owner exists only insofar as it is perceived by the Pet, containment might be right way. That's another point: sometimes external circumstances play a part in whether inheritance or containment or something else should be used. FWIW, my first stab at a Pet-Owner relationship would probably look something like this: class Family: def __init__(self,humans,pets): self.humans = humans self.pets = pets Note that a Family has Pets, and Pets are part of the Family, so containment would be a good idea for Family-Pet relationship. (The Pets and Humans would have a field referring back to the Family, and the pet could determine its owners that way.) A source of confusion with is a is that it doesn't necessarily imply a good inheritance relationship (aka Liskov substitutability). Consider a Rectangle class that has methods set_width() and set_height(). Should Square class inherit from Rectangle? A Square is a Rectangle, but it's not suitable as a subclass of Rectangle, because the width and height can't be set independently. You can't substitute a Square for a Rectangle and get reasonable behavior. Second reason I don't like is a and has a: They are misleading enough for concrete objects like Pets, Owners, Rectangles, and so on. But real programming is often done with abstract objects like SimulationContexts, EncryptedHTTPConnections, ItemSequencers, and FingerProtocols. Is-a and has-a relationships are not always clear for classes such as these. Also, I've seen talk that ideally you shouldn't have too many dots in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? I wouldn't worry about minimizing dots. If you find yourself often using a certain long expressions like self.owner.house.yard.grass_length you might want to delegate them on a case-by-case basis by writing methods like this: def get_home_grass_length(self): return self.owner.house.yard.grass_length But using getattr to do it automatically is tricky, error prone, and defeats the purpose of keeping seperate namespaces. OTOH, if you find yourself delving several dots deep a lot, it suggests that you need to refactor you code. Move some of the code from the shallower classes into the deeper classes, closer to the data it needs. Hope this helped and didn't confuse you even more. :) Good luck learning. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Interfaces.
Hi, Does anyone know what the state of progress with interfaces for python (last I can see is http://www.python.org/dev/peps/pep-0245/) I would argue that interfaces/(similar feature) are necessary in any modern language because they provide a way of separating the specification from the implementation of a module. I also had a new idea - when specifying the functionality of a module, it would be nice to combine examples of valid behaviour / some sort of testing. It might therefore be possible to combine unit testing with interfaces. What do you all think? Peter (new to python so be nice :) -- http://mail.python.org/mailman/listinfo/python-list
Re: no __len__ attribute in NodeList or the list base?
On Nov 15, 3:09 am, Hrvoje Niksic [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: i extract class object from an instance of NodeList (minicompat.py) like so PyObject *pclass = PyObject_GetAttrString( nodelistinsance, __class__); but PyObject_GetAttrString(pclass, __len__) returns NULL. Are you sure about that? my apologies for the false alarm. i was calling __len__ on Element rather than NodeList thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Interfaces.
On Nov 15, 8:55 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, Does anyone know what the state of progress with interfaces for python (last I can see ishttp://www.python.org/dev/peps/pep-0245/) I would argue that interfaces/(similar feature) are necessary in any modern language because they provide a way of separating the specification from the implementation of a module. I also had a new idea - when specifying the functionality of a module, it would be nice to combine examples of valid behaviour / some sort of testing. It might therefore be possible to combine unit testing with interfaces. What do you all think? Peter (new to python so be nice :) Status: Rejected If you really want an interface, make a class with methods that raise NotImplementedError. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCheck for a classes defined in python and user data in PyObject_HEAD
On Nov 1, 11:04 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 01 Nov 2007 22:13:35 -0300, [EMAIL PROTECTED] escribió: On Nov 1, 4:14 pm, [EMAIL PROTECTED] wrote: q#1: in C I want to check if a given PyObject is a xml.dom.minidom.Node (or a derivative). how do i extract a PyTypeObject for such a class? nevermind, i found an instance object that will work for me as long as i figure out where is the documentation beyond this: http://docs.python.org/api/instanceObjects.html on the data attrib access and extracting PyClassObject from it. classic_class = PyObject_GetAttrString( your_classic_instance, __class__) issue #2 I'm in a situation when i don't really need to extend python with any classes of my own but i do have extra luggage for the python data structures such as tuples, lists, dictionaries, etc on the c++ side. I see no place in PyObject_HEAD where i can stick a void* to my extra data. Assuming you can recompile all the extensions you use, you could insert your void* into _PyObject_HEAD_EXTRA and _PyObject_EXTRA_INIT i added two void pointers to head_extra and 0,0, to the extra_init. For some reason i get garbage in them from PyEval_EvalCode :-( (that's after i blew the build dir and rebuilt 2.4.4 from scratch so i don't think i have a bad build) -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCheck for a classes defined in python and user data in PyObject_HEAD
En Fri, 16 Nov 2007 00:27:42 -0300, [EMAIL PROTECTED] escribió: On Nov 1, 11:04 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 01 Nov 2007 22:13:35 -0300, [EMAIL PROTECTED] escribió: I'm in a situation when i don't really need to extend python with any classes of my own but i do have extra luggage for the python data structures such as tuples, lists, dictionaries, etc on the c++ side. I see no place in PyObject_HEAD where i can stick a void* to my extra data. Assuming you can recompile all the extensions you use, you could insert your void* into _PyObject_HEAD_EXTRA and _PyObject_EXTRA_INIT i added two void pointers to head_extra and 0,0, to the extra_init. For some reason i get garbage in them from PyEval_EvalCode :-( (that's after i blew the build dir and rebuilt 2.4.4 from scratch so i don't think i have a bad build) Can't you use instead the other approaches suggested on this thread? Like keeping a weakkey dictionary holding your additional attributes? Seems a lot safer to do that way. I've never changed that headers myself so I can't guarantee it works. Perhaps there are some assumptions somewhere in the code about a specific layout. But since _PyObject_HEAD_EXTRA is used in the debug build I think you should be able to add your own fields, at least in principle... Remember that this change invalidates ALL binaries for ANY library or extension you may be using. An additional check might be to change the Python release number to 2.9.9 or so, so none of your existing extensions can inadvertidely be used. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory problem
En Thu, 15 Nov 2007 10:10:06 -0300, Peter Otten [EMAIL PROTECTED] escribió: Rolf Wester wrote: Sorry, of course your are wright. I'm running Python2.5 on Linux, my program imports numpy, matplotlib, sys and a python module of my own. This module uses numpy and scipy.weave for imbedded C-code but no extension modules. I though the code to be to large to show, I hoped you could give me hint on what I could try. I think it is now safe to say that the embedded C code is a more likely culprit than the relative humidity of the moon... Sure; and among all things that could be wrong, I'd start checking the reference counts. Get it wrong by -1 and your objects suddenly dissapear; get it wrong by +1 and your objects will never be destroyed, demanding more and more memory like in this case. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Interfaces.
En Thu, 15 Nov 2007 22:55:13 -0300, [EMAIL PROTECTED] [EMAIL PROTECTED] escribió: Does anyone know what the state of progress with interfaces for python (last I can see is http://www.python.org/dev/peps/pep-0245/) You may be interested in PEP3119 http://www.python.org/dev/peps/pep-3119/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
implement random selection in Python
I need to implement a random selection algorithm which takes a list of [(obj, prob),...] as input. Each of the (obj, prob) represents how likely an object, obj, should be selected based on its probability of prob.To simplify the problem, assuming prob are integers, and the sum of all prob equals 100. For example, items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] The algorithm will take a number N, and a [(obj, prob),...] list as inputs, and randomly pick N objects based on the probabilities of the objects in the list. For N=1 this is pretty simply; the following code is sufficient to do the job. def foo(items): index = random.randint(0, 99) currentP = 0 for (obj, p) in items: currentP += w if currentP index: return obj But how about the general case, for N 1 and N len(items)? Is there some clever algorithm using Python standard random package to do the trick? Thanks, Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Interfaces.
Chris M wrote: On Nov 15, 8:55 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, Does anyone know what the state of progress with interfaces for python (last I can see ishttp://www.python.org/dev/peps/pep-0245/) I would argue that interfaces/(similar feature) are necessary in any modern language because they provide a way of separating the specification from the implementation of a module. I also had a new idea - when specifying the functionality of a module, it would be nice to combine examples of valid behaviour / some sort of testing. It might therefore be possible to combine unit testing with interfaces. What do you all think? Peter (new to python so be nice :) Status: Rejected Thank you for pointing out the obvious. But *truly* helpful would be insight into While at some point I expect that Python will have interfaces. Look for that sentence under the rejected part. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: implement random selection in Python
Bruza wrote: I need to implement a random selection algorithm which takes a list of [(obj, prob),...] as input. Each of the (obj, prob) represents how likely an object, obj, should be selected based on its probability of prob.To simplify the problem, assuming prob are integers, and the sum of all prob equals 100. For example, items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] The algorithm will take a number N, and a [(obj, prob),...] list as inputs, and randomly pick N objects based on the probabilities of the objects in the list. For N=1 this is pretty simply; the following code is sufficient to do the job. def foo(items): index = random.randint(0, 99) currentP = 0 for (obj, p) in items: currentP += w if currentP index: return obj But how about the general case, for N 1 and N len(items)? Is there some clever algorithm using Python standard random package to do the trick? Thanks, Ben This will not get you an A on your homework: x = [] [x.extend([i]*n) for (i,n) in items] random.choice(x) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Last chance for PyCon talk tutorial proposals!
Thanks to all the proposal authors so far, we have received lots of proposals for PyCon talks tutorials. But we'd like to have even more. Alas, the proposal submission deadline should have been set after a weekend, not before. So we have decided to extend the proposal submission deadline to Monday, November 19 at midnight (Chicago time). This gives you a *whole extra weekend* to write up your talk and tutorial ideas! If you've been procrastinating, stop! Get started on a proposal instead! See the call for conference talk proposals: http://us.pycon.org/2008/conference/proposals/ Topic ideas: http://wiki.python.org/moin/Talk_Subjects http://wiki.python.org/moin/PyCon2007/Feedback#head-e2dca74d1492e49fae11550e6cbc40fa18a17f40 See the call for tutorial proposals http://us.pycon.org/2008/tutorials/proposals/ Topic ideas from the PyCon 2007 feedback: http://wiki.python.org/moin/PyCon2007/Feedback/TutorialIdeas I hope to see (and hear) you at PyCon 2008! http://us.pycon.org -- David Goodger, PyCon 2008 Chair signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: evaluating object returned by PyParser_SimpleParseString fun ction
Thanks for this. TerryCompile the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). Can I call exec() or eval() as is from C or C++ program? What the equivalent calls for this in Python-C API? That's what I want to know. Regards, Ganesh == Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html == -- http://mail.python.org/mailman/listinfo/python-list