Return name of caller function?
Hello there, Did someone help you with this problem? I would like to know the solution as well. Do you know how to do in on C (CPP) environment ? Thanks anyway. BR. Moshe. This email and any files transmitted with it are confidential material. They are intended solely for the use of the designated individual or entity to whom they are addressed. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, use, distribution or copying of this communication is strictly prohibited and may be unlawful. If you have received this email in error please immediately notify the sender and delete or destroy any copy of this message -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
On 2008-01-13, Erik Lind [EMAIL PROTECTED] wrote: I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class instance by assignment. For some strange reason the literature seems to take this for granted. I'd appreciate any pointers or links that can help clarify this. I think you mean the following: You'd like to do p = Person('me', 'here', 31) and you are wondering why you need the __init__() function in class Person(object): def __init__(self, name, addres, age): self.name = name self.address = address self.age = age right? If so, the answer is that while you think you are doing Person('me', 'here', 31), you are in reality executing Person.__init__(self, 'me', 'here', 31), where 'self' is refers to a shiny new, empty object created for you. (and the 'self' is obtained by the Person.__new__ function I think, but others here have much better knowledge about this). Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Can you please type paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] f = open(paf, r) I think I was getting a ghost error from another try somewhere higher up. You are correct, this does open the file - no matter what the locale is. I have decided to keep the test for a decode error because files created under different locales should not be written-to under the current one. I don't know if one can mix encodings in a single text file, but I don't have time to find out. It is getting messy with my test files created in differing locales, and my code changing so quickly. See above. The encoding in codecs.open has no effect at all on the file name; it only talks about the file content. Thanks, I suspected as much but it's a subtle thing. Best, \d -- It is almost as if the human brain were specifically designed to misunderstand Darwinism, and to find it hard to believe.. -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
I have decided to keep the test for a decode error because files created under different locales should not be written-to under the current one. I don't know if one can mix encodings in a single text file, but I don't have time to find out. Of course it's *possible*. However, you need to have a detailed format specification to make it feasible. For example, in a font file, you could specify that the font name is in UTF-8, the vendor name is in Latin-1, and the description is in UTF-16, but it would be really stupid to specify such a format (not that this would stop people from specifying such formats - in ZIP files, some file names are encoded in CP437 and some in UTF-8, depending on a per-filename flag). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Rapid desktop application development
I am looking for Stephan Eilert who was an exchange student from Germany to the U.S. (Northern California) in the 1980's. Could you possibly be one in the same? Monica Erwin-Francis -- http://mail.python.org/mailman/listinfo/python-list
Re: NotImplimentedError
hakim ouaras wrote: Hi, I am begining with python, I want to know what is the utility and how to use the expression NotImplementedError. Thak you for your answers Hakim Never miss a thing. Make Yahoo your homepage. http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs It's meant to be used to mark a procedure that you intend to write, but have not yet done so. The procedure you have not yet written raises that exception to indicate that it is not yet implemented and should not be called: def DoSomething(some, args): This procedure will do ... great things someday. raise NotImplementedError Then *if* the writer of the application that will call it forgets that's it not yet implemented, and mistakenly tries to call it, an error will be raised. It's not so useful in a small application, or a single person project, but it does become useful if several people are writing different parts (say a library and an application) at the same time. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Elementary string-formatting
In article [EMAIL PROTECTED], John Machin [EMAIL PROTECTED] wrote: snip div operator? The integer division operator is // Yes, sorry, that's what I meant. -- Odysseus -- http://mail.python.org/mailman/listinfo/python-list
NotImplimentedError
Hi, I am begining with python, I want to know what is the utility and how to use the expression NotImplementedError. Thak you for your answers Hakim Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs-- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
How often do these things *actually* happen? Of those that actually do it, how many are clueless enough that when they run into problems they blame you for it? (And remember that you won't even find out about the non-clueless ones.) This is a rethorical question, right? -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Paul Sijben wrote: The problem: I have a client-server app written in python. I want to make sure that the client is not: 1) destabilized by users accidentally or on purpose dropping python files in the path (after which calling the helpdesk will not be useful) 2) extended with new features without me knowing about it (again resulting in calls to my helpdesk...) You could check the MD5 hashes of your files. robert -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Mike, thanks for the constructive feedback.Indeed i probably need to patch import in some way. Looks like there is no standard way to get this done. So I guess I have do it myself... In the famous last words department: how hard can that be? ;-) Paul Mike Meyer wrote: On Sat, 12 Jan 2008 09:47:26 +1100 Ben Finney [EMAIL PROTECTED] wrote: Paul Sijben [EMAIL PROTECTED] writes: I know that I can not stop a dedicated hacker deconstructing my code. A direct consequence of this is that you can not stop *anyone* from deconstructing your code if it's in their possession. It takes only one dedicated, skilled person to crack your obfuscation system and distribute an automated process for doing so to anyone interested. Except that's not what he's trying to do. However I can not imagine that I would be the first one planning to do this. So is there a solution like this available somewhere? Trying to make bits uncopyable and unmodifiable is like trying to make water not wet. And again, that's not what he's trying to do. He wants to arrange things so that he doesn't have to support unmodified versions of his code, by making it impossible to import modified modules. While that's still impossible, once you decide how difficult you want to make it for people to do that, you can *probably* make it that difficult - but the process gets progressively more difficult and expensive as you make it harder. I think he's contemplating only the simplest, least expensive step: adding an import hook that only allows imports of digitally signed modules. If planning to deploy on Windows, where he has to bundle a python with his application, he may well implement the hook in the interpreter instead of in python, so it's harder to find. If you wanted to go to the expense, you could probably arrange things so that the digital signatures are the more vulnerable attack vectors, but I'd expect to spend millions of dollars doing so. mike -- http://mail.python.org/mailman/listinfo/python-list
Pygtk Image Load Problem
Hey I have a simple image load written in Python. Here is a link to the pastebin http://pastebin.com/m490093b3 I am having a problem when loading the full screen images, it is displaying a gray line at the bottom of the image as can be seen in this screen shot http://www.xiano.co.uk/image_load.png I suspect its some sort of buffering problem but I am not sure how to work around it. It is worse on some images than others, but the gray line is still there. I need the image to display full screen without any defects. If anyone could help that'd be great, I am fairly desperate to get this working! Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: NotImplimentedError
Gary Herron [EMAIL PROTECTED] wrote: hakim ouaras wrote: Hi, I am begining with python, I want to know what is the utility and how to use the expression NotImplementedError. Thak you for your answers Hakim It's meant to be used to mark a procedure that you intend to write, but have not yet done so. More often it is used to mark a method which is some part of a class interface but is not implemented in that specific class. Typically you do this when writing an abstract base class: whoever uses it must implement particular methods, and if they forget then you raise NotImplementedError. For examples just grep the Python lib sources. e.g. optparse has an abstract class HelpFormatter which has a couple of methods that must be implemented in subclasses: class HelpFormatter: ... def format_usage(self, usage): raise NotImplementedError, subclasses must implement def format_heading(self, heading): raise NotImplementedError, subclasses must implement ... class IndentedHelpFormatter (HelpFormatter): Format help with indented section bodies. ... def format_usage(self, usage): return _(Usage: %s\n) % usage def format_heading(self, heading): return %*s%s:\n % (self.current_indent, , heading) and so on. -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Robert Latest wrote: Paul Sijben wrote: The problem: I have a client-server app written in python. I want to make sure that the client is not: 1) destabilized by users accidentally or on purpose dropping python files in the path (after which calling the helpdesk will not be useful) 2) extended with new features without me knowing about it (again resulting in calls to my helpdesk...) You could check the MD5 hashes of your files. robert indeed but I still need to hook into import to do that reliably, right? -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
On Mon, 14 Jan 2008 09:49:49 +0100, Paul Sijben wrote: How often do these things *actually* happen? Of those that actually do it, how many are clueless enough that when they run into problems they blame you for it? (And remember that you won't even find out about the non-clueless ones.) This is a rethorical question, right? No, it's a serious question. You distribute Python code, and you're worried that your users will modify the source code and then neglect to mention it when they report bugs which they introduced. Before you build an elephant-proof fence around your house, it is quite reasonable to ask whether or not there are actually elephants in your neighbourhood. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: (bit)torrent source code help
Hi, Try to use ABC. it based on bittornado Thnx -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
-On [20080113 13:36], Fredrik Lundh ([EMAIL PROTECTED]) wrote: given that they do different things, I'm not sure it's that helpful to describe them *both* as constructors. I am still behind in my learning. ;) To restate it more correctly: __init__ is akin to a constructor. I am not entirely sure I fully understand __new__'s semantics though. The first read-through of http://docs.python.org/ref/customization.html makes it sound very similar to a call like: var = Object(arguments=...) I must not be understanding something and __new__'s documentation there is not that clear to me, to be honest. -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ I think, therefore I am... -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
A.T.Hofkamp [EMAIL PROTECTED] writes: while you think you are doing Person('me', 'here', 31), you are in reality executing Person.__init__(self, 'me', 'here', 31), where 'self' is refers to a shiny new, empty object created for you. This is misleading, and founders on many discrepancies, not least of which is that '__init__' always returns None, yet the 'Person()' call returns the new instance. So it's quite untrue to say that one is in reality calling the '__init__' method. What one is in reality calling is the '__new__' method of the Person class. That function, in turn, is creating a new Person instance, and calling the '__init__' method of the newly-created instance. Finally, the '__new__' method returns that instance back to the caller. -- \ Probably the toughest time in anyone's life is when you have | `\ to murder a loved one because they're the devil. -- Emo | _o__) Philips | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
-On [20080113 14:03], Ben Finney ([EMAIL PROTECTED]) wrote: That's getting the two of them confused. __new__ is a constructor, __init__ is not. And there I just sent an email stating the wrong thing. I'll dig into it again, because I am really confusing something here (and jumping between 4 languages on the same day is not helping much to be honest). -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ If slavery is not wrong, nothing is wrong... -- http://mail.python.org/mailman/listinfo/python-list
Re: where do my python files go in linux?
Jeroen Ruigrok van der Werven [EMAIL PROTECTED] wrote: -On [20080112 12:03], Jorgen Bodde ([EMAIL PROTECTED]) wrote: app.py calls a lot of modules in {dir}/app. Horst says the python file goes in /usr/bin/app.py which is ok with me, but I have multiple python files, and I decided to use an app.sh script to call my python files. In the /usr/bin I do not see subdirs so I assume that is not really desirable. Personally I'd be loathe to put app.py in /usr/bin. This directory is normally reserved for OS-specific binaries. For personal/system-extended stuff I'd use /usr/local/bin or whatever your system mandates. I'd agree with that, except for the fact that he is making a .deb to be installed by the package manager. In Debian... /usr/bin is for stuff installed by the package manager which becomes effectively part of the OS. The package manager tracks every file it installes to ensure ovewrites can't happen etc... /usr/local/bin is for stuff installed from source, not using the package manager. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Threaded server
Giampaolo Rodola' [EMAIL PROTECTED] wrote: I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: Ran 50 tests in 1.515s OK Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPHandler.__del__ of pyftpdlib.ftpserver.FTPHandler connected 127.0.0.1:2 249 at 0xa4b080 ignored Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPServer.__del__ of pyftpdlib.ftpserver.FTPServer listening 127.0.0.1:543 21 at 0x9e1a30 ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). It looks like when python is shutting down, it has removed an object the ftphandler code relies on. I see you attempt to kill the ftp server with ftpd.stop(). That is good, but you don't wait for the thread to finish (it might take up to a second in ftpd.server_forever if I understand correctly). I expect if you put a self.join() at the end of the stop() method the problem will go away. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Paul Sijben wrote: You could check the MD5 hashes of your files. indeed but I still need to hook into import to do that reliably, right? Depends. In a job I once had I just supplied a shell script that spat out the MD5 sums of my sources. When I got a support request I had the customer run the script and email the result to me so I could check if anything had changed. (A malicious person could of course have stored the good MD5 sums, then done his changes, and then made his request, sending me the old sums.) If your customer is cooperative and trustworthy, this is a good way to find stupid mistakes. If he ain't, drop him ;-) robert -- http://mail.python.org/mailman/listinfo/python-list
Re: *** AMERICAN BASTARDS DESERVE TO BE RAPED ***
James Matthews wrote: When did this list become a politics dialog? Please keep on topic Python! Thanks James On Jan 12, 2008 8:07 PM, Joe Riopel [EMAIL PROTECTED] wrote: On Jan 12, 2008 2:00 PM, radiosrfun [EMAIL PROTECTED] wrote: Whether we agree on tactics or not - if it come to a battlefield with the two of us - or any Americans there - we're still going to fight the same enemy - not each other. This is a good resource for starting Python http://diveintopython.org/ -- http://mail.python.org/mailman/listinfo/python-lis indian = CreeIndian() indian.setVoice(lugubrious) indian.says(When the last tree is cut down, the last fish eaten and the last stream poisoned, you will realize that you cannot eat money.) :) -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Ben Finney [EMAIL PROTECTED] writes: What one is in reality calling is the '__new__' method of the Person class. That function, in turn, is creating a new Person instance, and calling the '__init__' method of the newly-created instance. Finally, the '__new__' method returns that instance back to the caller. This is also not entirely correct. __new__ doesn't call __init__; if it did, there would be no way to call __new__ without also calling __init__ (pickle, among other things, does that and needs to do that to correctly implement its logic). In reality executing Person(...) invokes the __call__ method of type(Person) (normally the standard metatype called type) bound to the Person type object. This is where the logic to call __new__ followed by __init__ is implemented, in code that does something close to this: obj = mytype.__new__(*args, **kwds) if isinstance(obj, mytype): mytype.__init__(obj, *args, **kwds) return obj -- http://mail.python.org/mailman/listinfo/python-list
who can give me a good list.i am a new learner.
in this list: mail.python.org Mailing Lists. which one suits for learner. thanks very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Steven D'Aprano wrote: No, it's a serious question. You distribute Python code, and you're worried that your users will modify the source code and then neglect to mention it when they report bugs which they introduced. Before you build an elephant-proof fence around your house, it is quite reasonable to ask whether or not there are actually elephants in your neighbourhood. Depending on where you are, there are probably plenty. Recently I started hacking around in a GPLed Python app (GRAMPS, if anybody cares). This program has a built-in bug report feature which makes it easy to email bugs with associated stack trace etc. to the developers. Unfortunately the bug report window also automatically popped up even when stuff went wrong within my own broken code. For such a case it would be good if a software could somehow detect modifications of itself and its associated modules. And, contrary to the advice I gave elsethread, unfortunately it's impossible to just drop uncooperative customers when you develop GPL software ;-) robert -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 14, 1:41 pm, Richard Szopa [EMAIL PROTECTED] wrote: However, there's one piece that doesn't completely fit to the puzzle: why does getattr work? The help says: getattr(...) getattr(object, name[, default]) - value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Does it work on the basis that getattr(x, 'y') is equivalent to x.y? What is then a named attribute for an object in Python? It seems not to be equivalent to the value of the item whose name is 'y' in the object's class __dict__... Cheers, -- Richard I really need to publish this one day or another, since these questions about super keeps coming out: http://www.phyast.pitt.edu/~micheles/python/super.html -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 13, 3:31 pm, thebjorn [EMAIL PROTECTED] wrote: They do, except for when it comes to what super(..) returns. It isn't really an object in the sense that they're presented in the tutorial, but rather a sort of proxy to the methods in the ancestor classes of the concrete object (self), relative to the current method's class. I can't imagine that sentence would ease any confusion however, suffice it to say that you have to call getattr(super(..), 'name') instead of super(..).__getattr__('name') and you have to call super(..).__len__() instead of len(super(..)) -- I can't imagine that lessens any confusion either :-/ Surprisingly, I think your first sentence *does* make something more clear. Let me check if I understand it right: when we call a method on super(Foo, self) it is as if we were calling call-next-method in Common Lisp or Dylan (i.e. the method of the class on the right of Foo in self.mro()). This however does not imply for super to have its dict the same as the class on the right of Foo---it remains the same as self's dict. However, there's one piece that doesn't completely fit to the puzzle: why does getattr work? The help says: getattr(...) getattr(object, name[, default]) - value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Does it work on the basis that getattr(x, 'y') is equivalent to x.y? What is then a named attribute for an object in Python? It seems not to be equivalent to the value of the item whose name is 'y' in the object's class __dict__... Cheers, -- Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: where do my python files go in linux?
On 14 Jan, 08:47, A.T.Hofkamp [EMAIL PROTECTED] wrote: Rather than re-inventing the wheel, please have a look at distutils: http://docs.python.org/lib/module-distutils.html It does most if not all of the things you want to do. If you want something more advanced, read about eggs. Although distutils does some of the work needed by the inquirer, it falls far short of what is needed to make a Debian package - that's why you have the new Debian Python policy and why the authors specifically refer to both distutils and setuptools in that document. Meanwhile, even stdeb [1] doesn't appear to completely automate the production of Debian packages using distutils. The Debian packages that I've attempted to make have, in fact, mostly employed distutils to install the files into the package, and as the policy document indicates, you have to turn off various setuptools features to persuade that software to play along if you're using it. However, there's a lot of other stuff that neither distutils nor setuptools do adequately, and setuptools' lack of integration with the non-Python universe doesn't exactly make it a great replacement for the system package and dependency managers in most GNU/Linux distributions. I've been tempted at various points to use something like SCons (or similar [2]) rather than work around undesirable behaviour in distutils. And although some might say that setuptools is an improvement on distutils, it's an improvement in a direction that interests me very little. Paul [1] http://stdeb.python-hosting.com/ [2] http://wiki.python.org/moin/ConfigurationAndBuildTools -- http://mail.python.org/mailman/listinfo/python-list
jpype with JFreeChart, anyone interested to help?
As you may know, there is no beautiful and free chart(not plot, you can find the examples at http://www.jfree.org/jfreechart, http://www.rmchart.com) module for python than runs on windows/linux/mac osx. On the other hand, there is a living package(http://www.jfree.org/jfreechart) for java, and it is nice. So what about make the interface to JFreeChart via jpype(http://jpype.sourceforge.net), or rewrite JFreeChart in and for Python to kick off JVM? I have tried this, but since I don't know Java, I did not go further. If anyone can help me with the following code, or organzie a py_jfreechart team, or put up a pyFreeChart team, that would be great. Thanks [code] import jpype p=r'e:\Java\j2re1.4.0\bin\client\jvm.dll' jpype.startJVM(p, r'-Djava.class.path=h:\jfreechart-1.0.9\lib\jfreechart-1.0.9.jar' ) pkg=jpype.JPackage(org.jfree.data) print pkg.DefaultKeyedValues print pkg.DefaultKeyedValues.DefaultKeyedValues print pkg.DefaultKeyedValues.DefaultKeyedValues.DefaultKeyedValues jc=jpype.JClass(org.jfree.data.DefaultKeyedValues) [/code] [msg] Java package org.jfree.data.DefaultKeyedValues Java package org.jfree.data.DefaultKeyedValues.DefaultKeyedValues Java package org.jfree.data.DefaultKeyedValues.DefaultKeyedValues.DefaultKeyedV alues Traceback (most recent call last): File H:\jfreechart-1.0.9\lib\b.py, line 11, in module jc=jpype.JClass(org.jfree.data.DefaultKeyedValues) File H:\jfreechart-1.0.9\lib\jpype\_jclass.py, line 54, in JClass raise _RUNTIMEEXCEPTION.PYEXC(Class %s not found % name) jpype._jexception.ExceptionPyRaisable: java.lang.Exception: Class org.jfree.data.DefaultKeyedValues not found [/msg] -- http://mail.python.org/mailman/listinfo/python-list
ucs2 or ucs4?
How do I tell if my python-2.5 is build with ucs2 or ucs4? -- http://mail.python.org/mailman/listinfo/python-list
Re: Threaded server
On 14 Gen, 12:30, Nick Craig-Wood [EMAIL PROTECTED] wrote: Giampaolo Rodola' [EMAIL PROTECTED] wrote: I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: Ran 50 tests in 1.515s OK Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPHandler.__del__ of pyftpdlib.ftpserver.FTPHandler connected 127.0.0.1:2 249 at 0xa4b080 ignored Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPServer.__del__ of pyftpdlib.ftpserver.FTPServer listening 127.0.0.1:543 21 at 0x9e1a30 ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). It looks like when python is shutting down, it has removed an object the ftphandler code relies on. I see you attempt to kill the ftp server with ftpd.stop(). That is good, but you don't wait for the thread to finish (it might take up to a second in ftpd.server_forever if I understand correctly). I expect if you put a self.join() at the end of the stop() method the problem will go away. -- Nick Craig-Wood [EMAIL PROTECTED] --http://www.craig-wood.com/nick- Nascondi testo tra virgolette - - Mostra testo tra virgolette - Tried it but the problem remains. The strange thing is that it sometimes happens, sometimes doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: ucs2 or ucs4?
On Jan 14, 12:56 pm, Neal Becker [EMAIL PROTECTED] wrote: How do I tell if my python-2.5 is build with ucs2 or ucs4? See if unichr(0x1) raises ValueError: if it does, you're ucs2. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
DBUS and exceptions
Hi, Im using DBUS in my application to detect HW hotplugging and removal, which works great except for one thing: The code executed when a hotplugging is detected does not raise exceptions, even if my code contains errors. The event will just stop silently at the point where the exception occurs, and no message is printed or logged. This makes it hard of course to detect errors I make in the signal handlers, when exceptions aren't raised. There is no try-except-pass clause in my code either which hides the exceptions. I was thinking perhaps its DBUS default behaviour to never fail in its signal handlers? Thanks, Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Threaded server
Giampaolo Rodola' wrote: On 14 Gen, 12:30, Nick Craig-Wood [EMAIL PROTECTED] wrote: Giampaolo Rodola' [EMAIL PROTECTED] wrote: I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: Ran 50 tests in 1.515s OK Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPHandler.__del__ of pyftpdlib.ftpserver.FTPHandler connected 127.0.0.1:2 249 at 0xa4b080 ignored Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPServer.__del__ of pyftpdlib.ftpserver.FTPServer listening 127.0.0.1:543 21 at 0x9e1a30 ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). It looks like when python is shutting down, it has removed an object the ftphandler code relies on. I see you attempt to kill the ftp server with ftpd.stop(). That is good, but you don't wait for the thread to finish (it might take up to a second in ftpd.server_forever if I understand correctly). I expect if you put a self.join() at the end of the stop() method the problem will go away. -- Nick Craig-Wood [EMAIL PROTECTED] --http://www.craig-wood.com/nick- Nascondi testo tra virgolette - - Mostra testo tra virgolette - Tried it but the problem remains. The strange thing is that it sometimes happens, sometimes doesn't. AFAIK you can safely ignore this error. It essentially stems from non-determinism when shutting down threads. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: ucs2 or ucs4?
Neal Becker wrote: How do I tell if my python-2.5 is build with ucs2 or ucs4? You can also check sys.maxunicode. import sys sys.maxunicode If it's 1114111, you're UCS-4. If it's something much lower, you're UCS-2. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: NotImplimentedError
By the way, why do we need both NotImplementedError and the NotImplemented singleton object ? Couldn't we have just one of them ? -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pylint 0.14 / logilab-astng 0.17.2
Hi there! I'm pleased to announce a new release of pylint [1] and logilab-astng [2]. I haven't personally found a lot of time to work on those projects since the latest releases but others contributors have and so I decided to publish releases including various contributions and other minor bug or crash fixes (some of which were pending for a while now). You're greatly encouraged to upgrade, see projects'changelog for more information about what changed. [1] http://www.logilab.org/projects/pylint [2] http://www.logilab.org/projects/logilab-astng Many thanks to every people who contributed! regards, -- Sylvain Thénault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: NotImplimentedError
On Jan 14, 2008 9:01 AM, George Sakkis [EMAIL PROTECTED] wrote: By the way, why do we need both NotImplementedError and the NotImplemented singleton object ? Couldn't we have just one of them ? I think we need both because an unimplemented method is an error, while an unimplemented rich comparison between disparate types is (usually) not. It could be made to work with one object fulfilling both functions, but then the name would be wrong for one case or the other. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: who can give me a good list.i am a new learner.
bill.wu a écrit : in this list: mail.python.org Mailing Lists. which one suits for learner. Depends on your definition of learner !-) python.list (http://mail.python.org/mailman/listinfo/python-list) is mostly the same thing as this newsgroup (there's a bridge between the list and the newsgroup), so you may as well post here (don't worry, we usually don't eat newbies). Tutor (http://mail.python.org/mailman/listinfo/tutor) is dedicated to those who are not only new to Python, but also new to programming. If Python is your very first language and you don't know anything about programming, you may be better posting to the tutor list - which doesn't prevent you from lurking here. Else, you're already at the right place. -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Jeroen Ruigrok van der Werven wrote: To restate it more correctly: __init__ is akin to a constructor. No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply). __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed via the __new__() method. __new__() actually /constructs/ a new instance. I am not entirely sure I fully understand __new__'s semantics though. Create a new (blank) instance of a class and return it. That's all there is to it. I must not be understanding something and __new__'s documentation there is not that clear to me, to be honest. It is somewhat confusing at first. But just bear in mind: 99 out of 100 times, you don't need to override __new__(). When you need it, you'll know. /W -- http://mail.python.org/mailman/listinfo/python-list
csv add lines
Hi, I'm new to this list and to python. I am wondering, am I able to make my program read the *.txt files from a directory and to add, at the top of the file, three new lines which are stored in a *.csv file? For each *.txt file I have a line in the *.csv file which has in the first column the name of the *.txt file and in the next three columns the lines that I want to add in the corresponding *.txt file. If it is possible I'd appreciate some help. Thank you! Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: csv add lines
On Jan 14, 2008 3:52 PM, Alexandru Dumitrescu [EMAIL PROTECTED] wrote: Hi, I'm new to this list and to python. I am wondering, am I able to make my program read the *.txt files from a directory and to add, at the top of the file, three new lines which are stored in a *.csv file? Maybe you are still not able to do it :-) But if you give a look at the csv module you probably will be in a short time. Just read http://docs.python.org/lib/module-csv.html where you will learn how to parse a csv file. bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
RE: encrypting python modules
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Paul Sijben Sent: Friday, January 11, 2008 4:45 AM To: python-list@python.org Subject: encrypting python modules The problem: I have a client-server app written in python. I want to make sure that the client is not: 1) destabilized by users accidentally or on purpose dropping python files in the path (after which calling the helpdesk will not be useful) 2) extended with new features without me knowing about it (again resulting in calls to my helpdesk...) Would the site module help with that? It looks like site will let you put your modules first in sys.path. Or what about just updating sys.path as the first action in your program? Or what about pulling clean copies of the files from a tar/zip/archive before execution? A shell script creates a temp dir and extracts the files to the temp dir to run. Not sure it would do any good to pull from an encrypted tar/zip/archive. Or what about pulling the client files from the server instead of a tar/zip/archive...? * The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625 -- http://mail.python.org/mailman/listinfo/python-list
Pydev 1.3.11 Released
Hi All, Pydev and Pydev Extensions 1.3.11 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: - * Code-analysis: Doesn't report 'statement without effect' within yield. * Code-analysis: @DynamicAttrs now works in direct class access (not only on instance access from a class). * Code-analysis: Names to consider in global do not trigger undefined variables when they have some attribute access. * Code-analysis: Accessing locals() will mark local variables as read. * Code-analysis: No indentation warnings on multiline strings that use double quotes. Release Highlights in Pydev: -- * Jython Integration: Java modules may be referenced from pydev projects (working with code-completion, go to definition, etc). * Jython Debugger: Does not attempt to run untraced threads if version = 2.2.1 (this was a Jython bug that's patched for the current trunk -- note: it prevented the debugger from working correctly with Jython). * Project build: Only referenced projects are rebuilt (and not all projects in the workspace -- e.g.: unreferenced c++ projects). * Spell checking (depends on JDT): Integrated for comments and strings within pydev (eclipse 3.4 should add the support for working without JDT. Reference: http://www.eclipse.org/eclipse/platform-text/3.4/plan.php). * Files without extension: A file without extension can have code-completion / go to definition (as long as the others around it do have extensions) * Debug: Variable substitution is no longer asked twice in debug mode. * Custom Filters: User-defined filters can be specified in the Pydev package explorer. * Debugger: performance improvements to get the existing frames for Python 2.4 and Jython 2.1. * Outline view: Better refresh (doesn't collapse the tree for simple structure changes). * Undo limit: The undo limit set in window preferences general editors text editors works for pydev. * Editor: Tabs as spaces: The newly added 'insert spaces for tabs' in the general preferences was conflicting with pydev (those settings are now ignored) * Patch by Laurent Dore: Added filter for *.py~ and comments * Delete *.pyc action: also deletes *.pyo files * Ctrl+Click: behaves exactly as F3. * Dedent: No auto-dedent after yield What is PyDev? --- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny -- Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: where do my python files go in linux?
Paul Boddie [EMAIL PROTECTED] wrote: On 14 Jan, 08:47, A.T.Hofkamp [EMAIL PROTECTED] wrote: Rather than re-inventing the wheel, please have a look at distutils: http://docs.python.org/lib/module-distutils.html It does most if not all of the things you want to do. If you want something more advanced, read about eggs. Although distutils does some of the work needed by the inquirer, it falls far short of what is needed to make a Debian package - that's why you have the new Debian Python policy and why the authors specifically refer to both distutils and setuptools in that document. It would be nice to have an equivalent to dh-make-perl which takes a CPAN module and makes a .deb directly. http://packages.debian.org/stable/devel/dh-make-perl What I usually do is python setup.py bdist_rpm Then use alien to convert the resulting .rpm into a .deb I don't think these create particularly policy compliant .debs but they are good enough for local usage. Meanwhile, even stdeb [1] doesn't appear to completely automate the production of Debian packages using distutils. Looks interesting though! [1] http://stdeb.python-hosting.com/ -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Given that getlocale() is not to be used, what's the best way to get the locale later in the app? I need that two-letter code that's hidden in a typical locale like en_ZA.utf8 -- I want that 'en' part. BTW - things are hanging-together much better now, thanks to your info. I have it running in locale 'C' as well as my other test locales. What a relief! \d -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Wildemar Wildenburger [EMAIL PROTECTED] writes: Jeroen Ruigrok van der Werven wrote: To restate it more correctly: __init__ is akin to a constructor. No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply). __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Take C++ and Java, the two most popular OO languages in existence. Their constructors also initialize an instance -- the actual allocation is left to the caller (new or stack in C++) or to the garbage collector. They even share with Python the convention of not returning the constructed value, they operate purely on side effect, just like Python's __init__. And yet, no one says that they are somehow not constructors because of that. Wikipedia calls the constructor a special method used in object oriented programming which puts the object's members into a valid state. Again, exactly what __init__ does. -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Hrvoje Niksic wrote: Wildemar Wildenburger [EMAIL PROTECTED] writes: Jeroen Ruigrok van der Werven wrote: To restate it more correctly: __init__ is akin to a constructor. No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply). __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Nevertheless, __init__ doesn't construct anything. You can even call it to reinitialize an existing object: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type help, copyright, credits or license for more information. class AClass (object): ... def __init__ (self): ... self.a = 4 ... a = AClass() a.a 4 a.a = 5 a.a 5 a.__init__() a.a 4 Cheers, Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: jpype with JFreeChart, anyone interested to help?
On Jan 14, 6:51 am, oyster [EMAIL PROTECTED] wrote: As you may know, there is no beautiful and free chart(notplot, you can find the examples athttp://www.jfree.org/jfreechart,http://www.rmchart.com) module for python than runs on windows/linux/mac osx. Actually, may I humbly suggest two: Chaco: http://code.enthought.com/chaco/gallery/index.shtml matplotlib: http://matplotlib.sourceforge.net/ -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Mel [EMAIL PROTECTED] writes: I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Nevertheless, __init__ doesn't construct anything. Only if by construct you mean allocate. __init__ starts out with an empty object and brings it to a valid state, therefore constructing the object you end up with. That operation is exactly what other languages call a constructor. -- http://mail.python.org/mailman/listinfo/python-list
module naming conventions
Obviously Java-style naming is a mistake in Python, since top-level names have to be unique. Is there a standard naming convention to facilitate mixing code from different sources, such as mygroupname_modulename? Is there a best practices guide for module naming? Thanks, David -- http://mail.python.org/mailman/listinfo/python-list
Re: [Kamaelia] TCPClient: How to sense connection failure?
Bjoern Schliessmann wrote: Whoops, the TCP client does in fact quit if the server closes connection :) Great - so it wasn't a problem with the TCPClient after all :-) For some reason, my Listener doesn't quit. I thought it's sufficient to exit the main method in some way to quit a component? That's what I do using break in the 'if self.dataReady(control)' part of main. It is sufficient, and running with Kamaelia from /trunk, your listener does indeed shutdown correctly - so it looks like it's a bug in that release of Kamaelia. That's my bad really because we haven't done a full release in quite some time. Looking at the old code, it appears that in that code the TCPClient wasn't forwarding shutdown messages correctly, so there *was* a bug, but there doesn't seem to be now. My suggestion for the moment would be to use the code on /trunk since this is stable at present (development happens on branches rather than /trunk) and that I really ought to sort out the next release - I really hadn't realised just how long it had been since the last release! steps: ~ svn co https://kamaelia.svn.sourceforge.net/svnroot/kamaelia/trunk kamaelia-trunk ~ cd kamaelia-trunk ~/kamaelia-trunk cd Code/Python/Axon ~/kamaelia-trunk/Code/Python/Axon sudo python setup.py install ~/kamaelia-trunk/Code/Python/Axon cd ../Kamaelia ~/kamaelia-trunk/Code/Python/Kamaelia sudo python setup.py install I've tested using this, and your code works as you'd expect. Regards, Michael. -- http://mail.python.org/mailman/listinfo/python-list
RE: __init__ explanation please
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Hrvoje Niksic Sent: Monday, January 14, 2008 11:29 AM To: python-list@python.org Subject: Re: __init__ explanation please Mel [EMAIL PROTECTED] writes: I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Nevertheless, __init__ doesn't construct anything. Only if by construct you mean allocate. __init__ starts out with an empty object and brings it to a valid state, therefore constructing the object you end up with. That operation is exactly what other languages call a constructor. Nah. Most other languages combine the constructor and an init function. Normally with c++ I'll have the constructor call an Init() function so I can re-initialize the object as needed. Python has explicitly split the two. Besides, the Python docs say that __new__ is the constructor and __init__ may or may not be called after the instance is created: __new__( cls[, ...]) Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls). ... If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked ... If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked. __init__( self[, ...]) Called when the instance is created. ... As a special constraint on constructors, no value may be returned; Also, how can a constructor require 'self' as an argument...? __init__(self, ...) If the __init__ function is called by the constructor it cannot return a value. However if called as a normal function, it can return a value. __init__ is just a function that gets called by the constructor, which is __new__. count = 0 class AClass (object): def __init__ (self): self.a = 4 global count if count 0: return 'hello world' count += 1 a = AClass() print a.a print a.__init__() c:\foo\a.py 4 hello world * The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE won't start in Python 2.5 for Windows
I was able to start IDLE from the command line, and reset my keyboard shortcuts. It works fine now. In case this happens again, where would I find the config file? -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 12, 6:56 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sat, 12 Jan 2008 15:47:05 -0500, Mike Meyer wrote: There's an apparently common bug here: you don't want to pass super self.__class__, but the class that the method is bound to. Given an instance method, is it possible to easily determine what class it is defined in? I thought the im_class attribute might do it, but it apparently just points to self.__class__. class Foo(object): ... def foo(self): ... pass ... class Bar(Foo): ... def bar(self): ... pass ... Bar().bar.im_class # expecting Bar class '__main__.Bar' Bar().foo.im_class # hoping for Foo class '__main__.Bar' Something like that seems to work for most cases: from inspect import getmro def getdef(obj,attr): try: objattrs = obj.__dict__ except AttributeError: objattrs = obj.__slots__ if attr in objattrs: return obj for cls in getmro(obj.__class__): if attr in cls.__dict__: return cls getdef(Bar(), 'bar') class '__main__.Bar' getdef(Bar(), 'foo') class '__main__.Foo' It probably misses some edge cases but I can't think of any off the top of my head. George -- http://mail.python.org/mailman/listinfo/python-list
bags? 2.5.x?
Is there a particular reason why bags didn't go into 2.5.x or 3000? I keep wanting something like them - especially bags with something akin to set union, intersection and difference. -- http://mail.python.org/mailman/listinfo/python-list
problem with logging exceptions with non-ASCII __str__ result
Dear all, I have a problem with logging an exception. environment: Python 2.4, Debian testing ${LANGUAGE} not set ${LC_ALL} not set ${LC_CTYPE} not set ${LANG}=de_DE.UTF-8 activating user-default locale with locale.setlocale(locale.LC_ALL, '') returns: [de_DE.UTF-8] locale.getdefaultlocale() - default (user) locale: ('de_DE', 'utf-8') encoding sanity check (also check locale.nl_langinfo(CODESET) below): sys.getdefaultencoding(): [ascii] locale.getpreferredencoding(): [UTF-8] locale.getlocale()[1]: [utf-8] sys.getfilesystemencoding(): [UTF-8] _logfile = codecs.open(filename = _logfile_name, mode = 'wb', encoding = 'utf8', errors = 'replace') logging.basicConfig ( format = fmt, datefmt = '%Y-%m-%d %H:%M:%S', level = logging.DEBUG, stream = _logfile ) I am using psycopg2 which in turn uses libpq. When trying to connect to the database and providing faulty authentication information: try: ... try to connect ... except StandardError, e: _log.error(ulogin attempt %s/%s failed:, attempt+1, max_attempts) print exception type :, type(e) print exception dir :, dir(e) print exception args :, e.args msg = e.args[0] print msg type:, type(msg) print msg.decode(utf8):, msg.decode('utf8') t,v,tb = sys.exc_info() print sys.exc_info() :, t, v _log.exception(u'exception detected') the following output is generated: exception type : type 'instance' exception dir : ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] exception args : ('FATAL: Passwort-Authentifizierung f\xc3\xbcr Benutzer \xc2\xbbany-doc\xc2\xab fehlgeschlagen\n',) msg type: type 'str' msg.decode(utf8): FATAL: Passwort-Authentifizierung für Benutzer »any-doc« fehlgeschlagen sys.exc_info() : psycopg2.OperationalError FATAL: Passwort-Authentifizierung für Benutzer »any-doc« fehlgeschlagen Traceback (most recent call last): File /usr/lib/python2.4/logging/__init__.py, line 739, in emit self.stream.write(fs % msg.encode(UTF-8)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 191: ordinal not in range(128) Now, the string FATAL: Passwort-Auth... comes from libpq via psycopg2. It is translated to German via gettext within libpq (at the C level). As we can see it is of type string. I know from the environment that it is likely encoded in utf8 manually applying which (see the decode call) succeeds. On _log.exception() the logging module wants to output the message as encoded as utf8 (that's what the log file is set up as). So it'll look at the string, decide it is of type str and decode with the *Python default encoding* to get to type unicode. Following which it'll re-encode with utf8 to get back to type str ready for outputting to the log file. However, since the Python default encoding is ascii that conversion fails. Changing the Python default encoding isn't really an option as it is advocated against and would have to be made to work reliably on other users machines. One could, of course, write code to specifically check for this condition and manually pre-convert the message string to unicode but that seems not as things should be. How can I cleanly handle this situation ? Should the logging module internally use an encoding gotten from the locale module rather than the default string encoding ? Karsten -- GPG key ID E4071346 @ wwwkeys.pgp.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
snipped time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. Take a look at datetime. It is good to the micro-second on Linux and milli-second on Windows. import datetime begin_time=datetime.datetime.now() for j in range(10): x = j+1 # wait a small amount of time print Elapsed time =, datetime.datetime.now()-begin_time ## You can also access the individual time values print begin_time.second print begin_time.microsecond ## etc. -- http://mail.python.org/mailman/listinfo/python-list
Parsing links within a html file.
Hello, I have a html file over here by the name guide_ind.html and it contains links to other html files like guides.html#outline . How do I point BeautifulSoup (I want to use this module) to guides.html#outline ? Thanks Shriphani P. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic inheritance question
On Jan 7, 2:46 am, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Lie a écrit : On Jan 5, 5:40 pm, [EMAIL PROTECTED] wrote: Jeroen Ruigrok van der Werven wrote: Shouldn't this be: self.startLoc = start self.stopLoc = stop Thanks! Of course it should. Old Java habits die slowly. No, seriously it isn't Java habits only, most other languages wouldn't need explicit calling of class name. Where is the explicit calling of class name exactly ? Perhaps I was a bit tired when writing that (I wouldn't understand what I wrote if I were you)... what I meant is most other languages doesn't usually enforce us to explicitly state the containing class name, which in python is generally called self. Most other languages 1) automatically assign the containing class' object in a keyword (Java: this, VB: Me) behind the screen, and 2) automatically searches variable name in both the local variable table and the containing class variable table (so to refer to a class variable named var from a method inside the class, we only need to write var, not self.var as in python). In VB, Me is extremely rarely used, in Python, self is all over the place. Well, there is positive and negative to both sides, convenience in VB, and flexibility in Python. Compare the following codes: VB.NET: Public Class A Dim var Public Function aFunction() return var Python: class A: def aFunction(self): return self.var -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython-wx.CheckListBox: changing item bacgkground color
On Jan 13, 9:22 am, Massi [EMAIL PROTECTED] wrote: Hi everyone! In my application (under windows) I'm using a wx.checklistbox. I would like the background color of an item to become red whenever an EVT_LISTBOX_DCLICK occurs. Is there any simple way to achieve it? Thanks in advance. Did you try chkbox.SetBackgroundColor('SomeColor') ? That might work, but I think that will just set the entire control's background to the color passed in. You're welcome to give it a try, though. Also, I would recommend posting this query to the wxpython's user group, which you can find at the wxPython website: www.wxpython.org Mike -- http://mail.python.org/mailman/listinfo/python-list
short path evaluation, why is f() called here: dict(a=1).get('a', f())
This append in both case dict(a=1).get('a', f()) dict(a=1).setdefault('a', f()) This should be nice if f() was called only if required. Regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: Exceptions - How do you make it work like built-in exceptions?
On Jan 14, 1:51 am, Mark Tolonen [EMAIL PROTECTED] wrote: Lie [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File F:\dir\code.py, line 43, in module a = 1/0 --- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File F:\dir\code.py, line 48, in module raise SomeException('Some Exception Message') --- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') Is it possible to make the user-made exception points out the offending code? The raise statement *was* the offending (unhandled exception) code. The ZeroDivisionError was handled by your except clause. Well, what you meant by offending code and what I meant by offending code is different, what I meant by offending code as the code that makes the exception _need_ to be called (i.e. the a=1/0) and in my view (in this case), anything inside the except clause is not a real code, as it doesn't do anything useful for the program. You can override the traceback your exception will use with the three-expression form of the raise statement (See Section 6.9 The raise statement in the Python Reference Manual) by passing the traceback of the original exception: ## CODE # import sys class SomeException(Exception): pass try: a=1/0 except: org_type,org_value,org_traceback = sys.exc_info() raise SomeException,'had some problems with this code',org_traceback ## OUTPUT ## Traceback (most recent call last): File exc.py, line 7, in module a=1/0 SomeException: had some problems with this code --Mark Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Jan 14, 2008 1:39 PM, aspineux [EMAIL PROTECTED] wrote: This append in both case dict(a=1).get('a', f()) dict(a=1).setdefault('a', f()) This should be nice if f() was called only if required. Shortcomings of those methods is probably why collections.defaultdict is so popular. def f(): ...return 7 ... d = defaultdict(f, a=1) d['a'] 1 d['b'] 7 get and setdefault aren't needed when using a default dict, and the default factory is called only when needed. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
On Jan 14, 2008 12:08 PM, Reedick, Andrew [EMAIL PROTECTED] wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Hrvoje Niksic Sent: Monday, January 14, 2008 11:29 AM Only if by construct you mean allocate. __init__ starts out with an empty object and brings it to a valid state, therefore constructing the object you end up with. That operation is exactly what other languages call a constructor. Nah. Most other languages combine the constructor and an init function. Normally with c++ I'll have the constructor call an Init() function so I can re-initialize the object as needed. Python has explicitly split the two. Besides, the Python docs say that __new__ is the constructor and __init__ may or may not be called after the instance is created: The documentation of __new__ carefully refrains from calling __new__ a constructor. Both __new__ and __init__ mention the object constructor expression, e.g., list(). __init__( self[, ...]) Called when the instance is created. ... As a special constraint on constructors, no value may be returned; Once again, the documentation is referring to constructor expressions. As you noted, __init__ may return a value when not called by a constructor expression. C++'s constructor initialization lists are the closest thing to Python's __new__. They can perform tasks for which Python might need __new__. For example, a class member that's a reference must be initialized in the initialization list, because it cannot be set once the body of the constructor begins. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Jan 14, 2008 12:39 PM, aspineux [EMAIL PROTECTED] wrote: This append in both case dict(a=1).get('a', f()) dict(a=1).setdefault('a', f()) This should be nice if f() was called only if required. Think about the change to Python semantics that would be required for this to be true, and then use collections.defaultdict instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: Magic function
Hi Rüdiger, Thanks for your message. I liked your approach and I've been trying something along exactly these sorts of lines, but I have a few problems and queries. The first problem is that the id of the frame object can be re-used, so for example this code (where I haven't defined InstanceTracker and getInstances, but they are very closely based on the ideas in your message): class A(InstanceTracker): gval = 0 def __init__(self): self.value = A.gval # each time you make a new object, give A.gval += 1 # it a value one larger def __repr__(self): return str(self.value) def f2(): a = A() # objects 0 and 2 return getInstances(A) def f3(): a = A() # object 1 return f2() inst2 = f2() inst3 = f3() print inst2 print inst3 The output is: [0] [0, 2] The A-variable with value 0 is not being garbage collected because it's saved in the variable inst2, but it's also being returned by the second call to getInstances because the frame of f2 is the same each time (which makes sense, but may be implementation specific?). The same problem doesn't exist when you use the stack searching method because from f2's point of view, the only bound instance of A is the one in that particular call of f2. If you had at the end instead of the inst2, inst3 stuff: print f2() print f3() The output is: [0] [2] Again, I guess this because A with value 0 is being garbage collected between print f2() and print f3(), but again I think this is implementation specific? You don't have a guarantee that this object will be garbage collected straight away do you? So my concern here is that this approach is actually less safe than the stack based approach because it depends on implementation specific details in a non-straightforward way. That said, I very much like the fact that this approach works if I write: a = [A()] a = [[A()]] etc. To achieve the same thing with the stack based approach you have to search through all containers to (perhaps arbitrary) depth. I also have another problem which is that I have a function decorator which returns a callable object (a class instance not a function). Unfortunately, the frame in which the callable object is created is the frame of the decorator, not the place where the definition is. I've written something to get round this, but it seems like a bit of a hack. Can anyone suggest an approach that combines the best of both worlds, the instance tracking approach and the stack searching approach? Or do I need to just make a tradeoff here? Thanks again for all your help everyone, Dan Goodman -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Jan 14, 7:49 pm, Chris Mellon [EMAIL PROTECTED] wrote: On Jan 14, 2008 12:39 PM, aspineux [EMAIL PROTECTED] wrote: This append in both case dict(a=1).get('a', f()) dict(a=1).setdefault('a', f()) This should be nice if f() was called only if required. Think about the change to Python semantics that would be required for this to be true, and then use collections.defaultdict instead. Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) -- d['a', f()] d.setdefault('a', f()) -- d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Reedick, Andrew [EMAIL PROTECTED] writes: Only if by construct you mean allocate. __init__ starts out with an empty object and brings it to a valid state, therefore constructing the object you end up with. That operation is exactly what other languages call a constructor. Nah. Most other languages combine the constructor and an init function. Maybe so, but the standard term for what Python calls __init__ is still constructor. Also, how can a constructor require 'self' as an argument...? __init__(self, ...) Think of it as the equivalent of Java's and C++'s this, except it's explicit in the argument list. Explicit is better than implicit and all that. :-) -- http://mail.python.org/mailman/listinfo/python-list
help with slicing/replacing matrix sections.
I see a more complicated thread on a similar sounding question, but my question is simpler, I hope. I have a large numpy matrix, initially created as: Mat = zeros((a,b), int) and a smaller array with other data Sub = [1,2,3,4,5],[6,7,8,9,0] I want to replace a section of Mat matrix with Sub matrix without having to loop through each cell in each matrix individually. I thought index/slice assignments, should be able to do that, but I can only get it to work (as per book examples) with simple arrays. Every syntax combination I have tried gives one error or another, typically can't broadcast an object, but intuitively it seems there should be a simple solution. In short, how do I insert the data in the two (or any number of) rows in Sub[0:2] into any part of Mat starting at Mat[x,y] without using for loops ? -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
[EMAIL PROTECTED] wrote: snipped time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. Take a look at datetime. It is good to the micro-second on Linux and milli-second on Windows. datetime.datetime.now() does the same thing as time.time(); it uses the gettimeofday() API for platforms that have it (and so does time.time()), and calls the fallback implementation in time.time() if gettimeofdat() isn't supported. from the datetime sources: #ifdef HAVE_GETTIMEOFDAY struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ gettimeofday(t); #else gettimeofday(t, (struct timezone *)NULL); #endif ... #else /* ! HAVE_GETTIMEOFDAY */ /* No flavor of gettimeofday exists on this platform. Python's * time.time() does a lot of other platform tricks to get the * best time it can on the platform, and we're not going to do * better than that (if we could, the better code would belong * in time.time()!) We're limited by the precision of a double, * though. */ (note the if we could part). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
On Jan 14, 8:21 am, Martin P. Hellwig [EMAIL PROTECTED] wrote: Giampaolo Rodola' wrote: Hi all, I'm trying to use the pywin32 extension to find out the user's home directory but currently I didn't find a solution yet. What I'd need to do is not getting the home directory of the currently logged in user but something like: get_homedir(frank) C:\home\users\frank get_homedir(josh) C:\home\users\josh Is there a way to do that? I tried to search through the Pywin32 documentation with no luck. In addition I'm not practiced with the Windows API at all. Well, windows, to my knowledge, uses the same base path for all profiles (this is not true for the My Documents folder which can differ). So what you could do is get the location from the ALLUSERPROFILE environment variable, go one folder higher and iterate through that. Ignoring the folders for the 'pseudo' users: 'All Users', 'Default User', 'LocalService' and 'NetworkService'. hth -- mph There is one problem with that, sometimes the folders for the users are not the same with the user name, usually because of deleting user name without deleting the profile, then recreate a user with similar name. It doesn't happens everytime, but it could. Possibly it is possible to get the SID of the user name (using the way described in Tim Golden's Microsoft Link' post), then find the user directory from the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft \Windows NT\CurrentVersion\ProfileList\[PUT SID HERE]\Profile Image Path -- http://mail.python.org/mailman/listinfo/python-list
Re: bags? 2.5.x?
Dan Stromberg wrote: Is there a particular reason why bags didn't go into 2.5.x or 3000? I keep wanting something like them - especially bags with something akin to set union, intersection and difference. How about this recepie URL:http://www.ubookcase.com/book/Oreilly/Python.Cookbook.2nd.edition/0596007973/pythoncook2-chp-18-sect-8.html? /W -- http://mail.python.org/mailman/listinfo/python-list
SyntaxError: 'import *' not allowed with 'from .'
Unless I missed it, PEP 328 doesn't mention anything about this. What's the reason for not allowing from .relative.module import *' ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: help with slicing/replacing matrix sections.
Erik Lind wrote: I see a more complicated thread on a similar sounding question, but my question is simpler, I hope. numpy questions are usually answered better on the numpy mailing list. http://www.scipy.org/Mailing_Lists I have a large numpy matrix, initially created as: Mat = zeros((a,b), int) and a smaller array with other data Sub = [1,2,3,4,5],[6,7,8,9,0] I want to replace a section of Mat matrix with Sub matrix without having to loop through each cell in each matrix individually. I thought index/slice assignments, should be able to do that, but I can only get it to work (as per book examples) with simple arrays. Every syntax combination I have tried gives one error or another, typically can't broadcast an object, but intuitively it seems there should be a simple solution. In short, how do I insert the data in the two (or any number of) rows in Sub[0:2] into any part of Mat starting at Mat[x,y] without using for loops ? In [11]: Sub = array([[1,2,3,4,5],[6,7,8,9,0]]) In [12]: Mat = zeros((10, 10), int) In [13]: Mat[5:5+2,4:4+5] = Sub In [14]: Mat Out[14]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 2, 3, 4, 5, 0], [0, 0, 0, 0, 6, 7, 8, 9, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: [Kamaelia] TCPClient: How to sense connection failure?
Michael Sparks wrote: It is sufficient, and running with Kamaelia from /trunk, your listener does indeed shutdown correctly Great, thanks for validating. :) My suggestion for the moment would be to use the code on /trunk since this is stable at present (development happens on branches rather than /trunk) I will. Regards, Björn -- BOFH excuse #243: The computer fleetly, mouse and all. -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
aspineux [EMAIL PROTECTED] writes: Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) -- d['a', f()] d.setdefault('a', f()) -- d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? Changing python semantics for something like this is nuts. Allowing passing a callable (sort of like re.sub allows) makes a certain amount of sense: d.get('a', default=f) You can also write (python 2.5, untested): d['a'] if 'a' in d else f() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
Thanks to Tim Golden suggestions I solved my problem. ...In case it would help someone: code import _winreg import win32security username = 'Administrator' sid = win32security.ConvertSidToStringSid( win32security.LookupAccountName(None, username)[0] ) key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, rSOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList + \ \ + sid ) value, type = _winreg.QueryValueEx(key, ProfileImagePath) print value /code -- http://mail.python.org/mailman/listinfo/python-list
Dynamical scoping
What's the best way to simulate dynamically scoped variables ala Lisp ? The use case is an open-ended set of objects that need to access the same piece of information (e.g. a dict, a ConfigParser object, a logger etc.). I know that the proper OO and functional way is to pass the information explicitly but that's less maintenable in the long run. Also this is in a web environment so the information can't be really global (though within-thread global should be fine). Is there some standard pattern for this scenario ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: paging in python shell
Hi Tim, Yes I mean piping the output into more for example. Alex On 14/01/2008, Tim Roberts [EMAIL PROTECTED] wrote: Alex K [EMAIL PROTECTED] wrote: Does anyone know if the python shell supports paging or if I should look into iPython? Thank you so much. Paging is an overloaded term. What do you mean, exactly? Do you mean something like piping the output into more? The Python shell does that for the help command, but maybe you could post a more precise example of what you want. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
On Jan 15, 4:50 am, [EMAIL PROTECTED] wrote: snipped time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. Take a look at datetime. It is good to the micro-second on Linux and milli-second on Windows. On Windows, time.clock has MICROsecond resolution, but your method appears to have exactly the same (MILLIsecond) resolution as time.time, but with greater overhead, especially when the result is required in seconds-and-a-fraction as a float: def datetimer(start=datetime.datetime(1970,1,1,0,0,0), nowfunc=datetime.datetime.now): ... delta = nowfunc() - start ... return delta.days * 86400 + delta.seconds + delta.microseconds / 100.0 ... tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td, diff)) ['1200341583.484', '1200381183.484', '39600.0'] tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td, diff)) ['1200341596.484', '1200381196.484', '39600.0'] tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td, diff)) ['1200341609.4530001', '1200381209.4530001', '39600.0'] tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td, diff)) ['1200341622.562', '1200381222.562', '39600.0'] The difference of 39600 seconds (11 hours) would be removed by using datetime.datetime.utcnow. import datetime begin_time=datetime.datetime.now() for j in range(10): x = j+1 # wait a small amount of time print Elapsed time =, datetime.datetime.now()-begin_time ## You can also access the individual time values print begin_time.second print begin_time.microsecond ## etc. Running that on my Windows system (XP Pro, Python 2.5.1, AMD Turion 64 Mobile cpu rated at 2.0 GHz), I get Elapsed time = 0:00:00.031000 or Elapsed time = 0:00:00.047000 Using 5 iterations, I get it down to 15 or 16 milliseconds. 15 ms is the lowest non-zero interval that can be procured. This is consistent with results obtained by using time.time. Approach: get first result from timer function; call timer in a tight loop until returned value changes; ignore the first difference so found and save the next n differences. Windows time.time appears to tick at 15 or 16 ms intervals, averaging about 15.6 ms. For comparison, Windows time.clock appears to tick at about 2.3 MICROsecond intervals. Finally, some comments from the Python 2.5.1 datetimemodule.c: /* No flavor of gettimeofday exists on this platform. Python's * time.time() does a lot of other platform tricks to get the * best time it can on the platform, and we're not going to do * better than that (if we could, the better code would belong * in time.time()!) We're limited by the precision of a double, * though. */ HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: paging in python shell
On Jan 15, 7:35 am, Alex K [EMAIL PROTECTED] wrote: Hi Tim, Yes I mean piping the output into more for example. Why don't you suck it and see??? E.g. C:\junkcopy con demomore.py for i in range(100): print 'line', i ^Z 1 file(s) copied. C:\junkpython demomore.py | more line 0 line 1 line 2 line 3 line 4 [snip] line 50 line 51 line 52 line 53 line 54 line 55 line 56 -- More -- -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
On Mon, 14 Jan 2008 22:18:44 +1100, Ben Finney wrote: What one is in reality calling is the '__new__' method of the Person class. That function, in turn, is creating a new Person instance, and calling the '__init__' method of the newly-created instance. Finally, the '__new__' method returns that instance back to the caller. But not if Person is an old-style class. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
hide object property from dir() function?
Hi, Sorry for this newbie question, I was puzzled why the existing property of an object is not shown in the dir() function output. v is an lxml Element object variable -- In [44]: v Out[44]: Element 'documentProperties' at 0x8363cf8 In [45]: dir(v) Out[45]: ['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'keys', 'makeelement', 'remove', 'set'] dir() output doesn't contain the .tag, which does exist -- In [46]: v.tag Out[46]: 'documentProperties' what is the rule governing the display of a property from dir()? Many thanks in advance! Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On 12 jan, 19:37, marcstuart [EMAIL PROTECTED] wrote: How do I divide a list into a set group of sublist's- if the list is not evenly dividable ? consider this example: x = [1,2,3,4,5,6,7,8,9,10] y = 3 # number of lists I want to break x into z = y/x what I would like to get is 3 sublists print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9,10] obviously not even, one list will have 4 elements, the other 2 will have 3., the overriding logic, is that I will get 3 lists and find a way for python to try to break it evenly, if not one list can have a greater amount of elements Would I use itertools ? How would I do this ? Thanks Hi, If you want to split the list in 4, do you want [1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist or [1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last sublists ? Assuming you want the second version : === def split_list(lst,nb): # ln = length of smaller sublists # extra = number of longer sublists (they have ln+1 items) ln,extra = divmod(len(lst),nb) pos = ln*(nb-extra) # position where larger sublists begin return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \ + [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)] == x = range(1,11) print split_list(x,1) [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] print split_list(x,2) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] print split_list(x,3) [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] print split_list(x,4) [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] print split_list(x,5) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] print split_list(x,10) [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] -- http://mail.python.org/mailman/listinfo/python-list
Re: paging in python shell
Thanks John, but would it be possible to remain in the python interpreter? On 14/01/2008, John Machin [EMAIL PROTECTED] wrote: On Jan 15, 7:35 am, Alex K [EMAIL PROTECTED] wrote: Hi Tim, Yes I mean piping the output into more for example. Why don't you suck it and see??? E.g. C:\junkcopy con demomore.py for i in range(100): print 'line', i ^Z 1 file(s) copied. C:\junkpython demomore.py | more line 0 line 1 line 2 line 3 line 4 [snip] line 50 line 51 line 52 line 53 line 54 line 55 line 56 -- More -- -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with logging exceptions with non-ASCII __str__ result
On Jan 14, 5:46 pm, Karsten Hilbert [EMAIL PROTECTED] wrote: Dear all, I have a problem withloggingan exception. environment: Python 2.4, Debian testing ${LANGUAGE} not set ${LC_ALL} not set ${LC_CTYPE} not set ${LANG}=de_DE.UTF-8 activating user-default locale with locale.setlocale(locale.LC_ALL, '') returns: [de_DE.UTF-8] locale.getdefaultlocale() - default (user) locale: ('de_DE', 'utf-8') encoding sanity check (also check locale.nl_langinfo(CODESET) below): sys.getdefaultencoding(): [ascii] locale.getpreferredencoding(): [UTF-8] locale.getlocale()[1]: [utf-8] sys.getfilesystemencoding(): [UTF-8] _logfile = codecs.open(filename = _logfile_name, mode = 'wb', encoding = 'utf8', errors = 'replace') logging.basicConfig ( format = fmt, datefmt = '%Y-%m-%d %H:%M:%S', level =logging.DEBUG, stream = _logfile ) I am using psycopg2 which in turn uses libpq. When trying to connect to the database and providing faulty authentication information: try: ... try to connect ... except StandardError, e: _log.error(ulogin attempt %s/%s failed:, attempt+1, max_attempts) print exception type :, type(e) print exception dir :, dir(e) print exception args :, e.args msg = e.args[0] print msg type:, type(msg) print msg.decode(utf8):, msg.decode('utf8') t,v,tb = sys.exc_info() print sys.exc_info() :, t, v _log.exception(u'exception detected') the following output is generated: exception type : type 'instance' exception dir : ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] exception args : ('FATAL: Passwort-Authentifizierung f\xc3\xbcr Benutzer \xc2\xbbany-doc\xc2\xab fehlgeschlagen\n',) msg type: type 'str' msg.decode(utf8): FATAL: Passwort-Authentifizierung für Benutzer »any-doc« fehlgeschlagen sys.exc_info() : psycopg2.OperationalError FATAL: Passwort-Authentifizierung für Benutzer »any-doc« fehlgeschlagen Traceback (most recent call last): File /usr/lib/python2.4/logging/__init__.py, line 739, in emit self.stream.write(fs % msg.encode(UTF-8)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 191: ordinal not in range(128) Now, the string FATAL: Passwort-Auth... comes from libpq via psycopg2. It is translated to German via gettext within libpq (at the C level). As we can see it is of type string. I know from the environment that it is likely encoded in utf8 manually applying which (see the decode call) succeeds. On _log.exception() theloggingmodule wants to output the message as encoded as utf8 (that's what the log file is set up as). So it'll look at the string, decide it is of type str and decode with the *Python default encoding* to get to type unicode. Following which it'll re-encode with utf8 to get back to type str ready for outputting to the log file. However, since the Python default encoding is ascii that conversion fails. Changing the Python default encoding isn't really an option as it is advocated against and would have to be made to work reliably on other users machines. One could, of course, write code to specifically check for this condition and manually pre-convert the message string to unicode but that seems not as things should be. How can I cleanly handle this situation ? Should theloggingmodule internally use an encoding gotten from the locale module rather than the default string encoding ? Karsten -- GPG key ID E4071346 @ wwwkeys.pgp.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 Please reduce to a minimal program which demonstrates the issue and log an issue on bugs.python.org. Best regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: X/Linux mouse_event (like in win32api)
Thank you Jorgen. Your answer helped me a lot. -- http://mail.python.org/mailman/listinfo/python-list
Re: hide object property from dir() function?
On Jan 14, 1:20 pm, jerryji [EMAIL PROTECTED] wrote: Hi, Sorry for this newbie question, I was puzzled why the existing property of an object is not shown in the dir() function output. v is an lxml Element object variable -- In [44]: v Out[44]: Element 'documentProperties' at 0x8363cf8 In [45]: dir(v) Out[45]: ['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'keys', 'makeelement', 'remove', 'set'] dir() output doesn't contain the .tag, which does exist -- In [46]: v.tag Out[46]: 'documentProperties' what is the rule governing the display of a property from dir()? You can also make properties by modifying the __getattr__ and __setattr__ methods of a class. When done that way it won't show up when dir is called. So it isn't necessarily a rule, just a different way of implementing a property. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Mon, 14 Jan 2008 12:08:52 -0800, Paul Rubin wrote: aspineux [EMAIL PROTECTED] writes: Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) -- d['a', f()] d.setdefault('a', f()) -- d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? Changing python semantics for something like this is nuts. Allowing passing a callable (sort of like re.sub allows) makes a certain amount of sense: d.get('a', default=f) But how can Python determine when you want the result to be *the callable* and when you want it to be *the result of calling the callable*? Functions and other callables are first-class objects, and it is quite reasonable to have something like this: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) The result I want is the class, not the result of calling the class (which would be an instance). If I wanted the other semantics, I'd be using defaultdict instead. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
On Mon, 14 Jan 2008 12:46:48 +, Robert Latest wrote: And, contrary to the advice I gave elsethread, unfortunately it's impossible to just drop uncooperative customers when you develop GPL software ;-) Just because you are writing GPLed code doesn't mean you are permanently linked to anyone you have supplied code to. You can send their emails straight to /dev/null. You don't have to give them any support, only the source code. And if you do give them support, the GPL doesn't limit what your hourly rates are: you are free to charge them one million dollars per hour, payable in advance in blocks of fifteen hours. If they don't like it, they can always fork the code, or find another person to support it, or simply stop being dicks. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Given that getlocale() is not to be used, what's the best way to get the locale later in the app? You get the full locale name with locale.setlocale(category) (i.e. without the second argument) I need that two-letter code that's hidden in a typical locale like en_ZA.utf8 -- I want that 'en' part. Not sure why you want that. Notice that the locale name is fairly system specific, in particular on non-POSIX systems. It may be English_SouthAfrica on some systems. If you are certain that *your* locale names will only ever be of the form languagecode[_countrycode][.[EMAIL PROTECTED] (or whatever the syntax is), take anything before the underscore as the language code. However, you should reevaluate why you need that. BTW - things are hanging-together much better now, thanks to your info. I have it running in locale 'C' as well as my other test locales. What a relief! Great! Martin -- http://mail.python.org/mailman/listinfo/python-list
import from question
Hi all I've got three files: file a1.py: the_number = None file a2.py: import a1 def init(): a1.the_number = 100 file a3.py: from a1 import the_number import a2 a2.init() print the_number, type(the_number) Runninr a3.py I get: None type 'NoneType' Changing a3.py to: import a1 import a2 a2.init() print a1.the_number, type(a1.the_number) gives: 100 type 'int' Why doesn't it work in the first version of a3.py? Thanks, iu2 -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
But how can Python determine when you want the result to be *the callable* and when you want it to be *the result of calling the callable*? Functions and other callables are first-class objects, and it is quite reasonable to have something like this: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) The result I want is the class, not the result of calling the class (which would be an instance). If I wanted the other semantics, I'd be using defaultdict instead. For an example of the defaultdict usage without calling it the first time: from collections import defaultdict def f(): print Doing some expensive calculation return 42 d = defaultdict(f) d['hello'] = 3.14159 print 'Hello:', d['hello'] print 'World:', d['world'] print 'World (again):', d['world'] This results in the expensive calculation only being executed once and having the result stored in the defaultdict. This is a good thing. If you're doing as Steven suggests, you can pass and store function objects or class objects with the same ease: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) Other than tromping on the map built-in, one can then instantiate the given class with my_instance = map.get(astring, default=Zclass)(params) Perfect for the factory pattern if you groove on that sort of thing. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 14, 1:41 pm, Richard Szopa [EMAIL PROTECTED] wrote: On Jan 13, 3:31 pm, thebjorn [EMAIL PROTECTED] wrote: They do, except for when it comes to what super(..) returns. It isn't really an object in the sense that they're presented in the tutorial, but rather a sort of proxy to the methods in the ancestor classes of the concrete object (self), relative to the current method's class. I can't imagine that sentence would ease any confusion however, suffice it to say that you have to call getattr(super(..), 'name') instead of super(..).__getattr__('name') and you have to call super(..).__len__() instead of len(super(..)) -- I can't imagine that lessens any confusion either :-/ Surprisingly, I think your first sentence *does* make something more clear. Let me check if I understand it right: when we call a method on super(Foo, self) it is as if we were calling call-next-method in Common Lisp or Dylan I don't remember if CLOS was changed to use C3 Linearization also, but the concept came from Dylan (http://www.webcom.com/haahr/dylan/ linearization-oopsla96.html) and that's what is implemented in Python. [...] However, there's one piece that doesn't completely fit to the puzzle: why does getattr work? The help says: getattr(...) getattr(object, name[, default]) - value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Does it work on the basis that getattr(x, 'y') is equivalent to x.y? What is then a named attribute for an object in Python? It seems not to be equivalent to the value of the item whose name is 'y' in the object's class __dict__... Conceptually, x.y is always get the y attribute of x and the same as getattr(x, 'y'). Depending on the type of x and y, and your familiarity with Python internals, what actually happens during a lookup might be surprising. In the vast majority of cases however, x.y is equivalent to one of x.__dict__['y'] type(x).__dict__['y'] but if you're a language geek like me, you might be excited that in some cases it is type(x).__dict__['y'].__get__(x, type(x)) which says you get the value of x.y by calling y and passing x as an argument -- if you know CLOS you'll recognize that it's a primitive multi-method call. (there are some other special cases too, although not as exciting ;-) Much more detail can be found in Raymond's paper on descriptors (http://users.rcn.com/python/download/Descriptor.htm) and Michele's paper on super (http://www.phyast.pitt.edu/~micheles/python/ super.html). -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Append zip files together, just get the binary data (in memory)
Is it possible to just build the binary content of a zip file. I want to create the content in memory (e.g. return binary data) and then get those byte strings representing the zip file? Is that possible? Or could I possibly override functions in the zip class. 1. Create a zip file object (e.g. dont actually create the file). 2. Append stuff to the zip file (e.g. a file) 3. Zip that content into memory (but still not touching the filesystem) 4. Extract those byte strings for (an array?) later use. My goal is to concatenate multiple zip files into another binary file. -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Hrvoje Niksic [EMAIL PROTECTED] writes: Wildemar Wildenburger [EMAIL PROTECTED] writes: __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. No. That would be '__new__', which actually constructs the instance, and actually returns it to the caller. '__init__' does neither of those. It so happens that, in Python, one usually overrrides the initialiser and not the constructor. Thus, the confusion is understandable, but still regrettable and avoidable. -- \ My, your, his, hers, ours, theirs, its. I'm, you're, he's, | `\ she's, we're, they're, it's. —anonymous, | _o__)alt.sysadmin.recovery | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: encrypting python modules
Robert Latest [EMAIL PROTECTED] writes: And, contrary to the advice I gave elsethread, unfortunately it's impossible to just drop uncooperative customers when you develop GPL software ;-) On the contrary. The GPL includes a big fat NO WARRANTY clause. If you're not selling warranties to people, don't provide any more support to them than you want to. The main benefit of software licensed under the GPL is that your customer has the freedom to take the software and get someone else to improve it instead of you. That's good for them *and* good for you, since you *can* drop them if it's to your advantage to do so. -- \ Everything is futile. -- Marvin of Borg | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: split parameter line with quotes
teddyber wrote: here's the solution i have for the moment : t = shlex.shlex(data) t.wordchars = t.wordchars + /+.- r='' while 1: token = t.get_token() if not token: break if not token==',': r = r+token else: r = r + ' ' self.DEBUG(r,'ok') for pair in r.split(' '): key,value=pair.split('=', 1) print(key+':'+value) i know this is not perfect still but i'm coming a long way from very bad php habits! :o) and thanks for your help! On 11 jan, 23:30, teddyber [EMAIL PROTECTED] wrote: wow! that's perfect this shlex module! thanks for pointing this! On 11 jan, 20:36, Joshua Kugler [EMAIL PROTECTED] wrote: teddyber wrote: first i'm a newbie to python (but i searched the Internet i swear). i'm looking for some way to split up a string into a list of pairs 'key=value'. This code should be able to handle this particular example string : qop=auth,auth-int,auth-conf,cipher=rc4-40,rc4-56,rc4,des, 3des,maxbuf=1024,charset=utf-8,algorithm=md5-sess i know i can do that with some regexp (i'm currently trying to learn that) but if there's some other way... Take a look at the shlex module. You might be able to fiddle with the shlex object and convince it to split on the commas. But, to be honest, that above would be a lot easier to parse if the dividing commas were spaces instead. j Maybe you like : x = 'qop = auth,auth-int,auth-conf,cipher=rc4-40,rc4-56,rc4,des, 3des,maxbuf=1024,charset=utf-8,algorithm=md5-sess' dict(zip([k[-1].strip() for k in (j.split(',') for j in ''.join(i for i in x if i != '').split('='))][:-1], [k[:-1] or k for k in (j.split(',') for j in ''.join(i for i in x if i != '').split('='))][1:])) {'maxbuf': ['1024'], 'cipher': ['rc4-40', 'rc4-56', 'rc4', 'des', ' 3des'], 'charset': ['utf-8'], 'algorithm': ['md5-sess'], 'qop': [' auth', 'auth-int', 'auth-conf']} -- http://mail.python.org/mailman/listinfo/python-list