python-dev Summary for 2006-08-16 through 2006-08-31
python-dev Summary for 2006-08-16 through 2006-08-31 .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-08-16_2006-08-31] = Announcements = --- Python communnity buildbots --- Want to make sure your package works with the latest and greatest development and release versions of Python? Thanks to Grig Gheorghiu, you can add your test suite to the `Python community buildbots`_ and the results of these tests will show up on the `Python buildbot results page`_. .. _Python community buildbots: http://www.pybots.org/ .. _Python buildbot results page: http://www.python.org/dev/buildbot/ Contributing thread: - `link to community buildbot? http://mail.python.org/pipermail/python-dev/2006-August/068552.html`__ = Summaries = - Fast subclass testing - Neal Norwitz was playing around with a patch that would make subclass testing for certain builtin types faster by stealing some bits from tp_flags. Georg Brandl thought this could be useful for exception handling in Python 3000 when all exceptions must be subclasses of BaseException. Guido also liked the patch and suggested it be checked into the `Python 3000 branch`_. .. _Python 3000 branch: http://svn.python.org/view/python/branches/p3yk/ Contributing thread: - `Type of range object members http://mail.python.org/pipermail/python-dev/2006-August/068267.html`__ - gcc 4.2 and integer overflows - Jack Howarth pointed out that intobject.c was using the test ``x 0 x == -x`` to determine if the signed integer ``x`` was the most negative integer on the platform. However, the C standard says overflow is undefined, so despite this code actually working on pretty much all known hardware, `gcc 4.2 assumes that overflow won't happen`_ and so optimizes away the entire clause. David Hopwood and Tim Peters provided a patch that casts ``x`` to an unsigned long (the unnecessary ``0`` is to make the Microsoft compilers happy):: x 0 (unsigned long)x == 0-(unsigned long)x .. _gcc 4.2 assumes that overflow won't happen: http://bugs.python.org/1545668 Contributing thread: - `gcc 4.2 exposes signed integer overflows http://mail.python.org/pipermail/python-dev/2006-August/068481.html`__ -- Python and 64-bit machines -- Thomas Heller explained that the _ctypes extension module was still a fair ways from building on Win64 and had to be removed from the installer for that platform. There was some discussion about in general how experimental the Win64 build of Python was, but Martin v. Lowis explained that despite the compiler warnings, Python has been running mostly fine on Win64 since version 2.4. In fact, Python has been running in 64-bit machines since 1993 (when Tim Peters ported it to 64-bit Crays) though of course not with the support that Python 2.5 brought through the Py_ssize_t changes. Contributing thread: - `ctypes and win64 http://mail.python.org/pipermail/python-dev/2006-August/068362.html`__ -- Guidelines for submitting bugs and patches -- Brett Cannon put together a rewrite of the `bug and patch guidelines`_. The bug guidelines now includes sections on how to: * Get a SourceForge account * Start a new bug * Specify the Python version * Specify special settings for your Python interpreter * Give sample code to reproduce bug * Submit! * Respond to requests from developers And the patch guidelines now includes sections on how to: * Read the Developer Intro to understand the scope of your proposed change * Add the appropriate unit tests * Add the proper document changes * Make your code follow the style guidelines * Generate a patch * Create a tracker item on SourceForge * Reference the patch in proper bug reports * Wait for a developer to contact you At Chad Whitacre's suggestion, Brett also included a section on the 5-for-1 rule, where some python-devvers have agreed to review your one patch if you post reviews of five others. The updates had not been posted to python.org at the time of this summary. .. _bug and patch guidelines: http://www.python.org/dev/patches/ Contributing threads: - `draft for bug guidelines http://mail.python.org/pipermail/python-dev/2006-August/068462.html`__ - `draft of patch guidelines http://mail.python.org/pipermail/python-dev/2006-August/068463.html`__ - Corner cases for continue/finally - Dino Viehland pointed out an odd corner case with ``continue`` in a ``finally`` clause that was causing Python to crash:: for abc in range(10): try: pass finally: try:
Re: Plotting histograms
Thanks Robert, My previous problem is solved(I was using 'from matplotlib.pylab import *') but now I am facing another problem. I want to plot the histogram of eigenvalues calculated and I am using the following code: ___ import numpy from matplotlib import pylab n=100 ra = numpy.random la = numpy.linalg A = ra.standard_normal((n,n)) S = (A + numpy.transpose(A))/(2*n^(1/2)) eig = la.eigvals(S) [N,x]=pylab.hist(eig, 10) # make a histogram - But again it is giving some error, which is given below: File C:\Documents and Settings\amitsoni\Desktop\New Folder\wignerpython, line 15, in module [N,x]=pylab.hist(eig, 10) # make a histogram ValueError: too many values to unpack Can anyone help me out with this?? Thanks Amit Robert Kern wrote: [EMAIL PROTECTED] wrote: hi, I have some values(say from -a to a) stored in a vector and I want to plot a histogram for those values. How can I get it done in python. I have installed and imported the Matplotlib package but on executing the code [N,x]=hist(eig, 10) # make a histogram I am getting an error saying NameError: name 'hist' is not defined. I presume what you did was something like this: from matplotlib import pylab [N,x] = hist(eig, 10) What you actually want is this: from matplotlib import pylab [N,x] = pylab.hist(eig, 10) Or, if you're at the interactive prompt (but remember that it is inadvisable to do so in modules): from matplotlib.pylab import * [N,x] = hist(eig, 10) You will probably want to review the section of the tutorial on importing modules if you don't understand the differences. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: string splitting
[EMAIL PROTECTED] wrote: Hello, I have thousands of files that look something like this: wisconsin_state.txt french_guiana_district.txt central_african_republic_province.txt I need to extract the string between the *last* underscore and the extention. So based on the files above, I want returned: state district province def extract(s): return s[s.rfind('_')+1:s.rfind('.')] George -- http://mail.python.org/mailman/listinfo/python-list
Re: I would like write some data recovery software
In [EMAIL PROTECTED], gel wrote: Dennis Lee Bieber wrote: On 17 Oct 2006 20:18:40 -0700, gel [EMAIL PROTECTED] declaimed the following in comp.lang.python: […] You also need very good documentation of the file system […] Yes, OK I guess NTFS would be of most interest to me. Then you'll have a hard time because NTFS specs are not available for free. Just reverse engineered stuff. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Plotting histograms
[EMAIL PROTECTED] wrote: Thanks Robert, My previous problem is solved(I was using 'from matplotlib.pylab import *') but now I am facing another problem. I want to plot the histogram of eigenvalues calculated and I am using the following code: ___ import numpy from matplotlib import pylab n=100 ra = numpy.random la = numpy.linalg A = ra.standard_normal((n,n)) S = (A + numpy.transpose(A))/(2*n^(1/2)) Note that this line won't do what you think it does. First, one integer divided by another integer returns an integer, so (1/2) == 0. Also, ^ is not exponentiation but bitwise XOR. Use ** for exponentiation. However, in this case, you should use numpy.sqrt(). eig = la.eigvals(S) [N,x]=pylab.hist(eig, 10) # make a histogram - But again it is giving some error, which is given below: File C:\Documents and Settings\amitsoni\Desktop\New Folder\wignerpython, line 15, in module [N,x]=pylab.hist(eig, 10) # make a histogram ValueError: too many values to unpack Can anyone help me out with this?? pylab.hist() does not return two values, it returns three. Sorry I didn't catch that earlier. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
In [EMAIL PROTECTED], Lee Harr wrote: But what if I have a whole bunch of these pwm properties? I made this: class RC(object): def _makeprop(name): prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop) return property(_get, _set) pwm01 = _makeprop('pwm01') pwm02 = _makeprop('pwm02') Not too bad, except for having to repeat the name. I would like to just have a list of pwm names and have them all set up like that. It would be nice if each one was set to a default value of 127 also Any thoughts? Use `__getattr__()` and `__setattr__()` methods and a dictionary of names mapped to values and another that maps the names to default values for the modulo operation. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python wrapper for C++ core
[EMAIL PROTECTED] wrote: Hi All Apologies in advance for the pretty basic question - but I can't seem to find an answer anywhere else. I am developing a fluid sim in C++ and have heard that many people use Python in conjunction with C++ for this sort of thing (especially in games dev). What I can't understand why you would want to do this. Obviously the core would be written in C++ (for my purposes anyway) so what parts would be written in Python? What is the benefit, in this situation, of using Python instead of C++? I 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? Maybe it's a flight sim; I suppose now computers are fast enough to attempt a low-fidelity CFD (computational fluid dynamics) in real time. (Or maybe you mean something different by fluid sim, like a puzzle game involving valves or something.) Anyways, combining Python with C is useful for all kinds of applications, not just games and simulations, because Python has different strengths than C. C is faster and can inteface easily with hardware and the OS; Python is better at pretty much everything else. It takes care of a lot of stuff you'd have to do yourself in C. Speaking as someone who studied a lot of CFD in college, I think Python in particularly is very useful for extreme numerical work. (If that's not what you're talking about, never mind the rest of the post.) The people who do fluid simulations are engineers (classical sense), not programmers. These people do NOT like to program. They like to fiddle with arrays and do arithmetic; stuff like memory management, input/output, and other computer-science-ish tasks are a pain in the neck. Time spent doing that kind of stuff is time not spent doing useful things like hand-optimizing the hell out of the numerical code. Python (even with Numeric) is simply too slow for high-end CFD applications, so the numerical part is almost always written in C or Fortran. But C and Fortran are terrible languages to do things like memory management and I/O in. Python, OTOH, is terrific for these things. It's a great language for people who don't like to program. Comparable languages such as Ruby are also good for I/O and stuff, but I think Python's the best of all for numerical work: 1. Large support community 2. Large standard library and lots of third-party packages out there, addresses all kinds of needs 3. A very spiffy package, pyfort, to interface with Fortran, which can also works for C functions that act like Fortran (which is often the case in a numerical application). Relatively straightforward general interface to C if pyfort won't do. 4. numpy, a very good, well-maintained package which allows Python programs to operate on arrays directly (useful for tasks that don't need to be hyper-optimized). 5. Superficially similar to C and Fortran, which is no small thing for engineers Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Lee Harr wrote: I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm) But what if I have a whole bunch of these pwm properties? I made this: class RC(object): def _makeprop(name): prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop) return property(_get, _set) pwm01 = _makeprop('pwm01') pwm02 = _makeprop('pwm02') Not too bad, except for having to repeat the name. I would like to just have a list of pwm names and have them all set up like that. It would be nice if each one was set to a default value of 127 also Any thoughts? Yes, what about this? import sys def defprop(name, default=127): loc = sys._getframe(1).f_locals prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop, default) loc[name] = property(_get, _set) class RC(object): defprop('pwm01') defprop('pwm02') rc = RC() print rc.pwm01 # 127 print rc.pwm02 # 127 rc.pwm02 = 1312 print rc.pwm02 # 32 This is a bit hackish, but I would prefer this over a metaclass solution. since it does not add any hidden magic to your class. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Flexable Collating (feedback please)
I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. While collating is not a difficult thing to do for experienced programmers, I have seen quite a lot of poorly sorted lists in commercial applications, so it seems it would be good to have an easy to use ready made API for collating. I tried to make this both easy to use and flexible. My first thoughts was to try and target actual uses such as Phone directory sorting, or Library sorting, etc., but it seemed using keywords to alter the behavior is both easier and more flexible. I think the regular expressions I used to parse leading and trailing numerals could be improved. They work, but you will probably get inconsistent results if the strings are not well formed. Any suggestions on this would be appreciated. Should I try to extend it to cover dates and currency sorting? Probably those types should be converted before sorting, but maybe sometimes it's useful not to? Another variation is collating dewy decimal strings. It should be easy to add if someone thinks that might be useful. I haven't tested this in *anything* yet, so don't plug it into production code of any type. I also haven't done any performance testing. See the doc tests below for examples of how it's used. Cheers, Ron Adam Collate.py A general purpose configurable collate module. Collation can be modified with the following keywords: CAPS_FIRST - Aaa, aaa, Bbb, bbb HYPHEN_AS_SPACE - Don't ignore hyphens UNDERSCORE_AS_SPACE - Underscores as white space IGNORE_LEADING_WS - Disregard leading white space NUMERICAL - Digit sequences as numerals COMMA_IN_NUMERALS - Allow commas in numerals * See doctests for examples. Author: Ron Adam, [EMAIL PROTECTED], 10/18/2006 import re import locale locale.setlocale(locale.LC_ALL, '') # use current locale settings # The above line may change the string constants from the string # module. This may have unintended effects if your program # assumes they are always the ascii defaults. CAPS_FIRST = 1 NUMERICAL = 2 HYPHEN_AS_SPACE = 4 UNDERSCORE_AS_SPACE = 8 IGNORE_LEADING_WS = 16 COMMA_IN_NUMERALS = 32 class Collate(object): A general purpose and configurable collator class. def __init__(self, flag): self.flag = flag def transform(self, s): Transform a string for collating. if self.flag CAPS_FIRST: s = s.swapcase() if self.flag HYPHEN_AS_SPACE: s = s.replace('-', ' ') if self.flag UNDERSCORE_AS_SPACE: s = s.replace('_', ' ') if self.flag IGNORE_LEADING_WS: s = s.strip() if self.flag NUMERICAL: if self.flag COMMA_IN_NUMERALS: rex = re.compile('^(\d*\,?\d*\.?\d*)(\D*)(\d*\,?\d*\.?\d*)', re.LOCALE) else: rex = re.compile('^(\d*\.?\d*)(\D*)(\d*\.?\d*)', re.LOCALE) slist = rex.split(s) for i, x in enumerate(slist): if self.flag COMMA_IN_NUMERALS: x = x.replace(',', '') try: slist[i] = float(x) except: slist[i] = locale.strxfrm(x) return slist return locale.strxfrm(s) def __call__(self, a, b): This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) return cmp(self.transform(a), self.transform(b)) def collate(slist, flags=0): Collate list of strings in place. return slist.sort(Collate(flags)) def collated(slist, flags=0): Return a collated list of strings. This is a decorate-undecorate collate. collator = Collate(flags) dd = [(collator.transform(x), x) for x in slist] dd.sort() return list([B for (A, B) in dd]) def _test(): DOC TESTS AND EXAMPLES: Sort (and sorted) normally order all words beginning with caps before all words beginning with lower case. t = ['tuesday', 'Tuesday', 'Monday', 'monday'] sorted(t) # regular sort ['Monday', 'Tuesday', 'monday', 'tuesday'] Locale collation puts words beginning with caps after words beginning with lower case of the same letter. collated(t) ['monday', 'Monday', 'tuesday', 'Tuesday'] The CAPS_FIRST option can be used to put all words beginning with caps after words beginning in lowercase of the same letter. collated(t, CAPS_FIRST) ['Monday', 'monday', 'Tuesday', 'tuesday'] The HYPHEN_AS_SPACE option causes hyphens to be equal to space. t = ['a-b', 'b-a', 'aa-b', 'bb-a'] collated(t)
Re: I would like write some data recovery software
gel a écrit : I would like to write some data recovery software as a learning thing. The sort of thing that you would use to recover data from a currupt HDD or floppy etc. I would like to be pointed in the right direction as far as modules to use and suggested approaches. Once you get a way to access the bytes to recover... the Hachoir library can be interresting as a model to map structures on these data. http://hachoir.org/ A+ Laurent. -- http://mail.python.org/mailman/listinfo/python-list
What happened to RuleDispatch
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 of RuleDispatch I would be very grateful. Cheers, Mich. -- http://mail.python.org/mailman/listinfo/python-list
Re: People's names (was Re: sqlite3 error)
Florian Diesch [EMAIL PROTECTED]wrote: 8-- In Germany von is just a part of the name since 1919 when the nobility was abolished by law. Thanks - was not aware of this - 1919 - just after the Great War, 1914-1918... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
[OT] a little about regex
*** Your mail has been scanned by InterScan MSS. *** Hello, I'm trying to get working an assertion which filter address from some domain but if it's prefixed by '.com'. Even trying to put the result in a negate test I can't get the wanted result. The tought in program term : def filter(adr): ... import re ... allow = re.compile('.*\.my(|$)') ... deny = re.compile('.*\.com\.my(|$)') ... cnt = 0 ... if deny.search(adr): cnt += 1 ... if allow.search(adr): cnt += 1 ... return cnt ... filter('[EMAIL PROTECTED]') 2 filter('[EMAIL PROTECTED]') 1 Seem that I miss some better regex implementation to avoid that both of the filters taking action. I'm thinking of lookbehind (negative or positive) option, but I think I couldn't realize it yet. I think the compilation should either allow have no '.com' before '.my' or deny should have _only_ '.com' before '.my'. Sorry I don't get the correct sintax to do it. Suggestions are welcome. F -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
Fixed... Changed the collate() function to return None the same as sort() since it is an in place collate. A comment in _test() doctests was reversed. CAPS_FIRST option puts words beginning with capitals before, not after, words beginning with lower case of the same letter. It seems I always find a few obvious glitches right after I post something. ;-) Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] a little about regex
Fulvio wrote: ... if deny.search(adr): cnt += 1 ... if allow.search(adr): cnt += 1 hint: under what circumstances are cnt decremented in the above snippet? /F -- http://mail.python.org/mailman/listinfo/python-list
RE: Where to find pydoc?
Hi, Can you be specific on which URLs can I find python-tools. Cause I tried the one under easy_install, I still can't find it. Thanks and hope to hear from you again. -- Edward WIJAYA SINGAPORE From: [EMAIL PROTECTED] on behalf of Fredrik Lundh Sent: Mon 10/16/2006 5:08 PM To: python-list@python.org Subject: Re: Where to find pydoc? look for python-tools or a similar package in your favourite package repository. /F -- http://mail.python.org/mailman/listinfo/python-list Institute For Infocomm Research - Disclaimer - This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
How to convert this list to string?
Hi all I have a list like: list [1, 2, 3] list[1:] [2, 3] I want to get a string 2 3 str(list[1:]) '[2, 3]' How can I do that ? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
On 18 Oct 2006 00:20:50 -0700, Jia Lu [EMAIL PROTECTED] wrote: I want to get a string 2 3 str(list[1:]) '[2, 3]' How can I do that ? ' '.join(str(i) for i in list[1:]) -- Theerasak -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: Hi all I have a list like: list [1, 2, 3] list[1:] [2, 3] I want to get a string 2 3 str(list[1:]) '[2, 3]' How can I do that ? .join(str(x) for x in list) -Travis -- http://mail.python.org/mailman/listinfo/python-list
Re: stdout not flushed before os.execvp()
On Wednesday 18 October 2006 00:25, Fredrik Lundh wrote: |feature. the exec system call operates on a lower level than the |stdio buffering system. I did in this manner: for exe in ('imap4', 'pop3'): if exe in cfgfil[optsrv + '.protocol']: exe = exe[:4]; exe = 'call_func = _call_' + exe.upper() \ + '(setting)' try: exec exe except ProtocolError: call_func = '#ERROR 02 = Protocol failed with %s' %optsrv break exists it a different way to do it? F -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Lee Harr wrote: I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm) But what if I have a whole bunch of these pwm properties? I made this: class RC(object): def _makeprop(name): prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop) return property(_get, _set) pwm01 = _makeprop('pwm01') pwm02 = _makeprop('pwm02') Not too bad, except for having to repeat the name. I would like to just have a list of pwm names and have them all set up like that. It would be nice if each one was set to a default value of 127 also Any thoughts? The metaclass solution. I use this idiom occasionally, whenever I want to fiddle with the class dict before letting the type constructor at it. class mod256metatype(type): def __new__(metatype,name,bases,clsdict): for sym in clsdict.get('__mod256__',()): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) clsdict[sym] = property(_get,_set) return type.__new__(metatype,name,bases,clsdict) class RC(object): __metaclass__ = mod256metatype __mod256__ = [pwm01,pwm02] Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to find pydoc?
Wijaya Edward wrote: Can you be specific on which URLs can I find python-tools. Cause I tried the one under easy_install, I still can't find it. it's an RPM. you should be able to get it from where you get other RedHat packages. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] a little about regex
Fulvio wrote: *** Your mail has been scanned by InterScan MSS. *** Hello, I'm trying to get working an assertion which filter address from some domain but if it's prefixed by '.com'. Even trying to put the result in a negate test I can't get the wanted result. The tought in program term : def filter(adr): ... import re ... allow = re.compile('.*\.my(|$)') ... deny = re.compile('.*\.com\.my(|$)') ... cnt = 0 ... if deny.search(adr): cnt += 1 ... if allow.search(adr): cnt += 1 ... return cnt ... filter('[EMAIL PROTECTED]') 2 filter('[EMAIL PROTECTED]') 1 Seem that I miss some better regex implementation to avoid that both of the filters taking action. I'm thinking of lookbehind (negative or positive) option, but I think I couldn't realize it yet. I think the compilation should either allow have no '.com' before '.my' or deny should have _only_ '.com' before '.my'. Sorry I don't get the correct sintax to do it. Suggestions are welcome. F Instead of using two separate if's, Use an if - elif and be sure to test the narrower filter first. (You have them in the correct order) That way it will skip the more general filter and not increment cnt twice. 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. Or are you writing a test at the moment, a 1 means it only passed one filter so you know your filters are working as designed? Another approach would be to assign values for filtered, accepted, and undefined and set those accordingly instead of incrementing and decrementing a counter. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: Hi all I have a list like: list [1, 2, 3] list[1:] [2, 3] I want to get a string 2 3 str(list[1:]) '[2, 3]' How can I do that ? http://effbot.org/zone/python-list.htm#printing /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Could the traits package be of help? http://code.enthought.com/traits/ Alexander Eisenhuth wrote: Hello, is there a assignement operator, that i can overwrite? class MyInt: def __init__(self, val): assert(isinstance(val, int)) self._val = val a = MyInt(10) # Here i need to overwrite the assignement operator a = 12 Thanks Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Michele Simionato wrote: Lee Harr wrote: I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm) But what if I have a whole bunch of these pwm properties? I made this: class RC(object): def _makeprop(name): prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop) return property(_get, _set) pwm01 = _makeprop('pwm01') pwm02 = _makeprop('pwm02') Not too bad, except for having to repeat the name. I would like to just have a list of pwm names and have them all set up like that. It would be nice if each one was set to a default value of 127 also Any thoughts? Yes, what about this? import sys def defprop(name, default=127): loc = sys._getframe(1).f_locals prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop, default) loc[name] = property(_get, _set) class RC(object): defprop('pwm01') defprop('pwm02') rc = RC() print rc.pwm01 # 127 print rc.pwm02 # 127 rc.pwm02 = 1312 print rc.pwm02 # 32 This is a bit hackish, but I would prefer this over a metaclass solution. since it does not add any hidden magic to your class. Why is this less hidden or magical than a metaclass ? I'd prefer the following instead: from itertools import chain, izip, repeat def ByteProperties(*names, **defaulted_names): def byte_property(name, default): return property(lambda self: getattr(self, name, default), lambda self,v: setattr(self, name, v%256)) def make_class(clsname, bases, dict): for name,default in chain(izip(names, repeat(127)), defaulted_names.iteritems()): assert name not in dict # sanity check dict[name] = byte_property('_'+name, default) return type(clsname,bases,dict) return make_class class RC(object): __metaclass__ = ByteProperties('pwm01', pwm02=64) rc = RC() print rc.pwm01, rc.pwm02 # 127 64 rc.pwm01 = 1312 print rc.pwm01, rc.pwm02 # 32 64 George -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: Lee Harr wrote: I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm) But what if I have a whole bunch of these pwm properties? I made this: class RC(object): def _makeprop(name): prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop) return property(_get, _set) pwm01 = _makeprop('pwm01') pwm02 = _makeprop('pwm02') Not too bad, except for having to repeat the name. I would like to just have a list of pwm names and have them all set up like that. It would be nice if each one was set to a default value of 127 also Any thoughts? The metaclass solution. I use this idiom occasionally, whenever I want to fiddle with the class dict before letting the type constructor at it. class mod256metatype(type): def __new__(metatype,name,bases,clsdict): for sym in clsdict.get('__mod256__',()): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) clsdict[sym] = property(_get,_set) return type.__new__(metatype,name,bases,clsdict) class RC(object): __metaclass__ = mod256metatype __mod256__ = [pwm01,pwm02] There's a subtle common bug here: all _get and _set closures will refer to the last property only. You have to remember to write def _set(self,v,prop=prop) and similarly for _get to do the right thing. By the way, I can't think of a case where the current behavior (i.e. binding the last value only) is the desired one. Is this just an implementation wart or am I missing something ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: Hi all I have a list like: list [1, 2, 3] list[1:] [2, 3] I want to get a string 2 3 str(list[1:]) '[2, 3]' How can I do that ? thanks Just to be different from the other suggestions... a = [1, 2, 3] str(a[1:]).strip('[]').replace(',', '') '2 3' By the way. It's a good idea to try not to use 'list' or other built-in names for your own objects. Best to start with good habits so that you avoid odd hard to find bugs later. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Bruno Desthuilliers wrote: neoedmund wrote: (snip) So I can reuse a method freely only if it's worth reusing. For the word inheritance, in some aspect, meanings reuse the super class, with the condition: must reuse everything from super class. Not really. In fact, inheritance *is* a special case of composition/delegation. A 'child' class is a class that has references to other classes - it's 'parents' -, and then attributes that are not found in the instance or child class are looked up in the parents (according to mro rules in case of multiple inheritance). And that's all there is. It's lack of a option to select which methods are to be reused. Methods not redefined in the 'child' class or it's instance are 'reusable'. Now they are only effectively 'reused' if and when called by client code. So the 'option to select which methods are to be reused' is mostly up to both the 'child' class and code using it. this is something should be improved for general OOP i think. So to answer What is your problem with having the other extra methods too ?, in real life, a class is not defined so well that any method is needed by sub-class. Then perhaps is it time to refactor. A class should be a highly cohesive unit. If you find yourself needing only a specific subset of a class, it may be time to extract this subset in it's own class. Given Python's support for both multiple inheritance and composition/delegation, it's usually a trivial task (unless you already mixed up too many orthogonal concerns in your base class...). -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) ivestgating the web, i found something similiar with my approch: http://en.wikipedia.org/wiki/Duck_typing Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: Why is this less hidden or magical than a metaclass ? Because it does not use inheritance. It is not going to create properties on subclasses without you noticing it. Also, metaclasses are brittle: try to use them with __slots__, or with non-standard classes (i.e. extensions classes), or try to use multiple metaclasses. I wrote a paper about metaclasses abuses which should be published soon or later; you can see the draft here: http://www.phyast.pitt.edu/~micheles/python/classinitializer.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
neoedmund wrote: ivestgating the web, i found something similiar with my approch: http://en.wikipedia.org/wiki/Duck_typing Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests that's not entirely correct, though: in Python, duck-typing typically uses Easier to Ask Forgiveness than Permission (EAFP), aka Just Do It, rather than Look Before You Leap (LBYL). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Bruno Desthuilliers wrote: neoedmund wrote: (snip) So I can reuse a method freely only if it's worth reusing. For the word inheritance, in some aspect, meanings reuse the super class, with the condition: must reuse everything from super class. Not really. In fact, inheritance *is* a special case of composition/delegation. A 'child' class is a class that has references to other classes - it's 'parents' -, and then attributes that are not found in the instance or child class are looked up in the parents (according to mro rules in case of multiple inheritance). And that's all there is. It's lack of a option to select which methods are to be reused. Methods not redefined in the 'child' class or it's instance are 'reusable'. Now they are only effectively 'reused' if and when called by client code. So the 'option to select which methods are to be reused' is mostly up to both the 'child' class and code using it. this is something should be improved for general OOP i think. So to answer What is your problem with having the other extra methods too ?, in real life, a class is not defined so well that any method is needed by sub-class. Then perhaps is it time to refactor. A class should be a highly cohesive unit. If you find yourself needing only a specific subset of a class, it may be time to extract this subset in it's own class. Given Python's support for both multiple inheritance and composition/delegation, it's usually a trivial task (unless you already mixed up too many orthogonal concerns in your base class...). -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) I donnot agree with your it's time to refactory very much, man has probly never has time to do such things. suppose a system is working soundly, you maybe has no time or motivation to do refactory instead of having a vocation to a island. it's easy to say, at lease myself has not the experience to do such things, :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: from itertools import chain, izip, repeat def ByteProperties(*names, **defaulted_names): def byte_property(name, default): return property(lambda self: getattr(self, name, default), lambda self,v: setattr(self, name, v%256)) def make_class(clsname, bases, dict): for name,default in chain(izip(names, repeat(127)), defaulted_names.iteritems()): assert name not in dict # sanity check dict[name] = byte_property('_'+name, default) return type(clsname,bases,dict) return make_class class RC(object): __metaclass__ = ByteProperties('pwm01', pwm02=64) Notice that you are NOT using a custom metaclass here, you are just using the metaclass hook and you will avoid all issues of custom metaclasses. This is exactly the approach I advocate in the paper I referred before, so I think your solution is pretty safe in that respect. Still I think in this particular problem avoiding the __metaclass__ at all is possible and it should be preferred, just for sake of simplicity, not of safety). Michele Simionato M -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: Michele Simionato wrote: import sys def defprop(name, default=127): loc = sys._getframe(1).f_locals prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop, default) loc[name] = property(_get, _set) class RC(object): defprop('pwm01') defprop('pwm02') rc = RC() print rc.pwm01 # 127 print rc.pwm02 # 127 rc.pwm02 = 1312 print rc.pwm02 # 32 This is a bit hackish, but I would prefer this over a metaclass solution. since it does not add any hidden magic to your class. Why is this less hidden or magical than a metaclass ? Devil's Advocate: he did say hidden magic TO YOUR CLASS. If you use a (real) metaclass, then you have the icky feeling of a class permanently tainted by the unclean metaclass (even though the metaclass does nothing other than touch the class dict upon creation); whereas if you use Michele Simionato's hack, the icky feeling of using a stack frame object goes away after the property is created: you are left with a clean untainted class. Personally, the former doesn't make me feel icky at all. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: Devil's Advocate: he did say hidden magic TO YOUR CLASS. If you use a (real) metaclass, then you have the icky feeling of a class permanently tainted by the unclean metaclass (even though the metaclass does nothing other than touch the class dict upon creation); whereas if you use Michele Simionato's hack, the icky feeling of using a stack frame object goes away after the property is created: you are left with a clean untainted class. Yep, exactly. Personally, the former doesn't make me feel icky at all. Please, do this experiment: take all classes defined in the Python standard library and add to them a custom do-nothing metaclass. See what happens. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: There's a subtle common bug here: all _get and _set closures will refer to the last property only. You have to remember to write def _set(self,v,prop=prop) and similarly for _get to do the right thing. Sorry. My mistake. By the way, I can't think of a case where the current behavior (i.e. binding the last value only) is the desired one. Is this just an implementation wart or am I missing something ? def some_function(a): def printvars(): print DEBUG: %r,%r,%r % (a,b,i) for i in some_range(): b = something(i) printvars() If you fix the value of the closure at function definition time, printvars() above doesn't work. One way or another, someone's going to get surprised. Better to let it be the experts. Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Tommi wrote: (please don't top-post - corrected) Alexander Eisenhuth wrote: Hello, is there a assignement operator, that i can overwrite? class MyInt: def __init__(self, val): assert(isinstance(val, int)) self._val = val a = MyInt(10) # Here i need to overwrite the assignement operator a = 12 Could the traits package be of help? http://code.enthought.com/traits/ How could it help ? -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic module loading via __import__, nonetype?
Gabriel Genellina wrote: At Monday 16/10/2006 13:33, John Allman wrote: If i manually import a module, this method works a treat, however if i attempt to dynamically load a module at runtime the create method fails with the following error: TypeError: 'NoneType' object is not callable Can you cut down a reproducible test case, with *only* this behavior and nothing more? Hi Gabriel Thanks for the reply. I actually spotted my error (simple, stupid that i hadn't noticed). I had the create method creating an object if it could find a suitable class and importing a suitable class if it couldn't find one. I rather stupidly forgot to actually create an object after importing the class! I was completely stuck - it's amazing what a night's sleep will do for you! Thanks, John -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Fulvio wrote: I'm trying to get working an assertion which filter address from some domain but if it's prefixed by '.com'. Even trying to put the result in a negate test I can't get the wanted result. [...] Seem that I miss some better regex implementation to avoid that both of the filters taking action. I'm thinking of lookbehind (negative or positive) option, but I think I couldn't realize it yet. I think the compilation should either allow have no '.com' before '.my' or deny should have _only_ '.com' before '.my'. Sorry I don't get the correct sintax to do it. Suggestions are welcome. Try this: def filter(adr):# note that filter is a builtin function also import re allow = re.compile(r'.*(?!\.com)\.my(|$)') # negative lookbehind deny = re.compile(r'.*\.com\.my(|$)') cnt = 0 if deny.search(adr): cnt += 1 if allow.search(adr): cnt += 1 return cnt HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Michele Simionato wrote: Carl Banks wrote: Devil's Advocate: he did say hidden magic TO YOUR CLASS. If you use a (real) metaclass, then you have the icky feeling of a class permanently tainted by the unclean metaclass (even though the metaclass does nothing other than touch the class dict upon creation); whereas if you use Michele Simionato's hack, the icky feeling of using a stack frame object goes away after the property is created: you are left with a clean untainted class. Yep, exactly. Personally, the former doesn't make me feel icky at all. Please, do this experiment: take all classes defined in the Python standard library and add to them a custom do-nothing metaclass. See what happens. Do you expect the result to be better or worse than if you applied stack frame hacks to the whole library? Come on, I don't think anyone's under the impression we're being indiscriminate here. Carl Banks (BTW, most of the standard library still uses old-style classes.) -- http://mail.python.org/mailman/listinfo/python-list
Wax: problem subclassing TextBox
Hey everyone, I've just started looking at Wax and have hit a problem I can't explain. I want an app to respond to every character input into a TextBox. Here's a simple, working example: +++ from wax import * class MainFrame(VerticalFrame): def Body(self): self.search = TextBox(self) self.search.OnChar = self.OnChar self.AddComponent(self.search, expand='h', border=5) def OnChar(self, event): print 'OnChar:', event.GetKeyCode() event.Skip() app = Application(MainFrame) app.Run() +++ This displays a TextBox and entering abcd results in: OnChar: 97 OnChar: 98 OnChar: 99 OnChar: 100 Rather than defining the OnChar hook on the main frame, though, it makes more sense (to me) to be defined on the TextBox itself, so I tried subclassing it as follows: +++ class NewTextBox(TextBox): def OnChar(self, event): print 'on char', event.GetKeyCode() event.Skip() class MainFrame(VerticalFrame): def Body(self): self.search = NewTextBox(self) self.AddComponent(self.search, expand='h', border=5) +++ With the same input of 'abcd', I get the following: on char 97 on char 97 on char 98 on char 98 on char 99 on char 99 on char 100 on char 100 As I understand it, event.Skip() should propagate the event up the inheritance chain, but I don't see how that would result in NewTextBox.OnChar being called _twice_ for each input. Stopping the event there by removing the event.Skip() does result in only one 'on char XX' line for each character, but also stops _all_ OnChar actions for the TextBox - such as updating the value and displaying it - and I really don't want to have to reimplement the full functionality just to prevent this. Is there something glaringly obvious that I'm doing wrong in the above code? Thanks for any help... - alex23 -- http://mail.python.org/mailman/listinfo/python-list
RE: making a valid file name...
Hi I'm writing a python script that creates directories from user input. Sometimes the user inputs characters that aren't valid characters for a file or directory name. Here are the characters that I consider to be valid characters... valid = ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' if I have a string called fname I want to go through each character in the filename and if it is not a valid character, then I want to replace it with a space. This is what I have: def fixfilename(fname): valid = ':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' for i in range(len(fname)): if valid.find(fname[i]) 0: fname[i] = ' ' return fname Anyone think of a simpler solution? I got; import re badfilename='£%^£^£$^ihgeroighroeig3645^£$^knovin98u4#346#1461461' valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' goodfilename=re.sub('[^'+valid+']',' ',badfilename) goodfilename ' ^ ^ ^ihgeroighroeig3645^ ^ knovin98u4 346 1461461' This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: Come on, I don't think anyone's under the impression we're being indiscriminate here. Ok, but I don't think that in the case at hand we should recommend a metaclass solution. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
Dennis Lee Bieber wrote: Python has a half dozen GUI toolkits, and multiple adapters for databases (some don't even follow DB-API2 specs). All independently written. So no, you are not going to find, say, a grid widget that automatically links to a database table/view/cursor, with bi-directional updates. Aren't we going round in circles here? There presumably are grid 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. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Web Site?
*% a écrit : Is there a problem with the Python and wxPython web sites? I cannot seem to get them up, and I am trying to find some documentation... Thanks, Mike All the sites hosted on sourceforge that rely on their vhost computer ( ie, site hosted on sourceforge that do not display the sourceforge.net address ) are broken. You get a blank page instead. http://wxpython.sourceforge.net/ works http://wxpython.org/ doesn't work It has been like that for a few hours already. -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
neoedmund [EMAIL PROTECTED] writes: Bruno Desthuilliers wrote: neoedmund wrote: in real life, a class is not defined so well that any method is needed by sub-class. Then perhaps is it time to refactor. A class should be a highly cohesive unit. If you find yourself needing only a specific subset of a class, it may be time to extract this subset in it's own class. I donnot agree with your it's time to refactory very much, man has probly never has time to do such things. I respectfully suggest that the *reason* you find yourself with little time to refactor is probably related to the fact that you *need* to refactor. If your code is crufty and poorly-designed, it is costing you every time you need to maintain it. Would it help if we called it preventative maintenance? -- \I bought a dog the other day. I named him Stay. It's fun to | `\ call him. 'Come here, Stay! Come here, Stay!' He went insane. | _o__) Now he just ignores me and keeps typing. -- Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
On 2006-10-18, neoedmund [EMAIL PROTECTED] wrote: ivestgating the web, i found something similiar with my approch: http://en.wikipedia.org/wiki/Duck_typing Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests It's pity it didn't get called quack typing. One ckecks if some unknown noun can quack, not if a duck can do something unknown. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
portable extensions options for external libraries
Hi. I want to create a portable setup.py file for windows / linux for an extension package that i need to link with external libraries (gsl and boost). on windows i do something like this: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/', 'C:/Program Files/boost/include/boost-1_35', 'C:/Program Files/GnuWin32/include'] ), library_dirs = [ 'C:/Program Files/GnuWin32/lib' ], libraries = [ 'libgsl', 'libgslcblas' ] ) obviously, the paths could vary. on unix, i need something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] ) ) so my question is: what is the right way of specifying extensions options (include_dirs, libraries, library_dirs) so that they are portable between windows and linux? i'm thinking environment variables. Though fairly easy to do, i was wondering if python/distutils provided something more convenient, like searching through common directories, though those aren't very standard on windows? Optimally, i would like to have something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] + boost_include_dirs + gsl_include_dirs ), library_dirs = boost_library_dirs + gsl_library_dirs, libraries = boost_libraries + gsl_libraries ) thx for any help. alex. -- http://mail.python.org/mailman/listinfo/python-list
matrix Multiplication
hi evrybody! I wan't to multiply two square matrixes, and i don't understand why it doesn't work. Could you explain me? def multmat(A,B): A*B if len(A)!=len(B): return error D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) for i in range(len(A)): for j in range(len(A)): for k in range(len(A)): C[i][j]+=A[i][k]*B[k][j] print C[i][j] print C[i] return C when i use it on : A=[[2,3,4],[5,8,6],[4,5,7]] B=[[1,0,0],[0,1,0],[0,0,1]] I get : 2 2 2 0 3 3 0 0 4 [2, 3, 4] 7 7 7 3 11 11 4 4 10 [7, 11, 10] 11 11 11 11 16 16 10 10 17 [11, 16, 17] [[11, 16, 17], [11, 16, 17], [11, 16, 17]] thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: making a valid file name...
Matthew Warren wrote: import re badfilename='£%^£^£$^ihgeroighroeig3645^£$^knovin98u4#346#1461461' valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' goodfilename=re.sub('[^'+valid+']',' ',badfilename) to create arbitrary character sets, it's usually best to run the character string through re.escape() before passing it to the RE engine. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Sssasss wrote: I wan't to multiply two square matrixes, and i don't understand why it doesn't work. def multmat(A,B): A*B if len(A)!=len(B): return error D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) append doesn't copy data, so you're basically adding len(A) references to the same D list to C. for more on this, see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Plotting histograms
[EMAIL PROTECTED] wrote: hi, I have some values(say from -a to a) stored in a vector and I want to plot a histogram for those values. How can I get it done in python. I have installed and imported the Matplotlib package but on executing the code [N,x]=hist(eig, 10) # make a histogram I am getting an error saying NameError: name 'hist' is not defined. Is there any other way to plot histograms over a given range? # create random vector ... from random import randrange a = 5 v = [randrange(-a, a+1) for i in xrange(100)] # print histogram ... for i in range(-a, a+1): ... print %+d %s % (i, '*' * v.count(i)) ... -5 * -4 * -3 * -2 ** -1 ** +0 * +1 +2 *** +3 * +4 +5 :) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
On Oct 18, 2:42 am, Ron Adam [EMAIL PROTECTED] wrote: I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. ,,, def __call__(self, a, b): This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) return cmp(self.transform(a), self.transform(b)) You document _call__ as useful for the key keyword to sort, but you implement it for the cmp keyword. The key allows much better performance, since it's called only once per value. Maybe just : return self.transform(a) -- George -- http://mail.python.org/mailman/listinfo/python-list
Re: making a valid file name...
You should use the s.translate() It's 100x faster: #Creates the translation table ValidChars = :./,^0123456789abcdefghijklmnopqrstuvwxyz InvalidChars = .join([chr(i) for i in range(256) if not chr(i).lower() in ValidChars]) TranslationTable = .join([chr(i) for i in range(256)]) def valid_filename(fname): return fname.translate(TranslationTable, InvalidChars) valid = ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' if I have a string called fname I want to go through each character in the filename and if it is not a valid character, then I want to replace it with a space. -- Ceci est une signature automatique de MesNews. Site : http://www.mesnews.net -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Fredrik Lundh wrote: Sssasss wrote: I wan't to multiply two square matrixes, and i don't understand why it doesn't work. def multmat(A,B): A*B if len(A)!=len(B): return error D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) append doesn't copy data, so you're basically adding len(A) references to the same D list to C. for more on this, see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list /F Ok!! Tank you very much, i understand now. ciao -- http://mail.python.org/mailman/listinfo/python-list
codecs.EncodedFile
Perhaps I'm just bad at searching for bugs, but anyhow, I wanted to know what you all thought about the following behavior. A quick search of pydev archives yielded a nice wrapper to apply to streams to perform decoding and encoding behind the scenes. Assuming I get the correct encodings from somewhere (that's a whole 'nother thread): Here's the docs: EncodedFile( file, input[, output[, errors]]) Return a wrapped version of file which provides transparent encoding translation. Strings written to the wrapped file are interpreted according to the given input encoding and then written to the original file as strings using the output encoding. The intermediate encoding will usually be Unicode but depends on the specified codecs. If output is not given, it defaults to input. errors may be given to define the error handling. It defaults to 'strict', which causes ValueError to be raised in case an encoding error occurs. Base on that, I wrote the following code at startup: sys.stdout = codecs.EncodedFile(sys.stdout, 'latin-1', 'cp437') sys.stdin = codecs.EncodedFile(sys.stdin, 'cp437', 'latin-1') Now my application never returns from its first call to sys.stdin.readline. It turns out to be troublesome for my case because the EncodedFile object translates calls to readline into calls to read. I believe it ought to raise a NotImplemented exception when readline is called. As it is it silently causes interactive applications to apparently hang forever, and breaks the line-buffering expectation of non-interactive applications. If raising the exception is too much to ask, then at least it should be documented better. -- Neil Cerutti The choir invites any member of the congregation who enjoys sinning to join the choir. --Church Bulletin Blooper -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Neil Cerutti wrote: On 2006-10-18, neoedmund [EMAIL PROTECTED] wrote: ivestgating the web, i found something similiar with my approch: http://en.wikipedia.org/wiki/Duck_typing Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests It's pity it didn't get called quack typing. That's because the quacks prescribe static typing. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
On 2006-10-18 14:15:17 +0200, Sssasss wrote: Fredrik Lundh wrote: Sssasss wrote: I wan't to multiply two square matrixes, and i don't understand why it doesn't work. def multmat(A,B): A*B if len(A)!=len(B): return error D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) append doesn't copy data, so you're basically adding len(A) references to the same D list to C. for more on this, see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list /F Ok!! Tank you very much, i understand now. You might also want to look at numpy/numarray. Gerrit. -- http://mail.python.org/mailman/listinfo/python-list
MemoryError - IMAP retrieve self._sock.recv(recv_size)
Hi there. I have been receiving MemoryErrors using the Windows version of Python 2.5. The script I have written times the sending and the reception of emails with various attachments. I get many exceptions when using the IMAP downloads. This happens randomly; sometimes the file downloads OK, and other times no. Using an exception and traceback function, I can see the following... MemoryError no args File C:\Documents and Settings\root\Desktop\TMO\Python scripts\imap-v2.3a.py, line 263, in main typ, data = M.fetch(num, '(RFC822)') File C:\Python25\lib\imaplib.py, line 437, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File C:\Python25\lib\imaplib.py, line 1055, in _simple_command return self._command_complete(name, self._command(name, *args)) File C:\Python25\lib\imaplib.py, line 885, in _command_complete typ, data = self._get_tagged_response(tag) File C:\Python25\lib\imaplib.py, line 986, in _get_tagged_response self._get_response() File C:\Python25\lib\imaplib.py, line 948, in _get_response data = self.read(size) File C:\Python25\lib\imaplib.py, line 236, in read return self.file.read(size) File C:\Python25\lib\socket.py, line 308, in read data = self._sock.recv(recv_size) Is this a know bug or is there something I can do to work around this? Thanks, Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
Stephen G [EMAIL PROTECTED] wrote: I get many exceptions when using the IMAP downloads. This happens randomly; sometimes the file downloads OK, and other times no. File C:\Python25\lib\socket.py, line 308, in read data = self._sock.recv(recv_size) Is this a know bug or is there something I can do to work around this? looks like this http://mail.python.org/pipermail/python-list/2005-December/317239.html or some variation thereof. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy-f2py troubles
Hi Andrea, you should post this to the numpy list: numpy-discussion@lists.sourceforge.net Cheers! Bernhard Andrea Gavana schrieb: Hello NG, I am using the latest Numpy release 1.0rc2 which includes F2PY. I have switched to Python 2.5 so this is the only alternative I have (IIUC). With Python 2.4, I was able to build a very simple fortran extension without problems. My extension contains 4 subroutines that scan a file and do simple operations. Now, attempting to run the second subroutine as: dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) Prompt a ValueError from Python: File D:\MyProjects\Carolina\MainPanel.py, line 894, in ReadSMSPECFile dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) ValueError: data type must provide an itemsize ?!? I have never seen anything like that and googling around didn't give me any answer. The function accepts two inputs: - smspec: a filename, maximum 1000 characters long - dimens: an integer and returns 3 array of chars, each of them with size (8, dimens). Does anyone know what I may be doing wrong? Thank you very much for every pointer. -- Andrea. Imagination Is The Only Weapon In The War Against Reality. http://xoomer.virgilio.it/infinity77/ -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Il 18 Oct 2006 04:17:29 -0700, Sssasss ha scritto: hi evrybody! I wan't to multiply two square matrixes, and i don't understand why it doesn't work. Can I suggest a little bit less cumbersome algorithm? def multmat2(A,B): A*B if len(A)!=len(B): return error # this check is not enough! n = range(len(A)) C = [] for i in n: C.append([0]*len(A)) # add a row to C for j in n: a = A[i]# get row i from A b = [row[j] for row in B] # get col j from B C[i][j] = sum([x*y for x,y in zip(a,b)]) return C regards D. -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Sssasss wrote: hi evrybody! I wan't to multiply two square matrixes, and i don't understand why it doesn't work. Could you explain me? def multmat(A,B): A*B if len(A)!=len(B): return error Wrong validation here: you _can_ multiply two matrices with a different number of rows! And instead of returning error you should raise an exception. [...] I suggest using a linear algebra package, but if you insist in using lists of lists: b = [[1, 2, 3, 4], ... [4, 5, 6, 7], ... [7, 8, 9, 10]] a = [[1, 2, 3], ... [4, 5, 6]] ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a] ab [[30, 36, 42, 48], [66, 81, 96, 111]] Straightforward from the definition of matrix multiplication. -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Thank you very much. I memoed all you views. :) -- http://mail.python.org/mailman/listinfo/python-list
PIL: Image.draft -- what are the modes that I can use?
I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller (file size) of an image. for example: im = ImageGrab.grab() im.save(tmp.gif) about 1.7mb im.save(tmp.jpeg) about 290kb anyways I want to save the image as a GIF, but not have it be so largeso I thought that the Image.draft method would be what I wanted im.draft(mode, size) Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a colour JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file. .what 'modes' can I use? or is there another way to shrink the size of the image (other than resizing it)? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
abcd wrote: I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller (file size) of an image. for example: im = ImageGrab.grab() im.save(tmp.gif) about 1.7mb im.save(tmp.jpeg) about 290kb anyways I want to save the image as a GIF, but not have it be so largeso I thought that the Image.draft method would be what I wanted GIF is horribly unsuitable for screenshots on modern machines. have you considered using PNG ? or even better, Flash? here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ im.draft(mode, size) Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a colour JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file. note the use of the words loader and loading. draft is used to speed things up when loading images, not compress things when storing them. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Fredrik Lundh wrote: GIF is horribly unsuitable for screenshots on modern machines. have you considered using PNG ? or even better, Flash? well I am trying to take screenshots and make them into an animated GIF, however, putting them into a Flash movie would be coolany idea how to go about doing either with python? (windows, possibly linux later) -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
abcd wrote: or even better, Flash? well I am trying to take screenshots and make them into an animated GIF, however, putting them into a Flash movie would be coolany idea how to go about doing either with python? (windows, possibly linux later) to repeat myself: here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
oh and vnc2swf would not be an option, i cant be setting up a vnc server, etc. just need to use python (and necessary packages). animated gif would probably be best i am assuming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Restart a Python COM Server
OK, well thank you for your help (merci pour ton aide!) M.E. MC wrote: Hi! It is the normal behavior of COM. Note that, Python being dynamic, you can modify Python script, OF THE INTERIOR, during execution. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Win32 python and excel macros
Hi Experts, Looking for a very quick bit on of advice on how to make some python code run. I'm a newbie to both VBA and Python, so i apologise if this is very easy but i'm about to tear my hair out after googling for the last 3 days. I have written a large python script which inside of it creates an Excel table, the name of this file and how many objects can change for each project i run. I have then written a VBA script which takes the info from Excel and drops it into a PowerPoint Pres. Both of these procedures work fine, but i am coming unstuck when i try to apply the macro, (or .xla) file to the new tables autmatically. Can anyone give me any guidance on this? The macro is called sub is CTP and the add-in file is CTP.XLA Below is the code i've managed to 'Stick' together Mike import win32com.client xl = win32com.client.Dispatch(Excel.Application) ppt = win32com.client.Dispatch(PowerPoint.Application) xl.Visible = 1 #open MS Excel ppt.Visible = 1 #open MS Powerpoint xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big output.xls') #A table for a project xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\CTP.xla') # Stored macro add-in ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic files\\Basic Template.ppt') xl.Application.ExecuteExcel4macro('CTP!CTP.xla()[big output.XLS]') -- http://mail.python.org/mailman/listinfo/python-list
Python RPM package arch compatability
Hello all, A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm curious if any of the packages at http://www.python.org/download/releases/2.4/rpms/ would suite my setup. If they don't can I simply build from source and not overwrite /usr/bin/Python (for the same reasons as listed at the above mentioned webpage)? Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Fredrik Lundh wrote: to repeat myself: here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ /F is there a way to make animated GIFs with python? vnc2swf is to much for what i was hoping. i have no problem with installing python packages, but having to use VNC is a bit much. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
Hi, thanks for the reply,but unfortunately this does not work with the type of classes I am dealing with. When trying to pickle the class I get the following error: File /usr/lib/python2.4/copy_reg.py, line 76, in _reduce_ex raise TypeError(a class that defines __slots__ without TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled So there is something missing in this class? Or any other idea how to do this? Alex Sybren Stuvel wrote: [EMAIL PROTECTED] enlightened us with: is it possible in python (with/without matplotlib, numpy etc) to store a whole class with its data into a file Check out the pickle module. Sybren -- Sybren Stüvel Stüvel IT - http://www.stuvel.eu/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python RPM package arch compatability
Christopher Taylor wrote: A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm curious if any of the packages at http://www.python.org/download/releases/2.4/rpms/ would suite my setup. If they don't can I simply build from source and not overwrite /usr/bin/Python (for the same reasons as listed at the above mentioned webpage)? if you use make altinstall instead of make install, the installation process will only install a pythonX.Y binary (e.g. python2.5). /F -- http://mail.python.org/mailman/listinfo/python-list
How to execute a linux command by python?
How to execute a linux command by python? for example: execute ls or useradd oracle Who can help me? thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
[EMAIL PROTECTED] wrote: On Oct 18, 2:42 am, Ron Adam [EMAIL PROTECTED] wrote: I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. ,,, def __call__(self, a, b): This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) return cmp(self.transform(a), self.transform(b)) You document _call__ as useful for the key keyword to sort, but you implement it for the cmp keyword. The key allows much better performance, since it's called only once per value. Maybe just : return self.transform(a) -- George Thanks, I changed it to the following... def __call__(self, a): This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) return self.transform(a) And also changed the sort call here ... def collate(slist, flags=0): Collate list of strings in place. slist.sort(key=Collate(flags)) Today I'll do some performance tests to see how much faster it is for moderate sized lists. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Python RPM package arch compatability
So just build it from source and use make altinstall instead? That simple huh? Will I need to do anything else to make sure things are put in their correct place? Respectfully, Christopher Taylor On 10/18/06, Fredrik Lundh [EMAIL PROTECTED] wrote: Christopher Taylor wrote: A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm curious if any of the packages at http://www.python.org/download/releases/2.4/rpms/ would suite my setup. If they don't can I simply build from source and not overwrite /usr/bin/Python (for the same reasons as listed at the above mentioned webpage)? if you use make altinstall instead of make install, the installation process will only install a pythonX.Y binary (e.g. python2.5). /F -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
fredrik, in other posts you have mentioned the use of gifmaker. i have tried that with the following: I am using gifmaker.py from PIL v1.1.5 on python 2.4.1. CODE import ImageGrab, gifmaker seq = [] while keepOnGoing: im = ImageGrab.grab() seq.append(im) fp = open(out.gif, wb) gifmaker.makedelta(fp, seq) fp.close() --- however I am getting this error: Exception in thread Thread-3: Traceback (most recent call last): File c:\Python24\lib\threading.py, line 442, in __bootstrap self.run() File c:\foo.py, line 10, in run gifmaker.makedelta(fp, seq) File c:\gifmaker.py, line 79, in makedelta for s in getheader(im) + getdata(im): File c:\Python24\Lib\site-packages\PIL\GifImagePlugin.py, line 383, in getdata ImageFile._save(im, fp, [(gif, (0,0)+im.size, 0, RAWMODE[im.mode])]) KeyError: 'RGB' Any ideas? Basically I want to make an animated GIF out of a bunch of images taken using the ImageGrab module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
[EMAIL PROTECTED] wrote: thanks for the reply,but unfortunately this does not work with the type of classes I am dealing with. When trying to pickle the class I get the following error: File /usr/lib/python2.4/copy_reg.py, line 76, in _reduce_ex raise TypeError(a class that defines __slots__ without TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled So there is something missing in this class? did you remember to read the error message before posting ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
Fredrik, Thanks for the response. I did see that, but having been dated 2005 I thought that it might have been patched. I am also sometimes getting the same problem with the urllib.py module. T his may have to do with the interaction between Python and the mobile optimization client that I am testing. I do not see this problem when using Internet Explorer and the optimization client, nor is there a problem when using Python and no optimization client. I am working with the optimization client vendor to have them test my Python script with their product. This problem is intermittent with the optimization client which is annoying since most of the time it works. Iteration Number 12 18/10/2006 14:01:23 Downloading http://tmotest.de/ftp/3MB.doc Error: problem downloading 3MB.doc error no args File C:\Documents and Settings\root\Desktop\TMO\Python scripts\http-v2.3a.py, line 130, in main urllib.urlretrieve(total_URL, downloaded_file) File C:\Python25\lib\urllib.py, line 89, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File C:\Python25\lib\urllib.py, line 248, in retrieve block = fp.read(bs) File C:\Python25\lib\socket.py, line 308, in read data = self._sock.recv(recv_size) I am hesitant to make any changes to the python libraries as I need to distribute these scripts with a standard Python install. I guess an other option is to try and learn something like Perl and recode all the test scripts... -- http://mail.python.org/mailman/listinfo/python-list
Re: Restart a Python COM Server
[EMAIL PROTECTED] wrote: Hello all. I am desperately in need for you help guys. Here is the story: 1- I have created a small simple COM serve with python (along the lines read in Win32 Programming with python). 2- If I start the server and call a function from VBE everything works fine 3- I then want to modify the function in the python COM server 4- I unregister the server and register it again hoping the changes will take effect 5- I make call to the function from VBE but the it seems that VBE doesn't reload/refresh the reference to the server. So I do I get VBE to point to the last version of the server? If I close VBE and reload it then it works. But I think there is probably a smarter way. Please, tell me there is! Few posts deal with the issue, but so far I couldn't find anything about it... Thanx all M.E I don't know how well this works for python-based COM components, but the general fix is to setup a Component Services package. This creates a proxy component which can be independently killed from the Component Services management console. -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Rob Wolfe wrote: ... def filter(adr):# note that filter is a builtin function also import re allow = re.compile(r'.*(?!\.com)\.my(|$)') # negative lookbehind deny = re.compile(r'.*\.com\.my(|$)') cnt = 0 if deny.search(adr): cnt += 1 if allow.search(adr): cnt += 1 return cnt Which makes the 'deny' code here redundant so in this case the function could be reduced to: import re def allow(adr):# note that filter is a builtin function also allow = re.compile(r'.*(?!\.com)\.my(|$)') # negative lookbehind if allow.search(adr): return True return False Though having the explicit allow and deny expressions may make what's going on clearer than the fairly esoteric negative lookbehind. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute a linux command by python?
haishan chang wrote: How to execute a linux command by python? for example: execute ls or useradd oracle Who can help me? start here: http://www.python.org/doc/lib/ /F -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
Stephen G wrote: I am hesitant to make any changes to the python libraries as I need to distribute these scripts with a standard Python install. well, you could at least check if the suggestions in that thread makes the problem go away... (if so, shipping a patched version with your program is trivial). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
[EMAIL PROTECTED] wrote: Hi, thanks for the reply,but unfortunately this does not work with the type of classes I am dealing with. When trying to pickle the class I get the following error: File /usr/lib/python2.4/copy_reg.py, line 76, in _reduce_ex raise TypeError(a class that defines __slots__ without TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled So there is something missing in this class? Or any other idea how to do this? Alex yes, read the documentation: http://docs.python.org/dev/lib/pickle-inst.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Dictionaries
How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? Thank you L. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute a linux command by python?
Fredrik Lundh wrote: start here: http://www.python.org/doc/lib/ make sure you skim though the *entire* list. when you've done that, see the process management section in the os module documentation (make sure to read the entire page before you decide which API to use), and also the subprocess module documentation. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
On 18 Oct 2006 08:24:27 -0700, Lad [EMAIL PROTECTED] wrote: How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. a={'a':1} b={'b':2} a.update(b) a {'a': 1, 'b': 2} -- Cheers, Simon B [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest quiet again before exit how
... every run of doctest after the first is verbose ... *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. Another path to the same bug: import doctest print doctest.testfile(__file__, verbose=False) print doctest.testfile(__file__, verbose=False) Mystifiedly yours, rank Python newbie, Pat LaVarre -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Lad wrote: How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? Thank you L. Yes, use update. Beware that this modifies a dictionary in place rather than returning a new dictionary. a={'a':1} b={'b':2} a.update(b) a {'a': 1, 'b': 2} Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. a.update(b) a {'a':1,'b':2} -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
[EMAIL PROTECTED] wrote: Hi Experts, Looking for a very quick bit on of advice on how to make some python code run. I'm a newbie to both VBA and Python, so i apologise if this is very easy but i'm about to tear my hair out after googling for the last 3 days. I have written a large python script which inside of it creates an Excel table, the name of this file and how many objects can change for each project i run. I have then written a VBA script which takes the info from Excel and drops it into a PowerPoint Pres. Both of these procedures work fine, but i am coming unstuck when i try to apply the macro, (or .xla) file to the new tables autmatically. Can anyone give me any guidance on this? The macro is called sub is CTP and the add-in file is CTP.XLA Below is the code i've managed to 'Stick' together Mike import win32com.client xl = win32com.client.Dispatch(Excel.Application) ppt = win32com.client.Dispatch(PowerPoint.Application) xl.Visible = 1 #open MS Excel ppt.Visible = 1 #open MS Powerpoint xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big output.xls') #A table for a project xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\CTP.xla') # Stored macro add-in ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic files\\Basic Template.ppt') xl.Application.ExecuteExcel4macro('CTP!CTP.xla()[big output.XLS]') It doesn't really make sense to apply a *file* to a *file* - you apply a sub or function in that file to a range in the other file (I'm assuming that your table is stored as a range of cells). What ExcecuteExcel4Macro is expecting as input is a string along the lines of 'CTP!MacroName(Workbooks(big output).Range(A1:C100))' (experiment with using instead of since VBA requires embedded to be escaped by - but since you are writing this in Python it might not be necessary). Maybe experiment with writing a VBA macro in Excel which can successfuly launch the macro you need and then translate the appropriate snippet to your python script. Also - are you sure that the add-in macro is an old-style Excel4 macro? That would make it about 10 years old or deliberately retro. If not - the run method might be more appropriate. You should probably open the workbooks in such a way that big output.xls is the active workbook (and not ctp.xla) since most add-ins assume that the calling workbook is the active workbook (although - I don't know how an old-style pre-VBA Excel4 macro handled things). Thus you would probably want to open big output.xls last (or use xl.Application.Workbooks(big output).Activate ) to make sure that it is the active workbook. Also - do you even have to open ctp.xla explicitly? If it is an installed add-in then that line might be redundant. A final potential problem is that big output.xls might require a reference to ctp.xla. This sometimes happens when you try to invoke add-in code from another VBA project - but I would think that the ExecuteExcel4macro would bypass that. I can't comment on the python part of the equation - I am a complete newbie there. You might consider reposting this in microsoft.public.excel.programming since many of the regular posters there know a lot about automating Excel from scripting languages. They could at least help you with the VBA side of the equation. I hope that my random thoughts don't misguide you too much. -John Coleman -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
Thanks for your advice on this matter, I'm actually using Excel 2003!! so it shows how much i know! i did manage to get the prog to run with the line xl.Application.Run(CTP.xla!sheet1.CTP) but it didn't do anything... i'm guessing it is along the lines of wht you were saying earlier about big output being the active worksheet. I'll give that a go now Thanks for the advice Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
dict(a.items() + b.items()) Lad wrote: How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote: How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? What should the result be if both dictionaries have the same key? a={'a':1, 'b'=2} b={'b':3} should the result be: {'a':1, 'b'=2} # keep the existing value {'a':1, 'b'=3} # replace the existing value {'a':1, 'b'=[2, 3]} # keep both values or something else? Other people have already suggested using the update() method. If you want more control, you can do something like this: 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 -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
After just running trying that update it hits the macro perfectly but hten i get an error message after i type in a couple of values.. as per below Traceback (most recent call last): File string, line 148, in ? File COMObject unknown, line 14, in Run File C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) I know you said you didn't know much about python, so if any other experts outthere can give me a clue.. i'll be very appreciative Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
abcd wrote: ... Are you sure you can't use VNC? An animated GIF based on full-screen grabs will be amazingly huge and have very low color quality at the same time. Installing VNC on Windows should take you about 30 seconds, honest. Or is this for some sort of project where you can't use anything but CPython software...? Brett Hoerner -- http://mail.python.org/mailman/listinfo/python-list
Install from source on a x86_64 machine
Hello all, Being relatively new to linux I'm a little confused about what options I need to use to build python from source. 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. 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 ? *** Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Brett Hoerner wrote: Are you sure you can't use VNC? An animated GIF based on full-screen grabs will be amazingly huge and have very low color quality at the same time. Installing VNC on Windows should take you about 30 seconds, honest. Or is this for some sort of project where you can't use anything but CPython software...? Brett Hoerner the latter. -- http://mail.python.org/mailman/listinfo/python-list