RELEASED Python 2.4.4, Final.
On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.4 (FINAL). Python 2.4.4 is a bug-fix release. While Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.4. This is the final planned release from the Python 2.4 series. Future maintenance releases will be in the 2.5 series, beginning with 2.5.1. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the more than 80 bugs squished in this release, including a number found by the Coverity and Klocwork static analysis tools. We'd like to offer our thanks to both these firms for making this available for open source projects. * Python 2.4.4 contains a fix for PSF-2006-001, a buffer overrun * * in repr() of unicode strings in wide unicode (UCS-4) builds. * * See http://www.python.org/news/security/PSF-2006-001/ for more. * There's only been one small change since the release candidate - a fix to configure to repair cross-compiling of Python under Unix. For more information on Python 2.4.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.4 Highlights of this new release include: - Bug fixes. According to the release notes, at least 80 have been fixed. This includes a fix for PSF-2006-001, a bug in repr() for unicode strings on UCS-4 (wide unicode) builds. Enjoy this release, Anthony Anthony Baxter [EMAIL PROTECTED] Python Release Manager (on behalf of the entire python-dev team) pgp4oqfdNFI6M.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: passing values to a program
[EMAIL PROTECTED] wrote: I almost have this thing running like I want it to run but I want the values to come from the program that calls this one. There are two things I want to pass File_Name and CutString. They both need to go to loadFile routine of Class WordGrid to replace constants. note that your code is already using sys.argv to read arguments from the command line (inside the main function), so obviously you know how to do that, and your code is passing arguments around (to both the constructor and the main function), so obviously you know how to do that. so what's the problem here? why not just use the mechanisms you already know how to use? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting method name from within the class method
Mitko Haralanov wrote: I need to be able to get the name of the currently executed method within that method. I know that the method object does have the __name__ attribute but I know know how to access it from withing the method. Something like this: class A: def a_method (self, this, that): print __name__ print a_method /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting method name from within the class method
Mitko Haralanov wrote: class test(object): ... def a_method(self,this,that): ... print self.a_method.__name__ Doing the above will obviously work! so will print a_method of course. no need to be silly when you don't have to. However, I don't want to have to use the name of the function in the print statement (the .a_method. part). Imagine having about 100 of the above print statements in the function and then you change the name of the function. I want all 100 of the print statements to work without having to change every one of them to reflect the new function name. why are you writing functions that needs to output their own name a 100 times? why should the program's *external* behaviour depend on such an irrelevant detail of its internal design? sounds like lousy design to me. if you want to tag 100 messages with the same name, and you want to make it easy to change that name, should the need arise, use a variable: def a_method(self, this, that): name = myname print name, is running print name, is about to return /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting method name from within the class method
Gabriel Genellina wrote: I could see some merit on getting that info in an automatic way. The only reason I can see for knowing the name of a function is for debugging purposes - maybe some kind of logging utility. If you are in debug mode, resources are not too important, but correct information is. Imagine a logfile that says that you were at function_a but instead you were at function_b (because of copypaste without replacing the names) imagine a log file that says that you're about to create a file when you're actually removing it (because of copypaste without replacing the message). focussing on function names when logging is pretty silly, anyway. it's usually better to focus on that the code is actually doing, rather than internal artifacts. but even if you want to output function names, it's of course better to put that functionality into the logging function itself: ## # Issues a log message. def log(fmt, *args): print who_called_me(2), -, fmt % args ## # Returns the name of the calling function or method, if known. # # @param depth Stack depth. Defaults to immediate caller. # @return The name of the calling function. def who_called_me(depth=1): return sys._getframe(depth).f_code.co_name /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot import a module from a variable
Cameron Walsh wrote: Woah, that actually works? Having the finally after the return? That could make some things easier, and some things harder... The whole point of having a clean-up handler is to make sure it runs no matter what: When a return, break or continue statement is executed in the try suite of a try-finally statement, the finally clause is also executed on the way out. http://pyref.infogami.com/try /F -- http://mail.python.org/mailman/listinfo/python-list
Re: passing values to a program
[EMAIL PROTECTED] wrote: I almost have this thing running like I want it to run but I want the values to come from the program that calls this one. There are two things I want to pass File_Name and CutString. They both need to go to loadFile routine of Class WordGrid to replace constants. Thank you for putting up with my quesitons in advance. import wx import wx.grid as gridlib #--- class WordGrid(gridlib.Grid): def __init__(self, parent, log): gridlib.Grid.__init__(self, parent, -1) self.loadFile() self.CreateGrid(len(self.rows), self.widestRow) for r, row in enumerate(self.rows): for c, col in enumerate(row): self.SetCellValue(r, c, col) self.SetColSize(c, 10*self.widestCol) for c, label in enumerate(self.header): self.SetColLabelValue(c, label) def loadFile(self): #from_file infile = open('test.sco', 'r') foundHeader = False self.rows = [] for line in infile: if ;sco_header in line: #removefirst = line.split(' ') self.header = line.split() #foundHeader = 'true' continue # we don't want to process this line any further else: self.rows.append(line.split()) self.widestRow = max([len(r) for r in self.rows]) self.widestCol = max([len(c) for c in [r for r in self.rows]]) #--- class TestFrame(wx.Frame): def __init__(self, parent, log): wx.Frame.__init__(self, parent, -1, Simple Grid Demo, size=(640,480)) grid = WordGrid(self, log) #--- #def main(): def main(From_File, string): import sys From_file = argv[1] #split_string = argv2[2] app = wx.PySimpleApp() frame = TestFrame(None, sys.stdout) frame.Show(True) app.MainLoop() pass if __name__ == '__main__': import sys main('test.sco', 'sfd') http://www.dexrow.com Try this code, save it in file called test.py def main(From_File, string): print 'From_File: %s' % From_File print 'string: %s' % string if __name__ == '__main__': import sys print 'command line' print sys.argv main(sys.argv[1], sys.argv[2]) print 'hardcoded' main('test.sco', 'sfd') H:\test.py arg1 arg2 command line ['H:\\test.py', 'arg1', 'arg2'] From_File: arg1 string: arg2 hardcoded From_File: test.sco string: sfd argv is in namespace sys, but you don't tell that. Also I would consider using a none built in and less generic name for the argument 'string' you're using. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting method name from within the class method
on that on what /F -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] a little about regex
*** Your mail has been scanned by InterScan MSS. *** On Wednesday 18 October 2006 15:32, Ron Adam wrote: |Instead of using two separate if's, Use an if - elif and be sure to test Thank you, Ron, for the input :) I'll examine also in this mode. Meanwhile I had faced the total disaster :) of deleting all my emails from all server ;( (I've saved them locally, luckly :) ) |It's not exactly clear on what output you are seeking. If you want 0 for | not filtered and 1 for filtered, then look to Freds Hint. Actually the return code is like herein: if _filter(hdrs,allow,deny): # allow and deny are objects prepared by re.compile(pattern) _del(Num_of_Email) In short, it means unwanted to be deleted. And now the function is : def _filter(msg,al,dn): Filter try to classify a list of lines for a set of compiled patterns. a = 0 for hdrline in msg: # deny has the first priority and stop any further searching. Score 10 #times if dn.search(hdrline): return len(msg) * 10 if al.search(hdrline): return 0 a += 1 return a # it returns with a score of rejected matches or zero if none The patterns are taken from a configuration file. Those with Axx ='pattern' are allowing streams the others are Dxx to block under different criteria. Here they're : [Filters] A01 = ^From:.*\.it\b A02 = ^(To|Cc):.*frioio@ A03 = ^(To|Cc):.*the_sting@ A04 = ^(To|Cc):.*calm_me_or_die@ A05 = ^(To|Cc):.*further@ A06 = ^From:.*\.za\b D01 = ^From:.*\.co\.au\b D02 = ^Subject:.*\*\*\*SPAM\*\*\* *A bit of fake in order to get some privacy* :) I'm using configparser to fetch their value and they're are joint by : allow = re.compile('|'.join([k[1] for k in ifil if k[0] is 'a'])) deny = re.compile('|'.join([k[1] for k in ifil if k[0] is 'd'])) ifil is the input filter's section. At this point I suppose that I have realized the right thing, just I'm a bit curious to know if ithere's a better chance and realize a single regex compilation for all of the options. Basically the program will work, in term of filtering as per config and sincronizing with local $HOME/Mail/trash (configurable path). This last option will remove emails on the server for those that are in the local trash. Todo = backup local and remote emails for those filtered as good. multithread to connect all server in parallel SSL for POP3 and IMAP4 as well Actually I've problem on issuing the command to imap server to flag Deleted the message which count as spam. I only know the message details but what is the correct command is a bit obscure, for me. BTW whose Fred? F -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
*** Your mail has been scanned by InterScan MSS. *** On Wednesday 18 October 2006 16:43, Rob Wolfe wrote: |def filter(adr): # note that filter is a builtin function also | import re I didn't know it, but my function _is_ starting by underscore (a bit of localization :) ) | allow = re.compile(r'.*(?!\.com)\.my(|$)') # negative lookbehind | deny = re.compile(r'.*\.com\.my(|$)') Great, it works perfectly. I found my errors. I didn't use r ahead of the patterns and i was close to the 'allow' pattern but didn't give positive result and KregexEditor reported wrong way. This specially because of '' inside the stream. I thing that is not a normal regex input. It's only python valid. Am I right? More details are the previous thread. F -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Steven, Thank you for help; Here is a code that works in a way I need A={'c':1,'d':2,'e':3,'f':2} B={'c':2,'e':1} if len(A)=len(B): Delsi=B C = A.copy() else: Delsi=A C = B.copy() for key, value in Delsi.items(): if C.has_key(key): C[key]=C[key]+value else: C[key]=value How easy :-) Regards, L. Steven D'Aprano wrote: On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote: Steven, Thank you for your reply and question. What should the result be if both dictionaries have the same key? The answer: the values should be added together and assigned to the key That is {'a':1, 'b':5} ( from your example below) Is there a solution? Of course there is a solution. You just have to program it. Look again at my example code before: def add_dict(A, B): Add dictionaries A and B and return a new dictionary. C = A.copy() # start with a copy of A for key, value in B.items(): if C.has_key(key): raise ValueError(duplicate key '%s' detected! % key) C[key] = value return C Can you see how to modify this function to do what you want? (Hint: instead of raising a ValueError exception, you want to do something else.) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Fulvio wrote: Great, it works perfectly. I found my errors. I didn't use r ahead of the patterns and i was close to the 'allow' pattern but didn't give positive result and KregexEditor reported wrong way. This specially because of '' inside the stream. I thing that is not a normal regex input. It's only python valid. Am I right? The sequence inside (?...) is an extension notation specific to python. Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: You sound as if you're avoiding metaclasses just for the sake of avoiding them, which is just as bad as using them for the sake of using them. Do you realize that you are effectively saying avoiding a complex tool in favor of a simpler one is just as bad as avoing the simple tool in favor of the complex one ? Here's how I see it: either it's ok to fiddle with the class dict, or it isn't. If it's ok, then a metaclass is the way to do it. If it's not ok to fiddle with the class dict, then he should be using __setattr__, or creating properties longhand. Messing with frames is not the answer for production code. I agree that messing with frames is not nice (however I should notice that this is how Zope interfaces are implemented, and they have been in production use for years) but I disagree with your point about the class dict. You should use a custom metaclass *only if you want to mess with the class dict of all subclasses at each derivation*: this is rarely the case, and definitely was not requested for the OP problem. Just for the hell of it, I decided to accept your challenge to run the standard library with a different metaclass applied to all new-style classes. I ran the 2.4.3 regression test, replacing the builtin object with a class that used the mod256metaclass I presented in this thread. The results: 229 tests OK. 34 tests failed: test___all__ test_asynchat test_cgi test_cookielib test_copy test_copy_reg test_cpickle test_decimal test_descr test_descrtut test_email test_email_codecs test_httplib test_imaplib test_inspect test_logging test_mailbox test_mimetools test_mimetypes test_minidom test_pickle test_pyclbr test_robotparser test_sax test_sets test_socket test_socket_ssl test_sundry test_timeout test_urllib test_urllib2 test_urllib2net test_urllibnet test_xpickle 34 tests failed, worse than I expected. Not A-OK, but not exactly mass-pandemonium either. There were plenty of modules used the the new base object and worked fine. There were only two causes for failure: 1. A class attempting to use __weakref__ slot. 2. There were also a few metaclass conflicts. Yes, this agree with my findings. I was curious to know if there were additional issues. IMO, neither of these failure modes argues against using a metaclass to preprocess the class dict. But they argue against using metaclasses in general, IMO! (or at least, against using them for users that are not aware of all the potential pittfalls). The __weakref__ error is not applicable; since it's an error to use it on any class with an instance dict. (In fact, the metaclass wasn't even causing the error: the same error would have occurred if I had replaced builtin object with an empty subclass of itself, without the metaclass.) Correct, this more of a problems of __slots__ that play havoc with inheritance than a problem of metaclasses. The metaclass conflict would only occur in the present case only if someone wanted to subclass it AND specify a different metaclass. Arguing that metaclasses should be avoided just to guard against this rare possibility is defensive to the extreme. Not too extreme in my opinion. Real life example: I had a debugging tool using a custom metaclass, I tried to run it on Zope 2.7 classes and I have got segmentation faults. In Zope 2.8 I get only metatype conflicts, and to avoid that I had to rewrite the tool :-( I did not uncover any kinds of subtle, unexpected behavior that can occur when metaclasses do weird things. I know such things are possible; how likely they are is another question. The tests I ran didn't uncover any. So for now, the results of these tests don't seem to support your point very well. Well, this is a matter of opinion. In my opinion your tests support my point pretty well, better than I expected ;) Appendix: Here's how I ran the test. I inserted the following code at the top of Lib/test/regrtest.py, and ran make test. I ran the tests on the Python 2.4.3 source tree, in Linux. === import sys class mod256metatype(type): def __new__(metatype,name,bases,clsdict): print sys.__stdout__, \ Creating class %s of type mod256metatype % name def makeprop(sym): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) return property(_get,_set) for sym in clsdict.get('__mod256__',()): clsdict[sym] = makeprop(sym) return super(metatype return type.__new__(metatype,name,bases,clsdict) class _object: __metaclass__ = mod256metatype import __builtin__ __builtin__.object = _object === I used a similar approach. I added in sitecustomize.py the following lines: import __builtin__ class chatty_creation(type):
Re: creating many similar properties
James Stroud wrote: However, I think that what you are saying about metaclasses being brittle relates more to implementation than language. In theory, these should be equivalent: (1) class Bob(object): pass (2) Bob = type('Bob', (), {}) And indeed a cursory inspection of the resulting classes show that they are indistinguishable. That they wouldn't be seems an implementation bug and perhaps that bug should be fixed rather than promoting the avoidance of (2) because it does not create classes that behave as number (1). You got something wrong ;) 'type' is the builtin metaclass, it works, I have nothing against it, and (1) and (2) are *exactly* equivalent. My gripe is against *custom* metaclasses, i.e. subclasses of 'type'. The paper is all about avoiding custom metaclasses and using 'type' instead (i.e. use the __metaclass__ hook, but not custom metaclasses). It is the same trick used by George Sakkis in this same thread. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
RELEASED Python 2.4.4, Final.
On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.4 (FINAL). Python 2.4.4 is a bug-fix release. While Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.4. This is the final planned release from the Python 2.4 series. Future maintenance releases will be in the 2.5 series, beginning with 2.5.1. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the more than 80 bugs squished in this release, including a number found by the Coverity and Klocwork static analysis tools. We'd like to offer our thanks to both these firms for making this available for open source projects. * Python 2.4.4 contains a fix for PSF-2006-001, a buffer overrun * * in repr() of unicode strings in wide unicode (UCS-4) builds. * * See http://www.python.org/news/security/PSF-2006-001/ for more. * There's only been one small change since the release candidate - a fix to configure to repair cross-compiling of Python under Unix. For more information on Python 2.4.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.4 Highlights of this new release include: - Bug fixes. According to the release notes, at least 80 have been fixed. This includes a fix for PSF-2006-001, a bug in repr() for unicode strings on UCS-4 (wide unicode) builds. Enjoy this release, Anthony Anthony Baxter [EMAIL PROTECTED] Python Release Manager (on behalf of the entire python-dev team) pgpO2AaqS8RU5.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
__delitem__ affecting performance
Hi, I was performing some timing tests on a class that inherits from the built-in list, and got some curious results: import timeit class MyList(list): def __init__(self): list.__init__(self) self[:] = [0,0,0] def __delitem__(self,index): print 'deleting' ml = MyList() def test(): global ml ml[0] += 0 ml[1] += 0 ml[2] += 0 t = timeit.Timer(test(),from __main__ import test) print t.timeit() 4.11651382676 import timeit class MyList(list): def __init__(self): list.__init__(self) self[:] = [0,0,0] ml = MyList() def test(): global ml ml[0] += 0 ml[1] += 0 ml[2] += 0 t = timeit.Timer(test(),from __main__ import test) print t.timeit() 2.23268591383 Does anybody know why defining __delitem__ is causing the code to run slower? It is not being called, so I don't see why it would affect performance. Overriding other sequence operators like __delslice__ does not exhibit this behavior. The speed difference doesn't really bother me, but I am curious. I used Python 2.4 for this test. -Karl -- http://mail.python.org/mailman/listinfo/python-list
UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
Hi! I'm struggling with the conversion of a UTF-8 string to latin-1. As far as I know the way to go is to decode the UTF-8 string to unicode and then encode it back again to latin-1? So I tried: 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'König', contains a german 'umlaut' but failed since python assumes every string to decode to be ASCII? How can I convert this string to latin-1? How would you write a function like: def encode_string(string, from_encoding, to_encoding): # Best regards, Noel -- http://mail.python.org/mailman/listinfo/python-list
Re: __delitem__ affecting performance
Karl H. wrote: Does anybody know why defining __delitem__ is causing the code to run slower? It is not being called, so I don't see why it would affect performance. probably because overriding portions of the internal sequence slot API (tp_as_sequence) means that Python needs to do full dispatch for all members of that API, instead of keeping things at the C level. /F -- http://mail.python.org/mailman/listinfo/python-list
libraries options not split in setup.cfg
Hi. I just noticed that the libraries options under the [build_ext] section in setup.cfg doesn't seem to get expanded. In particular, in distutils.command.build_ext.py of python 2.4. (line147): if type(self.libraries) is StringType: self.libraries = [self.libraries] though library_dirs for example gets split on ';' (line 156) elif type(self.library_dirs) is StringType: self.library_dirs = string.split(self.library_dirs, os.pathsep) is this a bug or am i using the libraries option in a wrong way in my setup.cfg libraries = libgsl;libgslcblas (btw, the above gets expanded on windows to libgsl;libgslcblas.lib on the cmdline (not splitting on the ';' character). thx for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
[EMAIL PROTECTED] wrote: 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'König', contains a german 'umlaut' but failed since python assumes every string to decode to be ASCII? No, Python would assume the string to be utf-8 encoded in this case: 'K\xc3\xb6ni'.decode('utf-8').encode('latin1') 'K\xf6ni' Your code must have failed somewhere else. Try posting actual failing code and actual traceback. -- http://mail.python.org/mailman/listinfo/python-list
Re: characters in python
I solve it. Just have to do another encoding: http://www.python.org/dev/peps/pep-0263/ -- http://mail.python.org/mailman/listinfo/python-list
Re: characters in python
Leo Kislov wrote: On Oct 18, 11:50 am, Stens [EMAIL PROTECTED] wrote: Stens wrote: Can python handle this characters: c,c,ž,d,š? If can howI wanna to change some characters in text (in the file) to the characters at this address: http://rapidshare.de/files/37244252/Untitled-1_copy.png.html You need to use unicode, see any python unicode tutorial, for example this one http://www.amk.ca/python/howto/unicode or any other you can find with google. Your script can look like this: # -*- coding: PUT-HERE-ENCODING-OF-THIS-SCRIPT-FILE -*- import codecs outfile = codecs.open(your output file, w, encoding of the output file): for line in codecs.open(your input file, r, encoding of the input file): outfile.write(line.replace(u'd',u'd')) thx Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'König', Köni, to be precise. Äh, yes. ;o) contains a german 'umlaut' but failed since python assumes every string to decode to be ASCII? that should work, and it sure works for me: s = 'K\xc3\xb6ni'.decode('utf-8') s u'K\xf6ni' print s Köni what did you do, and how did it fail? First, thank you so much for answering so fast. I proposed python for a project and it would be very embarrassing for me if I would fail converting a UTF-8 string to latin-1. I realized that my problem ist not the decode to UTF-8. The exception is raised by print if I try to print the unicode string. UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) But that is not a problem at all since I can now turn my UTF-8 strings to unicode! Once again the problem was sitting right in front of my screen. Silly me... ;o) Again, thank you for your reply! Best regards, Noel -- http://mail.python.org/mailman/listinfo/python-list
Re: Python wrapper for C++ core
Thanks everyone for the responses - I think I have a better understanding now. I can handle all the messy I/O in Python and use C for the number crunching. I especially like the idea of using python to output the results to excel. OK time to learn Python i think - any tips on best place to start (tutorials/documentation etc). I have a pretty comprehensive background in C/C++/Java and a bit of experience some other scripting languages so its really a matter of syntax/libraries rather than programming theory/constructs see fluid sim and games dev in the same post, which kind of makes me scratch my head. What would you need fluid sim for in a game? sorry i was just listing places I had seem people waxing lyrical on the benefits of python. I am not doing games development - I have just heard lots of games developers saying they use python Thanks again for all the help! Holly -- http://mail.python.org/mailman/listinfo/python-list
Re: Install from source on a x86_64 machine
Christopher Taylor wrote: Being relatively new to linux I'm a little confused about what options I need to use to build python from source. The README should provide sufficient information, although if you want to install Python into /usr rather than /usr/local (as I believe is the default), you need to run configure as follows: ./configure --prefix=/usr Currently, I have python installed as part of the inital RHEL4 load located at /usr/bin/Python and /usr/bin/Python2.3 . Some of the files are located in /usr/lib64/Python2.3 and in /usr/lib/Python2.3 . Please let me know if you need dir lsitings. In fact, it's /usr/bin/python, /usr/bin/python2.3, /usr/lib64/python2.3 and /usr/lib/python, since Red Hat hasn't decided to capitalise the name of the software. ;-) I'm trying to compile from source and plan on using the --enable-unicode=ucs4 option for the configure script due to some RHEL messing around with Tcl/Tk. *** How do I get make altinstall to put the appropriate files in /usr/lib64/Python2.4 and /usr/lib/Python2.4 respectively ? *** The configured Makefile together with the various other tools should work out where to put the libraries. I'm a newcomer to x86-64, although I've had some relatively recent experience with sparc64, and whilst I'm not really familiar with the way the various tools choose the install directory of libraries, I've noticed that sometimes 64-bit libraries end up in lib rather than lib64. Meanwhile, I notice that the Red Hat libraries do adhere correctly to the expectation that 32-bit libraries are found under /usr/lib/python2.3 and 64-bit libraries are found under /usr/lib64/python2.3. Perhaps you should configure and make Python, then run the install process in pretend mode: make -n altinstall You'll get a huge amount of output, but this should at least tell you what the installation process is thinking of doing, and it won't be overwriting anything important while it does so. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
Duncan Booth wrote: [EMAIL PROTECTED] wrote: 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'König', contains a german 'umlaut' but failed since python assumes every string to decode to be ASCII? No, Python would assume the string to be utf-8 encoded in this case: 'K\xc3\xb6ni'.decode('utf-8').encode('latin1') 'K\xf6ni' Your code must have failed somewhere else. Try posting actual failing code and actual traceback. You are right. My test code was: print 'K\xc3\xb6ni'.decode('utf-8') and this line raised a UnicodeDecode exception. I didn't realize that the exception was actually raised by print and thought it was the decode. That explains the fact that a 'ignore' in the decode showed no effect at all, too. Thank you for helping! Best regards, Noel -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible Collating (feedback please)
Ron Adam wrote: locale.setlocale(locale.LC_ALL, '') # use current locale settings It's not current locale settings, it's user's locale settings. Application can actually use something else and you will overwrite that. You can also affect (unexpectedly to the application) time.strftime() and C extensions. So you should move this call into the _test() function and put explanation into the documentation that application should call locale.setlocale self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) [snip] if NUMERICAL in self.flags: slist = self.numrex.split(s) for i, x in enumerate(slist): try: slist[i] = float(x) except: slist[i] = locale.strxfrm(x) I think you should call locale.atof instead of float, since you call re.compile with re.LOCALE. Everything else looks fine. The biggest missing piece is support for unicode strings. -- Leo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
Dennis Lee Bieber wrote: On 18 Oct 2006 02:20:15 -0700, Paul Boddie [EMAIL PROTECTED] declaimed the following in comp.lang.python: Aren't we going round in circles here? There presumably are grid Possibly -- it was the fairly recent lamentation about Delphi that made me think the initial desire had been for some such automatic linkage between GUI and database that would have been preferred... I think it's about finding the right level: the stated toolkits (Kiwi, Thyme, GNUe, TinyERP) are probably quite high-level or mix in various application-specific bonus material, and perhaps a fairly elementary datagrid widget is what is being sought. widgets connected to database tables/views/cursors, if only exposed via user interface toolkits and other frameworks such as PyQt, Dabo and so on, but I thought the questioner wanted to know how to implement these things from the ground up. ... lacking such automation, a search for books on how to do this was next. But given so many combinations of toolkits, I didn't think a general (cookbook?) solution would be available. True. Still, I can only point to things which might provide useful building blocks in developing some of the solutions mentioned above. For example, PyQt's QSqlRelationalTableModel and QTableView might be acceptable building blocks: http://www.riverbankcomputing.com/Docs/PyQt4/html/qsqlrelationaltablemodel.html See here for Python-based examples: http://indico.cern.ch/contributionDisplay.py?contribId=33sessionId=41confId=44 I'm sure other people can provide links to resources for other toolkits and frameworks. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: More Noob Questions
1) I'm also learning to program flash movies while I learn to do python. How can one implement flash movies into their python code? Depending on what implementing flash movies into Python code means. Python and Flash can be complementary. You can develop the UI in Flash and have it talk to Python via web services. I suppose that you can embed the Flash Player control in a wxPython app as well and drive it from there. But such integrations typically deal with some slightly advanced issues that are best left aside in context of a beginner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python wrapper for C++ core
On 19 Oct 2006 03:10:55 -0700, Holly [EMAIL PROTECTED] wrote: Thanks everyone for the responses - I think I have a better understanding now. I can handle all the messy I/O in Python and use C for the number crunching. I especially like the idea of using python to output the results to excel. OK time to learn Python i think - any tips on best place to start (tutorials/documentation etc). I have a pretty comprehensive background in C/C++/Java and a bit of experience some other scripting languages so its really a matter of syntax/libraries rather than programming theory/constructs Be sure to check Boost.Python to create Python bindings for your project(s): http://boost.org/libs/python/doc/tutorial/doc/html/index.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -- http://mail.python.org/mailman/listinfo/python-list
Type discrepancy using struct.unpack
Hallo, I have a 64 bit server with CentOS 4.3 installed, running Python. [EMAIL PROTECTED] pymsnt-0.11.2]$ uname -a Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT 2006 x86_64 x86_64 x86_64 GNU/Linux Consider the following two snippets, issuing a struct.unpack(...) using Python 2.3.4 and Python 2.5 respectively. [EMAIL PROTECTED] pymsnt-0.11.2]$ python Python 2.5 (r25:51908, Oct 17 2006, 10:34:59) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'int' [EMAIL PROTECTED] pymsnt-0.11.2]$ /usr/bin/python2.3 Python 2.3.4 (#1, Feb 17 2005, 21:01:10) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'long' I would expect type 'long' in both cases. Why is this not so? Regards Pieter Rautenbach -- http://mail.python.org/mailman/listinfo/python-list
Python Memory Leak Detector
Announcing Software Tools for Python We are pleased to inform you that we have completed the port and beta test of our Memory Analysis software tool to support Python. The software tools run on the Windows NT/2000/XP (and above) platforms. Python Memory Validator (a memory leak detection tool) http://www.softwareverify.com/python/memory/index.html The website provides 30 day evaluation versions of the software as well as full product versions of the software. The evaluation versions are fully functional with only the 30 day limit on usage. Stephen -- Stephen Kellett Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting -- http://mail.python.org/mailman/listinfo/python-list
Re: Type discrepancy using struct.unpack
Pieter Rautenbach wrote: Hallo, I have a 64 bit server with CentOS 4.3 installed, running Python. [EMAIL PROTECTED] pymsnt-0.11.2]$ uname -a Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT 2006 x86_64 x86_64 x86_64 GNU/Linux Consider the following two snippets, issuing a struct.unpack(...) using Python 2.3.4 and Python 2.5 respectively. [EMAIL PROTECTED] pymsnt-0.11.2]$ python Python 2.5 (r25:51908, Oct 17 2006, 10:34:59) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'int' [EMAIL PROTECTED] pymsnt-0.11.2]$ /usr/bin/python2.3 Python 2.3.4 (#1, Feb 17 2005, 21:01:10) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'long' I would expect type 'long' in both cases. Why is this not so? http://mail.python.org/pipermail/python-dev/2006-May/065199.html -- Leo. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use python in TestMaker
Paddy wrote: kelin,[EMAIL PROTECTED] wrote: Hello, Now I 'm learning python to do testing jobs, and want to use it in TestMaker. The problem is: I don't know how to use python in TestMaker. Just write python program in it or call .py files in it? I am really new about it and need some help. Thanks a lot! What/where is TestMaker? Well, TestMaker is a tool to do testing jobs. You can visit the following website for some info: http://www.pushtotest.com/. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use python in TestMaker
I don't know that TestMaker is written in Python before. So maybe it's my mistake. Then have you ever done testing jobs with Python? I know that many people do testing jobs with it. I just can't find a good tool to do Unit Test with Python. Could you please tell me any? Thanks a lot! Gabriel Genellina wrote: At Wednesday 18/10/2006 23:34, kelin,[EMAIL PROTECTED] wrote: Now I 'm learning python to do testing jobs, and want to use it in TestMaker. The problem is: I don't know how to use python in TestMaker. Just write python program in it or call .py files in it? I am really new about it and need some help. What do you mean by use python in TestMaker? TestMaker is written in Python, but you dont need to know Python to use it at all. Do you want to modify TestMaker itself? Then you should learn the Python language first. -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: More Noob Questions
Omar wrote: more to come! Please, use a more meaningful subject next time, like Integration of Python and Flash or Where can I find vido tutorials. That way it will be easier to people that knows about the subject to find your message and answer you. And please think of us, non-native English speakers, that don't know slang words like noob that don't even appear in the dictionaries and don't add anything to your question. Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
[EMAIL PROTECTED] wrote: print 'K\xc3\xb6ni'.decode('utf-8') and this line raised a UnicodeDecode exception. Works for me. Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console Check this out for understanding it: u = 'K\xc3\xb6ni'.decode('utf-8') s=u.encode('iso-8859-1') u u'K\xf6ni' s 'K\xf6ni' Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible Collating (feedback please)
Leo Kislov wrote: Ron Adam wrote: locale.setlocale(locale.LC_ALL, '') # use current locale settings It's not current locale settings, it's user's locale settings. Application can actually use something else and you will overwrite that. You can also affect (unexpectedly to the application) time.strftime() and C extensions. So you should move this call into the _test() function and put explanation into the documentation that application should call locale.setlocale I'll experiment with this a bit, I was under the impression that local.strxfrm needed the locale set for it to work correctly. Maybe it would be better to have two (or more) versions? A string, unicode, and locale version or maybe add an option to __init__ to choose the behavior? Multiple versions seems to be the approach of pre-py3k. Although I was trying to avoid that. Sigh, of course issues like this is why it is better to have a module to do this with. If it was as simple as just calling sort() I wouldn't have bothered. ;-) self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) [snip] if NUMERICAL in self.flags: slist = self.numrex.split(s) for i, x in enumerate(slist): try: slist[i] = float(x) except: slist[i] = locale.strxfrm(x) I think you should call locale.atof instead of float, since you call re.compile with re.LOCALE. I think you are correct, but it seems locale.atof() is a *lot* slower than float(). :( Here's the local.atof() code. def atof(string,func=float): Parses a string as a float according to the locale settings. #First, get rid of the grouping ts = localeconv()['thousands_sep'] if ts: string = string.replace(ts, '') #next, replace the decimal point with a dot dd = localeconv()['decimal_point'] if dd: string = string.replace(dd, '.') #finally, parse the string return func(string) I could set ts and dd in __init__ and just do the replacements in the try... if NUMERICAL in self.flags: slist = self.numrex.split(s) for i, x in enumerate(slist): if x: # slist may contain null strings if self.ts: xx = x.replace(self.ts, '') # remove thousands sep if self.dd: xx = xx.replace(self.dd, '.') # replace decimal point try: slist[i] = float(xx) except: slist[i] = locale.strxfrm(x) How does that look? It needs a fast way to determine if x is a number or a string. Any suggestions? Everything else looks fine. The biggest missing piece is support for unicode strings. This was the reason for using locale.strxfrm. It should let it work with unicode strings from what I could figure out from the documents. Am I missing something? Thanks, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Install from source on a x86_64 machine
The README should provide sufficient information, although if you want to install Python into /usr rather than /usr/local (as I believe is the default), you need to run configure as follows: ./configure --prefix=/usr Yeah, I saw that in the readme. In fact, it's /usr/bin/python, /usr/bin/python2.3, /usr/lib64/python2.3 and /usr/lib/python, since Red Hat hasn't decided to capitalise the name of the software. ;-) ok you got me, type-o The configured Makefile together with the various other tools should work out where to put the libraries. I'm a newcomer to x86-64, although I've had some relatively recent experience with sparc64, and whilst I'm not really familiar with the way the various tools choose the install directory of libraries, I've noticed that sometimes 64-bit libraries end up in lib rather than lib64. Meanwhile, I notice that the Red Hat libraries do adhere correctly to the expectation that 32-bit libraries are found under /usr/lib/python2.3 and 64-bit libraries are found under /usr/lib64/python2.3. Perhaps you should configure and make Python, then run the install process in pretend mode: make -n altinstall You'll get a huge amount of output, but this should at least tell you what the installation process is thinking of doing, and it won't be overwriting anything important while it does so. ok, so where does that leave me. I'm not even sure which files *should* be put in /lib64 vs lib. I guess what I'm expecting is a congifure option to specify where architecture dependent files should be put. Has anyone else mentioned this before? Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: passing values to a program
If it is as simple as using the sys and dot befour the argv then I have it made.. The example I was trying to get that from came from the first edition programming python (I think they were using version 1.3). thanks for the help I will give that a try. https://sourceforge.net/project/stats/?group_id=156455ugn=dex-tracker Fredrik Lundh wrote: [EMAIL PROTECTED] wrote: I almost have this thing running like I want it to run but I want the values to come from the program that calls this one. There are two things I want to pass File_Name and CutString. They both need to go to loadFile routine of Class WordGrid to replace constants. note that your code is already using sys.argv to read arguments from the command line (inside the main function), so obviously you know how to do that, and your code is passing arguments around (to both the constructor and the main function), so obviously you know how to do that. so what's the problem here? why not just use the mechanisms you already know how to use? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
Michael Ströder wrote: [EMAIL PROTECTED] wrote: print 'K\xc3\xb6ni'.decode('utf-8') and this line raised a UnicodeDecode exception. Works for me. Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console And that was the problem. I'm developing with eclipse (PyDev). The console is integrated in the development environment. As I print out an unicode string python tries to encode it to ASCII. And since the string contains non ASCII characters it fails. That is no problem if you are aware of this. My mistake was that I thought the exception was raised by my call to decode('UTF-8') because print and decode were on the same line and I thought print could never raise an exception. Seems like I've learned something today. Best regards, Noel -- http://mail.python.org/mailman/listinfo/python-list
Can I use decorators to manipulate return type or create methods?
I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc) To get the appropriate return types, I also have these methods. I have these convenience methods for every query method in my class. def getUsersAsXML(self, params): return self._toXML(self.getUsers(params)) def getUsersAsDict(self, params): return self._toDict(self.getUsers(params)) def getUsersAsList(self, params): return self._toList(self.getUsers(params)) Instead of creating these three methods for every query method, is there a way to use decorators to manipulate the return type. I'd still like to have the caller use getUsersAsXML, I just don't want to write the AsXML methods for every query method. So the decorator would essentially create the convenience methods instead of me coding them. One solution that I don't want to use is passing a variable into the query method that determines the return type. This is what I don't want to do. def getUsers(self, params, returnType): Any ideas on how I can accomplish this? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to RuleDispatch
On Oct 18, 10:41 pm, Adam Jones [EMAIL PROTECTED] wrote: exhuma.twn wrote: Hi all, yesterday I wanted to install TurboGears, which depends on RuleDispatch. However, I failed to download it. First I got the error Bad Gateway from the server, today it's simply a Not Found error. So what happened to it? Does somebody know? I would really need to install TurboGears in the next couple of days. So if someone knows where I can find a mirror ofRuleDispatchI would be very grateful.The required files for TG are mirrored on the turbogears.org download page. You should be able to get an installation by looking up the files there. Try this command: easy_install -fhttp://www.turbogears.org/download/index.html TurboGears That is actually the recommended way to install TurboGears, as it is not always compatible with the latest version of the components. -Adam Hmmm... this is wat I get: Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg Processing dependencies for TurboGears Searching for RuleDispatch Reading http://www.turbogears.org/download/index.html Best match: RuleDispatch 0.5a0.dev-r2115 Downloading http://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz error: Can't download http://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: 502 Bad Gateway Could this be a local issue? -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to RuleDispatch
On Oct 19, 3:44 pm, exhuma.twn [EMAIL PROTECTED] wrote: On Oct 18, 10:41 pm, Adam Jones [EMAIL PROTECTED] wrote: exhuma.twn wrote: Hi all, yesterday I wanted to install TurboGears, which depends on RuleDispatch. However, I failed to download it. First I got the error Bad Gateway from the server, today it's simply a Not Found error. So what happened to it? Does somebody know? I would really need to install TurboGears in the next couple of days. So if someone knows where I can find a mirror ofRuleDispatchI would be very grateful.The required files for TG are mirrored on the turbogears.org download page. You should be able to get an installation by looking up the files there. Try this command: easy_install -fhttp://www.turbogears.org/download/index.html TurboGears That is actually the recommended way to install TurboGears, as it is not always compatible with the latest version of the components. -AdamHmmm... this is wat I get: Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg Processing dependencies for TurboGears Searching forRuleDispatch Readinghttp://www.turbogears.org/download/index.html Best match:RuleDispatch0.5a0.dev-r2115 Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: 502 Bad Gateway Could this be a local issue? Forgot to say I also tried to download it via the web-browser. This gave me the following error (generated by the proxy I have to use): Server response could not be decoded using encoding type returned by server. This is typically caused by a Web Site presenting a content encoding header of one type, and then encoding the data differently. -- http://mail.python.org/mailman/listinfo/python-list
Python with MPI enable C-module
Hello All, A software project that I am working on currently has a C++ library that runs on a Beowulf cluster for parallel computation. The library code uses MPI for its implementation. We are currently developing python wrappers for the library. Our current design uses one Python process as a front end with processes created from the library code on the back end (it is processes of this type that run on all the nodes of the cluster). What I'm considering is delving into the possibility of having Python processes on all of the nodes of the cluster. These processes would wrap our C++ library. What I'm wondering is: 1) Would setting up an environment like this require modifying the Python interpreter or the C++ module that is being wrapped? What I'm hoping is that the C++ module can go on happily doing MPI operations despite the fact that it is actually being called by the Python interpreter. 2) Would it be possible to spawn these Python processes using mpiexec (or something similar), or would I need to use some of the MPI-2 features to dynamically set up the MPI environment? 3) Has anyone accomplished something like this already? I know there are extensions and modules that add MPI functionality to Python, but I'm hoping they could be avoided, since the Python code itself should never really have to be aware of MPI, only the C++ module that has already been written. Let me apologize up front if this has already been discussed before. I've done a few searches in this group and it seems that most of the discussion on this front took place many years ago, so the relevance is quite low. Thank you in advance for your attention. ~doug -- http://mail.python.org/mailman/listinfo/python-list
wxPython help wxSashWindow
Hi, I'm wondering if anyone can tell me here, or point to a specific tutorial ( I have searched for 1/2hour, but can find only reference style docs or not-quite-what-im-after help) on how to build a wxSashWindow in wxPython. I'm just starting out with wxPython, and the first thing i need to do is use 3 sash windows, 1 split vertically, and on the left and right of that a SashWindow splitting horizontally. I can make frames, buttons, use sizers etc.. as they are fairly intuitive, but SashWindow and SashLayoutWindow have stumped me. Thanks, Matt. -- http://mail.python.org/mailman/listinfo/python-list
Re: Install from source on a x86_64 machine
Christopher Taylor wrote: ok, so where does that leave me. I'm not even sure which files *should* be put in /lib64 vs lib. I'd imagine that anything which is a .so file (plus the modules which depend on it, I suppose) should be put in the appropriate library directory. Thus, 32-bit libraries should go into /usr/lib/python2.4/site-packages and 64-bit libraries should go into /usr/lib64/python2.4/site-packages. That said, I can see things that I've installed via distutils (and various make; make install combinations) that are in the wrong directory. I guess what I'm expecting is a congifure option to specify where architecture dependent files should be put. Generally, the install process should respect the prefix (ie. /usr in your case, /usr/local in the default case) and then choose the appropriate library directories below that (ie. /usr/lib, /usr/lib64 in your case), but I can't find anything obvious in the README about specifying architecture-dependent install directories. Has anyone else mentioned this before? I'd be interested to hear more about this as well. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Type discrepancy using struct.unpack
Leo Kislov wrote: Pieter Rautenbach wrote: Hallo, I have a 64 bit server with CentOS 4.3 installed, running Python. [EMAIL PROTECTED] pymsnt-0.11.2]$ uname -a Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT 2006 x86_64 x86_64 x86_64 GNU/Linux Consider the following two snippets, issuing a struct.unpack(...) using Python 2.3.4 and Python 2.5 respectively. [EMAIL PROTECTED] pymsnt-0.11.2]$ python Python 2.5 (r25:51908, Oct 17 2006, 10:34:59) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'int' [EMAIL PROTECTED] pymsnt-0.11.2]$ /usr/bin/python2.3 Python 2.3.4 (#1, Feb 17 2005, 21:01:10) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type help, copyright, credits or license for more information. import struct print type(struct.unpack(L, )[0]) type 'long' I would expect type 'long' in both cases. Why is this not so? http://mail.python.org/pipermail/python-dev/2006-May/065199.html -- Leo. Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Install from source on a x86_64 machine
Generally, the install process should respect the prefix (ie. /usr in your case, /usr/local in the default case) and then choose the appropriate library directories below that (ie. /usr/lib, /usr/lib64 in your case), but I can't find anything obvious in the README about specifying architecture-dependent install directories. Well that's pretty much what's happening ... either the 64bit libs aren't being put in /usr/lib64 ... they're all being put in /usr/lib or they were never compiled up in 64bit mode. The only think I can think of is that the configure script doesn't check the mode the OS is running in and take appropriate steps, ie.e compile the libs in both 32 and 64 bit mode and place them accordingly. I know this is a problem because when I try and compile up mod_python it's telling I'm getting the following error when it tries to link libpython2.4.a : /usr/bin/ld: /usr/lib/python2.4/config/libpython2.4.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/lib/python2.4/config/libpython2.4.a: could not read symbols: Bad value Which basically means to me that for whatever reason, when python compiled up, the ./configure script didn't see that the os was running in 64bit mode and compile the libraries in PIC mode, something I think that is required for libraries on a 64bit OS. Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
A suggestion/request for IDEs
I apologize for the slightly off-topic nature, but I thought I'd just throw this out there for anyone working on text editors or IDEs with auto-completion. I think it should be a feature, when an item is selected for auto-completion in a drop-down box, that pressing the spacebar (in addition to tab or enter) will automatically finish the word and add a space. This is how Microsoft's new IDEs for .NET work, and I found it very helpful to be able to just press space as normal and keep typing. I know it sounds minor, but I find it to be a time saver instead of having to press tab or enter, and then also the spacebar. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes and Functions - General Questions
John Salerno wrote: Setash wrote: And have class2 inherit class1 without any import statements, or need it be imported first? Or need class1 and class2 be both declared in the same .py file if there is inheritance? If the classes are in the same module, you don't need to do any importing or qualification. If they are in separate modules, you need to import the necessary module(s) and then you can use its contents. Quick clarification: even if you import a module, you still need to qualify a call to its attributes: import sys print sys.version #not 'print version' But you can use the 'from module import attribute' format to avoid this: from sys import version print version But this is very bad to do. The recommendation that I like is to only use from/import when you want a module from a package, not when you want classes, methods, etc. from a module. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython help wxSashWindow
MatthewWarren wrote: I'm just starting out with wxPython Hi there. Sorry I can't help you because SashWindow isn't something I've worked with yet, but I just wanted to let you know that there is also a dedicated wxPython newsgroup (not that the people here aren't geniuses!) :) gmane.comp.python.wxpython (newsgroup) [EMAIL PROTECTED] (mailing list) It's a great resource. -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible Collating (feedback please)
[EMAIL PROTECTED] wrote: Ron Adam: Insted of: def __init__(self, flags=[]): self.flags = flags self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) self.txtable = [] if HYPHEN_AS_SPACE in flags: self.txtable.append(('-', ' ')) if UNDERSCORE_AS_SPACE in flags: self.txtable.append(('_', ' ')) if PERIOD_AS_COMMAS in flags: self.txtable.append(('.', ',')) if IGNORE_COMMAS in flags: self.txtable.append((',', '')) self.flags = flags I think using a not mutable flags default is safer, this is an alternative (NOT tested!): numrex = re.compile(r'[\d\.]* | \D*', re.LOCALE|re.VERBOSE) dflags = {hyphen_as_space: ('-', ' '), underscore_as_space: ('_', ' '), period_as_commas: ('_', ' '), ignore_commas: (',', ''), ... } def __init__(self, flags=()): self.flags = [fl.strip().lower() for fl in flags] self.txtable = [] df = self.__class__.dflags for flag in self.flags: if flag in df: self.txtable.append(df[flag]) ... This is just an idea, it surely has some problems that have to be fixed. I think the 'if's are ok since there are only a few options that need to be handled by them. I'm still trying to determine what options are really needed. I can get the thousand separator and decimal character from local.localconv() function. So ignore_commas isn't needed I think. And maybe change period_as_commas to period _as_sep and then split on periods before comparing. I also want it to issue exceptions when the Collate object is created if invalid options are specified. That makes finding problems much easier. The example above doesn't do that, it accepts them silently. That was one of the reasons I went to named constants at first. How does this look? numrex = re.compile(r'([\d\.]* | \D*)', re.LOCALE|re.VERBOSE) options = ( 'CAPS_FIRST', 'NUMERICAL', 'HYPHEN_AS_SPACE', 'UNDERSCORE_AS_SPACE', 'IGNORE_LEADING_WS', 'IGNORE_COMMAS', 'PERIOD_AS_COMMAS' ) def __init__(self, flags=): if flags: flags = flags.upper().split() for value in flags: if value not in self.options: raise ValueError, 'Invalid option: %s' % value self.txtable = [] if 'HYPHEN_AS_SPACE' in flags: self.txtable.append(('-', ' ')) if 'UNDERSCORE_AS_SPACE' in flags: self.txtable.append(('_', ' ')) if 'PERIOD_AS_COMMAS' in flags: self.txtable.append(('.', ',')) if 'IGNORE_COMMAS' in flags: self.txtable.append((',', '')) self.flags = flags So you can set an option strings as... import collate as C collateopts = \ caps_first hyphen_as_space numerical ignore_commas colatedlist = C.collated(somelist, collateopts) A nice advantage with an option string is you don't have to prepend all your options with the module name. But you do have to validate it. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython help wxSashWindow
John Salerno wrote: MatthewWarren wrote: I'm just starting out with wxPython Hi there. Sorry I can't help you because SashWindow isn't something I've worked with yet, but I just wanted to let you know that there is also a dedicated wxPython newsgroup (not that the people here aren't geniuses!) :) gmane.comp.python.wxpython (newsgroup) [EMAIL PROTECTED] (mailing list) It's a great resource. Thanks, is that a newsgroup I can view through google groups? I tried seraching for it but google says no.. And I'll give that list a subscribe. I have found a wxPython google group, but only 11 members and a handfull of posts in a year... -- http://mail.python.org/mailman/listinfo/python-list
Re: Determining if a file is locked in Windows
Larry Bates wrote: elake wrote: I found this thread about a pst file in Windows being locked and I am having the same issue. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gstq=%27copying+locked+files%27rnum=1 The problem is that I have a script that can find the pst files on every machine in my network and back them up to a server for safe keeping. The problem is that when Outlook is running it locks the file and will not allow me to copy it to the destination. I am using the shutil module for the copy. Is there a way to first determine if the file is locked and then do the copy if it isn't? I thought about looking to see if Outlook.exe is running but the machines are shared and the process could be running but with a different pst file in use. Thanks in advance Try the copy and catch the exception instead. -Larry Bates Larry thanks for your suggestion. this is what I tried: #!/usr/bin/env python import os, shutil path = 'c:\documents and settings\username\Local Settings\Application Data\Microsoft\Outlook' src = 'Outlook.pst' dst = 'test.pst' os.chdir(path) try: shutil.copy2(src, dst) except IOError: print 'Must be locked by Outlook' print 'Finished' The problem is that even though I catch the IOError it overwrites the dst file and makes it 0kb. This is going to be for backing these files up and it wont be good to overwrite the backup with a bad copy. Is there another way to do this that I am missing. I am still kind of new to Python. If i could tell that outlook had the file locked before I tried the copy then I think that it would be prevented. -- http://mail.python.org/mailman/listinfo/python-list
Bad Magic Number with only .py deployed
I have a package of python modules deployed on an NFS mount on my network that I use for sysadmin tools. Since some of the machines use different versions of python I've only put the .py files in the mounted share. However, I'm getting ImportError: Bad Magic Number when I try to load any of the modules from the mount point. All the discussions I can find say that a bad magic number should only occur with a mismatched interpreter and compiled .pyc, but all that's deployed is the .py. This should mean that any scripts that load the modules will compile on import and so the interpreter should always be the same, but that doesn't seem to be the case. Could this be a permission issue? Does the interpreter panic and say Bad Magic Number if it can't write to the same location as the .py files are? There are only 3 versions of python on the network, but I'd rather not have to compile against each. Actually, I just tried it again and /usr/bin/python, which is 2.3.3 imports the top level module fine, but one of the network mounted version, which is 2.5, gives the Bad Magic Number problem on lib/__init__.py. Neither of the intrepreters should be writing the .pyc, so I don't see how they can get a Bad Magic Number from their own stuff. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes and Functions - General Questions
Setash enlightened us with: class1.py: class Class1(object): pass class2.py: import class1 This line imports class1.py and places its contents under the name class1. classes.py: class Class1 pass class Class2(Class1) pass That's correct. or would I still need to call it as: class Class2(classes.Class1) pass Nope, since the name classes is unknown. Sybren -- Sybren Stüvel Stüvel IT - http://www.stuvel.eu/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Ok. This IS homework ...
Frederic Rentsch wrote: Once upon a time programmers did things like this: BEGIN | --|- | | | | catch input| | | | | input type valid? - prompt for correct input --| | + | |input too large? + --- prompt for new input -- | - | add to running total | | | status report | | -- - running total = max? + report done | END It was called a flow chart. Flow charts could be translated directly into machine code written in assembly languages which had labels, tests and jumps as the only flow-control constructs. When structured programming introduced for and while loops they internalized labeling and jumping. That was a great convenience. Flow-charting became rather obsolete because the one-to-one correspondence between flow chart and code was largely lost. As long as you only draw your loops to the right (or left, just be consistent) and make sure you don't cross any lines, you're doing structured programming. (I think...) E.g. | v blah1+ | ^ v | if xx--foo | ||| vv| bar baz | ||| +---+| | | v | maybe+ | v -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
Gabriel Genellina wrote: At Wednesday 18/10/2006 21:36, Ron Adam wrote: Maybe changing the CAPS_FIRST to REVERSE_CAPS_ORDER would do? At least it's a more accurate name. There is an indirect way: test locale.strcoll(A,a) and see how they get sorted. Then define options CAPS_FIRST, LOWER_FIRST accordingly. But maybe it's too much trouble... I should of thought of that simple test. Thanks. :-) That would work, and it's really not that much trouble. The actual test can be done during importing. Maybe determining other useful values could be done at that time as well. You should try to make this part a bit more generic. If you are concerned about locales, do not use comma explicitely. In other countries 10*100=1.000 - and 1,234 is a fraction between 1 and 2. See the most recent version of this I posted. It is a bit more generic. news://news.cox.net:119/[EMAIL PROTECTED] Maybe a 'comma_is_decimal' option? I'd prefer to use the 'decimal_point' and 'thousands_sep' from the locale information. That would be more coherent with the locale usage along your module. Yes, it looks like I'll need to do this. The term I've seen before is called natural ordering, but that is more general and can include date, roman numerals, as well as other type. Sometimes that's the hard part, finding a name which is concise, descriptive, and accurately reflects what the code does. A good name should make obvious what it is used for (being these option names, or class names, or method names...) but in this case it may be difficult to find a good one. So users will have to read the documentation (a good thing, anyway!) I plan on making the doc strings a bit more informative so that help(collate) will give meaningful information on it's options. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
wxPython and PIL
I'm making a simple program to crop and scale images, essentially make thumbnails from a user defined subset of the image. I'm planning to use Python Image Library to crop and resize the images, mostly to make the resized smaller images look good. How do I display a PIL image with wxPython? -- http://mail.python.org/mailman/listinfo/python-list
Re: Determining if a file is locked in Windows
elake wrote: Larry Bates wrote: elake wrote: I found this thread about a pst file in Windows being locked and I am having the same issue. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gstq=%27copying+locked+files%27rnum=1 The problem is that I have a script that can find the pst files on every machine in my network and back them up to a server for safe keeping. The problem is that when Outlook is running it locks the file and will not allow me to copy it to the destination. I am using the shutil module for the copy. Is there a way to first determine if the file is locked and then do the copy if it isn't? I thought about looking to see if Outlook.exe is running but the machines are shared and the process could be running but with a different pst file in use. Thanks in advance Try the copy and catch the exception instead. -Larry Bates Larry thanks for your suggestion. this is what I tried: #!/usr/bin/env python import os, shutil path = 'c:\documents and settings\username\Local Settings\Application Data\Microsoft\Outlook' src = 'Outlook.pst' dst = 'test.pst' os.chdir(path) try: shutil.copy2(src, dst) except IOError: print 'Must be locked by Outlook' print 'Finished' The problem is that even though I catch the IOError it overwrites the dst file and makes it 0kb. This is going to be for backing these files up and it wont be good to overwrite the backup with a bad copy. Is there another way to do this that I am missing. I am still kind of new to Python. If i could tell that outlook had the file locked before I tried the copy then I think that it would be prevented. maybe try and open the file for reading first, then if it opens ok, just close it and do the copy? -- http://mail.python.org/mailman/listinfo/python-list
Re: A suggestion/request for IDEs
John Salerno wrote: I apologize for the slightly off-topic nature, but I thought I'd just throw this out there for anyone working on text editors or IDEs with auto-completion. I think it should be a feature, when an item is selected for auto-completion in a drop-down box, that pressing the spacebar (in addition to tab or enter) will automatically finish the word and add a space. This is how Microsoft's new IDEs for .NET work, and I found it very helpful to be able to just press space as normal and keep typing. I know it sounds minor, but I find it to be a time saver instead of having to press tab or enter, and then also the spacebar. Thanks. See I have to disagree with you. I always hated that spacebar would complete. I found it more natural that space would simply enter a space and you could keep typing. I found it slowed my down more having to change items that would autocomplete when I didn't want them to. Of course, it's a matter of preference and comfort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use decorators to manipulate return type or create methods?
On 19 Oct 2006 06:43:49 -0700, WakeBdr [EMAIL PROTECTED] wrote: I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc) To get the appropriate return types, I also have these methods. I have these convenience methods for every query method in my class. def getUsersAsXML(self, params): return self._toXML(self.getUsers(params)) def getUsersAsDict(self, params): return self._toDict(self.getUsers(params)) def getUsersAsList(self, params): return self._toList(self.getUsers(params)) Instead of creating these three methods for every query method, is there a way to use decorators to manipulate the return type. I'd still like to have the caller use getUsersAsXML, I just don't want to write the AsXML methods for every query method. So the decorator would essentially create the convenience methods instead of me coding them. One solution that I don't want to use is passing a variable into the query method that determines the return type. This is what I don't want to do. def getUsers(self, params, returnType): Any ideas on how I can accomplish this? You can't do it as fully magically as I'd like, because at the time decorators are run, the methods are just functions and aren't bound as methods yet (so you can't automagically add methods to the class, for example - you'd need to do that after the class definition finishes executing). You *could* decorate all the functions you want to have special return types, then (after the class definition) loop through those to generate the extra return funcs. You can do it with a minimum of boilerplate this way: from functools import wraps #only in 2.5, you can do this by hand in 2.4 #wrapped is the function we're calling and returning as XML #xmlfunc is the stub function we're replacing def returnXML(wrapped): def f(xmlfunc): @wraps(xmlfunc) def xmlMethod(self): return self.asXML(wrapped(self)) return xmlMethod return f class T(object): def getUser(self): return user def asXML(self, data): return xml%s/xml%(data) @returnXML(getUser) def getUserAsXML(self):pass t = T() print t.getUserAsXML() -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to RuleDispatch
exhuma.twn wrote: On Oct 19, 3:44 pm, exhuma.twn [EMAIL PROTECTED] wrote: On Oct 18, 10:41 pm, Adam Jones [EMAIL PROTECTED] wrote: exhuma.twn wrote: Hi all, yesterday I wanted to install TurboGears, which depends on RuleDispatch. However, I failed to download it. First I got the error Bad Gateway from the server, today it's simply a Not Found error. So what happened to it? Does somebody know? I would really need to install TurboGears in the next couple of days. So if someone knows where I can find a mirror ofRuleDispatchI would be very grateful.The required files for TG are mirrored on the turbogears.org download page. You should be able to get an installation by looking up the files there. Try this command: easy_install -fhttp://www.turbogears.org/download/index.html TurboGears That is actually the recommended way to install TurboGears, as it is not always compatible with the latest version of the components. -AdamHmmm... this is wat I get: Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg Processing dependencies for TurboGears Searching forRuleDispatch Readinghttp://www.turbogears.org/download/index.html Best match:RuleDispatch0.5a0.dev-r2115 Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: 502 Bad Gateway Could this be a local issue? Forgot to say I also tried to download it via the web-browser. This gave me the following error (generated by the proxy I have to use): Server response could not be decoded using encoding type returned by server. This is typically caused by a Web Site presenting a content encoding header of one type, and then encoding the data differently. I just tried it for myself (with my workplace's proxy) and had no problems. You might want to check on the TurboGears mailing list ( http://groups.google.com/group/turbogears ) to see if someone there can help you figure out what is going on. Downloading the eggs at another location and installing locally is also an option. -Adam -- http://mail.python.org/mailman/listinfo/python-list
[OT] Re: A suggestion/request for IDEs
John Salerno wrote: I apologize for the slightly off-topic nature, but I thought I'd just throw this out there for anyone working on text editors or IDEs with auto-completion. Well, Vim7's autocompletion already allows this. Earlier versions of vim also allowed similar behavior, but (AFAIK) didn't have a nice way to cancel the suggestion or to accept the suggestion without an additional character (or leaving insert mode). In Vim7, you can abort your current ^P/^N completion with ^E (to regain just what you typed, minus the current completion/suggestion) or you can accept it with ^Y (which won't add an extra character), or you can just continue typing to accept the completion, and then add the character you typed (such as space, period, etc). Other editors/IDEs may have similar functionality... -tkc -- http://mail.python.org/mailman/listinfo/python-list
Dictionaries again - where do I make a mistake?
I use the following code to sort dictionary. Olddict={'r':4,'c':1,'d':2,'e':3,'f':2} Newdict={} i = [(val, key) for (key, val) in Olddict.items()] i.sort() # by val i.reverse() # Get largest first. for (val, key) in i: print key,val Newdict[key]=val print Olddict print Newdict Sorting seems to be OK,. the command print key,val prints the proper values but I can not create Newdict to be sorted properly. Where do I make a mistake? Thank you for help. L -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries again - where do I make a mistake?
Lad wrote: Sorting seems to be OK,. the command print key,val prints the proper values but I can not create Newdict to be sorted properly. Where do I make a mistake? Thank you for help. Dictionaries are unordered -- the order in which items come out is unspecified. It's based on the details of their internal storage mechanism (a hash table), and you can't control it at all. If you need your pairs in a certain order, you'll have to use a list of tuples. Dustin -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries again - where do I make a mistake?
but I can not create Newdict to be sorted properly. Where do I make a mistake? By assuming that dictionaries *can* be sorted. For more reading: http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 They're intrinsically an unsorted datatype. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Komodo
Why is it that (On MAC OS X) in Komodo 3.5 Professional, if I try to find something in my script, I am unable to change the text it is searching for? -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to RuleDispatch
On Oct 19, 5:32 pm, Adam Jones [EMAIL PROTECTED] wrote: exhuma.twn wrote: On Oct 19, 3:44 pm, exhuma.twn [EMAIL PROTECTED] wrote: On Oct 18, 10:41 pm, Adam Jones [EMAIL PROTECTED] wrote: exhuma.twn wrote: Hi all, yesterday I wanted to install TurboGears, which depends on RuleDispatch. However, I failed to download it. First I got the error Bad Gateway from the server, today it's simply a Not Found error. So what happened to it? Does somebody know? I would really need to install TurboGears in the next couple of days. So if someone knows where I can find a mirror ofRuleDispatchI would be very grateful.The required files for TG are mirrored on the turbogears.org download page. You should be able to get an installation by looking up the files there. Try this command: easy_install -fhttp://www.turbogears.org/download/index.html TurboGears That is actually the recommended way to install TurboGears, as it is not always compatible with the latest version of the components. -AdamHmmm... this is wat I get: Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg Processing dependencies for TurboGears Searching forRuleDispatch Readinghttp://www.turbogears.org/download/index.html Best match:RuleDispatch0.5a0.dev-r2115 Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: 502 Bad Gateway Could this be a local issue? Forgot to say I also tried to download it via the web-browser. This gave me the following error (generated by the proxy I have to use): Server response could not be decoded using encoding type returned by server. This is typically caused by a Web Site presenting a content encoding header of one type, and then encoding the data differently.I just tried it for myself (with my workplace's proxy) and had no problems. You might want to check on the TurboGears mailing list (http://groups.google.com/group/turbogears) to see if someone there can help you figure out what is going on. Downloading the eggs at another location and installing locally is also an option. -Adam I'll do that. Thanks anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use decorators to manipulate return type or create methods?
WakeBdr schrieb: I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc) To get the appropriate return types, I also have these methods. I have these convenience methods for every query method in my class. def getUsersAsXML(self, params): return self._toXML(self.getUsers(params)) def getUsersAsDict(self, params): return self._toDict(self.getUsers(params)) def getUsersAsList(self, params): return self._toList(self.getUsers(params)) Instead of creating these three methods for every query method, is there a way to use decorators to manipulate the return type. I'd still like to have the caller use getUsersAsXML, I just don't want to write the AsXML methods for every query method. So the decorator would essentially create the convenience methods instead of me coding them. One solution that I don't want to use is passing a variable into the query method that determines the return type. This is what I don't want to do. def getUsers(self, params, returnType): Any ideas on how I can accomplish this? Use a metaclass. class Magic(type): def __new__(cls, name, bases, d): for name, function in d.items(): try: function._marked def toXML(self, *args, **kwargs): return self._toXML(function(self, *args, **kwargs)) def toFOO(self, *args, **kwargs): return self._toFOO(function(self, *args, **kwargs)) d[name + XML] = toXML d[name + FOO] = toFOO except AttributeError: pass return type(name, bases, d) def mark(f): f._marked = True return f class MyClass(object): __metaclass__ = Magic def _toXML(self, value): return Look Ma, its XML! %r % value def _toFOO(self, value): return Look Ma, its FOO! %r % value @mark def someMethod(self): return Its the data, son o = MyClass() print o.someMethod() print o.someMethodXML() print o.someMethodFOO() Diez -- http://mail.python.org/mailman/listinfo/python-list
invert or reverse a string... warning this is a rant
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x[::-1] Ruby: x = 'a_string' # Reverse the string print x.reverse The Ruby approach makes sense to me as a human being. The Python approach is not easy for me (as a human being) to remember. Can that be changed or should I just start blindly memorizing this stuff? P.S. I like Python better than Ruby 90% of the time and use Python 90% of the time, but 10% of the time, little things such as this drive me crazy! -- http://mail.python.org/mailman/listinfo/python-list
httplib problems -- bug, or am I missing something?
I'm building an interface to Amazon's S3, using httplib. It uses a single object for multiple transactions. What's happening is this: HTTP PUT /unitest-temp-1161039691 HTTP/1.1 HTTP Date: Mon, 16 Oct 2006 23:01:32 GMT HTTP Authorization: AWS cough:KiTWRuq/6aay0bI2J5DkE2TAWD0= HTTP (end headers) HTTP HTTP/1.1 200 OK HTTP content-length: 0 HTTP x-amz-id-2: 40uQn0OCpTiFcX+LqjMuzG6NnufdUk/.. HTTP server: AmazonS3 HTTP x-amz-request-id: FF504E8FD1B86F8C HTTP location: /unitest-temp-1161039691 HTTP date: Mon, 16 Oct 2006 23:01:33 GMT HTTPConnection.__state before response.read: Idle HTTPConnection.__response: closed? False length: 0 reading response HTTPConnection.__state after response.read: Idle HTTPConnection.__response: closed? False length: 0 ..later in the same connection.. HTTPConnection.__state before putrequest: Idle HTTPConnection.__response: closed? False length: 0 HTTP DELETE /unitest-temp-1161039691 HTTP/1.1 HTTP Date: Mon, 16 Oct 2006 23:01:33 GMT HTTP Authorization: AWS cough:a5OizuLNwwV7eBUhha0B6rEJ+CQ= HTTP (end headers) HTTPConnection.__state before getresponse: Request-sent HTTPConnection.__response: closed? False length: 0 File /usr/lib64/python2.4/httplib.py, line 856, in getresponse raise ResponseNotReady() If the first request does not precede it, the second request is fine. To avoid excessive memory use, I'm calling request.read(16384) repeatedly, instead of just calling request.read(). This seems to be key to the problem -- if I omit the 'amt' argument to read(), then the last line of the first request reads HTTPConnection.__response: closed? True length: 0 and the later call to getresponse() doesn't raise ResponseNotReady. Looking at the source for httplib.HTTPResponse.read, self.close() gets called in the latter (working) case, but not in the former (non-working). It would seem sensible to add 'if self.length == 0: self.close()' to the end of that function (and, in fact, this change makes the whole thing work), but this comment makes me hesitant: # we do not use _safe_read() here because this may be a .will_close # connection, and the user is reading more bytes than will be provided # (for example, reading in 1k chunks) What's going on here? Is this a bug I should report, or am I missing something about how one should use httplib? Thanks for any assistance. Dustin -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython help wxSashWindow
MatthewWarren wrote: Thanks, is that a newsgroup I can view through google groups? I tried seraching for it but google says no.. I'm not sure, but I don't think so. The way I have to do it is use Thunderbird (or equivalent) and subscribe first to the Gmane account, then to the specific newsgroup. You also have to send posts to the mailing list address, not to the newsgroup name itself (these seem to get sent, but never appear), so it's kind of funky. -- http://mail.python.org/mailman/listinfo/python-list
pywin32 COM sort in Excel (late binding fails, early binding works) (+py2exe)
ISSUE: COM Excel Sort works with Early Binding, but not Late Binding, but py2exe only does Late Binding I have code similar to this (type from notes, so there may be a typo...) import win32com.client xl = win32com.client.Dispatch(Excel.Application) xl.Visible = False xl.ScreenUpdating = False wb = xl.Workbooks.Open(h:\\p.xls) sht = wb.Sheets(SheetName) # wb.Worksheets(Sheetname) sht.Cells.Sort(Key1=sht.Cells(2,1), Order1=1, Header=1, Orientation=1) Python: 2.4.3 pywin32 200 py2exe 0.6.5 Office 2000 The sort DOES NOT work if called from a normal install (e.g. using late binding): the Header line gets sorted with all the data. ID Value Mort 232 2 54 54 33 232 --- 54 33 232 232 2 54 ID Value Mort HOWEVER, If I run makepy.py and select the Microsoft Excel 9.0 (-- I'm typing this from memory!) and run it, it creates the GUID'd py file in gen_py If I run the above code again (on a clean copy of the xls file), it DOES sort the sheet correctly --- the header line is left alone. ID Value Mort 232 2 54 54 33 232 --- ID Value Mort 54 33 232 232 2 54 Normally, this would not be an issue, but when I bundle my app using py2exe it does not grab the gen_py stuff. Any help appreciated... -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
On 2006-10-19, Michael Ströder [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: print 'K\xc3\xb6ni'.decode('utf-8') and this line raised a UnicodeDecode exception. Works for me. Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console No, the setting of the console encoding (sys.stdout.encoding) is ignored. It's a good thing, too, since it's pretty flaky. It uses sys.getdefaultencoding(), which is always 'ascii' as far as I know. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
rick wrote: Why can't Python have a reverse() function/method like Ruby? I'm not steeped enough in daily programming to argue that it isn't necessary, but my question is why do you need to reverse strings? Is it something that happens often enough to warrant a method for it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
Wolfgang Keller wrote: does anyone know of a good book that about development of database applications? Scott Ambler's Agile Database Techniques Regardless of whether you'll actually use a full MVC framework or not, I suggest that you write model classes that are fully decoupled from the UI. Work in a test-driven fashion, writing tests first and just coding until the test goes through, and then write the next test. See e.g. Kent Beck's Test-Driven Development. If you use an SQL database below some ORM, you can use SQLite with an in-memory database :memory: for your functional test. Fast and simple. I'd make the GUI as thin as possible, since GUI code it typically more complicated to test automatically. -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
rick [EMAIL PROTECTED] writes: Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x[::-1] The Ruby approach makes sense to me as a human being. The Python approach is not easy for me (as a human being) to remember. Can that be changed or should I just start blindly memorizing this stuff? You could use: print ''.join(reversed(x)) That also looks a little bit weird, but it combines well-known Python idioms straightforwardly. -- http://mail.python.org/mailman/listinfo/python-list
Calling functions
I have a small program that goes something like thisdef funcA() : passdef funcB() : passdef funcC() : passdef determine(f): t = f() return tWhat I would like to do is be able to n = determine(funcA)m = determine(funcB)But I can't really figure out how to do this (I think it is possible :) CheersTommy[EMAIL PROTECTED]http://homepage.mac.com/tgrav/"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
rick wrote: The Ruby approach makes sense to me as a human being. do the humans on your planet spend a lot of time reversing strings? it's definitely not a very common thing to do over here. anyway, if you do this a lot, why not define a helper function? def reverse(s): return s[::-1] print reverse(redael ruoy ot em ekat) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling functions
Tommy Grav wrote: I have a small program that goes something like this def funcA() : pass def funcB() : pass def funcC() : pass def determine(f): t = f() return t What I would like to do is be able to n = determine(funcA) m = determine(funcB) But I can't really figure out how to do this (I think it is possible :) Except for the spaces after the def's at the top (are those legal?), it should work as written. determine(funcA) results in 'f' being bound to 'funcA'; then 't = f()' results in 'funcA' being called, and its resulting being bound to 't'; 'determine' returns that result, and it's bound to 'n'. Is that not what you wanted? Dustin -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
In [EMAIL PROTECTED], Neil Cerutti wrote: Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console No, the setting of the console encoding (sys.stdout.encoding) is ignored. Nope, it is not ignored. This would not work then:: In [2]: print 'K\xc3\xb6nig'.decode('utf-8') König In [3]: import sys In [4]: sys.getdefaultencoding() Out[4]: 'ascii' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
RE: invert or reverse a string... warning this is a rant
John Salerno wrote: 'm not steeped enough in daily programming to argue that it sn't necessary, but my question is why do you need to reverse strings? Is it something that happens often enough to warrant a method for it? I've been programming professionally for over 10 years, and have never once needed to reverse a string. Maybe it's a lack of imagination on my part, but I can't think of a single instance this might be necessary. However, if I did ever run across this need while using Python, it would seem awkward to use [::-1], just from a clarity standpoint. A string.reverse() method would be a decent thing to have. Just my $.02. -Jeff P.S. How about a string.shuffle() method that splits the string in half into two new strings str1 and str2, and then recompiles the string by alternating one character from each str1 and str2 as it goes? Like shuffling cards. ;) This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling functions
Tommy Grav wrote: I have a small program that goes something like this def funcA() : pass def funcB() : pass def funcC() : pass def determine(f): t = f() return t What I would like to do is be able to n = determine(funcA) m = determine(funcB) But I can't really figure out how to do this really? the code you posted does work, to some extent (it doesn't raise any errors, but since your functions don't contain any return statements, they'll return None, and both n and m will be set to None). what did you expect this to do? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and PIL
Odalrick wrote: I'm making a simple program to crop and scale images, essentially make thumbnails from a user defined subset of the image. I'm planning to use Python Image Library to crop and resize the images, mostly to make the resized smaller images look good. How do I display a PIL image with wxPython? def piltoimage(pil,alpha=True): Convert PIL Image to wx.Image. if alpha: image = apply( wx.EmptyImage, pil.size ) image.SetData( pil.convert( RGB).tostring() ) image.SetAlphaData(pil.convert(RGBA).tostring()[3::4]) else: image = wx.EmptyImage(pil.size[0], pil.size[1]) new_image = pil.convert('RGB') data = new_image.tostring() image.SetData(data) return image def imagetopil(image): Convert wx.Image to PIL Image. pil = Image.new('RGB', (image.GetWidth(), image.GetHeight())) pil.fromstring(image.GetData()) return pil Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
On 2006-10-19, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], Neil Cerutti wrote: Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console No, the setting of the console encoding (sys.stdout.encoding) is ignored. Nope, it is not ignored. This would not work then:: In [2]: print 'K\xc3\xb6nig'.decode('utf-8') König In [3]: import sys In [4]: sys.getdefaultencoding() Out[4]: 'ascii' Interesting! Thanks for the correction. -- Neil Cerutti This scene has a lot of activity. It is busy like a bee dive. --Michael Curtis -- http://mail.python.org/mailman/listinfo/python-list
advice for web-based image annotation
Hello, I want to set up a system where I can have my family members write comments about a number of pictures, as part of a family tree project. Essentially, I want them to be able to log into a website (I already have the webspace, and the server runs python, but not mod_python), see images, and be able to fill in text boxes for comments and enter dates for the pictures. These comments and dates will then be viewable by the others logging in, so that I can keep track of collect stories, details, dates, etc...and also, who is writing what, when. I've written some basic CGI python scripts, and can imagine how to do this, but I was wondering if it would better to look into a framework like cherrypy, turbogears, zope, etc. I have never done any database programming, but have written CGI scripts to modify excel sheets and text files to store state. I am not adverse to learning the database end, but I don't want to climb that hill unless I feel there is a significant benefit. I don't have admin rights on the server, if that makes a difference. Any suggestions would be greatly appreciated! thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
RE: invert or reverse a string... warning this is a rant
John Salerno wrote: 'm not steeped enough in daily programming to argue that it sn't necessary, but my question is why do you need to reverse strings? Is it something that happens often enough to warrant a method for it? I've been programming professionally for over 10 years, and have never once needed to reverse a string. Maybe it's a lack of imagination on my part, but I can't think of a single instance this might be necessary. However, if I did ever run across this need while using Python, it would seem awkward to use [::-1], just from a clarity standpoint. A string.reverse() method would be a decent thing to have. Just my $.02. -Jeff P.S. How about a string.shuffle() method that splits the string in half into two new strings str1 and str2, and then recompiles the string by alternating one character from each str1 and str2 as it goes? Like shuffling cards. ;) This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling functions
That does work yes :) I just noticed that the script had another little error in it, making me believe that the function call was crooking.Cheers TommyOn Oct 19, 2006, at 12:30 PM, Dustin J. Mitchell wrote:Tommy Grav wrote: I have a small program that goes something like thisdef funcA() : passdef funcB() : passdef funcC() : passdef determine(f):t = f()return tWhat I would like to do is be able to n = determine(funcA)m = determine(funcB)But I can't really figure out how to do this (I think it is possible :) Except for the spaces after the def's at the top (are those legal?), it shouldwork as written.determine(funcA) results in 'f' being bound to 'funcA'; then 't = f()' resultsin 'funcA' being called, and its resulting being bound to 't'; 'determine'returns that result, and it's bound to 'n'. Is that not what you wanted?Dustin-- http://mail.python.org/mailman/listinfo/python-list CheersTommy[EMAIL PROTECTED]http://homepage.mac.com/tgrav/"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 to unicode or latin-1 (and yes, I read the FAQ)
On 2006-10-19, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], Neil Cerutti wrote: Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console No, the setting of the console encoding (sys.stdout.encoding) is ignored. Nope, it is not ignored. This would not work then:: In [2]: print 'K\xc3\xb6nig'.decode('utf-8') König In [3]: import sys In [4]: sys.getdefaultencoding() Out[4]: 'ascii' OK, I was thinking of the behavior of file.write(s). Thanks again for the correction. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
John Salerno wrote: rick wrote: Why can't Python have a reverse() function/method like Ruby? I'm not steeped enough in daily programming to argue that it isn't necessary, but my question is why do you need to reverse strings? Is it something that happens often enough to warrant a method for it? I'm home for lunch so my email addy is different. No, it doesn't happen very often, but when I need to reverse something (usually a list or a string). I can never remember right of the top of my head how to do so in Python. I always have to Google for an answer or refer back to old code. IMO, I should be able to intuitively know how to do this. Python is so user-friendly most every place else... why can it not be so here? I wrote this so I'll never have to remember this again: def invert(invertable_object): try: print invertable_object[::-1] return invertable_object[::-1] except: print 'Object not invertable' return 1 invert([1,2,3,4]) invert('string') invert({1:2, 3:4}) -- http://mail.python.org/mailman/listinfo/python-list
Re: Determining if a file is locked in Windows
MatthewWarren wrote: elake wrote: Larry Bates wrote: elake wrote: I found this thread about a pst file in Windows being locked and I am having the same issue. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gstq=%27copying+locked+files%27rnum=1 The problem is that I have a script that can find the pst files on every machine in my network and back them up to a server for safe keeping. The problem is that when Outlook is running it locks the file and will not allow me to copy it to the destination. I am using the shutil module for the copy. Is there a way to first determine if the file is locked and then do the copy if it isn't? I thought about looking to see if Outlook.exe is running but the machines are shared and the process could be running but with a different pst file in use. Thanks in advance Try the copy and catch the exception instead. -Larry Bates Larry thanks for your suggestion. this is what I tried: #!/usr/bin/env python import os, shutil path = 'c:\documents and settings\username\Local Settings\Application Data\Microsoft\Outlook' src = 'Outlook.pst' dst = 'test.pst' os.chdir(path) try: shutil.copy2(src, dst) except IOError: print 'Must be locked by Outlook' print 'Finished' The problem is that even though I catch the IOError it overwrites the dst file and makes it 0kb. This is going to be for backing these files up and it wont be good to overwrite the backup with a bad copy. Is there another way to do this that I am missing. I am still kind of new to Python. If i could tell that outlook had the file locked before I tried the copy then I think that it would be prevented. maybe try and open the file for reading first, then if it opens ok, just close it and do the copy? I tried to do that and it did let me open it without an error. Here is what I have done now and it seems work. def copyFile(src, dst): if os.path.isfile(dst): shutil.copy2(dst, dst_bak) try: shutil.copy2(src, dst) except IOError: if os.path.isfile(dst_bak): shutil.copy2(dst_bak, dst) os.remove(dst_bak) else: try: shutil.copy2(src, dst) except IOError: if os.path.isfile(dst_bak): shutil.copy2(dst_bak, dst) It check to see if the dst file is there first and them makes a backup of it first. That way if the copy goes bad then there is still a backup of it. Do you see anywhere that I could have done this better/differently? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython help wxSashWindow
MatthewWarren [EMAIL PROTECTED] wrote: Thanks, is that a newsgroup I can view through google groups? I tried seraching for it but google says no.. And I'll give that list a subscribe. I have found a wxPython google group, but only 11 members and a handfull of posts in a year... Gmane archives many mailing lists and also allows access to the lists through a news server gateway(news.gmane.org). Posting throught the news gateway is allowed for many groups(including this one), but not all. For more information and web access to the archives, visit http://gmane.org. max -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
On 2006-10-19, Brad [EMAIL PROTECTED] wrote: I'm home for lunch so my email addy is different. No, it doesn't happen very often, but when I need to reverse something (usually a list or a string). I can never remember right of the top of my head how to do so in Python. I always have to Google for an answer or refer back to old code. IMO, I should be able to intuitively know how to do this. Python is so user-friendly most every place else... why can it not be so here? I wrote this so I'll never have to remember this again: def invert(invertable_object): try: print invertable_object[::-1] return invertable_object[::-1] except: print 'Object not invertable' return 1 invert([1,2,3,4]) invert('string') invert({1:2, 3:4}) Shoot, now you'll have to remember where in heck you stashed that function the next time you need to reverse something. ;-) You'll still be better off in the long run memorizing the slice notation. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
Fredrik Lundh wrote: rick wrote: The Ruby approach makes sense to me as a human being. do the humans on your planet spend a lot of time reversing strings? it's definitely not a very common thing to do over here. On our planet, we're all dyslexic. We tend to do things 'backwards' so being able to easily invert what we do helps the people we show the code to on your planet make sense of it. anyway, if you do this a lot, why not define a helper function? def reverse(s): return s[::-1] print reverse(redael ruoy ot em ekat) Thanks, that's what I ended up doing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use decorators to manipulate return type or create methods?
WakeBdr wrote: I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc) To get the appropriate return types, I also have these methods. I have these convenience methods for every query method in my class. def getUsersAsXML(self, params): return self._toXML(self.getUsers(params)) def getUsersAsDict(self, params): return self._toDict(self.getUsers(params)) def getUsersAsList(self, params): return self._toList(self.getUsers(params)) Instead of creating these three methods for every query method, is there a way to use decorators to manipulate the return type. I'd still like to have the caller use getUsersAsXML, I just don't want to write the AsXML methods for every query method. So the decorator would essentially create the convenience methods instead of me coding them. One solution that I don't want to use is passing a variable into the query method that determines the return type. This is what I don't want to do. def getUsers(self, params, returnType): Any ideas on how I can accomplish this? Here's an odd approach, entirely based on naming conventions: from operator import attrgetter class Composer(object): def __getattr__(self, name): prefix, delim, suffix = name.rpartition(_as_) if prefix and suffix: cls = self.__class__ inner = attrgetter(prefix) outer = attrgetter(delim + suffix) def wrapped(self, *args): return outer(self)(inner(self)(*args)) setattr(cls, name, wrapped) return getattr(self, name) raise AttributeError(sorry, no %r % name) class A(Composer): def _as_xml(self, obj): return as_xml(%s) % (obj,) def _as_list(self, obj): return as_list(%s) % (obj,) def get_users(self): return get_users() class B(A): def _as_list(self, obj): return AS_LIST(%s) % (obj,) def get_artist_as_a_young_man(self, name): return get_artist_as_a_young_man(name=%r) % name if __name__ == __main__: a = A() b = B() print a.get_users_as_list() print b.get_users_as_list() print a.get_users_as_xml() print b.get_artist_as_a_young_man_as_xml(James) print a.get_artist_as_a_young_man_as_xml(James) # AttributeError Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Komodo
* SpreadTooThin wrote (on 10/19/2006 8:47 AM): Why is it that (On MAC OS X) in Komodo 3.5 Professional, if I try to find something in my script, I am unable to change the text it is searching for? Perhaps Emacs might work better ... :) Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
Demel, Jeff [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] John Salerno wrote: P.S. How about a string.shuffle() method that splits the string in half into two new strings str1 and str2, and then recompiles the string by alternating one character from each str1 and str2 as it goes? Like shuffling cards. ;) You mean: .join(sum(map(list,zip(s,s[len(s)/2:])),[])) perhaps? s = ABCDEFGHIJKLMNOPQRSTUVWXYZ .join(sum(map(list,zip(s,s[len(s)/2:])),[])) 'ANBOCPDQERFSGTHUIVJWKXLYMZ' -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting existing module/objects to threads
At Thursday 19/10/2006 00:01, [EMAIL PROTECTED] wrote: Consider using the asyncore module instead of threads. I think that is a good point and I am considering using asyncore/asynchat... i'm a little confused as to how i can make this model work. There is no server communication without connection from the client (me), which happens on intervals, not when data is available on a socket or when the socket is available to be written, which is always. Basically i need to determine how to trigger the asynchat process based on time. in another application that i write, i'm the server and the chat process happens every time the client wakes up...easy and perfect for asyncore That is a solution i'd like to persue, but am having a hard time getting my head around that as well. You have to write your own dispatcher (inheriting from async_chat) as any other protocol. You can call asyncore.loop whith count=1 (or 10, but not None, so it returns after a few iterations) inside your *own* loop. Inside your loop, when time comes, call your_dispatcher.push(data) so the channel gets data to be sent. Override collect_incoming_data() to get the response. You can keep your pending requests in a priority queue (sorted by time) and check the current time against the top element's time. Maybe you could successfully implement your application using threads - if none uses global variables, and no thread waits for another, it may be safe. But I prefer to avoid threads whenever possible, at least because debugging the application becomes harder. -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list