Re: Line segments, overlap, and bits
On Mar 26, 9:16 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: Sean Davis [EMAIL PROTECTED] writes: OR, NOT, etc.). Any suggestions on how to (1) set up the bit string and (2) operate on 1 or more of them? Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python. You could wrap something around the array module, or the bit vector objects from numarray, or use something like PyJudy (google for it). Or consider using something like a tree data structure that supports set operations, rather than a bitmap, if that's closer to what you're really trying to do. Keep it continuous. You're looking at holographic or specific on tree leaves. I can store a GPS a -lot- easier than words. Force impact from a direction? (Strong A, two Bs.) Record wind. Repose. On idle, broadcast at unique intervals, wait for something to do. (developmental reposition) I suppose you want perception in the medium, but I think a special mechanism is always more efficient. Can you have minispiders hand off instructions by rapid tactile contact? Dock incl. clock sync, dual transmit, undock, work. Sounds like modem (modulator/demodulator) and ATM. The DNA of an organism doesn't change over time, but it manages to perform multi-cellular operations. Each cell has its very own copy, read-only, of the whole's DNA. Can lightning bugs turn on and off instruction sets (exec, donotexec)? Mem. block: Yes 0 1 add 0001 Yes 0 2 add 0010 No 0 3 add 0011 Yes 0 4 add runs: ( add 1, add 2, add 4 ). Local can transmit modifications to neighbor sames. Local gradient is stronger, which takes us to chemical. There is no living model for bees that sync post-mortem live -- they get orders for the next day at dance. By the way, Queen bees, Workers and Drones have a developmental period of 16, 21, 24 days respectively. Conclude Workers are the special. Thing is, two adjacent cells in the animal body can vary pretty widely in trait. Stem cells can differentiate into a diverse range of specialized cell types. Is time a factor in response to mechanistic signal propogation. Make a uniform response to every signal, and you're a functional programmer. input f o output. -- http://mail.python.org/mailman/listinfo/python-list
Re: copy file over LAN
En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee [EMAIL PROTECTED] escribió: I have a file on another machine on the local network (my machine and local machines are on windows) and I want to copy it locally. Now the machine requires authentication and when I try to do a import shutil shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') and it gives me a IOError: [Errno 13] Permission denied: error, which I expect. How do I provide authentication to copy this file? Probably there are other ways, but the net use command looks easy enough. Execute net help use | more in a console to see the right syntax. Use the subprocess module to run the command from inside Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: copy file over LAN
Well, the solution seems to be something like (windows only) import os import os.path import shutil import sys import win32wnet def wnet_connect(host, username, password): unc = ''.join(['', host]) try: win32wnet.WNetAddConnection2(0, None, unc, None, username, password) except Exception, err: if isinstance(err, win32wnet.error): # Disconnect previous connections if detected, and reconnect. if err[0] == 1219: win32wnet.WNetCancelConnection2(unc, 0, 0) return wnet_connect(host, username, password) raise err if __name__ == '__main__': node = hostname dst = r'C:\temp\destination__' dst += node + r'.txt' wnet_connect(node,username,password) shutil.copyfile(r'\\' + node + r'\c$\temp\\al_lsf_log',dst) Gabriel Genellina wrote: En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee [EMAIL PROTECTED] escribió: I have a file on another machine on the local network (my machine and local machines are on windows) and I want to copy it locally. Now the machine requires authentication and when I try to do a import shutil shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') and it gives me a IOError: [Errno 13] Permission denied: error, which I expect. How do I provide authentication to copy this file? Probably there are other ways, but the net use command looks easy enough. Execute net help use | more in a console to see the right syntax. Use the subprocess module to run the command from inside Python. -- Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -- http://mail.python.org/mailman/listinfo/python-list
counting using variable length string as base
Hi, I'm fairly new to Python and to this list. I have a problem that is driving me insane, sorry if it seems simple to everyone, I've been fighting with it for a while. :)) I want to take a variable length string and use it as a base for counting, eg. given the string 'abc' the sequence would be: a b c aa ba ca ab bb cb ... ccc Basically I want to find every possible order of every combination. Its easy if you know how many characters there will be in your string (use nested for loops), but I am stuck with the variable length string. I think I have to use a generator but I'm not sure exactly how. Can anyone give me a pointer in the right direction? Thanks Daniel Browne -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.2.1 and select()
On Wed, Mar 26, 2008 at 07:11:15PM -0700, Noah Spurrier wrote: def set_nonblock(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) Then in the function, after calling popen: set_nonblock(io.fromchild.fileno()) set_nonblock(io.childerr.fileno()) Yay for smart people. You should still try Pexpect :-) As I recall there are also gotchas on the non-blocking trick. Well, you need to remember to read ALL the file descriptors (objects) that select() returns, and if you don't, your program will hang and spin... It might also be the case that if the child is using stdio functions for output, you'll need to set the buffering mode explicitly (which you can theoretically do, see below). Aside from that, there are none, and actually the problem with my program had nothing to do with stdio buffering modes. Pexpect is 100% pure Python. No extra libs to install. I looked at it, and (what I believe is) the very reason it manages to solve this particular problem is also the reason it won't work for me: it combines STDOUT and STDERR to one I/O stream. The reason I'm bothering with all this is because I need to keep them separate. Interestingly, were it not for that fact, I'm not sure that pexpect wouldn't still suffer from the same problem that plagued my original implementation. I had to drag out W. R. Stevens to remind myself of a few things before I continued with this discussion... Even though it forces the program to use line buffering, read() would still try to read until EOF, and if STDOUT and STDERR were separate files, it seems likely that it would eventually block reading from one file when the child program was sending its output to the other. The only way to prevent that problem, aside from non-blocking I/O, is to do a read(1) (i.e. read one character at a time), which will use silly amounts of CPU time. But mixing stdio and non-stdio functions is kind of funky, and I'm not completely sure what the behavior would be in that case, and couldn't quickly ind anything in Stevens to suggest one way or the other. Also, you could combine the streams yourself without using pexpect by having your subproc use the shell to redirect STDERR to STDOUT, or (if Python has it) using the dup() family of system calls to combine the two in Python [i.e. dup2(1,2)]. As far as I can tell, the whole pseudo terminal thing (though it definitely does have its uses) is a red herring for this particular problem... I also read (some of) the pexpect FAQ, and there are a number of incorrect statements in it, particularly in the section 'Why not just use a pipe (popen())? - a pipe, if programmed correctly, is perfectly fine for controlling interactive programs, most of the time. You will almost certainly need to use non-blocking I/O, unless your communicating programs are perfectly synchronized, or else you'll have I/O deadlocks. The only time a pipe isn't OK is where the program tries to use terminal services (e.g. writing to /dev/tty), in which case you will need a pseudo-terminal device (as the FAQ correctly points out with regard to entering passwords in SSH). - Any application which contains #include stdio.h does not necessarily make use of the stdio library (which isn't really a separate library at all, it's part of the standard C library). The file stdio.h is just a C header file which contains declarations of the prototypes for stdio-related functions, and various constants. It's often included in source files simply because it's so common to need it, or to make use of some constants defined there. You're only actually using stdio if you use stdio functions in your program, which are: printf, fopen, getc, getchar, putc, scanf, gets, puts, etc. In particular, open(), read() and write() are *not* stdio functions, and do *not* buffer I/O. They're Unix system calls, and the C functions by the same name are simply interfaces to those system calls. There is a kernel I/O buffer associated with all of the streams you will use them on, but this is not a stdio buffer. I have not checked Python's code, but based on its behavior, I assume that its read() function is a wrapper around the Unix read() system call, and as such it is not using stdio at all, and thus the stdio buffers are not relevant (though if the child is using stdio functions, that could be an issue). - The FAQ states: The STDIO lib will use block buffering when talking to a block file descriptor such as a pipe. This is only true *by default* and indeed you can change the buffering mode of any stdio stream using the setbuf() and setvbuf() stdio functions (though I don't know if Python provides a way to do this, but I assume it does). Since the python program is the one opening the pipe, it controls the buffering mode, and you have only to change it in your program, and
Re: counting using variable length string as base
On Mar 27, 1:15 am, Grimsqueaker [EMAIL PROTECTED] wrote: Hi, I'm fairly new to Python and to this list. I have a problem that is driving me insane, sorry if it seems simple to everyone, I've been fighting with it for a while. :)) I want to take a variable length string and use it as a base for counting, eg. given the string 'abc' the sequence would be: a b c aa ba ca ab bb cb ... ccc Basically I want to find every possible order of every combination. Its easy if you know how many characters there will be in your string (use nested for loops), but I am stuck with the variable length string. I think I have to use a generator but I'm not sure exactly how. Can anyone give me a pointer in the right direction? def cartesian_product(*args): Iterates over the Cartesian product of args[0], args[1], ... if not args: return elif len(args) == 1: for item in args[0]: yield (item,) else: for item in args[0]: for item2 in cartesian_product(*args[1:]): yield (item,) + item2 def string_cartesian_product(*args): return (''.join(combo) for combo in cartesian_product(*args)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Plugin framework - Overcomplicating things?
En Thu, 27 Mar 2008 01:50:56 -0300, [EMAIL PROTECTED] [EMAIL PROTECTED] escribió: All this comes to my question - am I overcomplicating this project? I can understand the use of something like the trac component system if I had multiple components and plugins that handled different areas of my project and different points of interaction, but I don't. I've got exactly one spot where I want to check all my plugins and hand off the message to which ever ones are looking for that command. As you said, it looks like you're really overengineering your design then. So really, should I even bother with trying to setup some framework for this or should I just be doing a simple loop over a directory, importing all the plugins and storing them in a list and then looping over them in the message handler to see which ones were looking for the command and letting them do their thing? That may be an option. You may want to setup a simple registry mechanism, so the plugin modules look like: ### begin niceplugin.py ### class AVeryNicePlugin(object): # or perhaps using a suitable base class def handle_message(self, message): ... from plugin import PluginRegistry PluginRegistry.register(AVeryNicePlugin) ### end niceplugin.py ### Your application scans a known directory for files ending in plugin.py and imports them; the modules register themselves any class (or classes), and at appropiate times the application calls some method(s) of the registered plugins. As an aside, if there is anyone who is an experience developer and designer and is willing to take some private correspondence, please let me know. I feel embarrassed for asking, but I've got a alot of questions that I don't want to litter this list with and would rather voice them in private. Why not? Get another free account, post using a pseudonym, and nobody will know that *YOU* were the guy that asked the most stupid question of the week :) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert latex-based docs written with Python 2.5 to 2.6 framework
On Mar 26, 1:37 pm, Michael Ströder [EMAIL PROTECTED] wrote: HI! I had a look on how Doc/ is organized with Python 2.6. There are files with suffix .rst. Hmm... I'm maintaing existing docs for python-ldap which I might have to convert to the new concept in the long run. What's the recommended procedure for doing so? Any pointer? Ciao, Michael. I found the original python docs converter here: http://svn.python.org/projects/doctools/converter/ Unfortunately it is very specific to the Python docs :) I did try to run it on python-ldap .tex files and I was partially successful. It has produced a skeleton of the docs in the new format. After couple of hours of manual conversion I got far enough to actually see some results. Whatever I did is definitely not in finished state but it could be a start. Send me an off-line email if you are interested in what I have got so far. Waldemar -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
That seems to give me the items in the list back in an iterator. Am I using it incorrectly? -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
On Mar 27, 2:33 am, Grimsqueaker [EMAIL PROTECTED] wrote: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? Use list( it ). -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: Am Mittwoch, 26. März 2008 19:04:44 schrieb David Anderson: HOw can we use express pointers as in C or python? There's no such thing as a pointer in Python, so you can't express them either. Was this what you were trying to ask? But if you really need then, you can fake them: memory = [None]*10 # get a pointer to a memory location ptr = 5 # and assign a function there memory[ptr] = lambda s: '$' + s + '$' assert memory[ptr]('hello') == '$hello$' # store a pointer to a pointer memory[3] = ptr assert memory[memory[3]]('bye') == '$bye$' In Python this is a silly trick, not worth doing because there are better ways to solve problems that other languages use pointers for. But in older languages like Fortran, before they gained pointers, this was a standard method for getting pointers into a language without pointers. Thank goodness those days are long-gone! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
do 'os.path' include 'os' for us?
Hi, I wrote a python script to list files in a directory but somehow did it wrongly by importing os.path instead of os. To my astonishment, it works just as charm: #!/usr/bin/python import os.path for file in os.listdir('/root/'): print file I was wondering why? os.path doesn't contain listdir, why there is no complaint like 'os: unknown name'? Does this mean, instead of importing os, we can import os.path? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
Grimsqueaker schrieb: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? No. Just put a list() around it. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: last mouse movment or keyboard hit
Ron Eggler schrieb: Hi, I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? Try hooking yourself into the OS screen-saver-code. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: do 'os.path' include 'os' for us?
On Mar 27, 6:41 pm, Jerry Fleming [EMAIL PROTECTED] wrote: Hi, I wrote a python script to list files in a directory but somehow did it wrongly by importing os.path instead of os. To my astonishment, it works just as charm: #!/usr/bin/python import os.path for file in os.listdir('/root/'): print file I was wondering why? os.path doesn't contain listdir, why there is no complaint like 'os: unknown name'? Does this mean, instead of importing os, we can import os.path? import os.path in effect imports os, and then os.path, and injects the latter into the former as an attribute. If it didn't, then when you tried to use (say) os.path.join, it would raise an exception. Why don't you do some experimentation at the interactive prompt e.g. import os.path type(os) dir(os) a = os a.path a = nonesuch # The above will show you what the actual meesage is instead of complaint like 'os: unknown name' :-) HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: genetic algors in practical application
On Mar 26, 9:55 pm, [EMAIL PROTECTED] wrote: I want to go in to construction. However, 'I' means 'newsgroup' and 'want to go' means 'is'. If you had an army of two-micron spiders, could we build something? Use case is an American skyscraper. They have powerful tricks. Clearly they can withstand a force. These can withstand more combined, greater-than-minimum. What is their command set? Braid. Hoist. Vine power and waste. Charge, double-pump circuit. Round-trip a dollar. I said round. (What's the square trip.) You do know that the brain has seven trillion atoms, right? Mass of water. You know, combine 'muscle fiber' with 'inhibition, excitation' and 'motor neuron circuit', and you might be on to something, and you might be right. Here's free from Neuro. 'Each motor neuron synapses with multiple muscle fibers. .. Cross section through the muscle shows the distribution of muscle fibers (red dots) contacted by the motor neuron.' Power-- Tools. Note that 'synapse' verb. Written English folks. 'myelin debris' too. Is your concern the actual construction of the nanospiders (interesting side note), or programming it? Get a team of programmers too. Who asked for the 'Python d.j. console'? Did -uuu- put that on line. I'd like to destruct a little English: pose, L., from pause. compose, depose, (de-com-pose?), dispose, expose, impose, opose, prepose, propose, repose, transpose, suppose. Stack a structure is a really useful operation. If structures are all guaranteed to compose with one another (is this generators?), you can pop several off, add yours, and push several on. But, where functions are structures, could leave several information. Sometimes I call my generator twice. I'm a GA, q.e.d. Do I correctly read, 'decline to use send and return of yield'? (Can't be right; it's in there; what do you use it?) What are you guys sending generators? I think a successful machine takes-impressions the environment, and recomposes it: digest, regest, repose. Three cells interface, tower- of-hanoi each other, and on their way. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to dynamically create class methods ?
On Wed, 26 Mar 2008 00:27:17 -0700, Arnaud Delobelle wrote: I'm hardly surprised. The naivety of those who insist that the best way to understand how new.function and new.code work is to look at the C source code for object is amusing. Since 'those who insist...' are just one person, me, you might as well name them. Firstly I didn't 'insist', I stated it once. Secondly I'm glad that I provided you with a few chuckles, but to proclaim that one is 'amused by the naivety of others' doesn't make one automatically right. Your criticism is accepted. You're not the only person who says Read the C source, so I wasn't pointing the finger at just you. Do you know how these functions behave? Have you looked at their documentation? new.function and new.code (implemented as Objects/ funcobject.c:func_new and Objects/codeobject.c:new_code) are not really documented (new.code.__doc__ is 'Create a code object. Not for the faint of heart.'). If you can't read the source then I don't think you should use the functions. *shrug* I don't know about that. People reverse-engineer programs without access to the source code all the time. Reading the source code may (but not always) make understanding the functions easier, but it's not compulsory. If I cared enough, the way I'd go about reverse-engineering the functions would be to start by pulling apart a Python function into a code object, then pulling apart the code object into its components, making small modifications to the components, then reversing the process (using new.code() and new.function()) to build up a function object I could call. Or I'd ask somebody who already knew how they worked to give an example or two of Python code that called new.code() and new.function(). It's not ideal, of course, in a perfect world whoever wrote new.code() would have written some better documentation, but it will do for non- production code. For production code that I relied on, I'd hire a C programmer to read the source and document it for me. *wink* -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to dynamically create class methods ?
On Wed, 26 Mar 2008 00:55:22 -0700, Arnaud Delobelle wrote: [snip] Except it only *appears* to work. What happens if were store the instances in a list and then execute them all in one go? Ah yes, nicely spotted. Another solution would be to use a proper factory function: def factory(record): def f(n): return (record + )*n return f class MyClass(object): pass records = [spam, ham] instances = [] for record in records: instance = MyClass() setattr(instance, 'execute', factory(record)) instances.append(instance) for instance in instances: instance.execute(5) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Partial Function Application and implicit self problem
Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Gabriel Rossetti schrieb: Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Use a bound-method instead. That has the self already bound to it. Like this: class Foo: def m(self, arg): print arg f = Foo() partial(f.m, 10) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Gabriel Rossetti wrote: Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel I also tried this : def __registerService(atomic, self, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) thinking that the self will be passed as the first argument of the registerService* calls and thus the second argument to the curried/partial method, but it doesn't work either, I get : Traceback (most recent call last): File /home/xxx/Documents/Code/Python/test/test_serv.py, line 245, in test_registeration self.f.registerServiceAtomic(self.serv) exceptions.TypeError: __registerService() takes exactly 3 arguments (2 given) I don't get it... Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Diez B. Roggisch wrote: Gabriel Rossetti schrieb: Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Use a bound-method instead. That has the self already bound to it. Like this: class Foo: def m(self, arg): print arg f = Foo() partial(f.m, 10) Diez Ok, thanks, I moved the partial defs to __init__() and now it seams to work (I still have a but elsewhere, but this part no longer gives an error : def __init__(): self.registerServiceAtomic = partial(self.__registerService, True) self.registerServiceNonAtomic = partial(self.__registerService, False) def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) Thanks, Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
On Thu, 27 Mar 2008 00:33:21 -0700, Grimsqueaker wrote: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? Given an iterator, you use it like this: for item in iterator: print item # or do something else If you're sure that the iterator is relatively small, you can do this: give_me_everything_at_once = list(iterator) but don't try that with this one: def ones(): # never-ending series of ones while True: yield 1 iterator = ones() -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe socket.gaierror (10093)
On 26 Mar, 23:08, Thomas Heller [EMAIL PROTECTED] wrote: Knut schrieb: The script can't resolve the server name. Try to do it by hand using nslookup or even ping (you may want to add a few print statements inside the script to see the exact host name it is trying to connect to, in case it isn't what you expect) If you can't resolve the host name using nslookup, there is a network problem, not in your script. If you can resolve it, try your script without py2exe if possible. -- Gabriel Genellina Thank you for the quick reply Gabriel. I have made sure the script works fine before I exe it. It is when I compile the program I get this error. I don't get how the compile changes server availability. Could it be a firewall issue? Thomas Hi Thomas, Thanks for the tip! Disabled the firewall to check if this could be the problem, but no help there either.. The mail server is on the local network, but I have also tried connecting to internal sockets to another program I have which sniffs a port. This works fine, until I run it as an exe.. My quest continues.. -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
OK, got that. If I use: for x in string_cartesian_product('abc'): print x I get: a b c What am I not understanding? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe socket.gaierror (10093)
Python Programming on Win32 wrote: The problem is running smtplib in a py2exe compiled exe file. When it tries to establish a socket to the mail server it fails. Just wondering someone has encountered this before, and if someone might be able to point me in the right direction. Unhandled exception in thread started by Traceback (most recent call last): File AutomationThread.pyc, line 152, in Run File mail.pyc, line 11, in sendMail File smtplib.pyc, line 244, in __init__ File smtplib.pyc, line 296, in connect socket.gaierror: (10093, 'getaddrinfo failed') In case it helps, this is the text for error 10093: WSANOTINITIALISED 10093 Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times. WSAStartup is called by a process which wants to use winsock, the Windows sockets implementation and it's called by Python's socket module at startup. I can't see anything in py2exe's source which should make any difference to socket initialisation so I'm at a loss. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
On 26 ožu, 20:11, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay [EMAIL PROTECTED] escribió: and then when my application execute code how can I set path to d3dx module to library.zip/d3dx.py. I'm not sure is this properly set question. use the module zipimport http://docs.python.org/lib/module-zipimport.html You don't have to do anything special to use zipimport; from http://docs.python.org/lib/module-zipimport.html : It is usually not needed to use the zipimport module explicitly; it is automatically used by the builtin import mechanism -- Gabriel Genellina Hello, I was add this into my application code: import sys import os my_dir=os.getcwd() sys.path.append(my_dir) sys.path.append(my_dir+\\libary.zip) sys.path.append(my_dir+\\libary.zip\\py2exe) # PY2EXE is folder f=open(path.txt,w) f.write(str(sys.path)) f.close() an the output in path.txt is : ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ \libary.zip\\py2exe'] But it still can't find module py2exe.What should I do now? Any examples? Regards, Vedran -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
Grimsqueaker wrote: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? With Dan's functions in cartesian.py you can do the following: from cartesian import * def count(digits): ... args = [] ... while 1: ... args.append(digits) ... for n in string_cartesian_product(*args): ... yield n ... from itertools import islice print .join(islice(count(abc), 30)) a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
En Thu, 27 Mar 2008 05:40:30 -0300, Gabriel Rossetti [EMAIL PROTECTED] escribió: if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() I see that you've already solved your original problem. But looking at those names, I wonder if you're using the mutex module; note that such mutex is absolutely useless in a multithreaded program, it doesn't guarantee mutual exclusion, the atomic testandset operation isn't atomic at all, by example. For a real mutex, use a threading.Lock object. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Gabriel Rossetti a écrit : Gabriel Rossetti wrote: Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel I also tried this : def __registerService(atomic, self, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) thinking that the self will be passed as the first argument of the registerService* calls and thus the second argument to the curried/partial method, but it doesn't work either, I get : Traceback (most recent call last): File /home/xxx/Documents/Code/Python/test/test_serv.py, line 245, in test_registeration self.f.registerServiceAtomic(self.serv) exceptions.TypeError: __registerService() takes exactly 3 arguments (2 given) I don't get it... Looks like functools.partial doesn't implement the protocol descriptor to behave like an ordinary function. I suppose there's some good reason for this, but anyway you'll have to either extend partial to add the appropriate descriptor support, or provide self by yourself (like Diez suggested). -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Gabriel Rossetti wrote: Gabriel Rossetti wrote: Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel I also tried this : def __registerService(atomic, self, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) thinking that the self will be passed as the first argument of the registerService* calls and thus the second argument to the curried/partial method, but it doesn't work either, I get : Traceback (most recent call last): File /home/xxx/Documents/Code/Python/test/test_serv.py, line 245, in test_registeration self.f.registerServiceAtomic(self.serv) exceptions.TypeError: __registerService() takes exactly 3 arguments (2 given) First, passing self not as first argument is not going to work, and a HUGE design flaw anyway: even IF it would work, it would mean that you *must* use partial to bind default-arguments before invoking a method. And it goes to much against the design of python. Apart from that, please post self-contained examples that produce the error. the above code is hard to grasp because it's unclear which is called from where with what. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: A question on decorators
Tim Henderson a écrit : Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2pickled_data1 pickled_data2 0woeif aposf (bin) (bin) 1ofime powe(bin) (bin) ... noiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. Congratulation, you just reinvented ORM. Good news is that there are already quite a few such packages in Python. May I recommand SQLAlchemy ?-) I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, Indeed, but not the one you mention. The problem is that storing serialized dicts / lists / any other non atomic data in a blob is, well, not exactly the best possible use of a *relational* database. Do yourself a favour: learn what 'relational' means, and replace your blobs with the appropriate tables in the database. (snip code) Now while this works, it is a lot of work. This is why it's better to use an existing package whenever possible. SQLAlchemy is here: http://www.sqlalchemy.org/ (snip mode code) -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
En Thu, 27 Mar 2008 06:00:26 -0300, [EMAIL PROTECTED] escribió: I was add this into my application code: import sys import os my_dir=os.getcwd() sys.path.append(my_dir) sys.path.append(my_dir+\\libary.zip) sys.path.append(my_dir+\\libary.zip\\py2exe) # PY2EXE is folder f=open(path.txt,w) f.write(str(sys.path)) f.close() an the output in path.txt is : ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ \libary.zip\\py2exe'] But it still can't find module py2exe.What should I do now? Any examples? I assume you're talking about the py2exe package available from www.py2exe.org - so it's not a module, it's a package. py2exe usually is only relevant on your *development* machine, so why do you want to put it inside a .zip? What do you want to do? Anyway, I tried the following and could import py2exe successully (but I don't know if it actually works as a distutils extension...) - compressed the py2exe folder into py2exe.zip - deleted the original py2exe folder - moved py2exe.zip onto some temporary directory - tried to import py2exe, failed as expected - added py2exe.zip to sys.path - tried to import py2exe, this time OK py import py2exe Traceback (most recent call last): File stdin, line 1, in module ImportError: No module named py2exe py import sys py sys.path.append(rC:\TEMP\pna\py2exe.zip) py import py2exe py py2exe.__path__ ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: subtract dates with time module
barronmo wrote: I'm trying to get the difference in dates using the time module rather than datetime because I need to use strptime() to convert a date and then find out how many weeks and days until that date. I'm a beginner so any help would be appreciated. Here is the code: Use strptime to create time-tuples, and use the fields in there to create datetime-objects. Then do the math with them. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python behave so? (removing list items)
Thomas Dybdahl Ahle a écrit : On Wed, 2008-03-26 at 23:04 +0100, Michał Bentkowski wrote: Why does python create a reference here, not just copy the variable? Python, like most other oo languages, will always make references for =, unless you work on native types (numbers and strings). There's nothing like a native type in Python, and numbers and strings are ordinary objects. Python will always use references, period. -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Bruno Desthuilliers wrote: Gabriel Rossetti a écrit : Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass self to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? registerServiceAtomic = partial(__registerService, atomic=True) registerServiceNonAtomic = partial(__registerService, atomic=False) Caveat: you'll have to either invert the order of the atomic and service params, or call the partials with named arg for service. HTH Ok, thanks, I didn't know you could do that, I though partial was always left to right (I had read that about curry) Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Print to end of line in a terminal
Hello again. I apologize for not replying earlier but I have been swamped in work lately. I appreciate your replies. Eventually I chose using curses for right-hand edge of the window as it seemed to be the most suitable solution. Thank you. ndlarsen -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. You sure can, but differently. I suppose any toolkit allows setting parameters like no border, flat border and 3d border, but which ones can set ANY type of border to ANY widget like Tkinter does? For example set GROOVE border to buttons and text widgets (instead of traditional wide raised/lowered borders), which is cool (in my opinion). The widgets subclass some base class, which contains some common methods which could be the border and relief for example. In the case of PyGtk, border width is controlled at Container, so most widgets will have this feature, but the relief style of the widget is not common to all widgets so you will need to check this one (Button has it). In wxPython, widgets will subclass Window, which has all you want and more. But PyQt doesn't seem to care much about this, you can change the widget to flat (if it makes sense to that widget have setFlat method) but not much related to the borders. You could recheck your use-cases and see if they are acceptable. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. Thanks. I haven't heard of Tile before, now I will keep this in mind. You forgot to mention WHAT you're planning to solve ;-) , so I have to add that Tile is modernization of Tk widgets (so it fixes ugly look). WHAT I'm planning to solve, quote from my own paragraph: I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. I would like to add the possibility to use Ttk widgets into tkinter, providing you have Tk 8.5. It would solve the problem of not enough widgets and the other one of being ugly mainly. Tk 8.5 also auto-fixes some other problems, it provides smooth-scrolling for the text widget, for example. But keep in mind that using Tk 8.5 in Python is not yet supported (but possible). Could anyone with experience in different toolkits help, please Thanks -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: subtract dates with time module
barronmo wrote: I'm trying to get the difference in dates using the time module rather than datetime because I need to use strptime() to convert a date and then find out how many weeks and days until that date. datetime.datetime.strptime was introduced in Python 2.5; what version are you using? If you really want to get to datetime, here's a quick bridge: import time, datetime def mystrptime(astr, format): ... return datetime.datetime(*time.strptime(astr, format)[:6]) ... mystrptime('2008-03-31', '%Y-%m-%d') datetime.datetime(2008, 3, 31, 0, 0) I'm a beginner so any help would be appreciated. Here is the code: def OBweeks(ptID): qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % (ptID) results = EMR_utilities.getAllData(qry) for items in results: r = re.search('\d\d\d\d-\d\d-\d\d', items) if r: d = time.strptime(r.group(), %Y-%m-%d') - You have at the start and ' at the end of what's supposed to be a string constant. That's a syntax error; it won't run. Please don't serve up what you thought you might have run -- use copy/paste. In this particular case, you can just use time.mktime to convert a time tuple into days since the epoch. # untested days = time.mktime(time.strptime(r.group(), %Y-%m-%d)) - int(time.mktime(time.localtime())) weeks, days = divmod(days, 7) time.localtime() weeks, days = divmod(d.days, 7) return '%s %s/7 weeks' % (weeks, days) This isn't working. I'm getting unsupported operand type for -: 'time.struct_time' and 'time.struct_time error. It *is* working. That is the correct result of the code that you executed. There is is nothing in the time docs to suggest that attempting to subtract time tuples produces anything useful. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: what does ^ do in python
On Mar 26, 1:36 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson [EMAIL PROTECTED] escribió: HOw can we use express pointers as in C or python? Traceback (most recent call last): File stdin, line 1, in module File parser.py, line 123, in parse_text tree = language.parse_text(text) File english.py, line 456, in parse_text tree = self.parse_sentence(sentence) File english.py, line 345, in parse_sentence raise ParserError, can't parse %r % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' Try to coil it up. It would explain part-of-speech errors (we make all the time over here). Coil goes so bad on blip-screen. We don't think in English. Hold. I meant, decoil it. Parts near each other on inferior rings of a circle: radius broadcasts in x**-2 (a.k.a. x/2 in logs) from a pole/ attractor, for redundancy-- distance along a harmonic around the attractor. It proposes path. Digital charter. Current sea. What's square curvature? Number's a square thought. Space and time are interchangable to verbal representations. (Space is money: see? And space doesn't grow on trees. So, what do you want for walls (same destination, new tack.-- high-dimension paths? I don't get what I (I) feel is mine-- you have to stay where you think you are. Spike the drink? What do you spike it with, nominal existence? What do -we- need and get at church, life and freedom?)? Microcircuitry and microplumbing in walls and microrecycling and microtransit could save a lot of energy and be safer and cheaper. The circles here suck. Graph vertices square and accept successfully. What is the identity relation in cause? Do you just like to build and eat coils? I'd like to (affirm/bolt) a structure that gets better at it. I deceive all the senses. My spelling is awe-ful. Am I trying to do the impossible? I like to regulate everything. What should I do? What is the good life? Give it some recoil and it works for me. Raise Locked coil. Sixth- grade English-native speakers don't discern (when prompted) commutations of 'is': 'a is c', 'b is c', therefore 'a is b'. ('Is' is causally intransitive to them.) Formal logic is pretty refined, or they're distracted. Do you? -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. I do not want to separate interface from code and I do not experience the need to use GUI designers. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. I wish toolkits I use to be able to place widgets one after another automatically. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. You sure can, but differently. I suppose any toolkit allows setting parameters like no border, flat border and 3d border, but which ones can set ANY type of border to ANY widget like Tkinter does? For example set GROOVE border to buttons and text widgets (instead of traditional wide raised/lowered borders), which is cool (in my opinion). The widgets subclass some base class, which contains some common methods which could be the border and relief for example. In the case of PyGtk, border width is controlled at Container, so most widgets will have this feature, but the relief style of the widget is not common to all widgets so you will need to check this one (Button has it). In wxPython, widgets will subclass Window, which has all you want and more. But PyQt doesn't seem to care much about this, you can change the widget to flat (if it makes sense to that widget have setFlat method) but not much related to the borders. You could recheck your use-cases and see if they are acceptable. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. Thanks. I haven't heard of Tile before, now I will keep this in mind. You forgot to mention WHAT you're planning to solve ;-) , so I have to add that Tile is modernization of Tk widgets (so it fixes ugly look). WHAT I'm planning to solve, quote from my own paragraph: I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. I would like to add the possibility to use Ttk widgets into tkinter, providing you have Tk 8.5. It would solve the problem of not enough widgets and the other one of being ugly mainly. Tk 8.5 also auto-fixes some other problems, it provides smooth-scrolling for the text widget, for example. But keep in mind that using Tk 8.5 in Python is not yet supported (but possible). I understood you. I added that sentence just to make it clear for anyone reading this. Your participation is appreciated greatly, thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application and implicit self problem
Gabriel Rossetti a écrit : Bruno Desthuilliers wrote: Gabriel Rossetti a écrit : (snip) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? registerServiceAtomic = partial(__registerService, atomic=True) registerServiceNonAtomic = partial(__registerService, atomic=False) Caveat: you'll have to either invert the order of the atomic and service params, or call the partials with named arg for service. Ok, thanks, I didn't know you could do that, I though partial was always left to right It's left to right for positional arguments. Using named arguments, you can pass them in whatever order. (I had read that about curry) Which 'curry' ?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Plugin framework - Overcomplicating things?
On Mar 27, 3:31 am, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 27 Mar 2008 01:50:56 -0300, [EMAIL PROTECTED] [EMAIL PROTECTED] escribió: All this comes to my question - am I overcomplicating this project? I can understand the use of something like the trac component system if I had multiple components and plugins that handled different areas of my project and different points of interaction, but I don't. I've got exactly one spot where I want to check all my plugins and hand off the message to which ever ones are looking for that command. As you said, it looks like you're really overengineering your design then. So really, should I even bother with trying to setup some framework for this or should I just be doing a simple loop over a directory, importing all the plugins and storing them in a list and then looping over them in the message handler to see which ones were looking for the command and letting them do their thing? You could set thing up so that there's no need to loop over the plugins. What you can do is register a plugin (as mentioned to you before by Gabriel - see below) and create an entry in a handler dict so that you can directly dispatch the message to the appropriate handler without having to loop over a list of them. Something like handlers[message]() That may be an option. You may want to setup a simple registry mechanism, so the plugin modules look like: ### begin niceplugin.py ### class AVeryNicePlugin(object): # or perhaps using a suitable base class def handle_message(self, message): ... from plugin import PluginRegistry PluginRegistry.register(AVeryNicePlugin) ### end niceplugin.py ### Your application scans a known directory for files ending in plugin.py and imports them; the modules register themselves any class (or classes), and at appropiate times the application calls some method(s) of the registered plugins. An alternative (which we found simpler with Crunchy) is to not have a class-based structure, but working with simple modules and functions. All modules are put in the plugin directory which are imported at the beginning. Each module contain at least two functions: 1. register() which create the handlers dict entry so that it point out to the appropriate function. 2. one or more function that is called based on the message received. Hope it helps, André -- http://mail.python.org/mailman/listinfo/python-list
Re: what are generators?
On Mar 25, 7:36 pm, Miki [EMAIL PROTECTED] wrote: On Mar 24, 8:17 am, [EMAIL PROTECTED] wrote: I'm looking for a cool trick using generators. Know any exercises I can work? Simple one the comes to mind is flattening a list: list(flatten([1, [[2], 3], [[[4)) [1, 2, 3, 4] I don't think it's well-defined. (But this is impossible and useless calling.) CMIIW? This is generic: def f(): ... __gen= None ... def g(): ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... def set( gen ): ... nonlocal __gen ... __gen= gen ... return g, set ... a, set= f() b= a() set( lambda x: print( x ) ) next( b ) 1 next( b ) 2 next( b ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with write binary data to OLE field in Access
lialie wrote: [... snip slightly confused indication that reading back a binary item using GetChunk appears to double its length ...] Well I don't know why this should be happening, but I do at least have a few suggestions: 1) Try using ADODB.Stream instead of GetChunk etc. 2) Try using the adodbapi dbapi-compliant wrapper 3) Try using ODBC (via PyODBC, CeODBC etc.) I've no idea if any of these will do any better but at least it gives you some possibilities :) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: counting using variable length string as base
On Mar 27, 4:01 am, Peter Otten [EMAIL PROTECTED] wrote: Grimsqueaker wrote: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? With Dan's functions in cartesian.py you can do the following: from cartesian import * def count(digits): ... args = [] ... while 1: ... args.append(digits) ... for n in string_cartesian_product(*args): ... yield n ... from itertools import islice print .join(islice(count(abc), 30)) a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc For the base, we Arabics use the cardinal; what letters you count in doesn't change anything. Don't just spell out numbers, unless: Are you reading marked-tally. Or do you want to yield a word and see the number that it spells out to? Be there or be around. I'm bad at spelling, but I can rearrange linear. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. I do not want to separate interface from code and I do not experience the need to use GUI designers. It is your opinion, it seems I can't change it for now but I hope you reconsider it for the future. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. For some level of perfect, of course. Also, I can't understand why you say it is hard to do such thing in a gui designer tool, which tool have you tried ? Maybe you are not familiar with them yet, and that could be the problem. I wish toolkits I use to be able to place widgets one after another automatically. They all make this possible, you could try doing something on another toolkit you are interested and check if it does what you want. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. You sure can, but differently. I suppose any toolkit allows setting parameters like no border, flat border and 3d border, but which ones can set ANY type of border to ANY widget like Tkinter does? For example set GROOVE border to buttons and text widgets (instead of traditional wide raised/lowered borders), which is cool (in my opinion). The widgets subclass some base class, which contains some common methods which could be the border and relief for example. In the case of PyGtk, border width is controlled at Container, so most widgets will have this feature, but the relief style of the widget is not common to all widgets so you will need to check this one (Button has it). In wxPython, widgets will subclass Window, which has all you want and more. But PyQt doesn't seem to care much about this, you can change the widget to flat (if it makes sense to that widget have setFlat method) but not much related to the borders. You could recheck your use-cases and see if they are acceptable. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. Thanks. I haven't heard of Tile before, now I will keep this in mind. You forgot to mention WHAT you're planning to solve ;-) , so I have to add that Tile is modernization of Tk widgets (so it fixes ugly look). WHAT I'm planning to solve, quote from my own paragraph: I'm planning to solve this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. I would like to add the possibility to use Ttk widgets into tkinter, providing you have Tk 8.5. It would solve the problem of not enough widgets and the other one of being ugly mainly. Tk 8.5 also auto-fixes some other problems, it provides smooth-scrolling for the text widget, for example. But keep in mind that using Tk 8.5 in Python is not yet supported (but possible). I understood you. I added that sentence just to make it clear for anyone reading this. Your participation is appreciated greatly, thank you. -- -- Guilherme H. Polo Goncalves
Re: Partial Function Application and implicit self problem
On Mar 27, 6:05 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: Gabriel Rossetti a écrit : Bruno Desthuilliers wrote: Gabriel Rossetti a écrit : (snip) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? registerServiceAtomic = partial(__registerService, atomic=True) registerServiceNonAtomic = partial(__registerService, atomic=False) Caveat: you'll have to either invert the order of the atomic and service params, or call the partials with named arg for service. Ok, thanks, I didn't know you could do that, I though partial was always left to right It's left to right for positional arguments. Using named arguments, you can pass them in whatever order. (I had read that about curry) Which 'curry' ?-) I think 'prefix' should go in there. Can you try: partial( G.f, a, b ) ( self= obj )? (If that's too brief let me know.) -- http://mail.python.org/mailman/listinfo/python-list
Re: what are generators?
On Mar 27, 6:19 am, [EMAIL PROTECTED] wrote: On Mar 25, 7:36 pm, Miki [EMAIL PROTECTED] wrote: On Mar 24, 8:17 am, [EMAIL PROTECTED] wrote: I'm looking for a cool trick using generators. Know any exercises I can work? Simple one the comes to mind is flattening a list: list(flatten([1, [[2], 3], [[[4)) [1, 2, 3, 4] I don't think it's well-defined. (But this is impossible and useless calling.) CMIIW? This is generic: Revise: def f(): ... __gen= None ... def set( gen ): ... nonlocal __gen ... __gen= gen ... yield set ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... a= f() set= next( a ) set( lambda x: print( x ) ) next( a ) 1 next( a ) 2 next( a ) 3 -- http://mail.python.org/mailman/listinfo/python-list
Psyco alternative
Hi, it seems that Psyco's author will not port it for the upcoming Python 3000 release :( So, for us who use it we will continue to use CPython 2.5.x version for some time to come. Is there an alternative to Psyco so i can have a look at ? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. I do not want to separate interface from code and I do not experience the need to use GUI designers. It is your opinion, it seems I can't change it for now but I hope you reconsider it for the future. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. For some level of perfect, of course. Also, I can't understand why you say it is hard to do such thing in a gui designer tool, which tool have you tried ? Maybe you are not familiar with them yet, and that could be the problem. Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkits with Tkinter's .pack() alternative
Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/27, Alex9968 [EMAIL PROTECTED]: Guilherme Polo wrote: 2008/3/26, Alex9968 [EMAIL PROTECTED]: Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. I do not want to separate interface from code and I do not experience the need to use GUI designers. It is your opinion, it seems I can't change it for now but I hope you reconsider it for the future. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. For some level of perfect, of course. Also, I can't understand why you say it is hard to do such thing in a gui designer tool, which tool have you tried ? Maybe you are not familiar with them yet, and that could be the problem. Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK localisation on Win32
I had no problem with using standard gettext way of doing i18n on Windows with PyGTK an Glade, apart some quirks with LANG environment variable. Basically, the code that works looks like this: import gettext, locale locale.setlocale(locale.LC_ALL, '') if os.name == 'nt': # windows hack for locale setting lang = os.getenv('LANG') if lang is None: defaultLang, defaultEnc = locale.getdefaultlocale() if defaultLang: lang = defaultLang if lang: os.environ['LANG'] = lang gtk.glade.bindtextdomain(appname, translation_dir) gtk.glade.textdomain(appname) gettext.install(appname, translation_dir, unicode=True) Be aware, that you can not change the locale setting from the command line like you do on Linux. I have the same problem. I did all as you wrote. gettext translations do work fine. But translations in glade does not work. The only way to turn it on is to set environment variable LANG explicitly before program run: set LANG=ru_RU python test.py -- http://mail.python.org/mailman/listinfo/python-list
Pickle: several class instance objects in one file?
Hi everyone I've never used the module 'pickle' so far, thus I've got some questions about how to use it: Lets say I have instances of class A and class B: a = A() b = B() Is it possible to pickle both of these instances to the same pkl-file or will that have any bad impact for unpickle (i.e. the instance are 'mixed' or 'destroyed')? Or should I rather use a seperate file for every class instance I want to pickle? Another very basic question about pickling class instances: To store the value of attributes of an instance is it enough for the pickling-algorithm to use the __dict__ or do I have to implement the _setstate_ and _getstate_ function? I didn't really get the meaning of those while reading the python user manual... Thanks in advance Dominique -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
king kikapu [EMAIL PROTECTED] writes: it seems that Psyco's author will not port it for the upcoming Python 3000 release :( I think the idea is it will be part of PyPy and you should use that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
On 27 Μαρ, 14:35, Paul Rubin http://[EMAIL PROTECTED] wrote: king kikapu [EMAIL PROTECTED] writes: it seems that Psyco's author will not port it for the upcoming Python 3000 release :( I think the idea is it will be part of PyPy and you should use that. I know that his efforts are on PyPy now but i do not know when PyPy is going to be stable and if i can use it with my current development stack (PyQt, Eric4 etc). I mean, i do not know if it will be possible to abandon CPYthon and use PyPy instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle: several class instance objects in one file?
On Thu, 27 Mar 2008 12:28:25 +, Dominique.Holzwarth wrote: Lets say I have instances of class A and class B: a = A() b = B() Is it possible to pickle both of these instances to the same pkl-file or will that have any bad impact for unpickle (i.e. the instance are 'mixed' or 'destroyed')? Or should I rather use a seperate file for every class instance I want to pickle? You can pickle a data structure, for example a tuple, that contains both instances. Or you can write one after the other into the pickle file. Then you'll have to retrieve them in two steps too. Another very basic question about pickling class instances: To store the value of attributes of an instance is it enough for the pickling-algorithm to use the __dict__ or do I have to implement the _setstate_ and _getstate_ function? I didn't really get the meaning of those while reading the python user manual... Usually `pickle` just works. Those methods can be used if you want to customize the process, for example if you don't want to pickle the entire object but just parts of it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2exe embed my modules to libary.zip
On 27 ožu, 10:44, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 27 Mar 2008 06:00:26 -0300, [EMAIL PROTECTED] escribió: I was add this into my application code: import sys import os my_dir=os.getcwd() sys.path.append(my_dir) sys.path.append(my_dir+\\libary.zip) sys.path.append(my_dir+\\libary.zip\\py2exe) # PY2EXE is folder f=open(path.txt,w) f.write(str(sys.path)) f.close() an the output in path.txt is : ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ \libary.zip\\py2exe'] But it still can't find module py2exe.What should I do now? Any examples? I assume you're talking about the py2exe package available from www.py2exe.org- so it's not a module, it's a package. py2exe usually is only relevant on your *development* machine, so why do you want to put it inside a .zip? What do you want to do? Anyway, I tried the following and could import py2exe successully (but I don't know if it actually works as a distutils extension...) - compressed the py2exe folder into py2exe.zip - deleted the original py2exe folder - moved py2exe.zip onto some temporary directory - tried to import py2exe, failed as expected - added py2exe.zip to sys.path - tried to import py2exe, this time OK py import py2exe Traceback (most recent call last): File stdin, line 1, in module ImportError: No module named py2exe py import sys py sys.path.append(rC:\TEMP\pna\py2exe.zip) py import py2exe py py2exe.__path__ ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] -- Gabriel Genellina Hello again, Thanks for previous post, it was useful! So now I know what is a problem, but I don't know how to solve it.Under my application user can convert his python code to executable, I was created this with subprocess: retcode =subprocess.Popen([ython,setup.py,py2exe,-d,exe], shell=True, stdout=subprocess.PIPE,creationflags = win32process.CREATE_NO_WINDOW) stdout_value = retcode.communicate()[0] ...Py2exe exit from process here: running py2exe creating C:\Users\veki\Desktop\python\PGS\dist\build creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32 creating C:\Users\veki\Desktop\python\PGS\dist\build \bdist.win32\winexe creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \collect-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \bundle-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \temp creating C:\Users\veki\Desktop\python\PGS\dist\exe *** searching for required modules *** ...it's trying to find d3d,d3dx,d3dc,d3dgui... modules but it can't cause these modules are in library.zip.How can I set target for finding path to library.zip , I'm running these py2exe compile process from my main excutable? Regards, Vedran -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
king kikapu wrote: On 27 Μαρ, 14:35, Paul Rubin http://[EMAIL PROTECTED] wrote: king kikapu [EMAIL PROTECTED] writes: it seems that Psyco's author will not port it for the upcoming Python 3000 release :( I think the idea is it will be part of PyPy and you should use that. I know that his efforts are on PyPy now but i do not know when PyPy is going to be stable and if i can use it with my current development stack (PyQt, Eric4 etc). I mean, i do not know if it will be possible to abandon CPYthon and use PyPy instead. Currently? No way. It's *way* to slow. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
On 27 Μαρ, 15:56, Diez B. Roggisch [EMAIL PROTECTED] wrote: king kikapu wrote: On 27 Μαρ, 14:35, Paul Rubin http://[EMAIL PROTECTED] wrote: king kikapu [EMAIL PROTECTED] writes: it seems that Psyco's author will not port it for the upcoming Python 3000 release :( I think the idea is it will be part of PyPy and you should use that. I know that his efforts are on PyPy now but i do not know when PyPy is going to be stable and if i can use it with my current development stack (PyQt, Eric4 etc). I mean, i do not know if it will be possible to abandon CPYthon and use PyPy instead. Currently? No way. It's *way* to slow. Diez Ok, i know this. The one that i do not know, is if, let'say, in 2 years it will be ready for seriously development, PyPy will aim to replace CPython entirely ?? We are talking about an whole new distribution ? As for psyco, are there any alternatives to use now ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
Ok, i know this. The one that i do not know, is if, let'say, in 2 years it will be ready for seriously development, PyPy will aim to replace CPython entirely ?? We are talking about an whole new distribution ? Most certainly not. It's the goal of each language to finally become self-hosted, and I hope we see that for python. But that's nothing that will happen anytime soon (soon being at least half a decade), and most probably not for the 2.x-versions. As for psyco, are there any alternatives to use now ? Nope, but I heard through the grapevine that while it won't be supported for all times to come, a new version is in the making. But ultimately, the author says that the approach is flawed, so at *some* point it will be discontinued. But that could be said about nearly everything, couldn't it? Diez -- http://mail.python.org/mailman/listinfo/python-list
And the reverse? Does os also import os.path?
If i do import os os.path.abspath(bla) '/home/wilbert/bla' it seems that just import os also makes available al os.path functions. But is that always true? Thanks, Wilbert -- http://www.wilbertberendsen.nl/ You must be the change you wish to see in the world. -- Mahatma Gandhi -- http://mail.python.org/mailman/listinfo/python-list
Checking processes running under Windows
Hello all! I'm trying to write a script that needs to check which processes are running under Windows (XP Pro, Home, whatever). The method I'm using is: process_list = os.popen('TASKLIST').read() However, XP Home doesn't have the tasklist.exe tool so, this is kind of useless in that OS. Do you have any other methods I can use for this? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Regarding __slots__ and other stuff: A couple of questions
I'm new to Python. I'm trying to understand the type/class/object(instance) model. I have read here: http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html and here: http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html as well as here: http://users.rcn.com/python/download/Descriptor.htm There are still a couple of issues I'm unclear about. I'll be very happy if one of you could help me. *first:* Why doesn't this works? code class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... c = C() c.foo = 'foo' c.bar = 'bar' c.bar, c.foo ('bar', 'foo') c.__slots__ ['foo', 'bar'] c.__slots__.append('eggs') c.__slots__ ['foo', 'bar', 'eggs'] c.eggs = 'eggs' Traceback (innermost last): File stdin, line 1, in module AttributeError: 'C' object has no attribute 'eggs' /code *second:* what happens here? Why can I write to spam using the class object but not the using the instance? code class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... C.spam = 50 C.spam 50 C.spam = 56 c = C() c.spam = 55 Traceback (innermost last): File stdin, line 1, in module AttributeError: 'C' object attribute 'spam' is read-only C.spam = 55 C.spam 55 /code *Third:* code class RevealAccess(object): A data descriptor that sets and returns values normally and prints a message logging their access. def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print 'Retrieving', self.name return self.val def __set__(self, obj, val): print 'Updating' , self.name self.val = val class A(object): def __init__(self): self.x = RevealAccess(10, 'var x') self.y = 5 class B(object): x = RevealAccess(10, 'var x') y = 5 a = A() b = B() a.x __main__.RevealAccess object at 0x00BAC730 a.x = 55 b.x Retrieving var x 10 b.x = 55 Updating var x /code Why the descriptor works only when created as a static variable and not as an instance variable? I'm sure all this questions stem from my lack of understanding python object model. But, please, what am I missing? Thanks Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
As for psyco, are there any alternatives to use now ? Nope, but I heard through the grapevine that while it won't be supported for all times to come, a new version is in the making. Aha!! It seems you have better sources than me! :) But ultimately, the author says that the approach is flawed, so at *some* point it will be discontinued. But that could be said about nearly everything, couldn't it? Diez It is a pity because this module *does* really solve some problems... -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
On Thu, 27 Mar 2008 15:19:11 +0100, Diez B. Roggisch [EMAIL PROTECTED] wrote: Ok, i know this. The one that i do not know, is if, let'say, in 2 years it will be ready for seriously development, PyPy will aim to replace CPython entirely ?? We are talking about an whole new distribution ? Most certainly not. It's the goal of each language to finally become self-hosted, and I hope we see that for python. But that's nothing that will happen anytime soon (soon being at least half a decade), and most probably not for the 2.x-versions. PyPy is self-hosted and has been for some time (a year or so?). Maybe you're saying that PyPy won't replace CPython for at least five years? Could be; prediction is hard. ;) PyPy is between 1x and 3x slower than CPython for a lot of things, which isn't so much of a difference. A bigger obstacle is the availability of third-party extension modules which currently must be re-implemented in order to be available on PyPy. This could easily take half a decade without a full-time or otherwise concerted effort. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Is subprocess.Popen completely broken?
I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: proc = subprocess.Popen (ls /tmp) Traceback (most recent call last): File stdin, line 1, in module File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 594, in __init__ errread, errwrite) File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with 2.6alpha on Mac OS X. Frustrated in Chicago... Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
king kikapu wrote: As for psyco, are there any alternatives to use now ? But ultimately, the author says that the approach is flawed, so at *some* point it will be discontinued. But that could be said about nearly everything, couldn't it? It is a pity because this module *does* really solve some problems... If it's about some problems, then maybe Cython is an alternative. http://cython.org Stefan -- http://mail.python.org/mailman/listinfo/python-list
Tkinter menus made easy
Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: http://www.martinrinehart.com/articles/menus.py Run it. Then look at the source (bottom of file). There's a bit more doc in the doc comment at the top. Peer review is most welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
2008/3/27, Skip Montanaro [EMAIL PROTECTED]: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: proc = subprocess.Popen (ls /tmp) proc = subprocess.Popen (ls /tmp, shell=True) or proc = subprocess.Popen ([ls, /tmp]) should work. Traceback (most recent call last): File stdin, line 1, in module File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 594, in __init__ errread, errwrite) File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with 2.6alpha on Mac OS X. Frustrated in Chicago... Skip -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus made easy
2008/3/27, [EMAIL PROTECTED] [EMAIL PROTECTED]: Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: I didn't look at it yet, but just in case you weren't aware there is a gui designer tool for tkinter called GUI Designer (what a bad name), which used to be called SpecTcl, where you can design the menus and it then converts to python code. http://www.martinrinehart.com/articles/menus.py Run it. Then look at the source (bottom of file). There's a bit more doc in the doc comment at the top. Peer review is most welcome. -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
If it's about some problems, then maybe Cython is an alternative. http://cython.org Stefan Hmmm...thanks but i think Pyrex-like solution is not the ideal one. Coming from C# and having 8 years of expertise on it, i have gain a very positive thinking about jit compilers and i think that psyco (ok, a just-in-time specializer) is a more easy (and more correct) way to go that mixing 2 languages. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Text widget
Is there a way of translating from the Text widget's width/height (in characters) to pixels so you can open an appropriately sized window? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
Skip Montanaro wrote: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: proc = subprocess.Popen (ls /tmp) Popen expects a list of program arguments. When passed a single string instead of a list, as in your example, it assumes that the string is the command, and looks for an executable named ls /tmp, which of course does not exist. Split your command into a list of separate parameters, with the executable as the first parameter, and it will work: subprocess.Popen(['ls', '/tmp']) subprocess.Popen object at 0xb7c569ec (ls output here) Jeffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
On Thu, Mar 27, 2008 at 10:53 AM, Skip Montanaro [EMAIL PROTECTED] wrote: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: proc = subprocess.Popen (ls /tmp) Traceback (most recent call last): File stdin, line 1, in module File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 594, in __init__ errread, errwrite) File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? It's looking for an executable named ls /tmp Since it can't find one, it raises an exception. If you just want to replace an os.system call, you need to pass shell=True to Popen, like this: proc = subprocess.Popen(ls /tmp, shell=True) That will get the shell to split your string into the program to be called, and the argument(s) to the program. Alternatively, you can do it yourself by passing a sequence to Popen: proc = subprocess.Popen([ls, /tmp]) Take a look at the documentation for Popen (http://docs.python.org/lib/node528.html) and the specific examples for replacing os.system (http://docs.python.org/lib/node536.html) -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
proc = subprocess.Popen (ls /tmp) proc = subprocess.Popen (ls /tmp, shell=True) or proc = subprocess.Popen ([ls, /tmp]) should work. Why should I need to set shell=True? I'm not globbing anything. The second case still fails: proc = subprocess.Popen ([/usr/bin/ls /tmp]) Traceback (most recent call last): File stdin, line 1, in ? File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 542, in __init__ errread, errwrite) File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 975, in _execute_child raise child_exception OSError: [Errno 20] Not a directory Thx, Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe socket.gaierror (10093)
This is frustrating. I was working on writing a sample for my problem. I start with dissecting my code which still gives the same error. Then I start thinking that it might be my setup file doing the damage. And i start it from scratch. Everything suddenly works. Fine! i think, i will have to start over with the setup file. Buy i give the old setup a last go, and guess what. It works. So I am honestly utterly frustrated.. I have no idea what what the reason for the problem, but apparently it is solved, for now. Thanks for all you comments and help. I really appreciate it! K -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
Why should I need to set shell=True? I'm not globbing anything. The second case still fails: RTFM -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking processes running under Windows
João Rodrigues wrote: Hello all! I'm trying to write a script that needs to check which processes are running under Windows (XP Pro, Home, whatever). The method I'm using is: process_list = os.popen('TASKLIST').read() However, XP Home doesn't have the tasklist.exe tool so, this is kind of useless in that OS. Do you have any other methods I can use for this? You can do this with WMI: http://timgolden.me.uk/python/wmi_cookbook.html#running_processes TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
2008/3/27, Skip Montanaro [EMAIL PROTECTED]: proc = subprocess.Popen (ls /tmp) proc = subprocess.Popen (ls /tmp, shell=True) or proc = subprocess.Popen ([ls, /tmp]) should work. Why should I need to set shell=True? The default is shell=False, which means that Popen will use os.excevp to execute your command, (talking about UNIX here), which in turn expects a list as the args parameter, but you are passing a string. Setting shell=True makes Popen execute the string passed through the shell. I'm not globbing anything. The second case still fails: proc = subprocess.Popen ([/usr/bin/ls /tmp]) Notice how yours is lacking a comma separating the strings while mine does include it. Traceback (most recent call last): File stdin, line 1, in ? File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 542, in __init__ errread, errwrite) File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 975, in _execute_child raise child_exception OSError: [Errno 20] Not a directory Thx, Skip -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking processes running under Windows
One way: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339 Another way: wmi # List all running processes # http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name # List all running notepad processes import wmi c = wmi.WMI () for process in c.Win32_Process (name=notepad.exe): print process.ProcessId, process.Name # Create and then destroy a new notepad process import wmi c = wmi.WMI () process_id, return_value = c.Win32_Process.Create (CommandLine=notepad.exe) for process in c.Win32_Process (ProcessId=process_id): print process.ProcessId, process.Name result = process.Terminate () João Rodrigues wrote: Hello all! I'm trying to write a script that needs to check which processes are running under Windows (XP Pro, Home, whatever). The method I'm using is: process_list = os.popen('TASKLIST').read() However, XP Home doesn't have the tasklist.exe tool so, this is kind of useless in that OS. Do you have any other methods I can use for this? Thanks! -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
Jerry Hill malaclypse2 at gmail.com writes: It's looking for an executable named ls /tmp Since it can't find one, it raises an exception. If you just want to replace an os.system call, you need to pass shell=True to Popen, like this: proc = subprocess.Popen(ls /tmp, shell=True) That will get the shell to split your string into the program to be called, and the argument(s) to the program. Alternatively, you can do it yourself by passing a sequence to Popen: proc = subprocess.Popen([ls, /tmp]) Oh crap. Missing the comma... *sigh* Sometimes adjacent string literals can be silent killers. Sorry for the noise. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
On Mar 27, 2008, at 10:53 AM, Skip Montanaro wrote: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: proc = subprocess.Popen (ls /tmp) Traceback (most recent call last): File stdin, line 1, in module File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 594, in __init__ errread, errwrite) File /home/titan/skipm/local/lib/python2.5/subprocess.py, line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with 2.6alpha on Mac OS X. Try proc = subprocess.Popen(('ls', '/tmp/')) or proc = subprocess.Popen('ls /tmp/', shell=True) See http://docs.python.org/lib/node528.html HTH, --- Lee Capps Technology Specialist CTE Resource Center [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Pystemmer 1.0.1 installation problem in Linux
Dear all, I am a newbie to Python community. For my project, I tried to install Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but unsuccessful. It produced the following error: running install running build running build_ext building 'Stemmer' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ limits.h:11, from libstemmer_c/src_c/../runtime/header.h:2, from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: limits.h: No such file or directory error: command 'gcc' failed with exit status 1 Did anyone experience this before? Any comment/suggestion is highly appreciated. Thank you. Best regards, Supheakmungkol -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
Skip Montanaro wrote: proc = subprocess.Popen (ls /tmp) proc = subprocess.Popen (ls /tmp, shell=True) or proc = subprocess.Popen ([ls, /tmp]) should work. Why should I need to set shell=True? I'm not globbing anything. The second case still fails: proc = subprocess.Popen ([/usr/bin/ls /tmp]) This line fails because of a typo. There needs to be a comma between the two list elements. Without the comma, this becomes proc = subprocess.Popen ([/usr/bin/ls/tmp]) which obviously fails. Gary Herron Traceback (most recent call last): File stdin, line 1, in ? File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 542, in __init__ errread, errwrite) File /opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py, line 975, in _execute_child raise child_exception OSError: [Errno 20] Not a directory Thx, Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Is subprocess.Popen completely broken?
Why should I need to set shell=True? I'm not globbing anything. The second case still fails: Jerry RTFM Thank you. I had. The bits about the type of the args parameter don't mention the shell parameter or that there was any difference between using strings or lists. I missed the reasoning in the discussion on the shell parameter. I think the subprocess module docs probably need some rework. In general, I understand that having a bunch of different ways to execute subprocesses can be confusing. The swiss army knife approach used in the subprocess module is also problematic. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Line segments, overlap, and bits
On Mar 26, 5:28 pm, Sean Davis [EMAIL PROTECTED] wrote: I am working with genomic data. Basically, it consists of many tuples of (start,end) on a line. I would like to convert these tuples of (start,end) to a string of bits where a bit is 1 if it is covered by any of the regions described by the (start,end) tuples and 0 if it is not. I then want to do set operations on multiple bit strings (AND, OR, NOT, etc.). Any suggestions on how to (1) set up the bit string and (2) operate on 1 or more of them? Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python. The solution depends on what size of genomes you want to work with. There is a bitvector class that probably could do what you want, there are some issues on scaling as it is pure python. http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html If you want high speed stuff (implemented in C and PyRex) that works for large scale genomic data analysis the bx-python package might do what you need (and even things that you don't yet know that you really want to do) http://bx-python.trac.bx.psu.edu/ but of course this one is a lot more complicated i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus made easy
On Mar 27, 3:54 pm, [EMAIL PROTECTED] wrote: Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: I did develop a proggy that takes the following as input, it's part of my agui project, you can use it as an idea to improve your code: menudef = File New,callNew,Ctrl-N New Window, callNewWindow, Ctrl-Shift-N __ Open, lambda e=0:para(1), Ctrl-O __ Save, lambda e=0:para(2), Ctrl-S Save As,CallSaveAs, F12 __ Minimize, called, Ctrl-M Magic, called, Alt-X Edit Cut,called, Ctrl-X Copy, called, Ctrl-C Paste, called, Ctrl-V __ Align Left, Right, ___ m = Menu(root, globals(), menudef) Callee: def __init__(self, root, globalVars, menuDef, font=None, fieldSep=,, itemSep=_): ... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
Diez B. Roggisch: the author says that the approach is flawed, so at *some* point it will be discontinued. Can't Psyco be improved, so it can compile things like: nums = (i for i in xrange(20) if i % 2) print sum(nums) I think the current Psyco runs slower than Python with generators/ iterators. To speed up that code with Psyco you have to write this: nums = [i for i in xrange(20) if i % 2] print sum(nums) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
dynimac code with lambda function creation
So I am trying to pass an object's method call to a function that requires a function pointer. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec(y=lambda x: testerObj.+method+(x)) return y Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. I have successfully created similar functions, except without using the exec() call. e.g. def functionCreator(a, b, c): return lambda d: myFunc(a, b, c, d) and it doesn't complain about the variables a, b, or c when being run. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Is there some other way to do this that I'm missing? I tried passing in 'method' as a function pointer (to the method of the object), but that didn't work either. Thanks, Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
On Thu, 27 Mar 2008 08:59:33 -0700 (PDT), [EMAIL PROTECTED] wrote: Diez B. Roggisch: the author says that the approach is flawed, so at *some* point it will be discontinued. Can't Psyco be improved, so it can compile things like: nums = (i for i in xrange(20) if i % 2) print sum(nums) Sure, it can be. That doesn't mean it will be. Someone has to do it. :) One reason attention is going to PyPy instead of Psyco is that PyPy's JIT doesn't require as much careful attention to support and maintain support for features like generators. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Dynamic code problem
My dynamic code failed at this site http://playwide1.extra.hu/, need some help thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco alternative
One reason attention is going to PyPy instead of Psyco... Jean-Paul I had a look at PyPy, it, indeed, have a very long way to go so we can consider it an alternative. -- http://mail.python.org/mailman/listinfo/python-list
Re: dynimac code with lambda function creation
Justin Delegard wrote: So I am trying to pass an object's method call to a function that requires a function pointer. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec(y=lambda x: testerObj.+method+(x)) return y You are making it too difficult. What about this: def objectMethodCallerFunctionCreator(testerObj, method): return getattr(testerObj,method) BTW, when you need to return a value (instead of simple code execution) you should use eval() instead of exec(). Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. That is true. The 'testerObj' parameter is assigned to the local namespace. The local namespace is created when the function is called. When you call exec, it creates a new namespace. Thus, testerObj is not available inside exec(). But please see above - you do not need exec for this. It is unsafe, slow and really not necessary. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Generally, you should not use exec, eval and their counterparts to access certain attributes of different objects. Same for defining functions, classes, create instances etc. If you still feel that you need to use eval or exec for some reason, drop me an email and hopefully I can help avoiding it. :-) Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: first interactive app
Miki [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello Tim, snip Any ideas on a simple interface for this? How about something like: Chapter 1 (001-200 200) Chapter 2 (200-300 100) -- 001-300 300 Chapter 3 (300-450 150) Chapter 4 (450-500 50) -- 300-450 250 Chapter 5 (500-600 100) -- 500-600 100 Where the user can move the divider up and down to create new volume, they can also add and delete dividers. The program will not allow to drag the divider above the 600 page limit. HTH, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com Hi Miki, that looks nice, simple, and intuitive. thanks for thinking about it. Now to dive into some gui coding! thanks, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: dynimac code with lambda function creation
Justin Delegard a écrit : So I am trying to pass an object's method call I assume you mean to pass an object's method, since I don't get what passing an object's method call could mean. to a function that requires a function pointer. s/pointer/object/ There's nothing like a pointer in Python, and Python's functions are plain objects (instances of class 'function'). FWIW and WWAI, Python's methods are thin callable wrappers around the function, the class and (for bound methods) the instance. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. easy ??? Here's the easy way to pass a method to a function: def func(method): return method(42) class MyClass(object): def __init__(self, name): self.name = name def foo(self, whatever): return I'm %s and whatever is %s % (self.name, str(whatever)) obj = MyClass('boo') print func(obj.foo) Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec(y=lambda x: testerObj.+method+(x)) return y My my my... Looks like you're in for the Rube Goldberg Award !-) Whenever you think exec (or eval FWIW) is the solution, odds are there's a way better solution. If what you want is to retrieve a reference to an attribute you only know by it's name, getattr() is your friend. And in Python, methods are attributes. def objectMethodCallerFunctionCreator(testerObj, method): y = lambda x: getattr(testerObj, method)(x) return y But as we've seen above, all this is useless overcomplexification. Just pass the method like it was any other attribute, and you're done. Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. This is related to exec as far as I can tell. I have successfully created similar functions, except without using the exec() call. e.g. def functionCreator(a, b, c): return lambda d: myFunc(a, b, c, d) and it doesn't complain about the variables a, b, or c when being run. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Is there some other way to do this that I'm missing? print func(getattr(obj, 'foo')) I tried passing in 'method' as a function pointer (to the method of the object), but that didn't work either. What did you try, and what result did you get ? 'does not work' is (almost) the most useless description of a problem. -- http://mail.python.org/mailman/listinfo/python-list
singleton decorator
Hallo, playing with the decorators from PEP 318 I found the elegant singleton decorator. def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class A: pass class B: pass a1=A() a2=A() a3=A() b1=B() b2=B() b3=B() for i in ((a1,b1),(a2,b2),(a3,b3)): print id(i[0]),id(i[1]) But I always get a syntax error declaring class A as singleton. reload ( decorator) Traceback (most recent call last): File stdin, line 1, in ? File decorator.py, line 27 class A: pass ^ SyntaxError: invalid syntax What's the problem with this code because it's only copied for the PEP 318? It doesn't work with python 2.4 and python 2.5. Greetings Rainer -- http://mail.python.org/mailman/listinfo/python-list
Re: singleton decorator
[EMAIL PROTECTED] a écrit : Hallo, playing with the decorators from PEP 318 I found the elegant singleton decorator. def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class A: pass (snip) But I always get a syntax error declaring class A as singleton. reload ( decorator) Traceback (most recent call last): File stdin, line 1, in ? File decorator.py, line 27 class A: pass ^ SyntaxError: invalid syntax What's the problem with this code because it's only copied for the PEP 318? It doesn't work with python 2.4 and python 2.5. A pep is a proposal, not a feature documentation. As written in pep318, class decorators have not been implemented so far. They'll be implemented in 2.6 (more exactly: they are implemented in 2.6, but 2.6 is still alpha so far). -- http://mail.python.org/mailman/listinfo/python-list
Re: And the reverse? Does os also import os.path?
Wilbert Berendsen a écrit : If i do import os os.path.abspath(bla) '/home/wilbert/bla' it seems that just import os also makes available al os.path functions. But is that always true? Nope. Not all packages expose their sub-packages. -- http://mail.python.org/mailman/listinfo/python-list
Re: Soup Strainer for ElementSoup?
erikcw wrote: I'm parsing real-world HTML with BeautifulSoup and XML with cElementTree. I'm guessing that the only benefit to using ElementSoup is that I'll have one less API to keep track of, right? If your real-world HTML is still somewhat close to HTML, lxml.html might be an option. It combines the ElementTree API with a good close-to-HTML parser and some helpful HTML handling tools. http://codespeak.net/lxml http://codespeak.net/lxml/lxmlhtml.html You can also use it with the BeautifulSoup parser if you really need to. http://codespeak.net/lxml/elementsoup.html Stefan -- http://mail.python.org/mailman/listinfo/python-list