From eternalsquire at comcast.net Wed Nov 3 22:59:43 2004 From: eternalsquire at comcast.net (The Eternal Squire) Date: Wed, 03 Nov 2004 20:59:43 -0700 Subject: pep 336: Make None Callable Message-ID: PEP: 336 Title: Make None Callable Version: $Revision: 1.1 $ Last-Modified: $Date: 2004/11/03 16:58:30 $ Author: Andrew McClelland Status: Draft Type: Standards Track Content-Type: text/plain Created: 28-Oct-2004 Post-History: Abstract None should be a callable object that when called with any arguments has no side effect and returns None. Motivation To allow a programming style for selectable actions that is more in accordance with the minimalistic functional programming goals of the Python language. Rationale Allow the use of None in method tables as a universal no effect rather than either (1) checking a method table entry against None before calling, or (2) writing a local no effect method with arguments similar to other functions in the table. The semantics would be effectively, class None: def __call__(self, *args): pass How To Use Before, checking function table entry against None: class Select: def a(self, input): print 'a' def b(self, input): print 'b' def c(self, input); print 'c' def __call__(self, input): function = { 1 : self.a, 2 : self.b, 3 : self.c }.get(input, None) if function: return function(input) Before, using a local no effect method: class Select: def a(self, input): print 'a' def b(self, input): print 'b' def c(self, input); print 'c' def nop(self, input): pass def __call__(self, input): return { 1 : self.a, 2 : self.b, 3 : self.c }.get(input, self.nop)(input) After: class Select: def a(self, input): print 'a' def b(self, input): print 'b' def c(self, input); print 'c' def __call__(self, input): return { 1 : self.a, 2 : self.b, 3 : self.c }.get(input, None)(input) References [1] Python Reference Manual, Section 3.2, http://docs.python.org/ref/ref.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From ods at strana.ru Fri Nov 19 05:10:42 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 19 Nov 2004 13:10:42 +0300 Subject: Importing files other than *.py In-Reply-To: <40050B97-39BE-11D9-B38F-003065B11E84@leafe.com> References: <40050B97-39BE-11D9-B38F-003065B11E84@leafe.com> Message-ID: <20041119131042.4d0507c5.ods@strana.ru> On Thu, 18 Nov 2004 19:02:06 -0500 Ed Leafe wrote: > If I have a Python script in a file named "burp.zz", is there > any way > to import it into another script as you can with files named with the > .py extension? > > I looked at the imp module, but was not able to make it do what > I > wanted. Is this possible, or is the py/pyc extension required? Yes, it's possible: $ cat > burp.zz < def f(): > print 'OK' > EOF $ python Python 2.4b1 (#1, Oct 29 2004, 15:00:34) [GCC 3.3.3 20040412 (ALT Linux, build 3.3.3-alt5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> fp = open('burp.zz', 'U') >>> import imp >>> module = imp.load_module('burp', fp, 'burp.zz', ('.py', 'U', 1)) >>> module >>> module.f >>> module.f() OK Alternatively you can use sys.path_hooks to install own importer being aware of your extentions. -- Denis S. Otkidach http://www.python.ru/ [ru] From tzot at sil-tec.gr Sat Nov 13 17:22:30 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 14 Nov 2004 00:22:30 +0200 Subject: Comparing two minidom objects References: <727daa7e.0411081033.276d5eba@posting.google.com> Message-ID: On 8 Nov 2004 10:33:24 -0800, rumours say that skip at pobox.com (Skip Montanaro) might have written: >I'd like to compare two xml.dom.minidom objects, but the naive attempt fails: > >>>> import xml.dom.minidom >>>> d1 = xml.dom.minidom.parse("ES.xml") >>>> d2 = xml.dom.minidom.parse("ES.xml") >>>> d1 == d2 >False > >My goal is to decide whether or not I need to prompt the user to save config >information at the end of a program run by generating a minidom object then >comparing it with the last saved version. Convert your minidom objects into sets of ("key", "value") tuples, where "key" represents the full path to the key starting from the root element. I assume that both "key" and "value" will or can be hashable. Compare the two sets. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From robin at reportlab.com Thu Nov 18 10:03:46 2004 From: robin at reportlab.com (Robin Becker) Date: Thu, 18 Nov 2004 15:03:46 +0000 Subject: PIL for Python 2.4? In-Reply-To: References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> Message-ID: <419CB9D2.2030504@chamonix.reportlab.co.uk> Christos TZOTZIOY Georgiou wrote: > On Thu, 18 Nov 2004 14:17:50 +0100, rumours say that Gerhard Haering > might have written: > > >>>Has anyone built PIL (1.1.4 or 1.1.5) for Python 2.4? If yes, >>>please let me know, [...] >> >>I haven't. But it would have been useful if you had mentioned which >>platform ;-) Windows? > > > Oh, yes, Windows... On Linux I built it myself. I just don't have > access to a MS compiler on Windows. > > Sorry for not being clear. well I have old MS VC++ 6 and building with setup.py Python 2.4b2 gives an error related to the compiler; :( I guess I need MSVC++ 7. I have MSDN subscription, but no idea whether I can get 6 & 7 to coexist. ##### running build_ext Traceback (most recent call last): File "setup.py", line 314, in ? ext_modules = MODULES, File "C:\python24\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\python24\lib\distutils\dist.py", line 946, in run_commands self.run_command(cmd) File "C:\python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\python24\lib\distutils\command\install.py", line 501, in run self.run_command('build') File "C:\python24\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\python24\lib\distutils\command\build.py", line 112, in run self.run_command(cmd_name) File "C:\python24\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\python24\lib\distutils\command\build_ext.py", line 253, in run force=self.force) File "C:\python24\lib\distutils\ccompiler.py", line 1177, in new_compiler return klass (None, dry_run, force) File "C:\python24\lib\distutils\msvccompiler.py", line 206, in __init__ self.__macros = MacroExpander(self.__version) File "C:\python24\lib\distutils\msvccompiler.py", line 112, in __init__ self.load_macros(version) File "C:\python24\lib\distutils\msvccompiler.py", line 128, in load_macros self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") File "C:\python24\lib\distutils\msvccompiler.py", line 118, in set_macro self.macros["$(%s)" % macro] = d[key] KeyError: 'sdkinstallrootv1.1' -- Robin Becker From thorsten at thorstenkampe.de Mon Nov 15 08:15:35 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 15 Nov 2004 14:15:35 +0100 Subject: Combining arbitrary lists References: <41982269$1_1@alt.athenanews.com> Message-ID: * Nick (2004-11-15 04:28 +0100) > Given that > > n = [ [1, 2, 3], [4, 5, 6], [7, 8] ] > > then the following code produces what I expect > > for x in n[0]: > for y in n[1]: > for z in n[2]: > print [x, y, z] > > --output-- > [1, 4, 7] > [1, 4, 8] > [1, 5, 7] > [1, 5, 8] > ... > [3, 6, 8] > -- -- > > How can I do this for an arbirary length of n? This is the Cartesian product of three sets. Have a look at http://www.thorstenkampe.de/python/utils.py: def cartes(seq0, seq1, modus = 'pair'): """ return the Cartesian Product of two sequences """ if modus == 'pair': return [[item0, item1] for item0 in seq0 for item1 in seq1] elif modus == 'triple': return [item0 + [item1] for item0 in seq0 for item1 in seq1] Then you would generate your output like this: >>> cartes(cartes([1, 2, 3], [4, 5, 6]), [7, 8], 'triple') From aleaxit at yahoo.com Sun Nov 7 09:14:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 Nov 2004 15:14:28 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <418D61D3.3040904@acm.org> Message-ID: <1gmvz4l.vo1rpk9zfdahN%aleaxit@yahoo.com> Maurice LING wrote: > > Not really. It's an impression you could easily get from several > > books about Python (e.g. O'Reilly's "Learning Python"), which > > make a rather big deal about Python being slow to execute, but > > fast to develop in. > > Come to think of it, yes, "Python, The Complete Reference", "Programming > Python" and "Learning Python" all seems to have that "speed warning" tag > in the beginning chapters. > > If this seems to be the wrong impression, should the authors do something? I guess they should, if they care about what they're communicating. This is how I put the issue in "Python in a Nutshell": ''' Good compilers for classic compiled languages can often generate binary machine code that runs much faster than Python code. However, in most cases, the performance of Python-coded applications proves sufficient. When it doesn't, you can apply the optimization techniques covered in Chapter 17 to enhance your program's performance while keeping the benefits of high programming productivity. ''' I'm biased, having written this, but it seems a balanced set of assertions which tries hard not to leave either wrong impression. Alex From deetsNOSPAM at web.de Mon Nov 8 18:50:02 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 09 Nov 2004 00:50:02 +0100 Subject: Determining combination of bits References: <8KQjd.121796$hj.4674@fed1read07> <418ff674$1@nntp0.pdx.net> <418fff99$0$87155$a1866201@visi.com> Message-ID: > > The least significant bit of 110 is this one here -----+ > ^ | > | | > +-----------------------+ > > It's a 0 (zero). > > What I think you're trying to say is something like the value > of the rightmost 1. Yup. -- Regards, Diez B. Roggisch From sylvain.thenault at nospam.logilab.fr Tue Nov 30 07:57:59 2004 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 30 Nov 2004 13:57:59 +0100 Subject: weird behaviour of "0 in [] is False" Message-ID: Hi there ! Can someone explain me the following behaviour ? >>> l = [] >>> 0 in (l is False) Traceback (most recent call last): File "", line 1, in ? TypeError: iterable argument required >>> (0 in l) is False True >>> 0 in l is False False This is really obscur to me... -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From tim.peters at gmail.com Mon Nov 15 10:56:15 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 15 Nov 2004 10:56:15 -0500 Subject: Will python ever have signalhandlers in threads? In-Reply-To: References: <4195419b.303035081@news.oz.net> Message-ID: <1f7befae0411150756122153c5@mail.gmail.com> [Antoon Pardon] > ... > AFAIU the Queue module doesn't block on a full/empty queue when > a timeout is specified but goes in a loop sleeping and periodically > checking whether place/items are available. With signals that > can be sent to a thread the queue could just set an alarm and > then block as if no timeout value was set and either unblock > when place/items are available or get signalled when the timeout > period is over. The only things CPython requires of the *platform* thread implementation are: 1. A way to start a new thread, and obtain a unique C long "identifier" for it. 2. Enough gimmicks to build a lock object with Python's core threading.Lock semantics (non-rentrant; any thread T can release a lock in the acquired state, regardless of whether T acquired it). Everything else is built on those, and CPython's thread implementation is extremely portable-- and easy to port --as a result. Nothing in CPython requires that platform threads support directing a signal to a thread, neither that the platform C library support an alarm() function, nor even that the platform have a SIGALRM signal. It's possible to build a better Queue implementation that runs only on POSIX systems, or only on Windows systems, or only on one of a dozen other less-popular target platforms. The current implementation works fine on all of them, although is suboptimal compared to what could be done in platform-specific Queue implementations. For that matter, even something as simple as threading.RLock could be implemented in platform-specific ways that are more efficient than the current portable implementation (which builds RLock semantics on top of #2 above). From dieringe at zedat.fu-berlin.de Tue Nov 23 11:22:23 2004 From: dieringe at zedat.fu-berlin.de (Martin Dieringer) Date: Tue, 23 Nov 2004 17:22:23 +0100 Subject: split large file by string/regex References: <41A1EF3E.1080409@holdenweb.com> <0ds972-sct1.ln1@pc.dieringer.dyndns.org> Message-ID: "Denis S. Otkidach" writes: > On Mon, 22 Nov 2004 20:48:16 +0100 > Martin Dieringer wrote: > >> "Denis S. Otkidach" writes: > [...] >> > re module works fine with mmap-ed file, so no need to read it into >> > memory. >> > >> >> thank you, this is the solution! >> Now I can mmap.find all locations and then read the chunks them via >> file.seek and file.read > > mmap-ed files also support subscription and slicing. I guess > mmfile[start:stop] would more readable. yes, even better :-) m. From mrjean1ATcomcastDOTnet at no.spam.net Thu Nov 25 13:49:36 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Thu, 25 Nov 2004 18:49:36 GMT Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: Message-ID: <251120041051005144%mrjean1ATcomcastDOTnet@no.spam.net> Just a comment. The w.strip() call in the last line is superfluous in this particular case. The items in the list resulting from the query.split() call will be stripped already. Example, >>> "a b c".split() ['a', 'b', 'c'] /Jean Bouwers In article , Diez B. Roggisch wrote: > import sets > KEYWORDS = sets.Set(['and', 'or', 'not']) > > query = "test and testing and not perl or testit or example" > > def decorate(w): > if w in KEYWORDS: > return w > return "*%s*" % w > > query = " ".join([decorate(w.strip()) for w in query.split()]) From vsafronovich at naumen.ru Fri Nov 5 03:45:28 2004 From: vsafronovich at naumen.ru (Victor Safronovich) Date: 5 Nov 2004 00:45:28 -0800 Subject: recursion in __cmp__ Message-ID: <3da35075.0411050045.379477af@posting.google.com> please comment this Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >>> class A: def __cmp__(self, other): print '%s|%s' %(`self`, `other`) return cmp(self, other) >>> a = A() >>> cmp(a,A()) <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> 0 >>> cmp(a,5) <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 <__main__.A instance at 0x00989838>|5 0 From bokr at oz.net Fri Nov 12 20:08:22 2004 From: bokr at oz.net (Bengt Richter) Date: Sat, 13 Nov 2004 01:08:22 GMT Subject: Python 2.4: Why only assignments to None are forbiden? References: <4195190f@pfaff2.ethz.ch> Message-ID: <41955a49.309353436@news.oz.net> On Fri, 12 Nov 2004 13:08:30 -0800, James Stroud wrote: > >Forbidding assignment to arbitrary things seems like a bad idea. > >I remember some learning manual recommended this (or the equivalent): > Two things wrong in the following, as noted: >def do_stuff_to_bob(bob=None): #XXX# > if not bob: if bob is None: # this is the usual gerneral idiom, so that e.g., one could # distinguish from a caller passing a legitimate empty list [] # (though of course you could use if not bob if that's what you meant ;-) > bob = ["carol","ted","alice"] # ^^^^^ -- this does not assign to None, it rebinds bob, # which has no effect on the previously bound object (in this case None) # That's a serious misunderstanding of python's assignment semantics, which # your momentary lapse should not be allowed to promote to newbies ;-) > #do stuff to bob > return bob > >otherwise bob would already be defined from the last call (because it is a >mutable type? I can't remember.). How else to handle this in 2.4? > >On Friday 12 November 2004 01:11 pm, Josef Meile wrote: > >> Hi, >> >> Textually from the highlights of python 2.4: >> >> "Assigning to None - the compiler now treats assigning to None as a >> SyntaxError." >> >> I think in general assignments to built-in types, functions, and >> variables should be also forbiden. > > >James Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> None = 'foo' SyntaxError: assignment to None >>> 1234 = 'foo' SyntaxError: can't assign to literal >>> bob = None >>> bob >>> repr(bob) 'None' >>> bob = 1234 >>> bob 1234 Regards, Bengt Richter From jlnespoulous at netscape.net Sat Nov 20 03:56:19 2004 From: jlnespoulous at netscape.net (Leuk) Date: Sat, 20 Nov 2004 09:56:19 +0100 Subject: Help for newbie Message-ID: <419f06a8$0$32335$636a15ce@news.free.fr> I would like to use ZODB, but I'm a newbie in Python, so I do not know if it be more easy for me to use PostgreSQL. Some one can tell me what database will be better to use? What are de differencies between this two databases? Thanks very much :-) From tjreedy at udel.edu Thu Nov 4 19:39:41 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 4 Nov 2004 19:39:41 -0500 Subject: exec code in "globaldict" References: Message-ID: "Gerald Senarclens de Grancy" wrote in message news:Nizid.55896$z77.3059 at news.chello.at... > Hi! > I kept searching my online and offline python ressources to figure out > how to execute some code in the global dictionary. Perhaps you are thinking of builtins. If so, leave it alone. > Basically I'm reading a options file that defines some variables. I want > to access those variables throughout my whole project, so I need them in > the global dictionary. Each module has its own global dict. For what you want, define a module globals.py or options.py or config.py or whatever, have that module read the options, and then import that module into all other modules. Terry J. Reedy From peter at somewhere.com Fri Nov 26 04:11:15 2004 From: peter at somewhere.com (Peter Maas) Date: Fri, 26 Nov 2004 10:11:15 +0100 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: Message-ID: Carlos Ribeiro schrieb: > I think that Delphi is *so* underated when it comes to language & > framework design... Delphi suffered from a couple of problems; first, > it was Pascal's child, and not C; also, because it was a proprietary > project, owned by a single company. Like VB :) but this only means that software decisions are largely driven by prejudice. I'm a long time supporter of Delphi (and C++Builder), fascinated by the design of the VCL and the IDE and could never understand why so many developers preferred VB which is just crap compared to Delphi. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From news-and-lists at the-me.de Thu Nov 11 07:02:03 2004 From: news-and-lists at the-me.de (Axel Bock) Date: Thu, 11 Nov 2004 13:02:03 +0100 Subject: re.compile.match() results in unicode strings - why? Message-ID: <2vh2mlF2lbkrdU1@uni-berlin.de> Hi, I am doing matches with the re module, and I am experiencing a strange problem. I match a string with exp = re.compile(blah) m = exp.match(string) a,b,c,d = m.groups() now a,b,c,d are all string variables, and they all come out as unicode strings (u"xxx"). now my question is: is that "normal" behaviour, for there really is NO character possibly triggering any unicode thing - at all. I mean, I don't really care, for the program works fine, but I _am_ curious a bit :-) thanks in advance & greetings, axel. From ed at leafe.com Thu Nov 18 19:42:52 2004 From: ed at leafe.com (Ed Leafe) Date: Thu, 18 Nov 2004 19:42:52 -0500 Subject: Importing files other than *.py In-Reply-To: <864d370904111816217f383d18@mail.gmail.com> References: <40050B97-39BE-11D9-B38F-003065B11E84@leafe.com> <864d370904111816217f383d18@mail.gmail.com> Message-ID: On Nov 18, 2004, at 7:21 PM, Carlos Ribeiro wrote: > However, there is a problem with 'import' from within the code being > executed; it will look for modules on the directory where the source > file is located. Thus, if your code tries to import a library from > your system, it may not find it (even if it was located in the same > directory where the code that called it via execfile() was). So, > *before* you call the code, update the sys.path to include any > directories from where you may need to import stuff. I was hoping to name certain files with certain extensions, even though they are all 100% Python code. This would make organizing simpler, and avoid having to adopt a naming convention for the main file name. > (btw, I've been checking Dabo from time to time. Good to know you're > making progress!). It's pretty exciting. Those who have worked with it are pretty enthusiastic! It's great to know that we're not the only ones looking for a tool like this! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From jan.dries at dcube-resource.be Mon Nov 29 12:13:56 2004 From: jan.dries at dcube-resource.be (Jan Dries) Date: Mon, 29 Nov 2004 18:13:56 +0100 Subject: [OT] Re: SysLogHandler is drivin me nuts PEBCAC In-Reply-To: References: Message-ID: <41AB58D4.2000902@dcube-resource.be> Slightly OT, but regarding the title, shouldn't it be PEBKAC, since it's keyboard and not ceyboard? Regards, Jan michael wrote: > Vinay Sajip wrote in message news:... > >>michael wrote: >> >>>Yep it was incomplete heres the complete config as it has to be >>> >> >>[config file snipped] >> >>The complete file looks OK. > > > Thx. with this file it is working. The syslogd configuration under AIX was buggy. > > regards > > Michael From ville at spammers.com Fri Nov 19 02:51:50 2004 From: ville at spammers.com (Ville Vainio) Date: 19 Nov 2004 09:51:50 +0200 Subject: RELEASED Python 2.4, release candidate 1 References: Message-ID: >>>>> "Anthony" == Anthony Baxter writes: Anthony> On behalf of the Python development team and the Python Anthony> community, I'm happy to announce the first release Anthony> candidate of Python 2.4. There's a slight nag however, I don't even know if it's worth posting here: The picture in the MSI installer looks quite weird (clunky / pixelated, with awkward colours). This happens with win2k/1280x1024x32 at least. -- Ville Vainio http://tinyurl.com/2prnb From cabria at fta.uva.es Fri Nov 5 16:11:34 2004 From: cabria at fta.uva.es (Iván Cabria) Date: Fri, 5 Nov 2004 16:11:34 MET Subject: sh: test: argument expected Message-ID: <200411051511.iA5FBYnO014379@relay.uva.es> Hi, I have run the script using "python scriptname.py" and the error does not go away. I got the same error: sh: test: argument expected I have checked again that the first line of the python script is #!/usr/bin/env python There are no blank lines or empty spaces before #!/usr/bin/env python I also did "grep loginname /etc/passwd" to confirm I was using bash, and the line I got ended with :/usr/bin/bash Iv?n From wweston at att.net Mon Nov 8 14:34:49 2004 From: wweston at att.net (wes weston) Date: Mon, 08 Nov 2004 19:34:49 GMT Subject: MySQLdb installation In-Reply-To: <418f99db$0$175$9b622d9e@news.freenet.de> References: <418f99db$0$175$9b622d9e@news.freenet.de> Message-ID: T. Kaufmann wrote: > Hi, > > RDBMS MySQL works fine on my machine. I want to install MySQL-python > 1.0.0 under Red Hat 9.0. > > >>> platform.platform() > 'Linux-2.4.20-8-i686-with-redhat-9-Shrike' > > There are some problems. If I call python > > setup.py build > > there are lots of errors: > > _mysql.c:41:19: mysql.h: File not found > > What can I do? How can I fix it? > > o-o > > Thomas Thomas, I believe the mysql.h file that is not being found is part of the mysql developement package (and not the MySQLDB package). If you do have mysql.h somewhere, it is not in your include path. wes From __peter__ at web.de Tue Nov 30 03:23:27 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Nov 2004 09:23:27 +0100 Subject: Question of Optionparse References: <41aba86d$0$2074$39db0f71@news.song.fi> Message-ID: Pekka Niiranen wrote: > How can I STOP Optionparse to process boolean > value as parameter. See this: > > >>> parser = optparse.OptionParser() > >>> parser.add_option("-x",dest='xxx', action="store_true",help="xxx") > >>> parser.add_option("-r",dest='root',help="directory",type="string") > >>> args = ["-r", "d:", "-x"] > >>> parser.parse_args(args) > (, []) > > Last line is correct: boolean 'xxx' gets set 'True' > and parameter 'root' to 'd:' > > However when value is NOT given for '-r' but '-x' exists: > > >>> args = ["-r", "-x"] > >>> parser.parse_args(args) > (, []) > > This is BS: I expected 'root' to be None and 'xxx' to be 'True'. > How can I make it so? I think you need a callback option. > Another question: Is there a way to store options > directly into user defined dictionary without assignment > like this: > > my_environment_values = {} > (options, args) = parser.parse_args() > environment_values["xxx"] = options.xxx environment_values.update(options.__dict__) Full example: import optparse def callback(option, opt, value, parser): rargs = parser.rargs if rargs and not rargs[0].startswith("-"): parser.values.root = rargs.pop(0) else: parser.values.root = "" parser = optparse.OptionParser() parser.add_option("-x", "--xtra-terrestrial", action="store_true") parser.add_option("-r", "--root", action="callback", callback=callback) options, args = parser.parse_args() environment = {} environment.update(options.__dict__) print environment Peter From fredrik at pythonware.com Mon Nov 22 06:50:32 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Nov 2004 12:50:32 +0100 Subject: Python-2.3.4 on OSF1 V4.0? References: <9fbcd7cf.0411191154.453fb8ff@posting.google.com><419e6590$0$562$9b622d9e@news.freenet.de> <9fbcd7cf.0411201747.1bfb160e@posting.google.com> Message-ID: Edmond Rusjan wrote: > I don't understand if the '_E' in '_Esetsockopt' is significant and/or > where it comes from, but that's one difference that strikes me. > > [V4.0]$ grep setsockopt Modules/socketmodule.c|wc > 11 39 498 > [V4.0]$ grep _Esetsockopt Modules/socketmodule.c|wc > 0 0 0 the OSF/1 C libraries support multiple Unix dialects through a variety of compatibility macros. I'm not 100% sure, but I think _E is used for things that explicitly require some level of X/Open-compatibility. try adding a #define _XOPEN_SOURCE_EXTENDED to your test program (before you include the socket stuff), and see if it still works. if that breaks your test program, adding a corresponding #undef to the socket module's source code might help. From edmond.rusjan at gmail.com Tue Nov 23 17:07:01 2004 From: edmond.rusjan at gmail.com (Edmond Rusjan) Date: 23 Nov 2004 14:07:01 -0800 Subject: Python-2.3.4 on OSF1 V4.0? References: <9fbcd7cf.0411191154.453fb8ff@posting.google.com><419e6590$0$562$9b622d9e@news.freenet.de> <9fbcd7cf.0411201747.1bfb160e@posting.google.com> Message-ID: <9fbcd7cf.0411231407.506bd81e@posting.google.com> Thank you so much, Martin and Fredrik. As you advised, added near the top of socketmodule.c (after #import Python.h): #undef _XOPEN_SOURCE_EXTENDED #define _POSIX_PII_SOCKET #undef HAVE_SOCKADDR_SA_LEN It built cleanly and socket now imports. From rtilley at vt.edu Sun Nov 7 20:41:20 2004 From: rtilley at vt.edu (Brad Tilley) Date: Sun, 07 Nov 2004 20:41:20 -0500 Subject: Stop spaces from appearing when printing to file In-Reply-To: <418ec9ff$1_2@newspeer2.tds.net> References: <418ec9ff$1_2@newspeer2.tds.net> Message-ID: <418ECEC0.3000205@vt.edu> Kent Johnson wrote: > Brad Tilley wrote: > >> I'm printing some info into a txt file that will be uploaded into a >> MySQL DB. I use ';' as field separaters. How can I stop spaces from >> appearing on both sides of the ';' > > > The spaces are a feature of print. To avoid them, use string formatting > to create a single output string. > >> print >> x,';',object,";",AN_string,";",ascii,";",sum > > > Try > print >> x, ';%s;%s;%s;%s' % (object, AN_string, ascii, sum) > > Kent Thanks Kent, this works great. From invalid at invalid.invalid Sun Nov 14 22:38:01 2004 From: invalid at invalid.invalid (Nicholas Wieland) Date: Mon, 15 Nov 2004 04:38:01 +0100 Subject: Zope 3.0, and why I won't use it References: Message-ID: - Will Stuyvesant : > Hello all, > > So Zope still lives, yay. Well, I like that they use Python. > > > > What amazed me is they write that they "added types to the variables > and hope that it will be added to the Python project too". Really. > ROFL. Sorry, probably I'm just tired (work to buy coffee <-> drink coffee to work inifite loop, as usual :p), but I can't find where exactly they made such a claim. I'm really interested in this because a friend of mine (Volonghi) asked me exactly the same question... I think that "someone - somewhere" misunderstood what interfaces are, but I'm not sure. The only thing I'm sure is that I'm writing components for ZopeX3 in plain old good Python from milestone 3 :) > And instead of working on the engine they should have put more work > into examples. Simple tutorials. What about the programmers tutorial (http://snipurl.com/amy9) and the Developer Book (http://snipurl.com/amyb) ? > Downloadable executables for Windows that you can click and install. Like the .exe here http://snipurl.com/amyd ? I'm not a Windows user, sorry, can't really help here :) > But most of all simple and good examples: webapplications like > - a wiki in zope http://snipurl.com/amyh > - a forum in zope, with agenda and calendar Maybe the example of the developer book can help: Stephan explains the main concepts of ZX3 by implementing a messageboard. > - a game like http://216.199.69.100/war/ in zope Can't help here. BTW, I think that the zwiki, the bugtracker and all the documentation is enought for now - I've seen too much ultrastable software with a man page and an hello world called "documentation" to complain the developers for that :) > They have a nice free webhosting thing for zope, but to expect new > users to do everything from scratch... > The "examples" I found were very disappointing. Why ? ... HAND, ngw From gabriel.cooper at mediapulse.com Mon Nov 29 15:49:30 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 29 Nov 2004 15:49:30 -0500 Subject: Python UPS / FedEx Shipping Module Message-ID: <41AB8B5A.2000005@mediapulse.com> Is there an existing UPS and FedEx capable shipping (as in, price quotes) module out there? I have UPS working but now I need FedEx and was curious whether I'd be reinventing the wheel. ;) Web searches didn't reveal anything particularly interesting. Also, anyone know what happened to the "payment" sourceforge.net project? it was only a few python files on CVS of connecting to various online stores, but it seems to be deleted now. I had to update it to work with newer python libraries, and wanted to contribute my changes back to it but in the mean time it disappeared from sourceforge! Thanks, Gabriel. From fake at not-real.bogus Fri Nov 5 14:50:34 2004 From: fake at not-real.bogus (Matt Garman) Date: Fri, 05 Nov 2004 19:50:34 GMT Subject: tempfile and curses (putwin() and getwin()) Message-ID: I've been working on a curses-based application in Python. My application effectively has a series of screens (or windows). When one screen closes, the previous screen should be exactly redrawin in its original state (i.e., before the sub-screen was created). As far as I can tell, the putwin() and getwin() functions can easily solve this problem. So I can do something like this: # draw/write some stuff on stdscr... addStuffToStdScr() # save the state of stdscr to a file named 'windata' f = open('windata', 'w+b') stdscr.putwin(f) f.close() # now create a subwindow (which over-writes some or all # of stdscr), and do whatever needs to be done... subWindowRoutine() # resurrect stdscr be reading 'windata' f = open('windata', 'r') stdscr = curses.getwin(f) f.close() stdscr.refresh() That works as I expect. However, I'd like to use the tempfile module, rather than manage my own window data cache (this data needs to exist only for the duration of the application). However, if I try to use the tempfile module, ala: addStuffToStdScr() tmpfile = tempfile.TemporaryFile() stdscr.putwin(tmpfile) subWindowRoutine() stdscr = curses.getwin(tmpfile) stdscr.refresh() Then an exception is thrown and I get the following message: stdscr.refresh() _curses.error: refresh() for a pad requires 6 arguments Any thoughts as to what I'm doing wrong? Or can tempfile simply not be used in such a manner? Is there a better (or more appropriate way) to get a generic file buffer? Or a better way to save screen state in curses? Thanks! Matt -- Matt Garman email at: http://raw-sewage.net/index.php?file=email From peter at engcorp.com Sun Nov 21 22:47:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Nov 2004 22:47:56 -0500 Subject: Nagging problem with MySQLdb In-Reply-To: References: Message-ID: Phillip wrote: > I hate the way one has to jump through countless hoops to put data in a > db and get it out again. You would have it much easier if you discovered how to use more of Python's capabilities to write shorter code... see some ideas below. > # going through the DictList and adding the > # datasets into the db > for line in sourceLinesDictList: > # also adding some data for fields that the DB table has but our > # DictList does't (data01,02,29) > data01 = 'source-one' > data02 = '0', > data03 = line['payments-status'], .... > data10 = line['sku'], > data11 = float(line['price'].replace(',','.',1)), .... > data16 = int(line['batch-id']), For this sort of code, you can often make it more data-driven, along these lines (I use globals() instead of an object since I'm not sure you're familiar with OO programming, but an object would make this even cleaner): for line in sourceLinesDictList: for i, (key, type) in enumerate([ ('source-one', 'direct'), ('0', 'direct'), ('payments-status', 'str'), ... ('sku', 'str'), ('price', 'float'), ('batch-id', 'int'), ...]): if type == 'direct': val = key elif type == 'str': val = line[key] elif type == 'float': val = float(line[key].replace(',','.',1)) elif type == 'int': val = int(line[key]) globals()['data%02d' % i] = val In other words, use a list containing the names and "types" of information, and programmatically create variables in the global namespace, eliminating all duplication in the extraction of data from "line". > baseFeed.execute( > """INSERT INTO position > (plattform, > position_id, > payments-status, > order-id, ... > VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, > %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""" > [data01, data02, data03, data04, data05, data06, data07, data08, > data09, data10, data11, data12, data13, data14, data15, data16, data17, > data18, data19, data20, data21, data22, data23, data24, data25, data26, > data27, data28, data29] > ) Having done the insertion into globals() above, you could now replace this monster with something like this: ... VALUES (%s);""" % ', '.join(dataList) (in other words, inserting the list of data items, with commas separating them) where dataList had previously been formed in a manner something like this: dataList = [globals()['data%02d' % i] for i in xrange(1, 30)] ...and similar ideas. I hope something in here helps you make this task more manageable... -Peter From __peter__ at web.de Wed Nov 10 04:05:14 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Nov 2004 10:05:14 +0100 Subject: Packing list elements into tuples References: Message-ID: Nickolay Kolev wrote: > I have a list whose length is a multiple of 3. I want to get a list??of > tuples each of which has 3 consecutive elements from the original list, > thus packing the list into smaller packets. Like this: > ... dictionaries ... would be even better: > l = [1,2,3,4,5,6] > > tups = [ > {'first':1,'second':2,'third':3}, > {'first':4,'second':5,'third':6} > ] itertools to the rescue: >>> from itertools import * >>> names = "first second third".split() >>> items = range(6) >>> map(dict, takewhile(bool, starmap(zip, repeat((names, iter(items)))))) [{'second': 1, 'third': 2, 'first': 0}, {'second': 4, 'third': 5, 'first': 3}] Fun, but not recommended. There must be a simpler expression where you need not mention len(names) explicitly - but right now I can't think of one. Note how the nonzero len(items) % len(names) case is handled: >>> map(dict, takewhile(bool, starmap(zip, repeat((names, iter(range(5))))))) [{'second': 1, 'third': 2, 'first': 0}, {'second': 4, 'first': 3}] However, in real life I would rather go with Steven Bethard's two-step approach... Peter From bokr at oz.net Thu Nov 25 14:28:00 2004 From: bokr at oz.net (Bengt Richter) Date: Thu, 25 Nov 2004 19:28:00 GMT Subject: dictionary initialization References: Message-ID: <41a62df4.1003031613@news.oz.net> On Thu, 25 Nov 2004 18:38:17 +0000 (UTC), wgshi at namao.cs.ualberta.ca (Weiguang Shi) wrote: >Hi, > >With awk, I can do something like > $ echo 'hello' |awk '{a[$1]++}END{for(i in a)print i, a[i]}' > >That is, a['hello'] was not there but allocated and initialized to >zero upon reference. > >With Python, I got > >>> b={} > >>> b[1] = b[1] +1 > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 1 > >That is, I have to initialize b[1] explicitly in the first place. > >Personally, I think > > a[i]++ > >in awk is much more elegant than > > if i in a: a[i] += 1 > else: a[i] = 1 > >I wonder how the latter is justified in Python. > You wrote it, so you have to "justify" it ;-) While I agree that ++ and -- are handy abbreviations, and creating a key by default makes for concise notation, a[i]++ means you have to make some narrow assumptions -- i.e., that you want to create a zero integer start value. You can certainly make a dict subclass that behaves that way if you want it: >>> class D(dict): ... def __getitem__(self, i): ... if i not in self: self[i] = 0 ... return dict.__getitem__(self, i) ... >>> dink = D() >>> dink {} >>> dink['a'] +=1 >>> dink {'a': 1} >>> dink['a'] +=1 >>> dink {'a': 2} >>> dink['b'] 0 >>> dink['b'] 0 >>> dink {'a': 2, 'b': 0} Otherwise the usual ways are along the lines of >>> d = {} >>> d.setdefault('hello',[0])[0] += 1 >>> d {'hello': [1]} >>> d.setdefault('hello',[0])[0] += 1 >>> d {'hello': [2]} Or >>> d['hi'] = d.get('hi', 0) + 1 >>> d {'hi': 1, 'hello': [2]} >>> d['hi'] = d.get('hi', 0) + 1 >>> d {'hi': 2, 'hello': [2]} >>> d['hi'] = d.get('hi', 0) + 1 >>> d {'hi': 3, 'hello': [2]} Or >>> for x in xrange(3): ... try: d['yo'] += 1 ... except KeyError: d['yo'] = 1 ... print d ... {'hi': 3, 'hello': [2], 'yo': 1} {'hi': 3, 'hello': [2], 'yo': 2} {'hi': 3, 'hello': [2], 'yo': 3} Regards, Bengt Richter From gtcopeland2002 at yahoo.com Mon Nov 15 10:53:41 2004 From: gtcopeland2002 at yahoo.com (Greg Copeland) Date: 15 Nov 2004 07:53:41 -0800 Subject: Python port? Message-ID: <1100534021.494482.28880@c13g2000cwb.googlegroups.com> I am nearing the completion of porting Python 2.3.4 to VxWorks 5.5. Unlike previous python/vxworks porting efforts, this project attempts to create a fully functional and robust port of Python, running on VxWorks 5.5+. I am attempting to create a Python SIG to support this effort. Now would be a great time to hear from those interested in this port. From edmond.rusjan at gmail.com Fri Nov 19 14:54:04 2004 From: edmond.rusjan at gmail.com (Edmond Rusjan) Date: 19 Nov 2004 11:54:04 -0800 Subject: Python-2.3.4 on OSF1 V4.0? Message-ID: <9fbcd7cf.0411191154.453fb8ff@posting.google.com> Hi All, I'd like to use Python-2.3.4 on OSF1 V4.0, but have trouble installing. With a plain "./configure; make" build, I cannot import socket. If I uncomment the socketmodule in Modules/Setup, the build fails. Using gcc 3.4.2. Had no problem on OSF1 V5.1, Linux and Sun. Have not been able to find reference to a similar problem in comp.lang.python. Thanks for any tip or reference, Edmond Details: Plain "./configure; make" build: [Python-2.3.4_no_socket]$ ./python Python 2.3.4 (#4, Nov 17 2004, 17:01:35) [GCC 3.4.2] on osf1V4 Type "help", "copyright", "credits" or "license" for more information. >>> import socket Traceback (most recent call last): ... import _socket ImportError: No module named _socket >>> With "_socket socketmodule.c" uncommented in Modules/Setup: [Python-2.3.4]$ make gcc -pthread -o python \ Modules/python.o \ libpython2.3.a -lrt -lm _Esetsockopt _Egetsockopt _Erecv _Esend _Esendto _Econnect _Ebind collect2: ld returned 1 exit status make: *** [python] Error 1 Wrote, compiled and ran a simple test program which binds to a socket and listens: no problem. First few line of config.log: ... It was created by python configure 2.3, which was generated by GNU Autoconf 2.57. Invocation command line was $ ./configure ## --------- ## ## Platform. ## ## --------- ## hostname = alpha-s16.ajb.org uname -m = alpha uname -r = V4.0 uname -s = OSF1 uname -v = 1229 /usr/bin/uname -p = alpha /bin/uname -X = unknown /bin/arch = unknown /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown hostinfo = unknown /bin/machine = alpha /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /usr/users/ajbddg/edmond/tools2/bin PATH: /usr/users/ajbddg/edmond/tools/bin PATH: /usr/local/bin PATH: /usr/bin PATH: /bin PATH: /usr/sbin PATH: /sbin PATH: /usr/local/bin PATH: /u01/app/oracle/product/8.1.6/bin ## ----------- ## ## Core tests. ## ## ----------- ## configure:1402: checking MACHDEP configure:1511: result: osf1V4 configure:1517: checking EXTRAPLATDIR configure:1532: result: configure:1545: checking for --without-gcc configure:1594: result: no configure:1600: checking for --with-cxx= configure:1621: result: no configure:1640: checking for c++ configure:1656: found /usr/users/ajbddg/edmond/tools2/bin/c++ configure:1666: result: c++ configure:1707: checking for C++ compiler default output configure:1710: c++ conftest.cc >&5 configure:1713: $? = 0 configure:1759: result: a.out configure:1764: checking whether the C++ compiler works configure:1770: ./a.out configure:1773: $? = 0 configure:1790: result: yes configure:1797: checking whether we are cross compiling configure:1799: result: no configure:1802: checking for suffix of executables configure:1804: c++ -o conftest conftest.cc >&5 configure:1807: $? = 0 configure:1832: result: configure:1906: checking for gcc configure:1922: found /usr/users/ajbddg/edmond/tools2/bin/gcc configure:1932: result: gcc configure:2176: checking for C compiler version configure:2179: gcc --version &5 gcc (GCC) 3.4.2 ... From atterdan at yahoo.com Fri Nov 5 04:43:40 2004 From: atterdan at yahoo.com (John Doe) Date: Fri, 05 Nov 2004 09:43:40 GMT Subject: Script Generation, help! References: Message-ID: Some times I think my question are cryptic. text name = a number. Try a dictionary myDict = {} # empty defination myDict[Spam1] = 123939392 myDict[Spam2] = 439322 myDict[Spam3] = 23233.232 Now as to storage with an extension. Thats not so tricky, it's just that your requirement is so vague. To save the data myDict ... import pickle fp = open('myfile.myspecialext', 'w') pickle.dump( myDict, fp ) fp.close() To reload the data ... import pickle fp = open( 'myfile.myspecialext', 'r') myDict = pickle.load( fp ) Now if you have some special format the data is stored in, you may want to visit Parser. I've not had a chance to use it, but the description is pretty neat. Hope this is something like what you want. On Fri, 05 Nov 2004 07:06:15 +0000, digital_ant2 wrote: > > I'm new to python, so I'll be at detailed as I can be. > > I need to generate a script where each line is like this: > > Spam=(x) > Spam=(y) > Spam=(z) > > each entry being on their own line, Spam is a string of text and > x,y,and z are random numbers, I also need it to be exported to a text > file with a specified extension.... being completely NEW to python I > push in the right direction would be really helpfull! > > Thanks, > Pat From peter at engcorp.com Tue Nov 2 09:01:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Nov 2004 09:01:16 -0500 Subject: Newbie question In-Reply-To: <783d0f8c.0411012330.4172d1d4@posting.google.com> References: <783d0f8c.0411012330.4172d1d4@posting.google.com> Message-ID: <8vudnfBCkdi2DhrcRVn-jA@powergate.ca> Uday wrote: > My problem is that I need to dynamically generate a unique > variable within a for loop in Python. The name of the variable > should be appended by the index of the loop. This is rarely a useful thing to do. How do you plan to access the variable in the rest of the code if the name is generated dynamically? Usually, people who think they want to do this should be using a dictionary instead. -Peter From changli_to at hotmail.com Thu Nov 25 12:14:30 2004 From: changli_to at hotmail.com (Chang LI) Date: 25 Nov 2004 09:14:30 -0800 Subject: Use Python library from C++ References: <89cc6e1f.0411241939.61a19596@posting.google.com> <1101364143.006433.314340@z14g2000cwz.googlegroups.com> Message-ID: <89cc6e1f.0411250914.24131f1b@posting.google.com> "Chris S." wrote in message news:... > zhao wrote: > > > Try boost.python and SWIG? > > (boost.sourceforge.net, swig.sourceforge.net) > > > > Both provide a interface between C/C++ and python > > if you want gui under python, you also can try wxpython or pygtk > > I thought SWIG ported C/C++ libraries to Perl, Python, Ruby, Tcl, etc? > How would you use it to port Python into C/C++? > SWIG is for Python to use C++. I am searching for in reverse. > I think what you're looking for is instruction on how to embed Python in > your C/C++ application. From Johannes.Nix at gmx.net Thu Nov 11 16:31:57 2004 From: Johannes.Nix at gmx.net (Johannes Nix) Date: Thu, 11 Nov 2004 22:31:57 +0100 Subject: permuting letters and fairy tales Message-ID: <67lld8kr76.fsf@aster.homelinux.net> Hello, yesterday I met a cute person (after my dance class) who told me about an interesting experiment regarding cognition. People were told to read a typed text; However, in every word in the text, only the first and the last letter were in the right place. The other letters had their positions changed in an arbitrary manner. The surprising result, I was told, was that people can read this mixed-up text fairly well. Because I am a somewhat sceptical guy, at times, and because I thought that I deserved some play, I decided to code the rule above in a scriptlet. The resulting 23 lines are below, and the outcome is quite interesting, not only from the point of view of librarians ;-) : -------------------------------------------------- #!/usr/bin/python import sys import locale import string import re import Numeric import RandomArray locale.setlocale(locale.LC_CTYPE, '') wordsep = re.compile('([^%s])' % string.letters) for line in sys.stdin.xreadlines(): for word in wordsep.split(line): if word and word[0] in string.letters: word = string.lower(word) wlen = len(word) if wlen > 3: wa = Numeric.array(word) perm = RandomArray.permutation(wlen-2) wa[1:wlen-1] = Numeric.take(wa[1:wlen-1],perm) word = wa.tostring() sys.stdout.write('%s' % word) -------------------------------------------------- For the Uninitiated, Numeric is a package which deals with array data; arrays are mutable sequences and Numeric.take() can reorder items in them; RandomArray.permutation() delivers the randomized reordering we need. Now I have two innocent questions: - Is it possible to make it a bit more concise ;-))) ? - Can it coerced to run a little bit faster ? (on my oldish, 300 MHz-AMD K6 , run time looks like this for a famous, 2663-word-long fairy tale from the Grimm's brothers: nix at aster:~> time v real 0m6.970s user 0m3.634s sys 0m0.120s And two remarks what is interesting about it: - It's a good example how powerful libraries, like Numeric, make one's life easier. (BTW, why is Numeric and stuff like take() still not included in the standard Library ? Batteries included, but calculator not ?) - Perhaps it's useful to protect messages in some regions with not-so-democratic forms of government against automatic scanning by making the message machine-unreadable, causing some Orwellian Confusion ;-) ? Of course, texts from Pythonistas would remain suspicious, due to the large number of "y" occurring in them.... have a nice evening.... Johannes From exarkun at divmod.com Wed Nov 10 21:38:48 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 11 Nov 2004 02:38:48 GMT Subject: Sorting email addresses by domain In-Reply-To: <20041111015848.QUUY10582.aamta03-winn.mailhost.ntl.com@Bender> Message-ID: <20041111023848.20649.1359029871.divmod.quotient.2245@ohm> On Thu, 11 Nov 2004 01:58:35 -0000, "Peter Murray" wrote: >Hi! I hope someone can assist me, I have been using Python for a year or > two, but I am not a programmer and only use it occasionally for small issues > or just for fun. So I perhaps do not have the right 'mindset' to always see > the answer to a problem. > > Anyway, I have a list of email address and I want to sort them by domain. > List.sort() wont work as this looks at the start of each address only. So > the answer I have come up with is to split each email address around the > "@", swap the position of the name and domain, build a new list with these > and then sort this. Then switch positions back, and join with an "@". It > works, but it seems a little inelegant. Is there a better, or easier way to > do this? In Python 2.3, def key(addr): parts = addr.split('@') parts.reverse() return parts addresses.sort(lambda a, b: cmp(key(a), key(b))) In Python 2.4, re-using the above definition of key: addresses.sort(key=key) Jp From codedivine at gmail.com Wed Nov 17 04:01:51 2004 From: codedivine at gmail.com (Rahul Garg) Date: 17 Nov 2004 01:01:51 -0800 Subject: arrays References: Message-ID: Hi. Thanks for the help. Its really simple and i shud have thought it myself. Some clarifications : 1. I will mostly be storing floating point numbers in 2 dimensional arrays which i will pass to a custom module written in C. The application is for scientific computing purposes.I just need python + wxPython for the GUI. 2.I am not using Numarray because i dont expect to do many operations on the matrices in Python itself. Most of that stuff will be handled in my C module. The decision of not doing the matrix operations in Python is because most of the C code is already ready. Though it is written as standalone command line app currently , converting it into an extension module shudnt be much of a problem. Rahul John Hunter wrote in message news:... > >>>>> "Rahul" == Rahul Garg writes: > > Rahul> Hi. Is there someway i can get something similar to > Rahul> multi-dimensional arrays in python.I dont want to use > Rahul> Numarray > > Yes, you can use lists of lists for example. > > x = [ [None for i in range(10)] for j in range (12)] > x[1][2] = 1 > > But it would help if you stated what your requirements are for the > multi-dim array, what kind of objects you want to store in them, what > kind of operations you need to be able to do, what your performance > requirements are, and why you don't want to use numarray or Numeric > for that matter. > > > JDH From zanesdad at bellsouth.net Wed Nov 10 08:18:28 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 10 Nov 2004 08:18:28 -0500 Subject: ANN: IPython 0.6.4 is out. In-Reply-To: References: Message-ID: <41921524.3010804@bellsouth.net> Fernando Perez wrote: >Robert Kern wrote: > > > >>Fernando Perez wrote: >> >> >> >>>Thanks! That is indeed my intention, so I'll probably follow your advice. >>>But will this mean that unsuspecting souls using CVS will get HEAD >>>automatically? If that's the case, I'll add a nice warning about HEAD >>>becoming _really_ >>>unstable for a while, so I don't burn anyone. So far HEAD has been the >>>place for users to get cutting-edge bugfixes, so at least I should warn them >>>that this may change in the future. >>> >>> >>You could also leave CVS HEAD as it is and hop on the SVN bandwagon for >>the new version. >> >>Come on! You know you want to! >> >> > >Mmh. I've thought about it. The problem is that I'm addicted to Cervisia >(KDE's CVS gui), esp. to its super-clean graphical diff interface. And SVN >support in cervisia is not there yet, unfortunately. Suggestions? > >f > > > Sounds like you need to get off of that dinosaur of an operating system you're running and move to something a little more modern. Like Windows XP. That way, you can use TortoiseSVN. :-) All joking aside, I've found that TortoiseSVN ( yes, on Windows) is actually a pretty good tool. I do all of my real work on my Linux station, then when I get ready to commit (or what have you), I go to my Windows box, look at the Samba network share, and use Tortoise. I just checked and there is a decent-looking-at-first-glance GUI tool available for SVN called RapidSVN. I downloaded it for Linux, but, alas, it requires wxWindows and I don't have that installed and configured on that box just yet. So, I installed it on ( again) Windows and it doesn't look too bad. I think I'll spend some time today and get RapidSVN running on my Linux box as I would love to be able to do everything from one place. So, if you're thinking about SVN, you may want to take a peek at Rapid (http://rapidsvn.tigris.org/). AFAICT, this is the only GUI client that will work on Linux that is being actively developed. Found a couple of projects on SourceForge, but nothing looks alive. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From frithiof.jensen at die_spammer_die.ericsson.com Thu Nov 25 07:11:12 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Thu, 25 Nov 2004 13:11:12 +0100 Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> <419E6C13.1040508@v.loewis.de> <419fc77d$0$198$9b622d9e@news.freenet.de> Message-ID: "Peter Hansen" wrote in message news:cnrm2b$l0s$1 at utornnr1pp.grouptelecom.net... > Hmm... sounds like they have set the bar very, very low right now... America has become The Land of The Lawyers - neatly illustrated by the replacement of Cowboys, Saloon and Praerie(?) with Armani Suits, Court Rooms and Open-plan Offices on Television programming - so the Lawyer-politicians decided to remove the bar altogether and leave the Lawyer-lawyers to get rich on debating the merits of trivial patents at USD 1000 per hour in the legal system. Eventually the tide will change again. From greg.lindstrom at novasyshealth.com Mon Nov 1 12:01:06 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Mon, 1 Nov 2004 11:01:06 -0600 Subject: Matching Control Characters Message-ID: <00fd01c4c034$612a48d0$054b12ac@D18SYX41> > Use the escape for Control-M: \x0D > Reinhold Thank-you. That does the trick! If you would be so kind, where does one look up the escape values for control sequences? As they say: Build a man a fire and he's warm for a day. Set a man on fire and he's warm for the rest of his life. Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From mrjean1ATcomcastDOTnet at no.spam.net Thu Nov 18 20:22:22 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Fri, 19 Nov 2004 01:22:22 GMT Subject: Wrapping a C library in Python References: Message-ID: <181120041723271813%mrjean1ATcomcastDOTnet@no.spam.net> Take a close look at Pyrex at /Jean Brouwers ProphICy Semiconductor, Inc. In article , Roy Smith wrote: > I've got a C library with about 50 calls in it that I want to wrap in > Python. I know I could use some tool like SWIG, but that will give me a > too-literal translation; I want to make some modifications along the way > to make the interface more Pythonic. > > For example, all of these functions return an error code (typically just > errno passed along, but not always). They all accept as one of their > arguments a pointer to someplace to store their result. I want to > change all that to returning the result directly and throwing exceptions. > > I also want to mutate some of the return types. A common way these > functions return a set of values is a pair of arrays of strings, forming > key-value pairs. In Python, it would make sense to return this as a > dictionary. > > I know what I'm describing is kind of vague, but are there tools around > which might help automate (at least in part) this translation process? From mwm at mired.org Wed Nov 10 16:16:26 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 10 Nov 2004 15:16:26 -0600 Subject: ZIP files References: <808f000f.0411100805.7bff7e5d@posting.google.com> Message-ID: Ivo Woltring writes: > On 10 Nov 2004 08:05:28 -0800, oriana.falco at thalesesec.com (Oriana) > You might wish to try using a larger buffer than 8192 bytes. BTW, > note that Python automatically closes the files since the file objects > are released when the function returns. This behavior of file objects isn't guaranteed and doesn't happen in Jython. It's better - and more pythonic - to explicitly close files. After all, explicit is better than implicit. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From zach at cs.uni-bonn.de Fri Nov 5 11:05:53 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 5 Nov 2004 16:05:53 GMT Subject: inferred typing References: Message-ID: Thanks for your responses. Both Boo and Starkiller sound quite interesting. Boo seems to have some momentum, but what about Starkiller, once the PhD is finished? Also, both are python compilers. I was hoping for something more like Hotspot for Java, i.e., something which compiles parts of the python script that turn out not to be really dynamic at run-time and that are executed a lot. Anything along those lines? In addition, I am not sure that any effort that is not integrated into mainstream Python will have a real chance to achieve widespread use ... Best regards, Gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From msw at iee.lu Fri Nov 5 06:17:44 2004 From: msw at iee.lu (Manfred Schwab) Date: Fri, 05 Nov 2004 12:17:44 +0100 Subject: Python for 8/16 Bit MSDOS ( 486 / 586 / K5 / K6/ Beck-IPC ) processors. Message-ID: <418B6158.3C7BD9B1@iee.lu> Hi there, which versions of python are usable under MS-DOS 5.0 oder 6.22 or Dr. DOS. I want to use it under a industrial environment to collect measuring data like temperature, moist and signalconditions with a Beck industrial PC. Did somebody try this already ? Is there a certain URL where i can get further information. Thanks in advance for help. Manfred -- This e-mail may contain trade secrets or privileged, undisclosed or otherwise confidential information. If you are not the intended recipient and have received this e-mail in error, you are hereby notified that any review, copying or distribution of it is strictly prohibited. Please inform us immediately and destroy the original transmittal from your system. Thank you for your co-operation. -------------- next part -------------- A non-text attachment was scrubbed... Name: msw.vcf Type: text/x-vcard Size: 348 bytes Desc: Card for Manfred Schwab URL: From gregory.lielens at fft.be Sat Nov 27 08:19:10 2004 From: gregory.lielens at fft.be (gregory lielens) Date: Sat, 27 Nov 2004 14:19:10 +0100 Subject: subclassing extension type and assignment to __class__ Message-ID: <41a87eb5$0$13482$ba620e4c@news.skynet.be> Hello, I am currently writing python bindings to an existing C++ library, and I just encountered a problem that I hope has been solved by more experienced python programmers: A C++ class (let's call it CClass) is binded using classical Python extension API to _PClass, which is accesible through python without any problem. The problem is that I want this class to be extended/extensible in python, and expose the python-extended version (PClass) to library users (_PClass should never be used directly nor be retruned by any function). The aim is to leave only performance critical methods in C++ so that the binding work is minimal, and develop the other methods in python so that they are easier to maintain/extend. We thus have something like this class PClass(_PClass): def overide_method(self,...): ... def new_method(self,...): ... and I can define a=PClass() and use my new or overiden method a.overide_method() a.new_method() as intended... So far, so good, trouble begin when I have a method from another class PClass2 derived from _PClass2 which bind the C++ class CClass2, that should return objects of type PClass: Let call this method troublesome_method: b=_PClass2() c=b.troublesome_method() type(c) gives _PClass. now I want to define a python class PClass2 for extending methods of _PClass2 like I have done for _PClass, in particular I want that PClass2 troublesome_method return objects of type PClass instead of _PClass... To this end I try something like this class PClass2(_PClass2): ... def troubelsome_method(self): base=_PClass2.troublesome_method(self) base.__class__=PClass and I have python complaining about TypeError: __class__ assignment: only for heap types... It seems thus that my approach is not possible, but problem is that I can not see another approach that would not involve far more efforts that this one (I have the impression I have to forget about making my PClass derived from _PClass, but instead embed a _PClass instance in PClass, far from ideal cause I would have to reimplement all method, not only those that I want to change :( ) This is particularly frustrating cause I also have the impression that want I want to do was at one time possible in python, let say in 2002-2003, when __class__ was already assignable but before assignment was forbidden for non-heap types Any hint on this problem? Thanks, Greg. From roy at panix.com Tue Nov 30 08:45:45 2004 From: roy at panix.com (Roy Smith) Date: Tue, 30 Nov 2004 08:45:45 -0500 Subject: comment out more than 1 line at once? References: Message-ID: Riko Wichmann wrote: > I'm using emacs (with python-mode) to do most of my editing. also tried > IDLE from python already, which is nice but an old dog doesn't like to > learn new tricks :) Emacs is great for stuff like this. There's probably other ways to do it, but what I would do is a quick keyboard macro. Go to the beginning of the first line and type: C-X ( # C-A C-N C-X ) That defines a macro which inserts a # then moves to the beginning of the next line. Then you need to execute that once for each additional line you want to comment out. If there's 17 additional lines, you would do: C-U 1 7 C-X E Hmmm. I just did help-appropos on "comment" and of course I found the better way I suspected must exist :-) You can just use M-X comment-region or M-X py-comment-region. Still, learning how to do keyboard macros will really improve your productivity in emacs. There's often a better way to do something, but for simple repetitive tasks, you can often write and execute a keyboard macro faster than you can look up the better way. From hugh-m at moving-picture.com Fri Nov 19 11:21:44 2004 From: hugh-m at moving-picture.com (Hugh Macdonald) Date: Fri, 19 Nov 2004 16:21:44 GMT Subject: Embedding/Extending Python at the same time... Message-ID: <20041119162144.787ca7c2.hugh-m@moving-picture.com> I've got a slight problem... and I'm stuck as to where to go with it... I'm running on Redhat7.2, using Python 2.2.2 I've got a compiled module that I wrote almost a year ago - it works fine, and I've never had any problems with it... I also did an extension to a plugin (Shake) using Python, so the plugin loads a python module and calls various functions in there.... all in all, fine - I thought I had my head around the system, and there were no problems... However, I've just hit a problem... If, in my plugin code, I import a module that is pure python, I'm fine. However, if I import my own compiled module, then I start having problems.... Initially, the module was compiled without linking to the actual python library. When I run the plugin, it fails, and PyErr_Print() prints out: Traceback (most recent call last): File "/usr/people/hugh-m/dev/apps/hub/python/modules/noarch/hubdbremote.py", line 19, in ? import hub ImportError: /usr/people/hugh-m/dev/apps/hub/python/modules/linux.redhat7.2.i386/hub.so: undefined symbol: PyFloat_Type If I modify the SConstruct file so that the module links to the python library, it gives the following error: Fatal Python error: Interpreter not initialized (version mismatch?) Any idea what I could do to get around either of these? Should python modules be compiled with the library linked in? The plugin is compiled with gcc3.2.1 (needed because it's a Shake plugin), and the module is compiled with gcc2.96 (because that is what Python needs it to be). Is this my issue? If so, how can I get around it? Any suggestions most welcome... and apologies for the large number of questions.. Cheers -- Hugh Macdonald The Moving Picture Company From news at svha.demon.co.uk Fri Nov 19 15:22:27 2004 From: news at svha.demon.co.uk (Svha) Date: Fri, 19 Nov 2004 20:22:27 +0000 Subject: Telnetlib & Term Types Message-ID: Greetings I'd like to do some tweaks on a telnet session as I have no control over the server side what so ever. However I cannot correctly negotiate a telnet connection to the server. I've gone back to basics on the code for simplicity here; Linux 2.6 : Python 2.3.4 Telnetlib Module - http://www.python.org/doc/2.3.4/lib/module-telnetlib.html import sys, telnetlib tn = telnetlib.Telnet("xxx.xxx.xxx.xxx") tn.mt_interact() All goes well if I point this code to telnet to 127.0.0.1 (Login etc) However if I point the code to telnet to the server I get; Debian GNU/Linux 3.0 xxx.xxx.org Error opening terminal: network. Note - telnet from the console to this address works fine. I have limited knowledge of telnet/terminals however I am beginning to think that the "server" is trying to negotiate a terminal type (vt100/vt220 I think) and telnetlib responds incorrectly/not at all. Any thoughts would be much appreciated / is there a more suitable library than telnetlib for my purpose? Many thanks ..... Svha From dave at pythonapocrypha.com Wed Nov 17 11:21:33 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 17 Nov 2004 09:21:33 -0700 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: <30001hF2ptnqcU1@uni-berlin.de> References: <30001hF2ptnqcU1@uni-berlin.de> Message-ID: <419B7A8D.9080501@pythonapocrypha.com> Greg Ewing wrote: > Jeremy Bowers wrote: > >> Generally, returning a tuple is either a sign that your return value >> should be wrapped up in a class, or the function is doing too much. > > > While I suspect you may be largely right, I > find myself wondering why this should be so. *Is* it largely right? I don't think so. As you said, there doesn't seem to be anything "wrong" with passing multiple pieces of data _into_ a function, so why should we assume that complex data passing should be so one way? One of my biggest pet peeves about programming in C, for example, is that you are often forced to wrap stuff up into a structure just to pass data back and forth - you create the structure, populate it, send it, and then pull out the data. In many, many cases this is nothing more than poor-man's tuple unpacking, and you end up with lots of extra work and lots of one-off structures. Also annoying is the use of "out" parameters, which is again basically manual tuple unpacking. Python isn't too different from C wrt deciding when to move from "bare" parameters to a structure or object - is the number of parameters becoming cumbersome? are the interrelationships becoming complex? will I need to use those same parameters as a group elsewhere? etc. The difference is that Python facilitates more natural data passing on the return. A function like divmod is a prime example; rather than having div = 0 mod = 0 divmod(x,y, &div, &mod) we instead have the much more elegant div, mod = divmod(x,y) We can definitely come up with some hints or guidelines ("if your function returns 10 parameters, that's probably bad" or "if the parameters are tightly coupled and/or are often used & passed along together to different functions, you probably should wrap them into an object"), but I don't think returning tuples is _generally_ a sign of anything good or bad. -Dave From tuglyraisin at aol.commcast Wed Nov 17 00:43:10 2004 From: tuglyraisin at aol.commcast (Andrew Burton) Date: 17 Nov 2004 05:43:10 GMT Subject: COM/IIS permissions question Message-ID: <20041117004310.22097.00000923@mb-m06.aol.com> Anyone know where else I can find instructions for "Launching OLE Servers from ISAPI Extensions"(1). I followed those instructions, even went so far as to give a few other accounts permission, but my Python -- that's Python 2.2 -- script keeps given me the following error: [error] Traceback (most recent call last): File "D:\JAROD\programming\python\pycgitunes\pycgitunes.py", line 12, in ? iTunes = win32com.client.Dispatch("iTunes.Application") File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 92, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2146959355, 'Server execution failed', None, None) [/error] Here's the code I'm using, in case anyone's curious -- this is my first, REAL Python program, so maybe it's just a glitch. Hoever, a thread from mail.python.org's archives(2) and the fact that it works from an Interactive shell makes me think that the ISAPI/COM security problem is the key. Anyway, code... [code] # Libraries import cgi import cgitb import win32com.client # COM stuff iTunes = win32com.client.Dispatch("iTunes.Application") # global variables form = cgi.FieldStorage() ##### # Subroutines # main code cgitb.enable() print "Content-type: text/html\n\n" print "Hello, world" [/code] Any help would be appreciated -- any IIS/Python tips especially. Thanks! --- 1. http://support.microsoft.com/kb/q156223/ 2. http://mail.python.org/pipermail/python-list/1999-November/015411.html Andrew Burton - tuglyraisin at aol dot com Felecia Station on Harvestgain - Jarod Godel in Second Life From brion at pobox.com Tue Nov 16 18:09:24 2004 From: brion at pobox.com (Brion Vibber) Date: Tue, 16 Nov 2004 15:09:24 -0800 Subject: Identifying bundles in MacOS X In-Reply-To: References: <2vt7veF2nues7U1@uni-berlin.de> <2vtsp6F2nlt2cU1@uni-berlin.de> Message-ID: <2vvfkvF2qc181U1@uni-berlin.de> Michael Tsai wrote: > On Nov 16, 2004, at 3:41 AM, Brion Vibber wrote: >> LSItemInfoRecord info; >> LSCopyItemInfoForURL(url, kLSRequestAllInfo, &info); > > I suggest using kLSRequestAllFlags instead of kLSRequestAllInfo, to > avoid leaking the strings in the LSItemInfoRecord. Whoops, thanks for pointing that out! -- brion vibber (brion @ pobox.com) From mwm at mired.org Fri Nov 19 18:51:44 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 19 Nov 2004 17:51:44 -0600 Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> <419E6C13.1040508@v.loewis.de> Message-ID: "Martin v. L?wis" writes: > Neal D. Becker wrote: >> Doesn't Python (along with probably every other language ever invented) >> display prior art here? > > Wrt. claim 1, yes. Actually, C is prior art here: you have two > expressions representing pointers, and you have a system where > you can determine that the pointers refer to different memory > locations. LISP has had NEQ for about 40 years. Can they actually get away with patenting the spelling of the keywords in a language? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From crjensen at gmail.com Fri Nov 26 18:48:12 2004 From: crjensen at gmail.com (Chris) Date: 26 Nov 2004 15:48:12 -0800 Subject: win32 problem with WM_COPYDATA Message-ID: Hi. I'm trying to make a python program that can recieve WM_COPYDATA messages. Not ideal, but the application I'll be receiving them from will only send it that way. So I wrote a small program to try to receive them, and a smaller one to send test messages. It't not happening for some reason. I'll post both below. The program that sends the test message finds the receiver ok, and SendMessage returns 0, but the receving program never calls its copydata handler. Any thoughts? Discalimer: I haven't done windows in years, so am kind of clueless about it now, but based on what I've seen around google, this seems ok. Never actually saw an example of someone recieveing messages though... only sending. BTW - the try/except thing around UnregisterClass is catching an invalid handle error for hinst. Not sure where that's coming from, but it still seems to unregister the class... so I'm happy for now... at least until I figure out my other issue. Any thougts on this error are welcome too. **code** # Recieving prog import sys import win32gui import win32api import win32con class gsWindow: def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COPYDATA: self.OnCopyData, } wc = win32gui.WNDCLASS() wc.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpszClassName = "QServer" wc.lpfnWndProc = message_map self.hinst = wc.hInstance = win32api.GetModuleHandle(None) self.cAtom = win32gui.RegisterClass(wc) print 'hinst: %s' % self.hinst self.hwnd = win32gui.CreateWindowEx( win32con.WS_EX_APPWINDOW, self.cAtom, "QuoteServer App", win32con.WS_OVERLAPPED | win32con.WS_SYSMENU, win32con.CW_USEDEFAULT, 0, win32con.CW_USEDEFAULT, 0, 0, 0, self.hinst, None) win32gui.ShowWindow(self.hwnd, win32con.SW_SHOWDEFAULT) win32gui.UpdateWindow(self.hwnd) def OnCopyData(self, hwnd, msg, wparam, lparam): print 'copydata(%s, %s, %s, %s)' % (hwnd, msg, wparam, lparam) def OnDestroy(self, hwnd, msg, wparam, lparam): win32gui.DestroyWindow(self.hwnd) try: win32gui.UnregisterClass(self.cAtom, self.hinst) except: pass win32gui.PostQuitMessage(0) def main(): w = gsWindow() win32gui.PumpMessages() main() ****** # Sending prog import struct import win32con import win32gui def main(): wnd = win32gui.FindWindow("QuoteServer", None) print wnd result = [] buff = struct.pack('11s', "XXXXX: YYYY") print win32gui.SendMessage(wnd, win32con.WM_COPYDATA, 0, buff) return main() From keith1377 at hotmail.com Sun Nov 7 04:58:50 2004 From: keith1377 at hotmail.com (keith) Date: 7 Nov 2004 01:58:50 -0800 Subject: EVIL FBI SADISTS should be KIDNAPPED and TORTURED for 3 YRS Message-ID: <34b3545c.0411070158.6532e02@posting.google.com> Someone emailed and requested me to post it on Usenet newsgroups. Sadistic FBI agents should be tortured the way how FBI sadists and perverts tortured this poor guy (non-muslim) for three years and continue to torture him even after he left america tracking him with implanted transponder chips and other methods. FBI is an evil organization and those FBI sadists and perverts deserve to be kidnapped and their eyes gouged, noses and ears chopped off, forced to eat their own feces and drink their own piss and extra hot red chilli powder poured into their eyes, make them cry and scream in pain and continue the torture mercilessly for three yearss to do justice to this poor guy. FBI sadists and perverts deserve every bit of torture these animals meted out to this poor chap. Evil FBI organization deserves 10000 Tim McVeighs and 10000 Osamas who should have gone after the vertical edgar hoover building instead of the horizontal pentagon or the fed building in oklahoma city. Half the worlds evil resides in edgar hoover building in Washington DC. Email I got: ************************************************************************************************* If you are a US Govt "PROGRAMMED SLAVE and MORON" OBSESSED with tin foils, aluminium foils, schizo meds etc I KINDLY REQUEST YOU to IGNORE the rest of this column and move on to the next post in the news group. Undercover FBI agents will attack me, ridicule me and discredit me with fictitious userids in response to this post and I request all readers to completely IGNORE those MANIPULATIVE, LYING FBI PERVERTS, SADISTS and THUGS. Email this column to all your friends, family members, coworkers and if you are done, then just send it to every email id in USA and OVERSEAS you can find on usenet. That will DRIVE the FBI SADISTS and PERVERTS ABSOLUTELY CRAZY. We the POWERLESS should UNITE and MENTALLY TORTURE the INFINITELY POWERFUL FBI SADISTS in every way possible. FBI sadists HATE PUBLICITY and EXPOSURE and hence please do whatever you can asap. IMAGINE a MILLION EMAILS containing this story going around the world and VISUALIZE how much it will DRIVE these FBI daughterfuckers CRAZY. Come on, we the POWERLESS can do it. To the rest of the LOW IQ MORONS who attacked and suggested I take schizo meds and cover myself with tin foils and aluminum foils: I already KINDLY REQUESTED YOU US Govt "PROGRAMMED SLAVES AND MORONS" to IGNORE the rest of the post in the VERY FIRST PARAGRAPH. Are you THAT FUCKING DUMB you cannot comprehend SIMPLE ENGLISH ? FBI SADISTS could possibly have installed a transponder chip in my body like Ethan did to Nyah in Mission Impossible 2. If any of you are KNOWLEDGEABLE about how to find transponders implanted using any methods including X-Rays, please post some relevant information here and HELP ME. It would be greatly appreciated. Undercover FBI SADIST J NIcklebaker listed in this column was able to figure out PRECISELY, the day I left home even though I am 8500 miles away from US borders and he could have done it ONLY by TRACKING ME with an implanted transponder chip in my body. 10/10/04 J NIcklebaker (Undercover FBI agent monitoring my websurfing activities) posted anonymously using Newsguy Usenet Service Provider in alt.liberalminded newsgroup and THREATENED ME. http://groups.google.co.in/groups?hl=en&lr=&threadm=8boim0p7tpeo9p991segp7o7bd4h7ov32s%404ax.com&rnum=4&prev=/groups%3Fhl%3Den%26lr%3D%26q%3DNicklebaker%26meta%3D You can educate yourself more about the EVIL FBI SADISTS and PERVERTED motherfuckers by reading these websites. www.datafilter.com/mc www.informationclearinghouse.info/article5637 www.4verichip.com/index.html PERVERTED FBI agents SEXUALLY ABUSED, RAPED and TORTURED ME for THREE YEARS which is 10000 times worse than the SEXUAL ABUSE of prisoners by Lyndie England though I am NEITHER an iraqi NOR a muslim. If the PERVERTED FBI agents can watch me real time live attending natures call and taking shower and other private moments in my rest room, bed room, living room and kitchen and HUMILIATE, DEHUMANIZE and SEXUALLY ABUSE me FOR THREE YEARS ILLEGALLY and AMUSE THEMSELVES, then the FBI SADISTS and SEX PERVERTS deserve to be ruthlessly BEHEADED and more. Remember, SADISTIC FBI DID NOT FOLLOW THE RULES, so NOBODY in the world has to follow the rules and the FBI agents SHOULD NOT have ANY IMMUNITY and are GAME for ANYBODY and EVERYBODY. It is as simple as that. You can SELL this FBI NOC LIST and MAKE MILLIONS like Tom Cruise (I know it is a CIA NOC LIST in MI) did in Mission Impossible. Please SAVE this post on your hard disks or email account and also bookmark it because the FBI SADISTS and PERVERTS are gonna force the websites to remove this posting for good. I ADDED a few more undercover FBI agents to the NOC LIST and also a few more facts about FBI. I request all you HACKERS on usenet to HACK these undercover FBI agents IP addresses and trace their REAL IDENTITIES and post the info here. I posted this on 10/26/04 just a few days ago and used keithm757 at yahoo.com and keithm757 at volcanomail.com to receive emails from newsreaders but the SADISTIC FBI "FORCED" both "yahoo" and "volcanomail" to CHANGE THE PASSWORDS and CLOSE my email accounts by the morning of 10/27/04. So if you are interested in helping me, please post your responses (anonymously if possible) on the web itself instead of emailing me. Somebody on the usenet suggested that I file a complaint with the District Attorney about FBI HARASSMENT and MENTAL TORTURE but an attorney by the name James Eidson (404-763-3401) with a RATING of "AV" on www.martindale.com website ADVISED me NOT TO file a complaint with US Attorneys office for reasons unknown to me. http://www.martindale.com/xp/Martindale/Lawyer_Locator/Search_Lawyer_Locator/search_result.xml?PG=0&STYPE=N&LNAME=Eidson&FNAME=James&FN=&CN=&CTY=&STS=11&CRY=1&LSCH= I am NOT a conspiracy theorist and everything I mentioned here actually happened to me and are ABSOLUTE FACTS. Even the psychiatrist REALIZED that all these things I mentioned are FOR REAL and ADVISED ME to leave US. To all of the 95% low IQ morons on usenet who accused me of schizo paranoia and looking for attention and asked me why I was cross posting to irrelevant newsgroups: Here is my answer. 1) I WANT ALL OF YOU to FOCUS on the FBI SADISM, PERVERSION, SEXUAL ABUSE and their BLATANT violation of human rights of an ordinary US citizen. 2) I want all of you to STAND UP and ask the EVIL, PERVERTED and SADISTIC FBI why they have to install video devices and watch me in my rest room, bedroom, living room and kitchen and PSYCHO-ANALYSE me 24X7 for three years and TORTURE, TERRORIZE, HUMILIATE and DEHUMANIZE me. 3) I am posting to this to all active newsgroups to EXPOSE the "INSTITUTIONALIZED FBI SADISM, PERVERSION and their SEXUAL ABUSE of ordinary US citizens. 4) FBI SADISTS, PERVERTS and TERRORISTS are LAUGHING their asses off reading you clowns' comments in response to my post on usenet because all you 95% "PROGRAMMED SLAVES" BEHAVED exactly the way the FBI SADISTS "PROGRAMMED" your minds. 5) There are very few intelligent guys who responded to my post and one of them is "bookwyrm" who figured why I was posting this to all active newsgroups and another by anonymous name "assassians" and another by the name "Anatid" who tried to really help me. http://groups.google.co.in/groups?hl=en&lr=&threadm=c54f0abe.0410100848.a515cf7%40posting.google.com&rnum=2&prev=/groups%3Fhl%3Den%26lr%3D%26q%3DFBI%2BSADISM%26meta%3Dgroup%253Dalt.security.alarms http://groups.google.co.in/groups?hl=en&lr=&threadm=415af813%40news.bnb-lp.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26q%3DFBI%2BSADISM%2Bbookwyrm%26meta%3D SADISTIC and PERVERTED FBI has beeen MENTALLTY TORTURING, TERRORIZING and SEXUALLY ABUSING me and BLATANTLY violating my civil rights non-stop for three years. Please forward and distribute this to as many senators, congressmen, journalists, editors, civil rights attorneys, civil rights activists, investigative reporters, radio talk show hosts, managers, co-workers, family and friends and all Americans concerned with civil liberties. I am not a muslim, I don't have even a single muslim friend, I am not a member of any religious organization, I am not a drug smuggler, I do not belong to any crime mafia, I did not kill anybody, I am not a spy and I never ever worked for any government and not even "remotely connected" to any government agency whatsoever, I do not have any prior criminal record, I am a US citizen and have been living in US for a little more than 15 yrs and I graduated with a masters degree in computers from a US university more than a decade ago. I am even willing to take "ANY NO.OF POLYGRAPH TESTS" to prove whatever I said is true and a fact, about my background. FBI has been MENTALLY TORTURING me with 24X7 surveillance for the last three years inside and outside my apartment with video surveillance devices and motion sensors around my apartment, my phone has been tapped, my web surfing is being monitored all the time for the last three years, my emails are being monitored, gps vehicle tracking devices and voice amplification devices have been placed in my car and undercover FBI agents have followed me to restaurants, grocery stores, malls, movie theatres, banks and even barber shops etc and forced me to live like an animal and a virtual prisoner for three years. FBI has interfered in my personal life for no reason and jeopardized my job opportunities. FBI is obsessed with me and has ruined, destroyed and wrecked my life for the last three years and destroyed my physical and mental health. The SADISTIC FBI agents are NOT charging me, NOT letting me find a job, NOT letting me have a normal life, NOT letting me have even an IOTA of PRIVACY and mentally TORTURING and TERRORIZING me with 24X7 surveillance, making 2000 UNSOLICITED phone calls to my unlisted phone#s, entering my apartment ILLEGALLY and STEALING personal belongings when I am not home, watching me real time live with video surveillance devices installed in my bedroom, living room, kitchen and DISGUSTINGLY even in my rest room and humiliating and dehumanizing me and BLATANTLY violating my civil rights and constitutional right to privacy and ABUSING the "DRACONIAN" PATRIOT ACT. The PERVERTED FBI "ILLEGALLY" installed tens of audio and video surveillance devices in my apartment, watching me NAKED, REAL TIME LIVE 24X7 even in my rest room taking shower, psychoanalyzing each and every move, each and every word I said, each and every second of my life, each and every blink of my eyes and each and every comment I posted on the web. Is there a LIMIT to FBI Sadism and Perversion ?? I spoke to at least 200 attorneys in both Michigan and Georgia for legal help but only about two or three attorneys were willing to help me but asked me to show physical proof of either gps or video surveillance devices. I did a lot of research and found a couple of private investigators (who were ex-FBI agents) more importantly who are knowledgeable about the latest "counter surveillance technologies" but they also DECLINED to help me on ONE PRETEXT or the OTHER even though I was willing to pay for their services. I told these two very HIGHLY QUALIFIED and KNOWLEDGEABLE private investigators Niles (Eagle services 866-691-7985) and another PI, Charles Middlestadt (404-252-5322) of ISC Worldwide Inc in the Atlanta area who are capable of finding the gps vehicle tracking devices in my car, that I am NOT A MUSLIM and they have NOTHING TO WORRY ABOUT ME and even offered them to go through my attorney and help me but still THEY DECLINED to help me OUT OF FEAR that I might be a muslim. Another Private Investigator by the name John Weeks (800-398-2775 or 770-220-1912) of Investigative Solutions www.invsol.com in Atlanta told me that it would be IMPOSSIBLE to find out these video, audio and gps surveillance devices if the GOVERNMENT (FBI) is doing it. I even went to their office personally and spoke with the founder of www.invsol.com Mr. Harold Copus whose picture is shown on the website and Mr John Weeks. And eventually I was forced to spend a $1000 as fees out of sheer desperation knowing fully well that the Private Investigator I hired has at best AVERAGE counter surveillance skills to sweep my car for gps vehicle tracking devices and he did a LOUSY JOB and found nothing, as I expected. Some attorneys I consulted told me in very CLEAR TERMS that FBI agents LIE, MANIPULATE, CHEAT and are VERY UNETHICAL in their MEANS and METHODS. The attorneys also told me that in order for me to file a civil lawsuit against the FBI, I have to PROVE the existence of surveillance devices and also the MENTAL TORTURE, the SEXUAL ABUSE and TERRORISM which will be quite a tall order for me to do without the help of willing attorneys and helpful private investigators and EVEN THEN the FBI sadists would have removed all those surveillance devices by the time the private investigators came to sweep my apartment for those devices after a couple of days since the FBI is listening to each and every goddamn word that came out of my mouth whether it be in my apartment or when I was speaking to these PI's and attorneys from pay phones or cell phones. You can investigate these undercover FBI agents yourself and find out the truth. Remember, some times vehicles are registered in parents or spouses names and also FBI uses fictitious front companies to employ their undercover agents. If any of you think, all these things are my paranoid delusions, I CHALLENGE you to send an email to undercover FBI agent Frank Spodek (sfrank9 at aol.com) OR call Kathleen Sue Taylor OR Maddelina Wahl OR Mediha Krijestorac or Janet Lorna Brown or the other FBI agents I listed at their phone numbers and confirm it with those FBI PERVERTED SADISTS themselves. Undercover FBI agents who followed me (partial list) ------------------------------------------------------------------------- 313-354-7380 Internal unlisted FBI# in Detroit office from which FBI agents called and harassed me at home in 2001. BOGEY 27 (MI) Registered to Maddelina C Wahl, 28087 Hickory Dr, Farmington.Hills MI 38331, ph: 248-324-1527, Caucasian Female, black car, Charter One bank, 3:00 pm, 12/20/03 This undercover FBI agent who followed me was a 30 yr old Caucasian Female to Charter One bank on W.12 Mile Road, Farmington Hills, MI in veh plate # BOGEY 27, ph:248-324-1527 PPL 587 (MI) Registered to Kathleen Sue Taylor, African American female, 29390 Bermuda Ln,Southfield, MI 48034, ph: 248-356-1946. This undercover FBI agent who followed me was a 27yr old African American female in MI veh plate# PPL 587 in July 2002 in a CVS Pharmacy on W.12 Mile Rd, Southfield, MI XRA 155 (MI) Registered to Mediha Krijestorac, Black car, 30408 Shiawasee Rd, Farmington MI 48336, ph:248-477-9161, White Male, Restaurant, 9:00pm, 12/12/03 This undercover FBI agent who followed me was a 20-22 yr old Caucasian Male in veh plate # XRA 155 to a restaurant on Grand River Ave in Farmington Hills, MI at 9:00 pm on 12/12/03. UFX 210 (MI) Registered to Kevin Miller, White SUV, 5871 Seneca St, Detroit, 48213, July 2002, 313-571-1095 #disconnected. This undercover FBI agent followed me in July 2002 at around 10:00 pm on Northwestern highway in bloomfield hills, MI. 5915CR (MI) Registered to Kenneth Allen, Red pickup truck, 18440 Alta Vista Dr, Southfield MI 48075 in Dec 2002. This FBI undercover agent followed me in a red pickup truck in an apartment complex was a 27-33 yr old Caucasian male in veh plate# 5915 CR in Dec 2002. 0978 JD (MI) Registered to Janet Lorna Brown, White Chevy, 20978 Delaware St, Southfield MI 48034 in 2002, ph# 248-350-2599 This FBI agent followed me in a white chevy once on Telegraph road on 3/14/02 and on a different occasion on 8 Mile Rd on 4/4/02 when I went for an oil change. 8CK U33 (MI) Registered to Doris Evelyn Person, 3611 S.Annabelle St, Detroit 48217, 313-388-5186 The African American female undercover FBI agent who followed me in MI veh plate# 8CK U33 was about 20 yrs old and might be a daughter of the female owner of this car and this happened in early Fall of 2002. 073 D1U (MI) Registered to Scott Alan Smith, 7536 Gary St, Westland MI 48185 This 25 yr old caucasian male undercover FBI agent about 25 yrs old followed me near my apartment in the fall of 2002. phone# 734-261-1587 in fall of 2002 (Disconnected) LQE 620 (MI) SUV, Registered to Samuel Pilato, 40460 Cove ct, Plymouth, MI 40460 Ph# 734-420-0521, 3/14/02 11:30AM This caucasian undercover FBI agent about 35yrs old followed me to a library in the spring of 2002 on Telegraph Rd, Southfield, MI EBAY Ebay Id: SpodekModek, sfrank9 at aol.com --> email Id of Frank Spodek - Undercover FBI Agent who monitored my Websurfing activities. You can do a quick investigative test by emailing to sfrank9 at aol.com and asking Frank if he is an undercover FBI agent and I am absolutely positive he WONT respond and DENY he is an FBI agent because then it will be a LIE. With this test you can conclude Frank Spodek is indeed an undercover FBI agent. EBAY Ebay Id: cbsan, cidneybetz at aol.com, email Id of Cidney Betz - Undercover FBI agent who monitored my websurfing activities in 2002. Possible old phone numbers of Cidney Betz: 407-370-3043 or 352-291-2112 in the year 2002. 351 FTK (GA) Maroon Car, 7/28/04, 6:00 pm, 20ish Caucasian Male and Female, Metro Atlanta 131 YBP (GA) 35 yr old Caucasian Male, Silver colored car, 7/22/04, 10:45 pm, Hotel, Metro Atlanta APZ 7647 (GA) 35 yr old Caucasian Male, Truck, 5/25/04, 3:00pm, Ridgeview Hospital, Metro Atlanta YUU 243 (GA) Pickup truck, Caucasian male, 8/25/04, 4:40pm, Holcrombe Bridge Rd, Metro Altanta AQG 2185 (GA) 27 yr old Caucasian Female, Red Cherokee, 5/21/04, 11 AM, Pep Boys, Cobb Parkway, Metro Atlanta WPS 578 (GA) SUV, One Caucasian Male and one female, 3/8/04, 8:30pm, Apartment Complex Coipel 770-577-0526 (5/2/04, 5:29pm), 4337 Lodgeview pl, Douglasville, GA 30315. undercover FBI agent in metro Altanta area. Ronnie Hill 678-755-2034 in June 2004 - Possibly an FBI agent Please allow three years plus or minus to the ages of the undercover FBI agents I mentioned here. 2/29/04 Undercover FBI agent with a fictitious name "Agent Johnson" and IP address 81.132.210.89 said on internet that they are using me as a training target and have got a bet on as to when I'll do something really stupid and also they are taking bets on what it will be in alt.astrology Usenet newsgroup on 2/29/04. This FBI agent from Michigan field office might have posted it anonymously and hence the IP address might be a fake one. Url for Agent Johnson's post follows. http://groups.google.com/groups?hl=en&lr=&selm=c1u06b%24780%241%40titan.btinternet.com&rnum=19 3/21/04 Undercover FBI agent by some fictitious internet name "THOR" and email Id: funk_a_del_ic2000 at yahoo.com and IP address 24.94.125.55 in the Washington DC area monitored my web surfing activities and posted on rec.sport.cricket Usenet news group. 10/10/04 J NIcklebaker (Undercover FBI agent monitoring my websurfing activities) posted anonymously using Newsguy Usenet Service Provider in alt.liberalminded newsgroup and THREATENED ME. http://groups.google.co.in/groups?hl=en&lr=&threadm=8boim0p7tpeo9p991segp7o7bd4h7ov32s%404ax.com&rnum=4&prev=/groups%3Fhl%3Den%26lr%3D%26q%3DNicklebaker%26meta%3D 10/6/04 Leonard (Undercover FBI agent monitoring my websurfing activities) with real IP address 24.209.79.66 (This IP address can be hacked) posted in rec.audio.car newsgroup http://groups.google.com/groups?hl=en&lr=&selm=263696fd.0410060414.319fd404%40posting.google.com 10/15/04 Els (Undercover FBI agent "Els" monitoring my websurfing activities) with probably fake IP address 82.169.229.173 posted in alt.test newsgroup http://groups.google.com/groups?selm=416fff7f%240%2444105%245fc3050%40dreader2.news.tiscali.nl&output=gplain I am absolutely confident all the above mentioned people are undercover FBI agents GUARANTEED. You can investigate them yourself and find out the truth. I request all you HACKERS on usenet to HACK these undercover FBI agents' IP addresses and trace their real REAL IDENTITIES and post the info here. FBI who is supposed to catch terrorists are WASTING humongous amount of tax payers money to ruin, wreck and destroy ordinary peoples lives and are MORE INTERESTED and spent three years to tell me how SMART and INFINITELY POWERFUL they are compared to me. FBI has even been eavesdropping, monitoring and recording my conversations with attorneys from pay phones when I was looking to hire an attorney to get help with this FBIs harassment, dehumanization, humiliation and mental torture. FBI agents have been entering my apartment regularly and torturing me by doing whatever they want because they know I am taking medication that puts me to sleep and I won't wake up until the next morning until the drug effect goes away. FBI has forced Google or used some technology at their disposal to cancel some of my comments from getting posted on INTERNET newsgroups misc.legal, trial.misc.legal from a library in Farmington Hills, MI and denied and VIOLATED my right to FREEDOM OF SPEECH in 11/03 or 12/03. I moved in with another person (who advertised on a website for a room mate) on 5/24/04 and I went out in his car on the night of 5/25/04 and the next morning 5/26/04, at 9:30am the SADISTIC FBI called me and made this phone# 678-560-1322 and the caller name "LOOKING FOR YOU" appear on my caller id to tell me, "Oh we were LOOKING for you last night, we did not know where you were because you went out in your room mates car". The sadistic and perverted FBI "ILLEGALLY" installed gps vehicle tracking devices in my room mates car the next day to TRACK ME, even though my room mate has nothing to do with me and we were COMPLETE STRANGERS until the previous day. The same day on 5/26/04 evening, I went out in my car and came back around 7:45 pm, parked my car in the parking lot and on the way I said "nice car" to my neighbor who was cleaning his car, to which he replied "thanks". Within a few minutes at 8:44 pm, the SADISTIC FBI called and made phone# 770-690-8489 with caller name "NEIGHBOR OUTREACH" appear on my caller id to tell me, "Oh we have seen and heard what you said to your neighbor in the parking lot". The FBI was able to see and hear my conversation because they installed VIDEO and AUDIO surveillance devices around my apartment. When I went to Best Buy in Feb 2002 to buy a cell phone, two caucasian FBI agents (possibly husband and wife) followed me into the store and observed me from a very close range and sent me a marketing fax for cell phones to my UNLISTED phone# THAT SAME EVENING to tell me that the SADISTIC FBI were WATCHING ME even in retail stores. SADISTIC FBI agents even PUNCTURED my room mates car tire and made it unusable and useless in June 2004 because of some casual NON-RELIGIOUS comments he made the previous day in our apartment. You might think this is crazy stuff, but I know it for a FACT that FBI SADISTIC MOTHERFUCKERS punctured my room mate's car tire INTENTIONALLY for the casual comments he made the previous day. FBI agents have terrorized me by calling my current unlisted phone# atleast 200 times in a month and a half in July and August 2004, intentionally asking for Roberto Fernandez (last name changed), knowing fully well that nobody by the name Roberto Fernandez lived in my apartment. I called undercover FBI agent, Kathleen Sue Taylor on 4/1/04 and told her I do not want to receive any HARASSING UNSOLICITED phone calls from the FBI and from next day onwards, the FBI had made my unlisted phone# appear on caller id of ordinary american people multiple # of times, where the owners of those phone#s listed below got upset and called me and left abusive messages in my answering machine. The owners of these phone numbers listed below called and asked me why I was calling them repeatedly, even though I DON'T KNOW who they are and I NEVER called them even once. 703-580-8992 4/2/04 Dale City, VA 540-309-1226 4/3/04 Roanoke VA 434-525-1448 4/3/04 Lynchburg, VA 757-404-1076 4/4/04 Harry Folsom left me an abusive message 703-820-6695 4/4/04 DC Suburb, VA 770-966-5236 4/4/04 Cooper P D, Woman left me an abusive message 757-483-0583 4/7/04 Norfolk, VA 540-463-7459 4/7/04 Lexington VA 770-253-6297 4/8/04 Hammond Stinson 703-541-0950 4/9/04 DC Suburb, VA FBI pretended to be me and made all these phone calls themselves from the FBI head office in Washington DC to those ordinary Americans and made my unlisted phone# appear on their phone caller ids, as if I am calling them. Please speak to, ADVISE and ENCOURAGE these people above to file lawsuits against the US government and FBI for violating their privacy and for phone harassment. (If you are RICH, you can use a PRIVATE EYE to get the PHONE CALL LISTS of these numbers above for the first 15 days of April 2004 and find a COMMON PHONE# among the lists on the SPECIFIC DAYS mentioned above to zero in on the unlisted phone#) FBI agents have destroyed my livelihood by assasinating my character with potential employers by making anonymous calls to them when I sent resumes since FBI is privy to all the email addresses and phone numbers of the recruiters and potential employers. I do NOT think this is an EXCEPTION and imagine how many ordinary Americans have been suffering this "FBI SADISM for years" without knowing it. Once a Caucasian male FBI agent in a Comcast van threatened to ram into my car from behind and came within half an inch of hitting me from behind even though there was no traffic altercation between us and there is no traffica at all on a city street in Southfield (Detroit metro area) in Feb 2002. Two FBI agents once shouted at me and abused me verbally in a Sports Authority store parking lot approximately around Feb 2002 in Livonia, MI. FBI ILLEGALLY stole passwords of all my email and internet accounts with the help of bugs installed on my computer. FBI agents have followed me even when I went to see a doctor. There was one Caucasian FBI agent in a white truck with GA license plate APZ 7647 on 5/24/04, waiting for me in a truck in Ridgeview hospital parking lot listening to the conversation I was having with the doctor, using voice amplification devices. I am currently living in a two bedroom apartment sharing it with another person and the FBI sadists made anonymous calls to the apartment management office with fictitious complaints and tried to get me evicted from the apartment in July 2004. FBI agents ILLEGALLY entered my apartment when I was not home in May 2004, stole a "yellow highlighter" and after I moved to a different Atlanta suburbs a month later entered my apartment again when I was not home and placed the "yellow highlighter" on the carpet in the middle of my bedroom by the time I came back from watching Fahrenheit 9/11 movie on 6/27/04. The FBI knew that I went to watch Fahrenheit 9/11 movie on 6/27/04 because they were watching me looking for directions and movie times on the internet and also with the help of gps vehicle tracking devices in my car. I spoke to an attorney from a pay phone on 6/24/04 and during the conversation I asked the attorney if we can get a court order to force the Internet Service Provider to reveal if my internet web surfing is being monitored by the FBI and lo and behold my internet account MYSTERIOUSLY DISAPPEARED from the ISP computers on 6/25/04. On inquiry my ISP told me somebody called and cancelled my internet account the previous day, which I never did. My room mate goes to work around 6 AM and on the night of 7/23/04 I pasted a 8.5 X 11 page note on the inside of the apartment entrance door for my room mate to wake me up when he leaves so I can bolt the hotel lock from inside and go back to sleep. My room mate woke me up like I requested and I bolted the hotel lock from inside of my apartment and went back to sleep at 6 AM on the morning of 7/24/04. The sadistic FBI agents STILL ENTERED my second floor apartment while I was asleep between 6:00 AM and 10:00 AM on 7/24/04 and REMOVED the 8.5X11 inch page pasted note on the inside of entrance door and LEFT IT on the ENTERTAINMENT CENTER in the living room just to TORTURE ME mentally and TERRORIZE me “We entered your apartment even when you locked the hotel lock bolt and did this, but what can you do ?” FBI agents ILLEGALLY entered my apartment on the night of 8/1/04 when I was asleep and stole prepaid calling card pin numbers from my trouser pockets. One of the prepaid calling cards in my trouser pocket was called "I Conexion" and the FBI next day called me on 8/2/04 and made the number 770-242-8775 with caller name "Internet Conexion" appear on my caller id to TERRORIZE me, that they entered my apartment the previous night and stole the prepaid calling numbers from my trouser pocket. The phone# above is NOT an FBI# but some other company. To protect myself from these SADISTIC FBI agents entering into my apartment and stealing things when I am asleep, I locked my bedroom door from the inside and put a small heavy box and a 19 inch TV on top of the box against the bed room door on the night of 8/7/04 so if the FBI agents try to open my bedroom door, the TV will fall off the box at the slightest movement of the door, make a big sound and wake me up. On the morning of 8/8/04 around 9:00 AM I woke up to a giant thudding sound of the TV falling on the floor from the box and FBI agents speeding away by the time I realized what happened. FBI agents entered my apartment and opened my locked bedroom and pushed the door at 9:00 AM so hard, they pushed the box a good two feet away from the door. The FBI SADISTS are even willing to break my 19 inch TV to TORTURE and TERRORIZE me. FBI agents ILLEGALLY CHANGED three passwords (even though I used Kinkos to keep my PASSWORDS PRIVATE) of my three email ids that I was using to send this document to investigative reporters between 8/26/04 and 8/28/04 to "PREVENT ME" from EXPOSING their SADISM, PERVERSION, TERRORISM, SEXUAL ABUSE and MENTAL TORTURE, by either ILLEGALLY installing key logging software on kinkos computers or by some other ILLEGAL MEANS unknown to me. So I created brand new email ids and sent this document and god knows when the SADISTIC FBI will change the passwords of my NEW email ids. SADISTIC FBI agents ILLEGALLY entered my apartment while I was taking SHOWER around 1:00pm and removed a shaving set scissors from the tote bag pocket in my bedroom and placed it on the iron board in my bedroom. FBI was able to execute this operation WHILE I WAS TAKING SHOWER because they were watching me taking shower "real time live" with video devices installed in my "bathroom". To escape this FBI sadism, I went and slept in an acquaintance's apartment in the first week of September 2004 and the SADISTIC FBI agents still came and entered that apartment, installed video surveillance devices in the acquaintance's apartment and drew a curvy line with a knife on the black colored apartment door of the acquaintance to TERRORIZE me. Sadistic FBI agents "reacted" to EACH and EVERY word that came out of my mouth for the last three years by making 2000 UNSOLICITED HARASSING phone calls at my unlisted private phone numbers. I know about all those no call list websites but FBI PERVERS and SADISTS just don't care. To all of you who are gonna advise me to wear tinfoil or take drugs for schizophrenic paranoia, the SADISTIC FBI wants all of you to think exactly that way so they can CONTINUE to carry on their PERVERSE SADISM on ordinary american citizens and MISDIRECT and PROGRAM all of the 290 mil american brains to treat the EVIL, SADISTIC, PERVERTED and DICTATORIAL FBI TERRORISTS like Gods. By now, you should have figured out the gist of what and how the FBI SADISTS and PERVERTS are TORTURING, TERRORIZING and SEXUALLY ABUSING me with their INFINITE POWER. You can read the rest of FBI SADISM below if you have time. ************************************************************************************* I rented a car on 7/14/04, bought a cell phone and stayed in a hotel that night and by next morning 7/15/04, the FBI has figured out where I was staying and wire tapped my cell phone and tracked me by placing gps vehicle tracking devices even in the rental car. FBI agents ILLGEALLY entered my apartment when I was not home on 7/16/04 and LOCKED the bathroom door from inside, by the time I came back in the evening. FBI agents ILLEGALLY entered my apartment when I was not home between 7/15/04 and 7/18/04 and logged on to my computer and REMOVED a stock list from my Yahoo account. FBI agents ILLEGALLY entered my apartment when I was not home on 7/18/04 in the morning and turned the Air Conditioner "ON" intentionally by the time I came back to TORTURE me. FBI agents ILLEGALLY entered my apartment on 7/18/04 when I was not home and placed a razor blade and a nickel (which they STOLE from my apartment in Marietta in May 2004) and put it in a plastic bag to TAUNT ME to say WHAT CAN YOU DO ? FBI agents ILLEGALLY entered my apartment in the early hours of 7/22/04 (while I was still sleeping in bed) and opened a tote bag I kept next to the pillow and unzipped a small bag (zip which I closed the previous night) inside, just to TERRORIZE ME as if to say, we can and will do anything to you and you can't do anything to us because we FBI are GODS. FBI agents ILLEGALLY entered my apartment when I was not home on 7/22/04 during the day time and placed the TV remote this time hanging on the edge of the bed to TERRORIZE me that they entered my apartment. FBI agents ILLEGALLY entered my apartment sometimes when I was not home, pretending to be Wall Street Journal delivery personnel and delivered sometimes MUTIPLE copies of the Journal on the same day and also sometimes delivered multiple chinese restaurant take out menus to avoid the neighbors noticing and suspecting them. FBI agents ILLEGALLY entered my apartment when I was not home in the evening on 7/24/04 and again opened the tote bag and unzipped a small bag which is inside the tote bag and also STOLE a one time use Kodak camera from my bedroom which I bought on 7/23/04 in Wal Mart. FBI agents have REGULARLY entered my apartment ILLEGALLY with laptops when I was not home and copied information from my computer and floppy disks and messed them up. Sadistic FBI agents called me at least 30 times repeatedly in the space of an hour and a half between 7:00 and 8:30 pm on 7/27/04 and asked for Roberto Fernandez knowing fully well that nobody by that name lived in my apartment and infact said "You are so funny" and made WEIRD SOUNDS like aye, uye, ick, ihe etc while watching me real time live all the time with the video surveillance devices installed in the ceiling of my bedroom when I answered the phone. FBI agents ILLEGALLY entered my apartment while I was asleep on 8/2/04 night even though the hotel lock was bolted from inside, and placed the tv remote face down on the end table of my bedroom, folded a prepaid calling card in my trouser pocket and formed a crease on the card, removed a library map from the file folder (which was inside a tote bag) and placed it outside the file folder and unzipped the back pocket of the tote bag half way down and left it there to torture me. FBI agents have been alerting the security departments of WalMart, Best Buy, JC Penney stores etc with fictitious complaints when I went there for shopping, so the security cameras in those stores are constantly focused on me and watching me while I was in those stores. I rented a car on 8/5/04 and stayed in a hotel to get some privacy and the sadistic FBI agents still tracked me down that night and left the rental car doors unlocked by next morning on 8/6/04. I changed the car rented the previous day on 8/6/04 and traveled a couple of hours on a highway, took an exit, parked my car in a strip mall parking lot and spent about 20 minutes in a retail store and by the time I got back to the car, FBI agents followed me and put two quarters on a plastic bag containing donuts in the back seat of the car just to taunt and terrorize me they are still following me even when I rented a car and drove out of the city. FBI agents STOLE a pilot pen pack (which I bought from CVS Pharmacy on 8/8/04) from my car on the night of 8/8/04 and entered my apartment on 8/9/04 when I was not home from 11 AM - 12 noon and placed the pilot pen pack under a chair on the carpet in the living room to torture me. FBI agents ILLEGALLY entered my apartment on 8/10/04 between 1:00pm and 1:15 pm (just 15 min) when I went to Publix and turned the TV "On" in my bedroom by the time I came back to mentally torture me. FBI agents ILLEGALLY entered my apartment even when the hotel lock was bolted from inside in the early hours of 8/16/04 while I was asleep and removed the middle row donuts in a 12 pack krispy kreme donut box in the refrigerator and placed them in the empty left row and placed the concord grape jelly bottle horizontally in the refrigerator and unplugged the tv cable from the cable outlet in my bedroom to TORTURE me that they are still entering my apartment anytime they want at their will. FBI agents ILLEGALLY entered my apartment while I was asleep in the early hours of 8/20/04 even when I put a coffee table against the apartment entrance door and a small heavy box and a 19in TV against my bedroom door from the inside and searched the locked tote bag and unzipped the back pocket of the tote bag half way down and left it there to TERRORIZE ME that they are still entering my apartment no matter what precautions I take. FBI agents ILLEGALLY entered my apartment on 8/22/04 around 7:30pm while I was taking a nap and turned the Air Conditioner "ON" to TAUNT me that they were entering my apartment EVEN WHEN I WAS still in my apartment. FBI agents stole a Gillette disposable razor on the night of 8/25/04 from my duffel bag and placed it between the drivers seat and driver side door near the trunk opening lever of my car. FBI agents ILLEGALLY opened the rental car I rented, in a hotel premises on the night of 8/27/04 and removed the cup holder and placed it infront of the parking brake of the car to HARASS ME that they are still following me even when I rented a car and stayed in a hotel. FBI agents ILLEGALLY even tapped MetroPCS cell phone numbers instantaneously as soon as I bought them on the same day. SADISTIC FBI agents AMUSED themselves by turning my bedroom table lamp in my bedroom, ON and OFF by using remote control devices, sometimes while I was browsing the web. FBI agents ILLEGALLY entered the hotel rooms even when locked from inside where I stayed in August and September and installed video surveillance devices and moved things around from the tote bag’s zipped side pocket into the tote bag to TERRORIZE me that they will INVADE my privacy and MENTALLY TORTURE me even when I slept in hotel rooms. Sometimes when I spoke to my roommate in non-English language, the psycho-analysis OBSESSED SADISTIC FBI agents called me on the phone immediately and said "komo-isthaaaa" in a SARCASTIC way and asked for Roberto Fernandez knowing fully well that nobody by that name lived in my apartment. From someone at microsoft.com Sun Nov 28 17:36:34 2004 From: someone at microsoft.com (Jive) Date: Sun, 28 Nov 2004 22:36:34 GMT Subject: A lock that times out but doesn't poll References: Message-ID: "Peter Hansen" wrote in message news:cocmon$k3c$1 at utornnr1pp.grouptelecom.net... > Python, of course, is unsuitable for many hard realtime systems, > and if you're using Windows you are probably on the wrong platform > in the first place. Well, there is that. The platform I'm using is a realtime operating system, but it has a Windoze lookalike API for OS functions like threads, semaphores, critical sections, events, and whatnot. [OT] I don't draw any distinction between "soft" and "hard" realtime. I've never seen definitions for those terms that I thought were useful. If some operations must be performed within a certain time window, to me that's realtime, neither hard, soft, smooth, lumpy, or just right. A realtime operating system has guaranteed latency. Depending on the application, it does not necessarily have to be fast. I have an application that runs fine on a realtime OS, but fails eventually under MS Windows running on a processor that's 3x as fast. [/OT] > The bar for putting things in the main distribution should be > very, very high. Agreed. IMHO the bar was not set high enough for the current threading module. > One of the conditions for doing that should > probably be that the code is fairly widely used and widely > required. Why? If the existing code could be better, why not improve it? > > Why not post it to an appropriate "recipe" page in the fledgling > Agile Control Forum site instead? (http://www.engcorp.com/acf) > That way others who *do* work in the machine control field will > have an early chance to try out your code, experiment, maybe > even improve it, fix bugs, Oh, there will be no bugs. > and basically do some of the work that > *should* be done before anything gets into the main Python distro... > I will give it a look. I had some spare time last year when I volunteered the first time. I don't have spare time now, and probably will not have before May at the earliest.. If someone would like to take over the code, I would be happy to contribute it and give as much help as I can. Jive From umdehoon at ux101.ecc.u-tokyo.ac.jp Thu Nov 18 07:32:08 2004 From: umdehoon at ux101.ecc.u-tokyo.ac.jp (umdehoon) Date: Thu, 18 Nov 2004 21:32:08 +0900 Subject: PyOS_InputHook enhancement proposal Message-ID: PyOS_InputHook is a pointer to a function that is called periodically (ten times per second) while Python is idle, for example, when waiting for a user command. Python C extension modules can set this pointer to a hook function defined in the extension module. For example, _tkinter.c makes use of PyOS_InputHook to get messages delivered to its widgets. A problem arises when two or more extension modules want to set PyOS_InputHook. For example, the scientific plotting package pygist needs PyOS_InputHook to get messages delivered to its graphics windows, and may therefore conflict with the Python GUI IDLE, which uses Tkinter. Chaining won't work, as it will fail when an extension module wants to remove its hook function. My suggestion is therefore to replace PyOS_InputHook by two functions PyOS_AddInputHook and PyOS_RemoveInputHook, and let Python keep track of which hooks are installed. This way, an extension module can add a hook function without having to worry about other extension modules trying to use the same hook. Any comments? Would I need to submit a PEP for this proposal? --Michiel, U Tokyo. From ndbecker2 at verizon.net Fri Nov 19 14:18:58 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Fri, 19 Nov 2004 14:18:58 -0500 Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > > My guess is Microsoft hopes to discourage Visual Basic knock-offs. Claim > 2 clearly seems to restrict the scope to BASIC. > > Seems pretty slimy. > Doesn't Python (along with probably every other language ever invented) display prior art here? From gitte at wange.dk Sun Nov 28 12:15:30 2004 From: gitte at wange.dk (Gitte Wange) Date: Sun, 28 Nov 2004 18:15:30 +0100 Subject: Timer hangs when quitting app Message-ID: Hello, I'm trying to create an application that needs a Timer() to do various checks. My class has a self.timer = Timer(900, self.sendDNSRequest) The timer itself works fine but whenever I try to exit the application, it simply hangs and I have to kill the proces using `kill pid` I have tried uncommenting the timer stuff, and then the app works as expected. Is there anything I need to do to kill the timer? I have tried to create a __del__(self) function in my app. It gets called when I leave out the timer, but with the timer enabled, it never gets called. Any hint will be appreciated :-) Greetings, Gitte Wange From oliver.schoenborn at utoronto.ca Sat Nov 13 00:09:37 2004 From: oliver.schoenborn at utoronto.ca (HumbdyDum) Date: Sat, 13 Nov 2004 00:09:37 -0500 Subject: problem with "setup.py bdist --formats=zip" In-Reply-To: References: Message-ID: Peter Hansen wrote: > Humpdydum wrote: > >> I would like to create a "binary" distribution for Windows, but in zip >> format, since the installer requires root access. > > > Not sure what you mean here. Windows doesn't have a "root" user, > though it has "Administrator". Is that what you meant? Yes. > I believe > you'll find that the installer has an option to install for the > current user only, so that you don't have to be an Administrator > to do it. Really? I've installed several (like Numeric etc) and looked but never seen that option, I must be blind. Actually, I remember clearly that they always say, after being started, something like "You don't have sufficient priviledge, you must be administrator". I'll take another look. Thanks, Oliver From dsa at unilestemg.br Tue Nov 23 16:50:23 2004 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Tue, 23 Nov 2004 21:50:23 +0000 Subject: Python GTK import error In-Reply-To: References: Message-ID: <200411232150.23219.dsa@unilestemg.br> Hi ! The error is that the system ins't finding this lib: /usr/lib/libgtk-x11-2.0.so.0 Try to see if your system has it. See ya ! Em Ter 23 Nov 2004 22:08, Qianqian Fang escreveu: > hi > > I installed Fedora Core 2 in my desktop and it has been running > flawlessly in the last few months until I upgraded some packages > (gtk/gtk-devel/python) to the latest version via apt-get. Now, when I > execute any system configuration gui program, i.e. > /usr/bin/system-config-*, it raises an error message as follows: > > File > "/usr/src/build/375621-i386/install/usr/lib/python2.3/site-packages/gtk-2.0 >/gtk/__init__.py", line 43, in ? > ImportError: /usr/lib/libgtk-x11-2.0.so.0: undefined symbol: > atk_object_add_relationship > > (the top line may vary, but the last line is the same for all of them) > and the script exits after the error. > > I don't know if anybody met this before, and how can I fix it? > thank you very much! > > Qianqian -- Douglas Soares de Andrade - UnilesteMG Linux User: #237615 dsa em unilestemg.br From jcarlson at uci.edu Wed Nov 17 22:29:50 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 17 Nov 2004 19:29:50 -0800 Subject: Parallel processing In-Reply-To: <51e59f27.0411171706.22a60438@posting.google.com> References: <51e59f27.0411171706.22a60438@posting.google.com> Message-ID: <20041117192812.F9B4.JCARLSON@uci.edu> jhujsak at neotopica.com (Jon) wrote: > > Josiah Carlson wrote in message news:... > > There are various other reasons why Python is not as parallelizable as > > you would think. Among them is the semantics of scoping, and whether > > there is shared or unshared scope among the processors/nodes. If shared, > > then any operation that could change scopes would need to be distributed > > (ick), or if unshared, then you are basically looking at an > > automatically distributed tuplespace (LINDA). It gets even uglier with > > certain kinds of generators. > > > > Regardless of which one is the case, heavy modifications to Python would > > necessarily need to be done in order to make them happen. > > > > > > - Josiah > > Even considering the above caveats, one can still employ Python based > interpretive layers such as pyMPI over quite solid parallel computing > tools such as MPI. See http://pympi.sourceforge.net/. Indeed. I wrote the equivalent of pyMPI in the spring of 2002 for an undergraduate senior project. It was never a matter of "can parallelization be done", it was a matter of "can loops be automatically parallelized". - Josiah From exarkun at divmod.com Tue Nov 2 16:51:21 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Tue, 02 Nov 2004 21:51:21 GMT Subject: dynamic or on-the-fly color changing in curses? In-Reply-To: Message-ID: <20041102215121.23443.195945597.divmod.quotient.339@ohm> On Tue, 02 Nov 2004 21:43:13 GMT, Matt Garman wrote: >I'd like to write a class or module in python that allows me to do > on-the-fly color changing in the curses module. > > [snip - curses examples] > > But when I do that, all strings show up as green. My assumption > here is that all strings are assigned to color_pair(1), and when > those strings are drawn, they assume the most recent definition of > color_pair(1). In other words, it appears you can't "recycle" color > pair definitions. > > So my second thought was to just pre-define every possible > combination, but, at least on Linux, I'm limited to 63 unique > colors, whereas I can create more than 63 color combinations > (foreground, background, and attribute combinations). > > Am I strictly limited to using at most curses.COLOR_PAIRS colors on > a per-application basis? There are only 64 combinations (8 of which render the text unreadable), so being limited to 63 doesn't seem like that big of a drawback to me. Am I missing something? Jp From andres.baravalle at gmail.com Mon Nov 15 07:49:09 2004 From: andres.baravalle at gmail.com (Andres Baravalle) Date: 15 Nov 2004 04:49:09 -0800 Subject: help with source package including eggtrayicon References: <45992f58.0411142022.323f5b58@posting.google.com> Message-ID: <45992f58.0411150449.6bdbb1de@posting.google.com> I could go on, and now I have my working Makefile and I can compile eggtrayicon, but I would like to include this compile in my setup.py, if possible. My Makefile is: # Makefile for eggtrayicon OBJECTS = eggtrayiconmodule.so # Compilation stuff CC = gcc PYTHON_VERSION = $(shell echo `python -c "import sys; print sys.version[0:3]"`) PYTHON_INCLUDE = -I/usr/include/python$(PYTHON_VERSION) \ -I/usr/include/pygtk-2.0 \ $(shell pkg-config gtk+-2.0 --cflags) \ $(shell pkg-config libgnomeui-2.0 --cflags) LIBS = $(shell pkg-config gtk+-2.0 --libs) \ $(shell pkg-config libgnomeui-2.0 --libs) CFLAGS = -Wall -g -fomit-frame-pointer $(PYTHON_INCLUDE) all:: $(OBJECTS) %.o : %.c $(CC) -fPIC $(CFLAGS) -c -o $@ $< %.so : %.o $(CC) -shared $(LIBS) -Wl,-soname,$@ $< -o $@ Suggestions? Thanks in advance. Andres From nehalmistry at gmx.net Tue Nov 23 16:31:17 2004 From: nehalmistry at gmx.net (Nehal) Date: Tue, 23 Nov 2004 13:31:17 -0800 Subject: cgi.FieldStorage() is slow In-Reply-To: <2c60a528.0411170547.2c68392@posting.google.com> References: <2c60a528.0411170547.2c68392@posting.google.com> Message-ID: <20041123133117.00000d71@nehal> On 17 Nov 2004 05:47:05 -0800 and-google at doxdesk.com (Andrew Clover) wrote: > Nehal wrote: > > > when uploading small files, you won't notice a difference, but > > if you upload files larger than 2 megs, you can notice it. > > Yep. Large file upload in cgi.py is slow. I don't immediately > see a way to speed it up without re-architecting some of its > internals. > > In any case I dislike(*) the cgi module's interface too, so I > rewrote the lot: > > http://www.doxdesk.com/software/py/form.html > > This isn't drop-in compatible, and is getting a bit crusty (I'm > expecting to rewrite most of it soon to be more > objecty/threadable, and support WSGI), but in my experience it's > considerably faster than cgi for very large files. (We were > commonly using files in the 10-50MB range.) > > (* - more then than now; cgi's interface has got slightly better > since Python 1.5.2's time.) > > -- > Andrew Clover I have tested Andrew's 'form.py' module, and also upload cgi scripts from other languages, i did some benchmarking, i tried uploading a 6 meg file to localhost and writing to an output file on apache 2.0.52 win32. here are the results (note: i checked the error log to make sure all scripts were working and processing the data as expected): ruby: 2 sec Andrew Clover's form.py: 2.5 sec perl: 2.5 sec tcl (3rd party module): 4.5 sec python: 8 sec of course in practice, most people won't be receiving data at 3 megs/sec, so you won't have to process data at such a speed. nevertheless, it will put a greater load on the CPU, which may be an issue for many servers. it would not be a good idea to put Andrew's form.py in the official python distribution and have 2 different modules for processing CGI. either it would have to somehow merged into CGI module, and keeping backward compatibility, or the existing CGI module must be optimized; maybe the above benchmark data will motivate someone to do so ;). until then, i'll stick to form.py -- thx, Nehal From phleum_nospam at chello.se Sun Nov 14 06:58:02 2004 From: phleum_nospam at chello.se (Carl) Date: Sun, 14 Nov 2004 12:58:02 +0100 Subject: Data structures for tree traversals? Message-ID: Dear friends, What are the best options for implementing fast and efficient trees in Python? The typical trees that I'm thinking of are those used by the finance industry to price different kinds of derivatives (ie forward simulation of prices/rates in binominal/trinominal trees and backward induction to price final claims). Intuitively, dictionaries seem to be ideal candidates for accessing objects at nodes and traversing the tree. Am I right or are there better choices? Are lists better? Has Numerical Python speed-efficient methods that are to be preferred in comparison with lists ad dictionaries? Carl From f.geiger at vol.at Tue Nov 9 13:52:58 2004 From: f.geiger at vol.at (F. GEIGER) Date: Tue, 9 Nov 2004 19:52:58 +0100 Subject: Umlauts, encodings, sitecustomize.py References: Message-ID: "Jeff Epler" schrieb im Newsbeitrag news:mailman.6167.1100019195.5135.python-list at python.org... > You should note that chr(0x84) is *not* a-umlaut in iso-8859-1. That's chr(0xe4). You may be using one of these Windows-specific encodings: > cp437.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp775.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp850.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp852.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp857.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp861.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS > cp865.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS I'm not sure what you mean by this. Do mean I use one of these accidentially? Or should I switch to one of these in my sitecutsomize.py? I'm a bit confused. When I let Python print an ? (umlaut a) by simply entering the 1-char string "?", it prints '\x84'. When I let a tiny script print the umlauts, I get: sys:1: DeprecationWarning: Non-ASCII character '\xe4' in file D:\Project\SchAG\Programme.Python\test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details These are Umlauts: ??? and ???. These are Umlauts: ??? and ???. Press any key to exit... There's the '\xe4' you are missing. Thanks and kind regards Franz GEIGER P.S.: Do you know a site, where this whole matter is explained somehow? P.P.S.: The script: print "These are Umlauts: ??? and ???. " s = "These are Umlauts: ??? and ???. " print s raw_input("Press any key to exit...") From aleaxit at yahoo.com Wed Nov 3 03:30:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 3 Nov 2004 09:30:34 +0100 Subject: saved sys.path References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> <8vudnfRCkdgHExrcRVn-jA@powergate.ca> Message-ID: <1gmo48i.1t3yslw1e7px39N%aleaxit@yahoo.com> Eric S. Johansson wrote: > basis, I really believe that configuration information should be > externalized from the program as much as humanly possible. So things I agree. But putting it in a scriptfile instead of a datafile is just as good, IMHO -- just like, say, config info for my bash shell sessions goes into a file .bashrc which is a script rather than being just a datafile. Most of what .bashrc does is setting environment variables, but the extra flexibility of it being a script may still help. Similarly, as I see things, config info for a big app (coded in Python, or in whatever other language as long as it's got a Python accessible interface) can be in a scriptfile instead of a datafile. The scriptfile starts up, adjusts environment info (sys.path foremost, but maybe other stuff too), imports the app's main module, launches 'main(sys.argv)' therein. It _is_ externalized from the program, in my view -- it's a configuration scriptfile. It just works better, with Python, to have the configuration scriptfile call the app's main, rather than doing it the other way round as you would in, say, C (where the app's main starts and then calls a configuration scriptfile). I do like what you've posted, don't get me wrong -- I'm just pointing out that our different preferences on app configuration architectures do not descend from differences on the "externalized from the program" philosophy! Alex From danperl at rogers.com Fri Nov 19 15:32:20 2004 From: danperl at rogers.com (Dan Perl) Date: Fri, 19 Nov 2004 15:32:20 -0500 Subject: Class Encapsulation Errors in Python 2.3.3 References: <47f7cc78.0411182007.1b77c2b1@posting.google.com> <47f7cc78.0411191005.7b793bf@posting.google.com> <10pskhnjt2met3f@corp.supernews.com> Message-ID: I fully agree with Jeff and I will make a couple of other small points. I saw you meant to use 'False' as a default value for the class-level attribute 'songs'. 'None' is the normal value for initializations like that. It's a small point but it kind of stuck in my mind as being unusual. If you still choose to use class-level attributes and to initialize them with default values, you have to keep in mind that you will encounter this kind of problem with all the initializations that are using complex types. That means lists like in the case of 'songs', but also strings like in the case of 'name' and 'artist'. Jeff pointed out in an earlier posting that there are also other ways you could get into trouble like this and it should be made clear that this is true for all the complex types, not only lists. Dan "Jeff Shannon" wrote in message news:10pskhnjt2met3f at corp.supernews.com... > Tim Henderson wrote: > >>Here is a partial implementation, i don't have the code with me but >>this is how the songs list is made >> >>code: >>------------------------------------------- >>class Album: >> name = '' >> songs = [] >> artist = '' >> >> def __init__(self, name, artist): >> self.name = name >> self.artist = artist >>------------------------------------------- >> > > Yes, this gives you class-level attributes, shared by all instances of > Album. In the case of name and artist, you're then creating > instance-level attributes ('self.name = name') which shadow the > class-level attribute. But you never bind 'songs' on the instance, so > you're just modifying the class-level (shared) songs list. > >>after reading the code i came up with a possible solution: >> >>possible code: >>------------------------------------------- >>class Album: >> name = '' >> songs = False >> artist = '' >> >> def __init__(self, name, artist): >> self.name = name >> self.artist = artist >> if songs == False: >> songs = [] >>------------------------------------------ >> > > That'll almost work -- within __init__(), you need to refer to songs as > self.songs (both times). But why bother with creating the class-level > attributes? If you just set them in __init__(), all will be fine. > > class Album: > > def __init__(self, name, artist): > > self.name = name > self.artist = artist > self.songs = [] > > will have the same net effect as your code, for the vast majority of > common purposes. (There are corner cases where having class-level > defaults is helpful, but I sincerely doubt that this is true for your > program.) > > Jeff Shannon > Technician/Programmer > Credit International > > From gregory.lielens at fft.be Sun Nov 28 16:45:33 2004 From: gregory.lielens at fft.be (gregory lielens) Date: Sun, 28 Nov 2004 22:45:33 +0100 Subject: subclassing extension type and assignment to __class__ In-Reply-To: References: <41a87eb5$0$13482$ba620e4c@news.skynet.be> <41a912a8$0$25051$ba620e4c@news.skynet.be> Message-ID: <41aa46de$0$13468$ba620e4c@news.skynet.be> > Sorry for the confusion. This looks like a situation best handled with > embedding rather than inheritance. The PClass and PClass2 wrapper classes > can share whatever relationship _PClass and _PClass2 share. > > class PClass: > def __init__(inst=None): > if inst is None: > inst = _PClass() > self._inst = inst > def override_method(self, ...): > self._inst.override_method(...) > def new_method(self, ...): > ... > > class PClass2: > self._inst = _PClass2() > def troublesome_method(self): > base = PClass(self._inst.troublesome_method()) > ... > return base Yes I was affraid this would be the conclusion: embedding instead of inheritance...But this means that not only the method that need to be modified need to be rewritten in python, all the other ones also just to delegate to the embedded instance... This is not too practical, even if such writing can be more or less automatized... For my purpose it seems that there was a big step backward between python 2.2 and 2.3, and I am surprised this has been mostly unnoticed...This problem should be common for many people trying to write mixed C/C++ / python classes. I found some reference on this in the list archive, a few people beeing anoyed by it, but the proposition to make the test about assignment to class less strict was not retained it seems...I plan to experiment a little with the python C implementation to see what happen if I bypass this test... > Alternatively you could provide a way to pass PClass back to the extension module > for _PClass2.troublesome_method to use instead of _PClass when creating a return > object. But the embedding approach seems more appropriate when _PClass is not to > be used directly. Yes but again this is not so practical, the purpose of the _PClass / PClass implementation was to make the bindings as light, and as easy to implement / extend as possible, and both the embedding and the creation of PClass within _PClass2 methods defeat this purpose... I think allowing assignment to class for native types should be done if possible, for example if the new class is a derived type (possibly using __slots__)... I saw a post on this by Guido, but the reason why it was not possible is not clear to me and the thread died without further explanations...Maybe my experiments will show me what happen, or someone more knowledgeable than me can explain why this is not possible? Greg. From duncan.booth at invalid.invalid Wed Nov 24 12:51:24 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Nov 2004 17:51:24 GMT Subject: HTML stylesheet expander? References: <8idd72-j1o.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: >> If you are not using Windows, or you want portability, then you are >> probably best doing this in Javascript. > > How exactly would I do that? There is no Javascript in Python and if > I had a way of displaying HTML then this is a non-issue. > What I meant was that you do the conversion once and then use the converted HTML in your program. Obviously if I misunderstood and the HTML is dynamically generated that won't be possible. From http Sun Nov 7 01:48:34 2004 From: http (Paul Rubin) Date: 06 Nov 2004 22:48:34 -0800 Subject: PEP new assert idiom References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> Message-ID: <7xy8hep325.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > Why do you need a statement for this? > IMO, a plain function will do the trick: I do write such functions sometimes, but using a statement is more natural. That's why the assert statement exists, for example. Because of that naturalness, the temptation to misuse the assert statement is very great, and I find myself doing it all the time thinking I'll clean it up later. So I think having a statement for runtime checking would be in the correct spirit. From bradtilley at gmail.com Tue Nov 2 13:53:27 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Tue, 02 Nov 2004 13:53:27 -0500 Subject: dicts & lists together In-Reply-To: References: Message-ID: Larry Bates wrote: > Brad Tilley wrote: > >> I have a dict that associates strings to numbers like this {'abc': 1, >> 'xyz':2, '123':3,...} I am then given a list of strings ['abc', 'xyz', >> '123',...] and asked to associate a number to each string in the list >> according to the string's value in the dict. I am at a loss as to how >> to do this, can someone show me where to start? > > > >>> xdict={'abc': 1, 'xyz':2, '123':3} > >>> xlist=['abc', 'xyz', '123'] > >>> tlist=[xdict.get(v, None) for v in xlist] > >>> print tlist > [1, 2, 3] > > Larry Bates > Syscon, Inc. Thank you Larry, I don't understand it, but it works ;) From moexu13 at gmail.com Wed Nov 3 00:37:09 2004 From: moexu13 at gmail.com (M. Bitner) Date: Tue, 2 Nov 2004 21:37:09 -0800 Subject: Should I learn Python? In-Reply-To: <624a388a.0411021328.5ac41f4c@posting.google.com> References: <624a388a.0411021328.5ac41f4c@posting.google.com> Message-ID: <57c312d304110221374fe98867@mail.gmail.com> On 2 Nov 2004 13:28:22 -0800, Sam wrote: > Hi, > I have been developing sites and cms's for the past few years using > PHP and mysql. I've been interested in learning a new language and was > considering Python. I have a pretty decent grasp of OOP concepts (i > know, you're skeptical since I mentioned PHP). I don't have a formal > programming background, just learning as I go. > > So, with that being said, here are some dumb questions. > > 1. What can I do with Python that I can't do with php? > > 2. Do you use both PHP and Python in conjunction with each other? > > 3. In what way could I utilize Python to compliment existing sites or > apps built with PHP? > > Thanks for any help. > -- > http://mail.python.org/mailman/listinfo/python-list > Learning Python would be an excellent next step in your development. Most programming textbooks recommend you learn at least one new language a year. Python is a clean, well designed language and should be straightforward (and fun) for you to learn. But to answer your questions: 1. PHP is a web scripting language and Python is a general purpose scripting language. You can use PHP outside of a web environment but that really isn't its strong point. You can use Python pretty much anywhere. 2. No. Where I work we have one internal app written in PHP but are moving towards developing exclusively in Python. We have thought about potentially using PHP for the presentation layer and Python for the business logic but haven't gotten that far yet. 3. Where do you need it? If PHP works for your site then Python may not be a necessary addition. HTH, Melissa From belred1 at yahoo.com Sat Nov 13 22:12:37 2004 From: belred1 at yahoo.com (Bryan) Date: Sun, 14 Nov 2004 03:12:37 GMT Subject: map, LC, genexp Message-ID: i thought that LC and genexp were supposed to be faster than map. i also thought i read somewhere in this group that the slowest looping mechanism in 2.4 is 20% faster than the fastest looping mechanism in 2.3. if i'm wrong about this, remembered wrong or did something wrong, please let me know. here are some timeit tests i did on my machine. notice that map is faster in both python versions and that LC24/LC23 is only a 5.5% speed improvement. python 2.3 timeit "for i in map(str, xrange(100)): pass" 10000 loops, best of 3: 118 usec per loop timeit "for i in [str(x) for x in xrange(100)]: pass" 1000 loops, best of 3: 200 usec per loop python 2.4b1 timeit "for i in map(str, xrange(100)): pass" 10000 loops, best of 3: 144 usec per loop timeit "for i in [str(x) for x in xrange(100)]: pass" 10000 loops, best of 3: 189 usec per loop timeit "for i in (str(x) for x in xrange(100)): pass" 10000 loops, best of 3: 185 usec per loop thanks, bryan From anthonybaxter at gmail.com Wed Nov 24 10:31:17 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Thu, 25 Nov 2004 02:31:17 +1100 Subject: asynchat and threading In-Reply-To: References: Message-ID: On Wed, 24 Nov 2004 14:57:44 GMT, Rob Snyder wrote: > Greetings - > > I've embarked on a small learning project, trying to get a better grasp of > the asyncore and asynchat modules. The project involves building a simple > instant messenger application for use on our LAN - nothing heavy duty, as > 99% of my reason for doing this is just to learn. I can only paraphrase what I said in a recent python-dev thread - absolutely *no-one* should be starting new projects using asyncore and asynchat. Use twisted, instead - it's cleaner, saner, has an active development community, and is in all ways a better solution than the asyncore approach. asyncore based code causes bleeding from the eyes and brain leakage through the ears. From mefjr75 at hotmail.com Mon Nov 29 05:28:47 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 29 Nov 2004 02:28:47 -0800 Subject: Help on creating a HTML by python References: <50d96c9b.0411281856.6c8d2ae9@posting.google.com> Message-ID: <18282ecb.0411290228.7b4f88b4@posting.google.com> evil_pizz at hotmail.com (sepgy) wrote in message > Can anyone help me to use a python to create an HTML photo gallery > generator. When it's finished, it will be able find all the picture > files (i.e. .jpg, .gif. .png files) in any given folder on the > computer, automatically create smaller thumbnails for each image, and > then generate a complete HTML file that displays a clickable image > gallery. When viewed in a web browser, the HTML file will display the > thumbnails in a neatly formatted table, and if you click on one of the > thumbnails the full-size image will appear. Hello, You want to look at this: http://www.uselesspython.com/thumbnail.py I also did this very thing when i first started learning Python. Found it quite educational and learned much in the process. Here was my try at 'improving it': http://bellsouthpwp.net/m/e/mefjr75/python/Thumbz.py You can see my dumb newbie code , of course that was two years ago ;) There are others out there too try thumbnail.py in a Google search sometime ;) > Thanks your welcome ... HTH, M.E.Farmer From deetsNOSPAM at web.de Tue Nov 2 12:58:53 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 02 Nov 2004 18:58:53 +0100 Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> Message-ID: >> Strong/weak typing is about how much you care of types at all - in php, >> its perfectly legal to add strings to numbers - the string simply gets >> converted to a number beforehand, that conversion yielding 0 when there >> is nothing useful and numberlike can be extracted from the string. So >> typing is weak, as it doesn't constrain the possible operations on >> variables with certain values. > > By this definition, Python is also weakly typed: > >>>> 2.0 + 1 > 3.0 I'm not sure how things are implemented internally, but I'd still say my definition is correct even for this example: The + operator can be viewed as overloaded with the signature (float, int) -> float But its not for (string, int) - albeit * e.g. is. > The point here is that I consider C weakly typed because, with no error of > any sort, it allows me to reinterpret a block of memory in as many ways as > I like. > A strongly typed language like Python does not allow this. Even in my > Python example above, we're not *reinterpreting* the block of memory > representing 1 as a floating point value; we're *coerceing* the integer 1 > into the floating point value 1.0 (which probably means allocating a new > float variable at the C level) before performing the addition. This is definitely weak typing. The question remains if permanent coercions as php (and afaik perl) do can also be considered weak typing, as you won't end up with an error for more or less anything you do. I say yes, but maybe thats a matter of taste. -- Regards, Diez B. Roggisch From michael.bierenfeld at web.de Fri Nov 26 05:07:48 2004 From: michael.bierenfeld at web.de (michael) Date: 26 Nov 2004 02:07:48 -0800 Subject: SysLogHandler is drivin me nuts PEBCAC References: Message-ID: Vinay Sajip wrote in message news:... > The config file appears incomplete - can you post the whole of it (if > it's not too big)? I would have expected to see lines like Yep it was incomplete heres the complete config as it has to be [loggers] keys=root,syslog [handlers] keys=syslog,file,stdout [logger_syslog] qualname=syslog level=INFO handlers=syslog [logger_root] qualname=root level=INFO handlers=stdout [handler_syslog] class=handlers.SysLogHandler level=ERROR formatter=syslog args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) [handler_stdout] class=StreamHandler level=INFO formatter=stdout args=(sys.stdout,) [handler_file] class=FileHandler level=INFO formatter=stdout args=('python.log', 'w') [formatters] keys=syslog,stdout [formatter_syslog] format=%(module)s %(levelname)s %(message)s [formatter_stdout] format=%(module)s %(asctime)s %(levelname)s %(message)s Thanks for the help Michael From canali at aliceposta.it Thu Nov 18 02:45:48 2004 From: canali at aliceposta.it (linuxUser) Date: 17 Nov 2004 23:45:48 -0800 Subject: (not so)useful scripts Message-ID: http://www22.brinkster.com/canali From kartick_vaddadi at yahoo.com Fri Nov 12 08:17:51 2004 From: kartick_vaddadi at yahoo.com (kartik) Date: 12 Nov 2004 05:17:51 -0800 Subject: escape sequences in list comprehensions Message-ID: <940ee3e8.0411120517.488d16ca@posting.google.com> Escape sequences don't seem to work in strings within list comprehensions: >>> print ['%s\n' %i for i in [1,2,3]] ['1\n', '2\n', '3\n'] What am I missing? Thank you. From peter at engcorp.com Tue Nov 2 08:41:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Nov 2004 08:41:47 -0500 Subject: saved sys.path In-Reply-To: References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> Message-ID: <8vudnfRCkdgHExrcRVn-jA@powergate.ca> Eric S. Johansson wrote: > one of the things I've been bothered with using Python for larger > applications is path manipulation. For example, how does one create the > search path necessary to find your own modules if you do not wish > pollute site-packages with your private code. > > the path file looks like this might be a good solution in preference to > modifying sys.path in your code. Are there any scope or limitation > rules for this path modifier? Can this modification be made specific to > an application or is the new path visible to the entire world (which > reintroduces the namespace pollution problem). Most questions relating to this which haven't already been answered by Alex can be answered by a perusal of the site.py source. It makes good readin'... Note that between PYTHONPATH and .pth files, possibly the addition of a little sitecustomize.py file (see again site.py), and the ability to modify sys.path in the __main__ module of the app as Alex suggests, you can do pretty much anything you think is a good thing to do. -Peter From steve at holdenweb.com Sat Nov 13 17:45:44 2004 From: steve at holdenweb.com (Steve Holden) Date: Sat, 13 Nov 2004 17:45:44 -0500 Subject: Advice needed In-Reply-To: References: Message-ID: Eddie Parker wrote: > God can make mistakes too -- look at Country music. :) > No, no, no, you're supposed to *listen to* music :-) regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From rkern at ucsd.edu Wed Nov 17 05:46:18 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 17 Nov 2004 02:46:18 -0800 Subject: arrays In-Reply-To: References: Message-ID: Rahul Garg wrote: > Hi. > Thanks for the help. Its really simple and i shud have thought it > myself. > Some clarifications : > 1. I will mostly be storing floating point numbers in 2 dimensional > arrays which i will pass to a custom module written in C. The > application is for scientific computing purposes.I just need python + > wxPython for the GUI. > > 2.I am not using Numarray because i dont expect to do many operations > on the matrices in Python itself. Most of that stuff will be handled > in my C module. > The decision of not doing the matrix operations in Python is because > most of the C code is already ready. Though it is written as > standalone command line app currently , converting it into an > extension module shudnt be much of a problem. You still might want to use numarray or Numeric in this case. The memory representation of a numarray/Numeric array is the same as in C. You won't have to duplicate memory and waste time converting between a memory block of doubles and lists of lists of Python floats. Speaking from experience, I would say that numarray/Numeric greatly eases the burden of communicating arrays between Python and C even if one does not need to do anything complicated with the arrays in Python. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Tue Nov 2 19:50:30 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 03 Nov 2004 00:50:30 GMT Subject: Problems with profiling results (hotshot or normal) : almost all are incorrect References: <41881ba2$0$78738$e4fe514c@news.xs4all.nl> Message-ID: <41882aa4.1466900701@news.oz.net> On Wed, 03 Nov 2004 00:43:31 +0100, Irmen de Jong wrote: >Hello >I haven't received any responses on my original posting, >and it could very well be that it never made it to the newsgroup >(because I can't find it back on my news server here). >So I'm posting this again. Sorry if it *did* make it to >the group.. Please consider trying my test-program that is given >here and let me know how it works on your python installation. > >Thanks for any insight on this. > Traceback (most recent call last): File "C:\pywk\clp\irmen2.py", line 86, in ? import hotshot, hotshot.stats, wait ImportError: No module named wait Where does wait come from? Regards, Bengt Richter From brian at sweetapp.com Thu Nov 11 05:55:14 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 11 Nov 2004 11:55:14 +0100 Subject: Status of BaseHTTPServer In-Reply-To: <4e4a11f8.0411110023.52526404@posting.google.com> References: <4e4a11f8.0411110023.52526404@posting.google.com> Message-ID: <41934512.2060302@sweetapp.com> Simon Wittber wrote: > BaseHTTPServer uses the mimetools module, which is deprecated. > > Are the maintainers of modules that are in the standard library listed > somewhere? Who could/should I send patches to? Patches, bugs, etc. should be done through Sourceforge: http://sourceforge.net/projects/python Cheers, Brian From aleaxit at yahoo.com Thu Nov 4 05:11:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 Nov 2004 11:11:30 +0100 Subject: pep 336: Make None Callable References: Message-ID: <1gmq3sg.13vqunmdm9pcbN%aleaxit@yahoo.com> Terry Hancock wrote: ... > > It would be more sensible to promote the addition to builtins of a > > predefined null function -- one somewhat equivalent to 0, [], and {}. > > Maybe, but I think it's worth asking -- what use is the traceback from > the None object when it is called? Does it help in QA of code? Is Yes: it wards against the reasonably common bug of forgetting a return statement, for example -- def make_adder(addend): def adder(augend): return addend + augend the programmer forgot a 'return adder' as the last line -- oops, no big deal, it will be caught extremely soon, thanks to None not being callable. > there a common idiom that would be broken by a callable None? None I can think of, but then, the same could be said of many possible loosenings -- accepting, say, " 2 + '23' " and returning either '223' or 25 would break no common idioms, either... it would just make Python less good at catching some common bugs. Errors should not pass silently... "Null Object" is a great Design Pattern (not in the Gof4 book, but still a classic, from a reasonably early PLOP), and I would love it if Python embodied it, as it embodies so many other useful ones. But we should not overload None to play the role of Null, I think. Rather, Null should be another object, either built-in or in some module. Besides the equivalent of a 'def __call__(self, *a,**k): return self', it should have many other "do-nothing" special methods -- including a __getattr__, btw. We should also have type(Null) is Null -- and Null should be subclassable too, because there are a few design choices which, however we make them in the Null class, may need tweaking in a user-coded subclass (e.g., should str(Null) be 'Null' or ''?). There are Null Object classes in the cookbook -- all the way from a simple 'donuttincallable' to a full-fledged Null Object -- and that's where I'm putting all of my considerations on the issue, but I'll be glad to have them embodied in a PEP if needed. But the Null should NOT be None, the DEFAULT return value of functions without a return statement etc etc. Explicit is better than implicit. Alex From rkern at ucsd.edu Thu Nov 25 12:37:43 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 25 Nov 2004 09:37:43 -0800 Subject: Use Python library from C++ In-Reply-To: <89cc6e1f.0411250914.24131f1b@posting.google.com> References: <89cc6e1f.0411241939.61a19596@posting.google.com> <1101364143.006433.314340@z14g2000cwz.googlegroups.com> <89cc6e1f.0411250914.24131f1b@posting.google.com> Message-ID: Chang LI wrote: > "Chris S." wrote in message news:... > >>zhao wrote: >> >> >>>Try boost.python and SWIG? >>>(boost.sourceforge.net, swig.sourceforge.net) >>> >>>Both provide a interface between C/C++ and python >>>if you want gui under python, you also can try wxpython or pygtk >> >>I thought SWIG ported C/C++ libraries to Perl, Python, Ruby, Tcl, etc? >>How would you use it to port Python into C/C++? >> > > > SWIG is for Python to use C++. I am searching for in reverse. Elmer is the reverse of SWIG, and should be easier to use than using the Python C API itself. Elmer will handle the conversion of types between Python and C++ and will expose a nice API on the C++ side. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pekka.niiranen at wlanmail.com Tue Nov 9 12:27:14 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Tue, 09 Nov 2004 19:27:14 +0200 Subject: Concise idiom to initialize dictionaries In-Reply-To: References: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> Message-ID: <4190FDF2.7020601@wlanmail.com> Hi, You do not need to initialise dictionaries, if you access them with idiom: >>> mydict = {"pekka":1} >>> mydict.get("pekka", "") 1 >>> mydict.get("james", "") '' -pekka- Brian Quinlan wrote: > Frohnhofer, James wrote: > >> My initial problem was to initialize a bunch of dictionaries at the >> start of a >> function. >> >> I did not want to do >> def fn(): >> a = {} >> b = {} >> c = {} >> . . . >> z = {} >> simply because it was ugly and wasted screen space. >> >> First I tried: >> >> for x in (a,b,c,d,e,f,g): x = {} >> >> which didn't work (but frankly I didn't really expect it to.) >> Then I tried: >> >> for x in ('a','b','c','d','e','f','g'): locals()[x]={} >> >> which did what I wanted, in the interpreter. When I put it inside a >> function, >> it doesn't seem to work. If I print locals() from inside the >> function, I can >> see them, and they appear to be fine, but the first time I try to >> access one >> of them I get a "NameError: global name 'a' is not defined" >> >> Now obviously I could easily avoid this problem by just initializing each >> dictionary, but is there something wrong about my understanding of >> locals, >> that my function isn't behaving the way I expect? > > > The locals dictionary should be considered read-only. Wouldn't having a > list of dictionaries be a better strategy? > > Cheers, > Brian From thorsten at thorstenkampe.de Tue Nov 9 19:53:17 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 10 Nov 2004 01:53:17 +0100 Subject: Packing list elements into tuples References: Message-ID: <1u0yu7b2dn58p$.dlg@thorstenkampe.de> * Nickolay Kolev (2004-11-09 22:29 +0100) > I have a list whose length is a multiple of 3. I want to get a list of > tuples each of which has 3 consecutive elements from the original list, > thus packing the list into smaller packets. Like this: > > l = [1,2,3,4,5,6] > > tups = [(1,2,3), (4,5,6)] > > or > > l = [1,2,3,4,5,6,7,8,9] > > tups = [(1,2,3), (4,5,6), (7,8,9)] Fragment[1] from a general purpose partitioning utility: def part(seq, slice): """ partition seq """ return [seq[slice * index:slice * (index + 1)] for index in range(len(seq) / slice + bool(len(seq) % slice))] > if i can dictionaries it would be even better: > > l = [1,2,3,4,5,6] > > tups = [ > {'first':1,'second':2,'third':3}, > {'first':4,'second':5,'third':6} > ] You're losing order and therfore you're attaching 'first', 'second' and so on because you obviously need the original order. So don't use a dictionary. Thorsten [1] Just for the record: def part(seq, slice = None, modus = None): """ partition seq syntax: part(seq, boolean_function, modus = 'bool') -> [[first_true_items], [first_false_item, remaining_items]] part('str', 'separator', modus = 'sep') or part('str', ['separators'], modus = 'sep') part(list, item, modus = 'sep') part(n, modus = 'set') -> len([all_possible_partitions_of_[0, 1, ..., n]]) part(list, modus = 'set' -> [all_possible_partitions_of_list] part(seq, int, modus = 'size') -> [seq0, seq1, ..., seqn] - where len(seq(i)) = int part(seq, [n0, n1, ..., n(i)], modus = 'size' -> [seq0, seq1, ..., seq(i)] - where len(seq(i)) = n(i) """ From merman at snafu.de Tue Nov 9 17:45:42 2004 From: merman at snafu.de (T. Kaufmann) Date: Tue, 09 Nov 2004 23:45:42 +0100 Subject: MySQLdb installation In-Reply-To: <-ji*zidzq@news.chiark.greenend.org.uk> References: <418f99db$0$175$9b622d9e@news.freenet.de> <418fba73$0$161$9b622d9e@news.freenet.de> <418fcca7$0$165$9b622d9e@news.freenet.de> <-ji*zidzq@news.chiark.greenend.org.uk> Message-ID: <4191472c$0$192$9b622d9e@news.freenet.de> Sion Arrowsmith wrote: > T. Kaufmann wrote: > >>Diez B. Roggisch wrote: >> >>>Install the package mysql-devel. >> >>I can't find it!? > > > "libraries and header files" on MySQL downloads. Sorry - here is the right place: http://linux.maruhn.com/sec/mysql-devel.html o-o Thomas From steven.bethard at gmail.com Thu Nov 4 13:55:53 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 18:55:53 +0000 (UTC) Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> Message-ID: Diez B. Roggisch web.de> writes: > > > Does this make my concern any clearer? What I'm asking for is an example > > like yours above that not only shows that you can treat, say, the bits of > > a float as an integer, but also shows why this would be useful. > > The question is not so much if there is an actual usecase, but more that if > things _can_ be done, they inevitably _will_ be done. No, the (my) question really was for an actual usecase. ;) People do a lot of things in programming languages, not all of them particularly good or appropriate. The recent example of intrinsics.replace to change the behavior of Python's str class strikes me as one such example. =) I would be much more convinced that weak-typing is useful if someone could actually use it for me. ;) > I can remeber abusing 32bit pointers in 68k processors by > altering the most-significant byte. It took advantage of the fact that the > old 68k had only 24 address registers, thus ignoring the msbyte. That > allowed to pass 2 parameters in one pointer. And was for a short period of > time considered a clever trick.... I'm not sure I see how this is taking advantage of weak-typing, unless I misunderstand what you were doing here. Did you ever interpret your two-parameter structure as anything other than either a set of bits or the two parameters? You didn't ever treat the set of bits as a float, for example, right? You *could* have, of course, but I'm guessing your interpretation of the bits was consistent... My point here is that I think in most code, even when people do a bunch of bit-twiddling, they have a single underlying structure in mind, and therefore you see them treat the bits as one of two things: (1) The sequence of bits, i.e. the untyped memory block, or (2) the intended structure. IMHO, an example of taking advantage of weak-typing would be a case where you treat the bits as three different things: the sequence of bits, and two (mutually exclusive) intended structures. I guess I'm drawing a thin line here, but I see a difference between using the untyped (bit-based) representation of a structure and actually converting a structure between two different types. Steve From dthierbach at gmx.de Sun Nov 28 09:15:22 2004 From: dthierbach at gmx.de (Dirk Thierbach) Date: Sun, 28 Nov 2004 15:15:22 +0100 Subject: protocols, inheritance and polymorphism References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> <786dnYZkrq-ieT7cRVn-tw@rogers.com> <1101273995.954137@yasure> <41a6340f$0$307$636a15ce@news.free.fr> <1101575782.366954@yasure> Message-ID: <20041128141522.995.0.NOFFLE@ID-7776.user.dfncis.de> Donn Cave wrote: > Quoth Jacek Generowicz : > Given a model for polymorphism that means smuggling an object > around wrapped in some degree of mystery about its type, elegant > and sound static typing does seem unlikely. But C++ and its > descendents have always been easy targets. Would you happen to > know something about how Objective CAML's OO system approaches this? In several ways: First, by using parametric polymorphism (not defined as in this thread above, but by allowing "type variables" (type parameters) which are applied as necessary, both in every expression, and in object types. Second, by using so-called "row types", i.e. types for incomplete records (in OCaml, they are denoted by the trailing dots in a type like < get_x : int; set_x : int -> 'a; .. > ). Together, they allow you to statically type most of the usual applications of inheritance, virtual methods, etc. There used to be an somewhat more contrived example in the OCaml manual with a subject/observer pattern, virtual methods, and both abstract and concrete classes, but I think they removed that some time ago. As for >> Specifically, dynamic polymorphism is impossible without dynamic >> typing. I haven't heard the term "dynamic typing" in this context, and I think it's a bit unfortunate, because it's not "typing" in the usual sense. If Jacek just means virtual methods, as in >> In C++ you turn your classes into dynamically typed ones with the >> "virtual" keyword, which introduces a vtable and run-time type >> identification (RTTI). that's easy to do in OCaml, and it also works in the type classes of Haskell. The problem Jacek describes here: >> As soon as you want to use a method present in the subclass but not >> in the superclass, it is up to you to faff around with dynamic_cast >> and checking of the resulting pointer; is solved by keeping the parametric type "uninstantiated" as long as possible, and instantiate it with the concrete type only when it is clear that you really need the method present in the subclass. Or, you handle this with the row types. It does not work in every case one can think of right from the start (you have to be able to statically guarantee that you have really the subclass to work with at this point of your code, and not the superclass), so you might to rewrite your code a bit to make it work. Maybe it's easier to see if we do concrete examples. > I see in the on-line documentation this paragraph: > > Be aware that subtyping and inheritance are not related. [...] > I'm thinking that this might be more or less typical of academic > ideas about OO typing, and it seems conceptually appealing. I > don't know the details though. The "inheritance is not subtyping"-motto is somewhat orthogonal to this issue. It comes originally from a paper by Benjamin Pierce, with IIRC the same title. If you think this concept through, it really helps to sort out some of the confusion that comes with the "usual" OOL's like Java and C++. - Dirk From wab104 at hotmail.com Tue Nov 30 08:17:13 2004 From: wab104 at hotmail.com (wab104) Date: 30 Nov 2004 05:17:13 -0800 Subject: dynamical linking problem Message-ID: I compiled Python on one Linux box and copied it to another Linux box. This causes an import problem: >>> import urllib Traceback (most recent call last): File "", line 1, in ? File "/edl3/wb104/analysis/python2.2/lib/python2.2/urllib.py", line 26, in ? import socket File "/edl3/wb104/analysis/python2.2/lib/python2.2/socket.py", line 41, in ? from _socket import * ImportError: libssl.so.0.9.7: cannot open shared object file: No such file or directory On the first Linux box I have: /usr/lib/libssl.so -> /usr/lib/libssl.so.0.9.7 /usr/lib/libssl.so.0.9.7 On the second Linux box I have: /usr/lib/libssl.so -> /lib/lib/libssl.o.0.9.7a /lib/lib/libssl.o.0.9.7a If I create an extra symbolic link on the second Linux box with name libssl.so.0.9.7 (and also one for libcrypto, which has a similar problem) then all is fine. But the problem is that I want to ship a binary distribution to third parties who might not be so confident to do this (and might think I've shipped a duff product). Why is the Linux linker looking for the specific libssl.so.0.9.7 rather than the generic libssl.so? (Obviously on the first Linux box the generic is pointing to the specific, but that's hardly a good excuse.) Is there any (sensible) way to convince it to do otherwise? This problem makes creating binary distributions difficult. (What are the odds that people have exactly the same version of every system library?) From jzgoda at gazeta.usun.pl Fri Nov 19 16:04:43 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Nov 2004 22:04:43 +0100 Subject: Microsoft Patents 'IsNot' In-Reply-To: <1100898065.354777.219400@z14g2000cwz.googlegroups.com> References: <16798.16559.745209.751967@montanaro.dyndns.org> <3073pnF2rf1v9U1@uni-berlin.de> <1100898065.354777.219400@z14g2000cwz.googlegroups.com> Message-ID: mustafademirhan at gmail.com wrote: > But it is approved :( As I see, it's patent application, so it is not approved yet. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From jepler at unpythonic.net Mon Nov 8 20:42:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Nov 2004 19:42:41 -0600 Subject: Mixing Python And Bash In-Reply-To: References: Message-ID: <20041109014240.GB15990@unpythonic.net> The bash manpage says: set [--abefhkmnptuvxBCHP] [-o option] [arg ...] [...] -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of an until or while loop, part of an if statement, part of a && or ?? list, or if the command?s return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. So place "set -e" at the top of your script, and it will exit as soon as the first "simple command" exits with a nonzero exit status. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cjw at sympatico.ca Thu Nov 11 09:16:30 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 11 Nov 2004 09:16:30 -0500 Subject: distutils and Debian In-Reply-To: References: <4192AD69.5040707@sympatico.ca> Message-ID: Sam Holden wrote: > On Wed, 10 Nov 2004 19:08:09 -0500, Colin J. Williams wrote: > >>The distutils download page has: >>-------------------------------------------------------- >>Current stable release >> >>The current stable release is Distutils 1.0.2; you can download it as: >> >> * Distutils-1.0.2.tar.gz (source distribution) (233k) >> * Distutils-1.0.2.zip (source distribution) (274k) >> * Distutils-1.0.2.win32.exe (Windows installer) (187k) >> >>If you are running Python version 1.6 or later, you do not need to >>download the Distutils: they're included with Python. However, if you >>have a Distutils more recent than your Python, you might want to install >>it: see the Distutils README.txt file. Version 1.0.2 is identical to the >>version included in Python 2.1. >>--------------------------------------------------------- >> >>With Debian, it seems that distutils is not included for >>Python 2.2 or 2.3. >> >>Should this be reported as a Debian bug? > > > No. > > It's in the python2.x-dev packages. > > Debian often split large things up into smaller packages, distutils > isn't needed by the basic debian user who only installs debian > packages after all. > > "apt-cache search distutils" finds it easily enough for those who do > want it. > Thanks for pointing this out, but I have checked and Python2.3.4-dev is installed. Colin W. From alban.minassian at wanadoo.fr Fri Nov 5 02:15:00 2004 From: alban.minassian at wanadoo.fr (alban.minassian at wanadoo.fr) Date: 4 Nov 2004 23:15:00 -0800 Subject: SystemError: com_backpatch: offset too large References: <781f5e76.0411032335.57bf5ae4@posting.google.com> <1gmqfmp.amq50rbaii20N%aleaxit@yahoo.com> Message-ID: <781f5e76.0411042315.4d05d451@posting.google.com> Thank, but same problem (now, i have com_backpatch: offset too large at line 4567 !) Alban From rowen at cesmail.net Thu Nov 18 15:07:12 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 18 Nov 2004 12:07:12 -0800 Subject: [ANN] RO package updated Message-ID: RO utility package 2004-11-18 has been released. RO is a package of python utilities I wrote to support a telescope control interface. RO has a strong emphasis on the Tkinter GUI library, networking, astronomy and cross-platform support (my telescope user interface is regularly used on unix, MacOS X and Windows). For more information about the package, see: The most visible changes are in RO.Wdg.FTPLogWdg and overhaul of the underlying ftp package (RO.Comm.GetFile->RO.Comm.FTPGet) to avoid a bug in urllib. In addition, there are a few refinements to RO.Wdg.Checkbutton and RO.Wdg.Label. For detailed release notes see: -- Russell From contact at alanlittle.org Wed Nov 10 15:40:34 2004 From: contact at alanlittle.org (Alan Little) Date: 10 Nov 2004 12:40:34 -0800 Subject: Beginner's scoping question Message-ID: <4ef0f3a4.0411101240.21132006@posting.google.com> a=1 b=[] class C(): def __init__(self): a=2 b.append(3) c = C() print b # [3] # but ... print a # 1 ??? From gsakkis at eden.rutgers.edu Tue Nov 9 20:31:35 2004 From: gsakkis at eden.rutgers.edu (George Sakkis) Date: Tue, 9 Nov 2004 20:31:35 -0500 (EST) Subject: MethodType in python 2.2 Message-ID: Hi all, I wonder why types.MethodType fails under python 2.2: Python 2.2.2 (#1, Jun 25 2003, 18:52:43) [GCC 3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import types >>> class X: ... def f(self,attr): return getattr(self,attr) ... g = types.MethodType(f,None) ... Traceback (most recent call last): File "", line 1, in ? File "", line 3, in X TypeError: cannot create 'instance method' instances The same code under 2.4 (and I believe 2.3) runs fine. Python 2.4b1 (#1, Oct 25 2004, 17:07:48) [GCC 3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import types >>> class X: ... def f(self,attr): return getattr(self,attr) ... g = types.MethodType(f,None) ... >>> X().f("f") > >>> X().f("g") > Is it possible to get around this in 2.2 ? Thanks in advance, George From vze4rx4y at verizon.net Mon Nov 8 14:47:32 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 08 Nov 2004 19:47:32 GMT Subject: PEP new assert idiom References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com><1gmvgit.vzj5g4hv9dsrN%aleaxit@yahoo.com><1099815505.15924.9.camel@localhost.localdomain> Message-ID: [F?bio Mendes] > I think my PEP is getting more and more nonsensical... I give up! LOL. The PEP is the same. It is it's author's world view that has changed ;-) Raymond From eddie at kickingdragon.com Sun Nov 14 03:27:47 2004 From: eddie at kickingdragon.com (Eddie Parker) Date: Sun, 14 Nov 2004 01:27:47 -0700 Subject: .pyc files... In-Reply-To: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> Message-ID: Hrmm, this is more a *NIX discussion, but I'm curious: That could be problematic if you have too many .pyc files found - overflow the command buffer, no? Something like: "find . -name '*.pyc' | xargs -i rm -f {}", would solve that, as xargs executes each encountered argument individually, I believe (I think the -exec command does similar, in Stephen's original post). Anyways - I've just ran into problems with overflows.. Granted, cygwin, not a real *NIX. :) -e- -----Original Message----- From: python-list-bounces+eddie=kickingdragon.com at python.org [mailto:python-list-bounces+eddie=kickingdragon.com at python.org] On Behalf Of Simon John Sent: Sunday, November 14, 2004 1:17 AM To: python-list at python.org Subject: Re: .pyc files... Stephen Waterbury wrote: > > OK, stupid question, but it's been bothering me for ages.. J > > > > I love Python to bits, but .pyc files always litter my source tree, and > > they've always bothered me. ... > One solution (on unices, at least): > > alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" or with backticks: rm -rf `find . -name '*.pyc'` -- http://mail.python.org/mailman/listinfo/python-list --- Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 11/1/2004 --- Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 11/1/2004 From merkosh at hadiko.de Sun Nov 28 10:47:35 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 28 Nov 2004 16:47:35 +0100 Subject: files in non-blocking mode? References: Message-ID: Sunday 28 November 2004 14:49 pm Mathias Waack wrote: > Uwe Mayer wrote: >> I want two python programs to communicate over stdIO channels. The >> one executes the other via the popen3 function: >> >> amc = Popen3("./amc/amc.py", True, 0) >> line = stdin.readline() >> amc.tochild.write(line) >> amc.tochild.flush() >> print amc.fromchild.readlines() >> >> The problem is that although amc.tochild gets flushed the data >> never reaches the client until the .tochild fd is closed. Is there >> any way to put IO channels into non-blocking mode in python? > How do you read the data in the client? Maybe you're using a line > buffered read? Does your code work if the server includes a trailing > CR and/or NL in the string before it calls the flush? Yes, I used line = stdin.readline() and made sure the sending client had a newline ("\n") char appended to the text. Still, the receiving client's readline() function does not return. Uwe From ark at acm.org Mon Nov 29 12:35:52 2004 From: ark at acm.org (Andrew Koenig) Date: Mon, 29 Nov 2004 17:35:52 GMT Subject: how to drop all thread ?? References: Message-ID: This reply is off topic but I couldn't resist: The best way to get rid of thread is to adopt a kitten. In fact, one of my cats is named Snobol because she is such a good string manipulator. From mdraghi at prosud.com Sun Nov 14 22:57:03 2004 From: mdraghi at prosud.com (Mariano Draghi) Date: Mon, 15 Nov 2004 00:57:03 -0300 Subject: Combining arbitrary lists In-Reply-To: <41982269$1_1@alt.athenanews.com> References: <41982269$1_1@alt.athenanews.com> Message-ID: Nick wrote: > Given that > > n = [ [1, 2, 3], [4, 5, 6], [7, 8] ] > > then the following code produces what I expect > > for x in n[0]: > for y in n[1]: > for z in n[2]: > print [x, y, z] ... > > How can I do this for an arbirary length of n? I think this is what you're looking for: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 > Muchos Gracias De nada ;) -- Mariano From babloojhala at rediffmail.com Tue Nov 2 06:14:27 2004 From: babloojhala at rediffmail.com (babloojhala at rediffmail.com) Date: 2 Nov 2004 11:14:27 -0000 Subject: vacation mail Message-ID: <20041102111427.2700.qmail@webmail14.rediffmail.com> Hi, Thank you for your mail. I'm away on work and will be back as early as possible. Will reply as soon as I get back. Regards, Babloo From niels_bohr at uol.com.br Sun Nov 7 03:22:33 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 06:22:33 -0200 Subject: PEP new assert idiom In-Reply-To: <418dc217.1833351810@news.oz.net> References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> <418dc217.1833351810@news.oz.net> Message-ID: <1099815753.15924.11.camel@localhost.localdomain> Thanks for clarification :-) Fabio Em Dom, 2004-11-07 ?s 07:43 +0000, Bengt Richter escreveu: > On Sun, 07 Nov 2004 03:50:43 GMT, "Raymond Hettinger" wrote: > > >[Fbio Mendes] > >> This is very similar to what I'm proposing, with the only inconvinience > >> that is uglier to type: > >> > >> assert \ > >> exp1 and \ > >> exp2 and \ > >> ... > >> expn, > >> 'ErrorMsg' > >> > >> Instead of: > >> > >> assert \ > >> exp1, > >> exp2, > >> ... > >> expn, > >> 'Errormsg' > >> > >> Well, I realize I didn't expressed my thoughts very clearly and that > >> it's indeed a very minor change in python's syntax. It won't let anyone > >> does anything new, IFAIK, but it makes a common pattern of code a little > >> more beautiful, (and why not? more expressive). If one consider the fact > >> that it won't break old code (only in one very unlikely case) I don't > >> see it as a completely unreasonable suggestion. Other people may think > >> differently though. > > > >The odds of Guido accepting this proposal are about zero. As you say, it > >doesn't do anything new, but it does require altering the grammar. Besides, > >TOOWTDI. > > > >Also, Guido tends to not be persuaded by arguments about "too much typing". > >This is doubly true is you're talking about replacing an "and" with a comma (big > >whoop). > > > >Also, one of the existing alternatives is quite readable: > > > >err = 'Errormsg' > >assert exp1, err > >assert exp2, err > >assert exp3, err > > > >The alternative has the advantage that a failure will point to the exact > >expression that failed. The disadvantage is the repetition of the error > >message; however, I disagree that your use case is common. Instead, it is > >likely more advantageous to have different error messages for each expression. > >For example, the following comes from the post condition checks in QR matrix > >decomposition: > > > >assert Q.tr().mmul(Q)==eye(min(m,n)), "Q is not orthonormal" > >assert isinstance(R,UpperTri), "R is not upper triangular" > >assert R.size==(m,n), "R is does not match the original dimensions" > >assert Q.mmul(R)==self, "Q*R does not reproduce the original matrix" > > > >One could link all of these by an "and" or the proposed comma, but then you > >end-up with a single, less informative error message, "The QR decomposition > >bombed, but I won't tell you why ;-) ". > > > Besides, if you want the single message with comma-delimited expressions, > you can already write: > > >>> assert False not in map(bool, ( > ... True, > ... 1, > ... 2==2 > ... )), 'Error message' > > Or to show what happens > >>> assert False not in map(bool, ( > ... True, > ... 1, > ... 2==3 > ... )), 'Error message' > Traceback (most recent call last): > File "", line 1, in ? > AssertionError: Error message > > Or with a little helper, and then two boilerplate lines for the assert, > you can have individual messages: > > >>> def fff(*xm): > ... """find first false xpr in seq xpr ,msg, xpr, msg and yield pair""" > ... it = iter(xm) > ... for x in it: > ... m = it.next() > ... if not x: yield x, m; break > ... > >>> def test(x): > ... assert not [t for t in fff( > ... > ... True, 'true msg', > ... 1, 'one msg', > ... 2==x, '2 eq x msg', > ... 'xx', 'xx msg' > ... > ... )], 'Error: expr == %r, msg = %r'%t > ... > >>> test(2) > >>> test(3) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > AssertionError: Error: expr == False, msg = '2 eq x msg' > > Actually, why not just make a utility function "asserts" to do it: > > >>> def asserts(*expr_msg_seq): > ... """find first false expression value and assert it with paired message""" > ... it = iter(expr_msg_seq) > ... for x in it: > ... m = it.next() > ... if not x: > ... assert x, '%r -> %r'%(x, m) > ... > >>> def test(x): > ... asserts( > ... True, 'true msg', > ... 1, 'one msg', > ... x, 'bool(x) is not True', > ... x==2, '2 eq x msg', > ... 'xx', 'xx msg' > ... ) > ... > >>> test(2) > >>> test(3) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > File "", line 7, in asserts > AssertionError: False -> '2 eq x msg' > >>> test(0) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > File "", line 7, in asserts > AssertionError: 0 -> 'bool(x) is not True' > >>> test(()) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > File "", line 7, in asserts > AssertionError: () -> 'bool(x) is not True' > >>> test(type('foo',(),{'__nonzero__':lambda self:0})()) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > File "", line 7, in asserts > AssertionError: <__main__.foo object at 0x02EF17AC> -> 'bool(x) is not True' > >>> test(type('foo',(),{'__nonzero__':lambda self:1})()) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in test > File "", line 7, in asserts > AssertionError: False -> '2 eq x msg' > >>> test(type('foo',(),{'__nonzero__':lambda self:1, '__cmp__':lambda s,o:0})()) > > I doesn't shortcut, so you could get an exception in preparing the arg list for > a sequence like > asserts( > den !=0, 'denom must be zero', > num/den>5, 'better write it as assert num>5*den' > ) > which would be safer as > assert den !=0, 'denom must be zero' > assert num/den>5 'better write it as assert num>5*den' > > Not to mention side effects, but you shouldn't have those in asserts anyway. > > Silliness ;-) > > Regards, > Bengt Richter From aleaxit at yahoo.com Sun Nov 14 12:57:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 14 Nov 2004 18:57:26 +0100 Subject: Tkinter and Graphics References: <10pf6ersh138jbe@corp.supernews.com> Message-ID: <1gn98g2.1uhohpdpev85hN%aleaxit@yahoo.com> Andrew wrote: > Hi I was wondering if there is anyway in Tkinter to create GUIs using > Graphics, like windows media player or other tools like that I guess you could do just about anything with Canvas, it that's what you mean. Alex From adalke at mindspring.com Fri Nov 5 12:54:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 05 Nov 2004 17:54:27 GMT Subject: Usage statistics? In-Reply-To: References: Message-ID: Gabriel Zachmann wrote: > For some reason, I would like to have some statistics about how often > Python is used in the *scientific* communities (such as astronomy, > genetics, electrical engineering, ...), as opposed to C++ or Java > or other "common" programming languages. It would be nice to know the reason. You're not in computational genetics since you didn't mention Perl as a "common" programming language. You ask for broad fields -- experimental, computational, sequencing/assembly, annotation, gene expression, genology and cladistics are all aspects of genetics. In the one I know best, bioinformatics (overlaps well with computational genetics), people use Perl, Java, Python, then Ruby and others. Guessing based on talking to people at conferences I'll put the numbers at 75% (Perl), 10% (Java), 10 (Python), 5% (other). Whereas the sequence assembly most widely used are in C/C++ for performance reasons and the cladistic programs I know of are in C because they were started in the 1980s. But I don't know those fields well. Andrew dalke at dalkescientific.com From mwm at mired.org Tue Nov 2 14:40:51 2004 From: mwm at mired.org (Mike Meyer) Date: Tue, 02 Nov 2004 13:40:51 -0600 Subject: Python needs a CPyAN References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman writes: > Ville Vainio wrote: >> I think you are overselling CPAN a little bit here. It is not an >> absolute requirement, and I think Python can easily surpass Perl in >> popularity even without CPAN functionality. Perl popularity in general >> seems to be going down, and I don't think Perl is something to worry >> about anymore. Hell, people rarely even mention Perl these days >> anyway. > > Just today we required a module that was not installed on our system. > > sudo perl -MCPAN -e 'install Data::Pager' With PyPI and distutils, we've got 90% of that already. PyPI needs to grow a link to the tarball, and a way to turn a package name into that link. Then you need a tool bundled with Python that gets the link from PyPI, downloads the package, and runs "python setup.py install". If you wanted to be brave about it, you could try scraping the download link out of the PyPI page, then look for the link to the tarball on that page. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From spammers-go-here at spam.invalid Wed Nov 24 11:37:20 2004 From: spammers-go-here at spam.invalid (Madhusudan Singh) Date: Wed, 24 Nov 2004 11:37:20 -0500 Subject: Book recommendation References: <30ictaF2vhlgoU1@uni-berlin.de> Message-ID: <30jrh8F31n13eU1@uni-berlin.de> Paul Robson wrote: > On Tue, 23 Nov 2004 22:21:34 -0500, Madhusudan Singh wrote: > >> I am trying to teach myself Python. I have extensive prior programming >> experience in Fortran, a little in C/C++, Pascal, etc. >> >> So far, I have been reading online tutorials at www.python.org and a book >> I found at the library - Martin Brown's The Complete Reference Python. Is >> there a standard classic book to learn from that I could buy ? >> >> Say something like Metcalf and Reid's Fortran 90/95 Explained or >> Kernighan and Ritchie's The C Programming Language. > > Hi there Madhusudan :) > Hi :) > There's a couple of brief introductions worth reading ; one is by the > language's creator Guido van Rossum, and the other by a chap called > Swaroop (A byte of Python I think it's called). Both of these are quick > read introduction type things. > > A most entertaining and completely backward book is "Dive into Python" > (all these are free downloads but you can buy the latter as a book) which > has the approach where each section starts of with a relatively > complex working chunk of Python code, then pulls it apart and shows you > how all the bits work, and explains the various concepts as you go along. > "Dive into Python" seems to be the favorite so far in this NG. > Once you've done that, if you want some useful bits of coding just to get > the feel of it, try answering some of the Perl or Ruby Quiz-of-the-week > questions (archives are online search for Perl|Ruby quiz of the week). perl-qotw was interesting and language agnostic (If perl can do something, so should Python - not that I know much perl). I will look into it on a regular basis when I get my bearings. > > None of the tasks are more than a page or two of python, but it's a quick > way of getting a feel for the language. > > The other thing that's handy to have to hand is the Quick Reference which > is about 20 or so pages and handy for a quick look up. Yep. > > There are many IDEs and Editors about from the quick and dirty through to > full IDEs (which personally I find too much of a clutter). I personally > like Scite which is the former. I use emacs for everything except authoring webpages. An operating system disguised as an editor :) > > Remember, for i in range(100): print "Murali chucks" :) The above is syntactically correct only if you did not install python-larry :) From __peter__ at web.de Fri Nov 26 04:15:37 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Nov 2004 10:15:37 +0100 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: Message-ID: Peter Maas wrote: > Diez B. Roggisch schrieb: >> import sets >> KEYWORDS = sets.Set(['and', 'or', 'not']) >> >> query = "test and testing and not perl or testit or example" >> >> def decorate(w): >> if w in KEYWORDS: >> return w >> return "*%s*" % w >> >> query = " ".join([decorate(w.strip()) for w in query.split()]) > > Is there a reason to use sets here? I think lists will do as well. Sets represent the concept better, and large lists will significantly slow down the code (linear vs constant time). Unfortunately, as 2.3's Set is implemented in Python, you'll have to wait for the 2.4 set builtin to see the effect for small lists/sets. In the meantime, from a performance point of view, a dictionary fares best: $cat contains.py from sets import Set # we need more items than in KEYWORDS above for Set # to even meet the performance of list :-( alist = dir([]) aset = Set(alist) adict = dict.fromkeys(alist) $timeit.py -s"from contains import alist, aset, adict" "'not' in alist" 100000 loops, best of 3: 2.21 usec per loop $timeit.py -s"from contains import alist, aset, adict" "'not' in aset" 100000 loops, best of 3: 2.2 usec per loop $timeit.py -s"from contains import alist, aset, adict" "'not' in adict" 1000000 loops, best of 3: 0.337 usec per loop Peter From bearsprite at gmail.com Thu Nov 25 01:29:03 2004 From: bearsprite at gmail.com (zhao) Date: 24 Nov 2004 22:29:03 -0800 Subject: Use Python library from C++ In-Reply-To: <89cc6e1f.0411241939.61a19596@posting.google.com> References: <89cc6e1f.0411241939.61a19596@posting.google.com> Message-ID: <1101364143.006433.314340@z14g2000cwz.googlegroups.com> Chang LI wrote: > I want to use the Python Libray from my C++ program. > The Python Libray is no GUI. How can I mix C++ and > Python? > > One way is to run PY library as an independent process. > Another way is to start PY as a C++ thread. > The third way is to run Python engine as part of the C++. > Which way is better? > > No intention to access all the Python's code but only > access APIs of a module. Try boost.python and SWIG? (boost.sourceforge.net, swig.sourceforge.net) Both provide a interface between C/C++ and python if you want gui under python, you also can try wxpython or pygtk From aleaxit at yahoo.com Sun Nov 14 04:07:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 14 Nov 2004 10:07:01 +0100 Subject: How to load new class definitions at runtime? References: Message-ID: <1gn8ja3.7d3sbhuk94khN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > attached to it. So simple object instances would not cut it. To allow > the system to be customized without taking the application server > offline, there must be a solution for these new class definitions to > be loaded at runtime. If you need them to be _updatable_ at runtime, look at a recipe by Michael Hudson in the cookbook -- I've updated it for the printed version 2nd ed (since we do have __subclasses__ now, yay!) but that's not done yet. My vote for most useful custom metaclasses ever... > My current solution is simple. Class definitions have to be executed, > and for it to work, the class name and the source code (or the > compiled bytecode) is stored in a database. A class factory function > retrieves the correct class definition (based on the name), and simply > executes the code. You can pickle the bytecode etc (again, cookbook recipes show how) but that has no real advantage wrt storing the source or bytecode. Just make sure, for performance, that if you store the source the bytecode also gets stashed away when first made. Unless for some weird reason you need your code repository to support multiple releases of Python at the same time (eek), you might as well store the bytecode at the time the source is stored -- upgrading release of Python in the future _will_ require a DB conversion and some downtime for the switch. > Now, talking about executing arbitrary code retrieved from a database > isn't exactly a safe proposition. But I can't see any other way to > make it work. I'm now looking for more ideas on how do other people > solved the same problem in other projects. Pointers are welcome. If you want to allow arbitrary class definitions to happen at runtime, "a safe proposition" is an oxymoron -- obviously you have to trust *entirely* the repository of the code (and pickles would be just about the same thing). Digital signatures to ensure the repository has not been tampered with would also need to be stored somewhere entirely trustable, so you might as well declare that the trust must be towards the repository, in all practical cases I can think of. >From past experience with this sort of thing, my practical suggestion is: make sure you have a development/debug mode in which the classes are first looked for on ordinary modules in the filesystem, then gotten from the DB only if the ordinary modules don't have them. When you're developing and debugging, you'll heavily use this feature, believe me, and also Michael Hudson's recipe above-mentioned, since tweaks and mods to the classes will come at a hefty pace. It's a harder deployment decision whether the normal system operation should also support the filesystem, or just the database. The latter makes development less convenient, but distributed processing much easiery to manage, updates are transactional and atomic, etc. It depends on how much customization-during-operation you'll need, vs the other deployment issues. Alex From gaudette at ele.uri.edu Wed Nov 24 00:58:12 2004 From: gaudette at ele.uri.edu (Jason) Date: 23 Nov 2004 21:58:12 -0800 Subject: namespace & imported modules Message-ID: <799208ed.0411232158.2a6d0782@posting.google.com> Hi, I've been having trouble understanding the difference between global namespace within and between modules. For example, I can program a subthread to see a global name (a threaded event to be specific); however, somehow when I break up my code into different modules, the subthread can no longer see the global name in the main program. Here's an example of what I'm trying to accomplish: Working script pseudo-code: ====================================================== # main.py --------------------------- import std modules def thread1 def thread2 launch thread1: wait for event launch thread2: signal thread1's event ====================================================== #END: Broken script pseudo-code and here's it's seemingly equivalent part... #START: Broken script pseudo-code ====================================================== # subfile.py: --------------------------- import std modules def thread1 def thread2 --------------------------- # main.py import std modules from subfile import thread1, thread2 # this should be the only difference launch thread1: wait for event launch thread2: signal thread1's event ====================================================== #END: Broken script pseudo-code The broken code would yield the following exception when thread2 tries to signal thread1's event: "NameError: global name 'myName' is not defined" I hope I didn't simplify the problem too much, but I didn't want to paste 200 lines of code for no one to read. Obviously I'm missing something regarding namespace and global scopes. Would anyone be able to point out what I've overlooked? Any help is appreciated. -Jason From peter at engcorp.com Thu Nov 4 21:31:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Nov 2004 21:31:04 -0500 Subject: Has anyone released a Python "mock filesystem" for automated testing? Message-ID: The term "mock filesystem" refers to code allowing unit or acceptance tests to create, read and write, and manipulate in other ways "virtual" files, without any actual disk access. Everything is held in memory and therefore fast, without risk of damaging real files, and with none of the messiness of leftover files after testing. Googling the archives and the web suggests that only I and Remy Blank have done much along these lines. I don't see any sign that anyone has actually released such a beast yet, however. My own past work in this area was always proprietary, and as "you can't take it with you" I've been starting over on a new project and have the basics working. If nobody can point me to a more complete implementation, I'll be happy to continue to work on mine and release it in the near future. For now, in case anyone is interested, I have support for basic open, read/write, __iter__, close, "r" and "w" modes, a couple of the most basic exceptions, and a tiny handful of lesser things. All well supported by their own unit tests, of course, to ensure quality. Stripped class/def lines shown below, as that may be an easier way for you to picture what this is about: class MockFile(object): def __init__(self, fs, path, data='', mode=''): def _getContents(self): def read(self): def write(self, data): def close(self): def __iter__(self): class FileSystem(object): '''Acts like a real file system to support testing.''' def __init__(self, mocktime=False): def _createFile(self, path, data): def _getFile(self, path): def open(self, path, mode='r'): Thanks for any pointers to more advanced stuff. -Peter From steve at holdenweb.com Tue Nov 2 20:18:41 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Nov 2004 20:18:41 -0500 Subject: Newbie Question In-Reply-To: <783d0f8c.0411012335.196183ce@posting.google.com> References: <783d0f8c.0411012335.196183ce@posting.google.com> Message-ID: <418831F1.8020405@holdenweb.com> [posted and mailed] Uday wrote: > Hi, > I would like to know how can I create and assign variables by > de-referencing the values in other variable in Python. > > I can illustrate what I mean by an example of perl > > $a = "task_id"; > $i = "1"; > $c = $a."_".$i; > $$c = 2; > print "$task_id_1\n"; > # Gives the answer as 2 > > My problem is that I need to dynamically generate a unique > variable within a for loop in Python. The name of the variable > should be appended by the index of the loop. > > In the above example if $i were an array index, then as we > traverse through the array, a unique variable is defined. > > Is there any way to do it in Python?? > > I am not in python.users mailing list, please reply to me directly. > > Thanks, > Uday It's bad enough doing that in Perl, but in Python you should definitely use a dictionary (in Perl read "hash") for applications like this. What do you see as the advantage of your code over using a hash? regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From wolfgang.keller.nospam at gmx.de Thu Nov 4 14:35:33 2004 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Thu, 4 Nov 2004 20:35:33 +0100 Subject: JMS for CPython via JPype? References: <1b2k1czwwox4i$.ae466jlsmeu2$.dlg@40tude.net> Message-ID: Hello, and thanks for your reply. >> would JPype make it possible >> for a CPython program to use JMS? > I am not very well versed in JMS, but unless it absolutely REQUIRE > subclassing, JPype will allow you to make full use for it without problem. > > How to actually interpret the contents of the JMS message is left as an > exercise to the reader ;) Err, does JPype not provide something for interfacing with Java like CTypes provides it for interfacing with C? I.e. working with Java/C types in Python as if they were Python variables? TIA, Regards Wolfgang Keller From exarkun at divmod.com Sat Nov 27 13:28:02 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 27 Nov 2004 18:28:02 GMT Subject: Replacing words from strings except 'and' / 'or' / 'and not' In-Reply-To: Message-ID: <20041127182802.17481.1840580316.divmod.quotient.8311@ohm> On Sat, 27 Nov 2004 12:54:02 -0500, Peter Hansen wrote: >Peter Maas wrote: > > Diez B. Roggisch schrieb: > >> import sets > >> KEYWORDS = sets.Set(['and', 'or', 'not']) > >>... > >> def decorate(w): > >> if w in KEYWORDS: > >> return w > >> return "*%s*" % w > >> > > Is there a reason to use sets here? I think lists will do as well. > > Sets are implemented using dictionaries, so the "if w in KEYWORDS" > part would be O(1) instead of O(n) as with lists... > > (I.e. searching a list is a brute-force operation, whereas > sets are not.) And yet... using sets here is slower in every possible case: exarkun at boson:~$ timeit.py -s 'from sets import Set; x = Set(["and", "or", "not"])' 'None in x' 1000000 loops, best of 3: 1.54 usec per loop exarkun at boson:~$ timeit.py -s 'from sets import Set; x = Set(["and", "or", "not"])' '"not" in x' 1000000 loops, best of 3: 1.49 usec per loop exarkun at boson:~$ timeit.py -s 'from sets import Set; x = Set(["and", "or", "not"])' '"or" in x' 1000000 loops, best of 3: 1.48 usec per loop exarkun at boson:~$ timeit.py -s 'from sets import Set; x = Set(["and", "or", "not"])' '"and" in x' 1000000 loops, best of 3: 1.46 usec per loop exarkun at boson:~$ timeit.py -s 'x = ["and", "or", "not"]' 'None in x' 1000000 loops, best of 3: 0.5 usec per loop exarkun at boson:~$ timeit.py -s 'x = ["and", "or", "not"]' '"not" in x' 1000000 loops, best of 3: 0.235 usec per loop exarkun at boson:~$ timeit.py -s 'x = ["and", "or", "not"]' '"or" in x' 1000000 loops, best of 3: 0.21 usec per loop exarkun at boson:~$ timeit.py -s 'x = ["and", "or", "not"]' '"and" in x' 10000000 loops, best of 3: 0.186 usec per loop exarkun at boson:~$ This is a pretty clear example of premature optimization. When developing any software, the first goal should be to make it work, as simply as possible. Then, when a need for improved performance is identified, the software should be profiled. Finally, when real hot spots are identified, they should be optimized. Going out of order is often detrimental, and the above example is a clear case of this: the "optimization" slowed down the function by a factor of no less than 3 and no more than 8.2. Jp From baza at themauvezone.fsnet.co.uk Sat Nov 13 13:25:01 2004 From: baza at themauvezone.fsnet.co.uk (Baza) Date: Sat, 13 Nov 2004 18:25:01 +0000 Subject: idle on mac os 10.3.5 References: Message-ID: > You'll need to get MacPython2.3 for panther from > http://homepages.cwi.nl/~jack/macpython/download.html > > Install it and launch /Applications/MacPython-2.3/PackageManager. > Install tkinter. > > You may, or may not - can't remember, have to install TclTkAqua-8.4.7 > from http://tcltkaqua.sourceforge.net/ It seems there is a, 'show stopper' bug in this that prevents idle from running, it's mentioned on their site. So I'm stuck with using a texted editor and >>> for the moment it seems. Barry From duncan.booth at invalid.invalid Tue Nov 30 08:24:42 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2004 13:24:42 GMT Subject: weird behaviour of "0 in [] is False" References: Message-ID: Sylvain Thenault wrote: > Hi there ! > > Can someone explain me the following behaviour ? > >>>> l = [] >>>> 0 in (l is False) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required >>>> (0 in l) is False > True >>>> 0 in l is False > False > > > This is really obscur to me... > >From the language reference (5.9 Comparisons): > comparison ::= or_expr ( comp_operator or_expr )* > comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" > | "is" ["not"] | ["not"] "in" > > ...snip... > > Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy > are comparison operators, then a opa b opb c ...y opy z is equivalent > to a opa b and b opb c and ... y opy z, except that each expression is > evaluated at most once. In other words '0 in l is False' is equivalent to '0 in l and l is False'. From bokr at oz.net Sun Nov 7 18:36:19 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 07 Nov 2004 23:36:19 GMT Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: <418e8f90.1885952706@news.oz.net> On Sun, 07 Nov 2004 10:33:01 +1100, Maurice LING wrote: > >> >> dude that "comparision" from twistedmatrix you refrence is ANCIENT!!! > >I am wondering the impact when IBM decided that the base memory to not >exceed 64kb, in the late 1960s... > >I suppose more experienced people in this list can agree that certain >decisions made can be almost an edict. So, there is a re-building >process every now and then, hopefully to by-pass such edicts. Python >itself is already such an example. > >> >> it is comparing versions that are YEARS out of date and use! > >Are the codebase of Python 1.5.2 and Java 1.1 totally replaced and >deprecated? > >Lisp compiler is the 1st compiler to be created (according to the >Red-Dragon book, I think) and almost all others are created by >bootstrapping to LISP compiler. What are the implications of design >decisions made in LISP compiler then affecting our compilers today? I >don't know. I repeat myself, I DO NOT KNOW. > google is your friend. I would suggest prefixing "UIAM" to statements or strong implications of "fact" that you are not really sure of ;-) Perhaps you are not familiar with the various typical ways of softening the assertiveness of statements in English? I notice several statements above that start out looking like authoritative statements of fact, but which you qualify in your way, yet it seems you were unsatisfied with the effect, and added the last sentence. "We are all ignorant, only on different subjects", as (UIAM ;-) Will Rogers said. But here at c.l.py it is unlikely that all are totally ignorant on a particular computer language subject, so if you post an unqualified statement of "fact" (or slip an implicit statement of "fact" into a question, as in the subject line of this thread ;-) that may not be so, someone will notice, and wonder why you are doing that (since you haven't annnounced that you're a political candidate ;-) One reason might be language difficulties, but your English is too good for that to jump immediately to mind. Another reason might be forgetting that posting here is actually engaging other human beings, and thinking of c.l.py posts as a kind of automated google mechanism which has no feelings about how it is being used. But humans do care, and provocative techniques of eliciting response do "provoke." Kids intent on their immediate goals sometimes forget, but generally respond to a gentle reminder. Another reason might be to spread disinformation for some private reason, e.g. as a sleazy way to discredit competition. I don't think that applies here. Or are you heavily invested in particular stocks? ;-) Anyway, I think the best we can do is to help each other find out what the real facts are, which requires not presenting suppositions as fact, while recognizing that appearances are often deceiving to even the most experienced. In that spirit, we wind up expressing doubts without bruising egos, and thanking each other for contributions to improved understanding instead of defending against feeling a fool for having believed something that was not so, or being annoyed at careless spread of disinformation. (of course, I haven't personally verified the "facts" stated in the following sites ;-) http://www.emacswiki.org/cgi-bin/wiki/CommonLisp """ The first Lisp compiler was developed by JohnMcCarthy at Dartmouth College between 1955 and 1959. This makes it the second oldest programming language in common use today (only Fortran is older, developed between 1954 and 1957). """ http://www.ibiblio.org/pub/languages/fortran/ch1-1.html """ This wonderful first FORTRAN compiler was designed and written from scratch in 1954-57 by an IBM team lead by John W. Backus and staffed with super-programmers like Sheldon F. Best, Harlan Herrick, Peter Sheridan, Roy Nutt, Robert Nelson, Irving Ziller, Richard Goldberg, Lois Haibt and David Sayre. By the way, Backus was also system co-designer of the computer that run the first compiler, the IBM 704. """ http://www.latrobe.edu.au/philosophy/phimvt/sympas/s49hiteco.html http://www.moorecad.com/standardpascal/pcom.pas Regards, Bengt Richter From robin at SPAMREMOVEjessikat.fsnet.co.uk Sun Nov 28 05:49:16 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 28 Nov 2004 10:49:16 +0000 Subject: C API PyErr_Clear vs PyObject_HasAttrString In-Reply-To: References: <41A88448.4010501@jessikat.fsnet.co.uk> Message-ID: <41A9AD2C.1010404@jessikat.fsnet.co.uk> Andrew MacIntyre wrote: ..... > > Rule: if you call a Python API function, _always_ check its return > status (unless documented as void). if it fails, check for an > exception. if you want to ignore the exception, clear the > exception, otherwise cleanup and bailout. > > This is a paraphrase (from memory) of a previous reply from Tim Peters. > > Notwithstanding this, segfaulting in a Python API function is not welcome > (especially one documented as always succeeding!). > > I had a look at the source (from a CVS checkout this morning), and the > only thing that looks like a source of such trouble would be an extension > class with a tp_getattr implementation. It is such a beast, but the exciting test case looks like ##################### import _test g=_test.gstate() for a in ('strokeColor','strokeColor'): try: setattr(g,a,(1,2,3)) print 'Wrong handling of bad '+a except ValueError: pass ##################### so the tp_getattr slot isn't being used. > > If you are using such a beast, you might want to look at the tp_getattr > implementation first. Otherwise I'd suggest filing a bug report on SF. > BTW, have you tried this with 2.4c1? Can't today, but I'll try and build the cut down extension with 2.4c1 tomorrow. -- Robin Becker From ken at perfect-image.com Tue Nov 30 00:35:45 2004 From: ken at perfect-image.com (Ken Godee) Date: Mon, 29 Nov 2004 22:35:45 -0700 Subject: threading, qt, and the freakout In-Reply-To: <604fc0ca.0411291928.4d59781d@posting.google.com> References: <604fc0ca.0411291928.4d59781d@posting.google.com> Message-ID: <41AC06B1.9050809@perfect-image.com> Ben Floyd wrote: > Hey everyone, > > Why doesn't this work? The code speaks much more clearly than I do, > so i shortened it and pasted it below. Running this > and clicking on 'Break Me' will... freak out the window... You can not mix GUI threads and non GUI threads. Just changing text may seem to work, but even that will get you eventually. Here's an article that explains how to do it... http://www.informit.com/articles/article.asp?p=30708 From rdsteph at mac.com Wed Nov 24 14:44:22 2004 From: rdsteph at mac.com (Ron Stephens) Date: 24 Nov 2004 11:44:22 -0800 Subject: Is there any tools to create User Interface (Dialogs...) for wxPython visually? References: <41a4adf0$0$17787$626a14ce@news.free.fr> Message-ID: Yes, there are a plethora of good options. For starters, you might try looking here: http://www.awaretek.com/toolkits.html From thorsten at thorstenkampe.de Sat Nov 6 06:34:05 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 6 Nov 2004 12:34:05 +0100 Subject: executing python code References: Message-ID: * Darren Dale (2004-11-05 23:47 +0200) > Some time ago I asked about executing a python program or script. For > windows, I was informed that the .py extension could be added to some list > of executable extensions, and then I could just type "mycode" instead of > "python mycode.py". Great advice, worked like a charm. "PATHEXT" > I recently jumped ship, and have been running Gentoo Linux for about two > months. Is it possible to get the same behavior on Linux? No. > I thought it > would have something to do with adding the #!/usr/bin/env python line to my > code, but I'm not sure what this is supposed to do (it didnt work, that > much I know.) > > Could I get some advice? You're confusing a lot of things. Something like "PATHEXT" doesn't exist on Linux. So you always have to type the full name of the script (or use tab completion). You can type "./myapp.py" if the script has the "she bang" first line mentioned above and the file is executable. You can type "myapp.py" if the script has the "she bang" first line mentioned above and the file is executable and the current directory is in your path (which it is /not/ the default under Linux - contrary to Windows - and which is not advised). You can type myapp.py - even if the script is not executable and not in your path and doesn't have a "#!" line if you use an advanced shell like zsh (Z Shell) and add a suffix alias ("alias -s py=python") to your .zshrc Just typing "myapp" won't work. Thorsten From tchur at optushome.com.au Wed Nov 3 16:12:56 2004 From: tchur at optushome.com.au (Tim Churches) Date: 04 Nov 2004 08:12:56 +1100 Subject: Can someone show me a code example that stuffs data into a web page and scrpaes the result ? In-Reply-To: References: Message-ID: <1099516376.1241.56.camel@emilio> On Thu, 2004-11-04 at 08:00, Al Dykes wrote: > Can someone point me to some python code that puts data into several > fields in a web page, clicks on a button to send the page and then > looks for a string in the resulting page and gives me the number > string to thr right of it. See http://wwwsearch.sourceforge.net/ -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From drs at remove-to-send-mail-ecpsoftware.com Mon Nov 29 15:51:50 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Mon, 29 Nov 2004 20:51:50 GMT Subject: Random number generation from functions Message-ID: Is there any way to generate random numbers based on arbitrary real valued functions? I am looking for something like random.gauss() but with natural log and exponential functions. thanks, -d From rahlf at informatik.uni-bonn.de Mon Nov 22 08:34:17 2004 From: rahlf at informatik.uni-bonn.de (Sebastian Rahlf) Date: Mon, 22 Nov 2004 14:34:17 +0100 Subject: pyKDE tutorial Message-ID: Hi! Does anyone know a good tutorial for pyKDE? Seb. -- Sebastian Rahlf rahlf[at]informatik.uni-bonn.de From carribeiro at gmail.com Sat Nov 6 13:29:53 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 6 Nov 2004 16:29:53 -0200 Subject: cherrypy/cheetah vs twisted/nevow In-Reply-To: <69cbbef2.0411050857.6dfe11bd@posting.google.com> References: <418818ca$0$19452$626a14ce@news.free.fr> <69cbbef2.0411050857.6dfe11bd@posting.google.com> Message-ID: <864d370904110610293de941ef@mail.gmail.com> On 5 Nov 2004 08:57:21 -0800, has wrote: > Carlos Ribeiro wrote in message: > > In a way, you're right. The problem is that none of the templating > > models that I know of completely separates the 'M' from the 'V'. > > Plenty of templating systems allow Model-View separation. Not all > *enforce* it, but this is a matter of philosophy [1], not an indicator > that a template system is good or bad. > > Some templating systems (e.g. Nevow.Renderer, PyMeld and HMTLTemplate) > additionally separate presentation logic from markup via an approach > that's strongly reminiscent of Apple-style MVC, where the View layer > consists purely of GUI widget/template node instances and the > Controller layer contains code for (1) manipulating these objects and > (2) connecting to the Model layer. I'm not sure if I understand your point, and it may be the case that I'm really missing something. I think that, by its very definition, templating systems (including variables, conditionals, loops, and other control structures) *do* mix some aspects from the model into the view. One may argue at which extent it's possible to keep both apart -- at some point, there must be an interface -- so it may be a matter of personal choice. My current standing (after a long break from applications development, which allowed me to re-enter with a fresh perspective, but also a little 'rusty') is that the templating interface should be made simpler, not more powerful, and that the model should take care of the intermediation. For example, I *feel* that repetitive elements (like lists and reports) shouldn't be modelled as programming loops inside a template. I really don't have a solution for this yet. Albeit confusing, XSLT is a step in the right direction, but it sometimes feels like they're trying to fit a square peg into a round hole. Nevow implement a very intriguing idea: it allows to derive the *structure* from the template. I'm still looking, though. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jerf at jerf.org Sun Nov 14 18:38:53 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 14 Nov 2004 18:38:53 -0500 Subject: using python on the command line with 'here-documents' and pipes References: Message-ID: On Sun, 14 Nov 2004 18:12:42 +0100, calmar wrote: > It would be possible to use here-documents (for having the correct > identation during e.g while loops) for writing python code on the fly, but > then how and where to get the pipe output: > > echo -e 'line1\nline2' | python < > Does not really work... > > Would anybody have an idea how to use python like e.g. awk etc. As a tool > within, where I can handle the stdin data, and write the code right there > (e.g. with here documents)? Can you post a working example for awk? I'll admit I'm not a shell expert, but it seems like you are trying to stuff two files onto stdin, the "echo" result and the python program. I don't understand how that could ever work, and now you've piqued my curiosity. From irond_will at yahoo.com Tue Nov 30 17:55:25 2004 From: irond_will at yahoo.com (irond_will) Date: 30 Nov 2004 14:55:25 -0800 Subject: PIL interpolation access References: <9654e9e8.0411301118.15ce43ee@posting.google.com> Message-ID: <9654e9e8.0411301455.243ad248@posting.google.com> I managed to get steps 2 and 4 fixed (grabbing and putting the pixels). I converted some code found at http://effbot.org/zone/pil-numpy.htm written by Fredrick Lundh. Currently, it only works for RBG bitmaps. I'm certain that there are better ways to do some of this, but it's pretty zippy as it stands. Now I really need to figure out the bicubic interp, since that's the part that takes hours right now. import image import numarray def image2numarray(im): #This function returns an array of RGB pixel values #The dimensions correspond as follows: #Dim 1 = column or x value #Dim 2 = row or y value #Dim 3 = color value or [R,G,B] for [0, 1, 2] if im.mode not in ("L", "F","RGB"): raise ValueError, "Unsupported image type" if im.mode == "L": a = fromstring(im.tostring(), UInt8) a.shape = im.size[1], im.size[0] elif im.mode == "F": a = fromstring(im.tostring(), Float32) a.shape = im.size[1], im.size[0] else: a = fromstring(im.tostring(), UInt8) a.shape = (im.size[1], im.size[0],3) a.transpose((1,0,2)) return vect_math.array_flip(a,1) def numarray2image(a): #This function returns an array of RGB pixel values #The dimensions correspond as follows: #Dim 1 = column or x value #Dim 2 = row or y value #Dim 3 = color value or [R,G,B] for [0, 1, 2] #The standard adopted here is that the lower-left corner is [0,0] a = a.astype('UInt8') b = vect_math.array_flip(a,1) b.transpose((1,0,2)) return Image.fromstring('RGB', (b.shape[1], b.shape[0]), b.tostring()) def array_flip(X,ndim): #flips X along specified axis return take(X,tuple(range(X.shape[ndim]-1,-1,-1)),axis=ndim) "Caleb Hattingh" wrote in message news:... > Hi > > I can't help you directly, but I am also finding im.putpixel to be > extremely slow - as the docs recommend, can you try using the > pixel-placing method of Draw? This is what I am going to try for my > application (resampling algorithms). > > Thx > Caleb From mpapec at yahoo.com Mon Nov 22 11:21:26 2004 From: mpapec at yahoo.com (Matija Papec) Date: Mon, 22 Nov 2004 17:21:26 +0100 Subject: for(each) element aliasing Message-ID: <2844q0l5ccahj6poumolghrcm2u2boo9ka@4ax.com> I know how to alter the list via list indicies but I would like to know if there is posibility to write in Python something like: my @arr = 1..3; for my $element (@arr) { $element *= 2; } print "@arr\n"; and get the result ------- 2 4 6 -- Matija From ahaas at airmail.net Sat Nov 13 13:43:17 2004 From: ahaas at airmail.net (Art Haas) Date: Sat, 13 Nov 2004 12:43:17 -0600 Subject: [ANNOUNCE] Nineteenth release of PythonCAD now available Message-ID: <20041113184317.GR7238@artsapartment.org> I'm pleased to announce the nineteenth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or Python 2.3. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. As of the sixteenth release, a Cocoa based front end is available for people on OS X having the Python/Objective-C bindings. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The nineteenth release of PythonCAD fixes a file saving bug found shortly after the eighteenth release was made public. The bug affected drawings that had text entities. A fix for this bug was found and tested by the bug reporter (thanks Ed Richley!) and confirmed to fix the problem. The serious nature of the bug called for making this new release. The only other change appearing in this release is the addition of the PostScript command 'showpage' appearing at the end of the generated plot file. Anyone using the eighteenth release is urge to upgrade immediately. The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From jepler at unpythonic.net Wed Nov 17 14:22:38 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 17 Nov 2004 13:22:38 -0600 Subject: os.system vs os.system inside thread -> why is there any difference? In-Reply-To: References: Message-ID: <20041117192237.GC25465@unpythonic.net> On POSIX systems, Python blocks the delivery of signals to threads, and installs a 'pthread_atfork' handler to restore the default behavior when fork() is called, because otherwise it leads to weird behavior in programs started with fork+exec. In the case of arping, I suspect the of the SIGALRM signal remains blocked, and arping waits forever for either the signal or the return packet. On Linux, at least, system() never calls the pthread_atfork handler, and the redhat maintainers have made it clear that they believe this behavior is allowed by the Open Group unix specification. Here's an entry-point into a python-dev thread on the subject: http://mail.python.org/pipermail/python-dev/2003-December/041311.html with links to the Open Group specification and the closed redhat bug. I suggest you write a replacement for system() in terms of fork + exec and then you should get the behavior you want. I continue to believe this is a redhat or glibc bug but my opinion doesn't seem to matter. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ark at acm.org Sat Nov 20 09:32:57 2004 From: ark at acm.org (Andrew Koenig) Date: Sat, 20 Nov 2004 14:32:57 GMT Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> <419E6C13.1040508@v.loewis.de> Message-ID: "Steve Holden" wrote in message news:b8ynd.1301$QR.263 at lakeread01... > I seriously wonder how long the US Patent Office is prepared to continue > making an ass of itself. I do not know if this is still true, but I heard a number of years ago that the US Patent office, in response to Congress denying their request for more funding for patent examiners, combined with court rulings that require them to accept software patents, decided to accept any software patent that is filed. Of course, such acceptance does not guarantee that the patent is worth anything. What happens instead is that if there is an infringement case, the defendant has the opportunity to claim that the patent is invalid, either because it is obvious or because there is prior art. So in effect the Patent Office is shifting their financial burden onto the shoulders of prospective defendants. From dfh at forestfield.co.uk Thu Nov 4 05:50:44 2004 From: dfh at forestfield.co.uk (David Hughes) Date: 4 Nov 2004 02:50:44 -0800 Subject: How do you execute an OS X application (bundle) from Python? Message-ID: <70bb9f8d.0411040250.1f4ac1a@posting.google.com> For example, in Python in a Nutshell, Alex Martelli shows how you can run a Windows (notepad.exe) or Unix-like (/bin/vim) text editor using os.spawnv(os.P_WAIT, editor, [textfile]) But how would you call the OS X text editor /Applications/TextEdit.app - which appears to be a whole directory inside /Applications? I'm sorry if the answer is blindingly obvious. I work alone and sometimes just get stuck, then have to ask in public and risk appearing a noodle brain. David From tjreedy at udel.edu Fri Nov 26 16:34:42 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Nov 2004 16:34:42 -0500 Subject: dictionary initialization References: <740c3aec04112613043a0b0d2b@mail.gmail.com> Message-ID: "BJ?rn Lindqvist" wrote in message news:740c3aec04112613043a0b0d2b at mail.gmail.com... > >>> del x > >>> x *= 5 > Maybe Python can't guess it, but *I* can guess, with 99% certainity, > that the user wants x to be 0. :) However, it is 'obvious' to me that the 'proper' initialization is 1 and the intended result should be 5. Or that the programmer forgot something and that the proper response is to raise an error, as Python does. Wanting 5 * undisclosed something to be 0 strikes me as unlikely and a distant third since x = 0 is much easier to say. Also: 'x op= y' is defined as being semantically equal to 'x = x op y' except for the single rather than double evaluation of x. Therefore, if the latter raises an error for unbound x, so should the former. Terry J. Reedy From simon.alexandre at cetic.be Fri Nov 12 08:59:54 2004 From: simon.alexandre at cetic.be (simon.alexandre at cetic.be) Date: Fri, 12 Nov 2004 14:59:54 +0100 Subject: Accessing an instance via its memory address (instance at ...) Message-ID: Hi I have a list containing several instance address, for example: [, , ] I'd like to invoke a method on each of these instance but I don't know : 1. if its possible 2. how to proceed someone can help me ? tks simon From jcarlson at uci.edu Tue Nov 16 20:29:05 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 17:29:05 -0800 Subject: why python? In-Reply-To: References: Message-ID: <20041116172320.F97C.JCARLSON@uci.edu> "99%SugarFree" wrote: > For those of you who used Python, have you used Prolog or ML??What do u > think of these 3 language comparing to each other when you are coding? Yes, I've used both Prolog and SML-NJ. Prolog was nifty, as was SML-NJ. Being that they take completely different approaches in the way you think of and implement algorithms, I am not sure they are comparable in any useful sense of the word. > I've just known about Python language recently for a research project. > I'm just wondering what kind of applications out there using Python?? Many. http://sourceforge.net/softwaremap/trove_list.php?form_cat=178 Is just a start. > Where can I find more information about the philosophical, technical and > design features of Python?? >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! From hungjunglu at yahoo.com Sun Nov 14 03:22:58 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 14 Nov 2004 00:22:58 -0800 Subject: Creating combination of sequences References: <7dc80c2.0411131026.c4cf2e@posting.google.com> Message-ID: <8ef9bea6.0411140022.447d03fb@posting.google.com> minho_chae at yahoo.com (Minho Chae) wrote: > I'm trying to create combinations of sequences. > For example, if the sequence is 'acgt' and the length is 8, > then I would like to have 4^8 results such as > 'aaaaaaaa', 'aaaaaaac', 'aaaaaaag', 'aaaaaaat', ... 'tttttttt' strings = lambda Xs, k: reduce(lambda r, i: [p + x for p in r for x in Xs], range(k), ['']) print strings('acgt', 8) This has been recently discussed. See http://groups.google.com/groups?hl=en&lr=&selm=8ef9bea6.0410231916.450f67d%40posting.google.com http://groups.google.com/groups?hl=en&lr=&selm=1gm5ojm.10239ef1m2hnrpN%25aleaxit%40yahoo.com and other previous threads and follow-ups. This question seems to pop up more often than I thought. Kamsahapnida, Hung Jung From ialbert at mailblocks.com Mon Nov 1 13:56:49 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 01 Nov 2004 13:56:49 -0500 Subject: Few questions In-Reply-To: <5c882bb5.0411010835.5a409600@posting.google.com> References: <5c882bb5.0411010835.5a409600@posting.google.com> Message-ID: bearophile wrote: > but the memory used by the list isn't free even a little time later. Moreover won't ever be freed (from the operating system's view) until the program ends. That's how C works and has nothing to do with the kind of object that was allocated for. The only thing that a free() operation is required to do is to make the freed memory available for allocation within the same program. Istvan. From wenshengwang at gmail.com Tue Nov 30 15:40:42 2004 From: wenshengwang at gmail.com (ws Wang) Date: 30 Nov 2004 12:40:42 -0800 Subject: MySQLdb problem with mod_python, please help References: <7b22037d.0411262345.dcff5bb@posting.google.com> <313b0qF36dhk7U1@uni-berlin.de> Message-ID: <7b22037d.0411301240.53b6dc2d@posting.google.com> Damjan wrote in message news:<313b0qF36dhk7U1 at uni-berlin.de>... > > MySQLdb is working fine at command line, however when I tried to use > > it with mod_python, it give me a "server not initialized" error. > > Maybe its this problem? > http://www.modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp yep! that's the culprit. I havent' recompile php, but by removing loadmodule php, mod_python+mysql worked. Thank you very much Damjan. From exarkun at divmod.com Wed Nov 17 10:43:52 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 17 Nov 2004 15:43:52 GMT Subject: how do I read a series of pickled objects from a socket? In-Reply-To: <20041116205506.22904.qmail@web21205.mail.yahoo.com> Message-ID: <20041117154352.27631.836308475.divmod.quotient.1294@ohm> On Tue, 16 Nov 2004 12:55:06 -0800 (PST), Ryan Grow wrote: >Hi, > > I am trying to figure out the correct and most > reliable way to read a series of pickled objects from > a socket. > I've found examples that do something like this: > > while 1: > data = conn.recv(500) > obj = pickle.loads(data) > # do stuff with object > > I don't think the above example would work for my > application. The above example might work if the > server never expects to get more than one object on > the socket at a time. > > The server I'm writing will get a series of objects so > it will need to know where each pickled object ends in > the stream so it knows where to start reading the next > object from. > > Is there a correct way to identify the terminator of a > pickled object? Is there a standard and correct way > for the pickle module to easily read pickled objects > from a socket? > The above approach has several problems. The most obvious of these are that it is unbelievably insecure, anyone who can connect to the server can cause it to execute arbitrary code, and that it lacks the necessary buffering code to make the right bytes actually show up in the right place. Instead of creating your own, you may wish to investigate an existing remote object protocol. Python has quite a group of them. One reasonable starting place is the "Perspective Broker" section of http://twistedmatrix.com/documents/current/howto/ Jp From bdesth.quelquechose at free.quelquepart.fr Thu Nov 4 09:05:30 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Nov 2004 15:05:30 +0100 Subject: Should I learn Python? In-Reply-To: <624a388a.0411030512.3cf84547@posting.google.com> References: <624a388a.0411021328.5ac41f4c@posting.google.com> <418807d0$0$19691$626a14ce@news.free.fr> <624a388a.0411030512.3cf84547@posting.google.com> Message-ID: <418a370d$0$7210$636a15ce@news.free.fr> Sam wrote: > So you're saying, in order to write smart, clean, well structured, > readable code, and have fun doing so, I'm going to have to drop PHP > and use Python? Err... You might not have notice, but this was enclosed in a tag !-) You can of course write smart, clean, well structured, readable code in PHP - it's just that's it's easier and more fun (IMVHO) to do so in Python. > I'm not really interested in finding a replacement for PHP, it works > just fine for me. > > I apologize for not phrasing my questions clearly, I wasn't looking > for critisisms of PHP or why I shouldn't use it. I apologize for being a troll. > What i'm really > after, is given that I use PHP to develop sites currently, what types > of situations would/could i use Python in web development? Well, there's no exact answer to this question. It's not a matter of raw functionnalities, PHP has it all (or almost, but well...). What Python has to offer is : - the language itself, which is IMHO cleaner, smarter and more fun - frameworks or application servers like Zope, Twisted, Nevow etc Zope is somewhat not easy to 'get into', but it's worth the effort, and you can experience productivity gain even on the first project (well... I did at least). > Is there a > point when learning Python, that I'll say to myself "why use php?". Depends on you. I personnally still use PHP for quick&dumb stuffs like includes, simple forms etc., cause Python itself would not buy me anything for such things and using Zope would be overkill. > Thanks You're welcome (and please forgive my trollness) Bruno From pecora at anvil.nrl.navy.mil Sun Nov 7 09:26:45 2004 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sun, 07 Nov 2004 09:26:45 -0500 Subject: Installed MacPython 10.3 Addons - Can't find Modules, even standard ones. Message-ID: I upgraded to Panther a month ago and just upgraded to MacPython 10.3 Addons (as per Jack Jansen's page - thanks, Jack). But now my programs can't even find standard modules. from Numeric import * brings up the error window: Can't find module Numeric. Even trig functions sine and cosine generate the same type of error. I've looked over the FAQ and can't see any answers (maybe I missed something). I'm guessing this is a Path problem, but I'm stumped. I have PYTHONPATH set to some of my modules (which seems to work), but not sure what to do about standard stuff. Any clues appreciated. Thanks. -- Lou Pecora (my views are my own) P.S. I posted this on Python-Mac-SIG email list, too. Sorry if you are seeing it again. From syd.diamond at gmail.com Mon Nov 1 20:09:53 2004 From: syd.diamond at gmail.com (syd) Date: 1 Nov 2004 17:09:53 -0800 Subject: general class functions Message-ID: In my project, I've got dozens of similar classes with hundreds of description variables in each. In my illustrative example below, I have a Library class that contains a list of Nation classes. In one case, I might want a Library class with only Nations of with the continent variable "Europe", and so I'll do something like library.getContinent('Europe') which will return a Library() instance with only European nations. Similarly, I could also want a Library() instance with only 'small' size nations. My question follows: is there a way I can make a general function for getting a subclass with my specific criteria? For instance, can I pass in an equivalence test or something like that? I have hundreds of variables like "nation", "continent", and so forth, and do want to write a separate "get______" function for each. This stumped everyone I work with. Help would be greatly appreciated!! #!/usr/bin/python class Library: def __init__(self,list=None): self.list=list def add(self,nation): try: self.list.append(nation) except: self.list=[nation] def defineNation(self,name,continent,size): nation=Library.Nation() nation.name=name nation.continent=continent nation.size=size self.add(nation) def getContinent(self,continent): library=Library() for nation in self.list: if nation.isContinent(continent)==True: library.add(nation) return library def getSize(self,size): library=Library() for nation in self.list: if nation.isSize(size)==True: library.add(nation) return library def getNameList(self): outList=[] for nation in self.list: outList.append(nation.name) return outList class Nation: def __init__(self,name=None,continent=None,size=None): self.name=name # eg, Spain self.continent=continent # eg, Europe self.size=size # eg, medium def isContinent(self,continent): if self.continent==continent: return True else: return False def isSize(self,size): if self.size==size: return True else: return False library=Library() library.defineNation('Spain','Europe','medium') library.defineNation('USA','NorthAmerica','large') library.defineNation('Luxembourg','Europe','small') library.defineNation('Portugal','Europe','medium') print library.getNameList() print library.getContinent('Europe').getNameList() print library.getContinent('Europe').getSize('small').getNameList() From davidf at sjsoft.com Tue Nov 23 13:52:29 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 23 Nov 2004 20:52:29 +0200 Subject: Pure Python JPEG parser In-Reply-To: References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com><419d002e$1@nntp0.pdx.net> Message-ID: David Fraser wrote: > Fredrik Lundh wrote: > >> David Fraser wrote: >> >>> It *did* make me think "I wish there was some Pure Python >>> image-handling code". It seems like the C linkage is mainly required >>> for image formatting handling - I couldn't find any JPEG >>> reading/writing code in Pure Python ... would be nice :-) >> >> >> and incredibly slow. PIL uses C for a reason. >> > > I've recently discovered you can use the EXIF module to read thumbnails > that are embedded in a JPEG or TIFF file without having to parse all the > JPEG stuff. All I'm doing for my particular task is creating thumbnails > - I can imagine that this may be reasonably fast within Python. > Even if it was slow, it wouldn't neccessarily have to be *incredibly* > slow :-) I couldn't resist it... I found a C++ simple (and imperfect) JPEG parser (http://www.codeproject.com/bitmap/TonyJpegLib.asp) and converted it by hand to pure Python ... It can basically decode most JPEG files and then output the result as a BMP. Not surprisingly, it's fairly slow. Using Psyco can speed it up. Here's a table of a brief test, image size and execution time under Standard Python and Psyco running on my Athlon Image Size | Standard Python | Psyco photo, 2048 x 1536 | 32 minutes | 46 seconds cartoon, 604 x 446 | 16 seconds | 4 seconds I would guess that the algorithms being designed for C is a major factor, and that doing some simple recoding would speed it up a fair bit. I've put the code at http://davidf.sjsoft.com/files/pyjpeg/ I wrote a basic BMP format handler as well that the test handler requires so that's there too. Note 1: I am only beginning to understand JPEG from converting the code :-) And the original C++ code doesn't convert the image perfectly, it has plenty of smudges which my Python code faithfully reproduces Note 2: The code is horribly ugly for Python code Anyone welcome to clean and speed it up... David From harry.g.george at boeing.com Tue Nov 30 09:25:50 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 30 Nov 2004 14:25:50 GMT Subject: SOAPpy/ZSI/Twisted SOAP over stdin/stdout? Message-ID: Normally the SOAP Servers are designed to take control of a port and run their own sockets via inheritance from SocktServer. But under inetd and xinetd, the port is controlled elsewhere and the service just gets the stdin/stdout. I need to configure (or tweak) one of the SOAP servers to use that connection. Has anyone done this with any of the above named SOAP servers? Recommmendations or hints if I try it myself? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From brion at pobox.com Tue Nov 16 03:41:13 2004 From: brion at pobox.com (Brion Vibber) Date: Tue, 16 Nov 2004 00:41:13 -0800 Subject: Identifying bundles in MacOS X In-Reply-To: References: <2vt7veF2nues7U1@uni-berlin.de> Message-ID: <2vtsp6F2nlt2cU1@uni-berlin.de> Michael J. Fromberger wrote: > Actually, Apple's developer documentation seems to imply that there is a > "bundle bit" in the Finder info (or possibly the extended Finder info) > for directories, and that if this bit is set, the Finder will treat the > folder as a bundle. It's worse than that... the bundle bit _might_ or _might not_ matter, since it's not always present, and some extensions are known or not or... ugh. Fortunately, it should be possible to get this information out of Launch Services instead of replicating all the same checks: one of the flags bit it can return is 'kLSItemInfoIsPackage'. It seems to make the correct bundle/not bundle determination in my admittedly limited spot checking. I'm not sure if there's a standard Python module to expose Launch Services, but here's a C snippet; use it as you like: #include bool isFilePackage(const char *file) { CFStringRef path = CFStringCreateWithCString( NULL, file, kCFStringEncodingUTF8); CFURLRef url = CFURLCreateWithFileSystemPath( NULL, path, kCFURLPOSIXPathStyle, false); CFRelease(path); LSItemInfoRecord info; LSCopyItemInfoForURL(url, kLSRequestAllInfo, &info); CFRelease(url); return 0 != (info.flags & kLSItemInfoIsPackage); } (error checking snipped for brevity) -- brion vibber (brion @ pobox.com) From grante at visi.com Tue Nov 9 12:26:03 2004 From: grante at visi.com (Grant Edwards) Date: 09 Nov 2004 17:26:03 GMT Subject: sockets: How to know when your data is sent References: <4190e27f$0$95596$a1866201@visi.com> Message-ID: <4190fdab$0$87168$a1866201@visi.com> On 2004-11-09, Sion Arrowsmith wrote: >>> When I use the send function, it will happily send a buffer of >>> a megabyte and more in one shot. But of course, the data is >>> still in the network buffer... [ ... ] The problem is, how >>> can I know when it's done? >> >>Under Linux, there is no way to tell. IIRC, there's no way to >>tell under BSD either. I actually wrote some kernel mode code >>once upon a time to provide an ioctl() that I could call from >>user space to find out when the data I had written to a socket >>was actually sent. > > I may well be missing the point of the problem here, but wouldn't > just turning TCP_NODELAY on guarantee that send() won't return > until the last ACK has returned? Nope. Send returns as soon as the the data is copied to a a kernel-space buffer. TCP_NODELAY has no effect on that. It only changes the stack's behavior as it's taking data from that buffer and putting it on the wire. Eventually, the TCP window will fill up, and after than the tx buffer will fill up, and after that, send will block. There's no practical way to predict the size of either the TCP window or the tx buffer. There's also no practical way to determine how much data is still waiting to be acked (unless you want to do kernel hacking). > And if you're not using TCP: > >>The way to tell that data has been sent is to use an >>application-level protocol that acknowleges the data transferr. > > applies in spades if you care about reliability. Unfortunately, many people who write network applications (and protocols) make all sorts of bizarre assumptions, and somebody ends up jumping through hoops later to try to fix things when those assumptions turn out to be wrong. :/ -- Grant Edwards grante Yow! I wonder if I should at put myself in ESCROW!! visi.com From lynn at crazedimaginations.net Sat Nov 20 19:02:42 2004 From: lynn at crazedimaginations.net (Lynn) Date: Sat, 20 Nov 2004 16:02:42 -0800 Subject: stopping the sound server in PySol code -- how? References: Message-ID: Lynn wrote: > I have a SuSe 9.1 linux box (although this isn't a new issue) with > reasonably up to date everything. When I run PySol, it grabs the sound > system in a rude and complete way. > > I don't listen to sound and I NEED my sound system available even if PySol > is running. > > Does anyone have a simple way of ripping the sound functionality our of > PySol? I've not enough of a python programmer to deal with this. > Everything I've tried has just generated a ton of errors. > Solved. Not elegant, but solved. I found several places in the scripts where tests for the presense of pysolsoundserver were being made. And a couple more places where the option for sound was being tested. The test returns what ever it returns, but I just force the answer to always be "failed" and "nosound." I think there were five places to change an assignment statement. Thanks to everyone for your responses. It helped. I learned more about python than I intended. And that can't be bad. :) -- Peace, Love and Absolute Pleasure Crazed Imaginations RHPS cast www.crazedimaginations.net From bokr at oz.net Wed Nov 10 13:02:33 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 10 Nov 2004 18:02:33 GMT Subject: Learning curve - was: Re: Tutorials on Windows GUI programming with References: Message-ID: <419251df.110591442@news.oz.net> On 9 Nov 2004 15:06:20 GMT, mjackson at alumni.caltech.edu (Mark Jackson) wrote: >Gerhard Haering writes: >> >> --cNdxnHkX5QqsyA0e >> Content-Type: text/plain; charset=us-ascii >> Content-Disposition: inline >> >> On Tue, Nov 09, 2004 at 08:47:08AM -0600, Larry Bates wrote: >> > [...] the learning curve > is pretty steep. >> >> Anybody care to explain the term "learning curve" to me? >> >> I'd assume that you have time on the x-axis, and knowledge on the >> y-axis. So a steep curve would mean that you know much in short time. > >One would think so, but. . . > >> But that doesn't seem to be how the terms steep/flat learning curve is >> used :-S > >Evidently it's > > | > | > | > | >Effort | >Required | > | > | > |___________________ > Capability > IMO it's more like Capability level ^ Guru --+ | __ Pro --+ /x | |xx | ___/xxx Useful Wkr-+ /xxxxxxx | __/ xxxxxxx Newbie --+ / xxxxxxx |/_ xxxxxxx +------+------+-----------> Time ^ ^ ^ | | | Job Start Project Start Useful Deadline Work I.e., if you have a near deadline and have to learn a lot in order to produce the required work (x), then d/dt is the slope of the learning curve, and it will have to be steep. Whether one has the horsepower for rapid ascent is another matter, but the fun in python is a good fuel additive ;-) Regards, Bengt Richter From jsbenson at bensonsystems.com Sun Nov 21 14:16:48 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Sun, 21 Nov 2004 19:16:48 GMT Subject: The Microsoft Platform Ahead by David Platt; thoughts about Python and Zope Message-ID: Hi, I've been reading the above-titled book and it looks like some major Python and Zope features have been cherry-picked for pushing down into .NET, like application memory management (Python interpreter), and prefabricated website user management (Zope). I know that these didn't originate with Python and Zope, and also that .NET adds extra Microsoft-specific goodies. However, the real possibility is that the Microsoft-centricity of .NET may diminish in time when VB.NET/C# /ASP.NET provide an attractive multiplatform alternative to Python and Zope or other content-management/portal/web service frameworks. The question I'd like to pose is: Will the open-source web service frameworks suffer the same fate as the Netscape browser? The most likely scenario I see is that Python will remain important as a standalone language and one of the Microsoft CLR (Common Language Runtime) language alternatives (like VB.NET and C#) but that great frameworks (like Zope and Twisted) will be crowded out as Microsoft appropriates and repackages their functionality. Comments? The one opportunity for Python and the open-source frameworks to survive and thrive is that Microsoft has targeted XML Web Services and authentication as basic functionality in .NET. That is, as it currently understands them. The admission in the book that Web Services are in their infancy leaves open the possibility that Microsoft may be playing catch-up with smaller and more agile frameworks in this area until the technology matures. Please forgive the oxymoron. It is probable that no computer technology matures: it either evolves or dies, or hangs on in the living death of legacy maintenance.) From jepler at unpythonic.net Tue Nov 9 13:51:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 9 Nov 2004 12:51:13 -0600 Subject: sh: test: argument expected and os.environ II In-Reply-To: <200411091823.iA9INua4024825@relay.uva.es> References: <200411091823.iA9INua4024825@relay.uva.es> Message-ID: <20041109185113.GG3567@unpythonic.net> Please post your messages as replies, rather than as new threads. When I answered your question about SHELL, I had no idea you were trying to solve some other problem. > The message error 'sh: test: argument expected' comes from the sentence: > energy = atoms.GetPotentialEnergy() > in the python script I am running. Could be that this sentence is always > invoking somehow the Bourne shell? Since 'atoms.GetPotentialEnergy()' seems to refer to some class that is not a part of Python itself, perhaps you should ask on a list for that package. If this is the package known as "ASE" (that's what a google search gives me) then the mailing list you should try may be http://listserv.fysik.dtu.dk/mailman/listinfo/campos Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at holdenweb.com Sun Nov 21 16:07:03 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Nov 2004 16:07:03 -0500 Subject: thread; interrupt_main() doesn't seem to work? In-Reply-To: References: Message-ID: Jerry Sievers wrote: > Fellow Pythonists; According to the docs > > +-----------------+ > |interrupt_main(|)| > +-----------------+ > > Raise a KeyboardInterrupt in the main thread. A subthread can use > this function to interrupt the main thread. New in version 2.3. > > Therefore, I was expecting this short test prog to run and then finish > with the KeyboardInterrupt exception at the bottom in the pause > routine. It doesn't stop there but I can do a manual keyboard > interrupt and get the expected bactrace and program exit. > > --- > > from signal import pause > from socket import socket > from thread import start_new_thread, interrupt_main > from time import sleep > > def go(): > print 'go' > while f.readline(): > print 'line' > print 'empty' > interrupt_main() > print 'done' > > s = socket() > s.connect(('localhost', 80)) > f = s.makefile() > print 'connected' > > start_new_thread(go, ()) > > sleep(2) > s.shutdown(2) > pause() # expecting to get KeyboardInterrupt exception here > > --- > > connected > go > empty > done > ....hangs here as if interrupt_main() does nothing. > > Manual Control-C required to wake up from pause() and exit. > > Traceback (most recent call last): > File "test.py", line 23, in ? > pause() # expecting to get KeyboardInterrupt exception here > KeyboardInterrupt > > Python 2.3.3 on RedHat 7x. > > Wondering what's wrong? > > Thanks > > Perhaps the main thread has to actually be running to respond to the raised exception. Did you try a shortish sleep() instead of the pause? That would at least test this theory. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From niels_bohr at uol.com.br Thu Nov 18 21:28:05 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Fri, 19 Nov 2004 00:28:05 -0200 Subject: Exponential Notation and integers In-Reply-To: References: Message-ID: <1100831285.9260.4.camel@localhost.localdomain> Em Qui, 2004-11-18 ?s 15:49 -0800, Erik Max Francis escreveu: > Timothy Fitz wrote: > > > Why are all numberical literals in exponential notation floats? To me > > it is counter-intuitive for 1e3 to behave so fundamentally different > > from 1000. > > Probably primarily by convention. Most language use computerized > scientific notation to represent floating point numbers, not integers. > It makes sense, after all: should 1.344e3 be an int, but 1.344e2 be a > float? > As far as readbility is concerned, some languages provide the 1_000_000 syntax (1000000 is just too hard to read). Is there any plans to add this to python? Thanks, Fabio > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > I'll have to get over this sooner or later. Why not now? > -- Louis Wu From mauriceling at acm.org Sat Nov 6 18:51:51 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 07 Nov 2004 10:51:51 +1100 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> Message-ID: <418D6397.8020906@acm.org> > Maybe as the old-timers go off, the next batch of old-timers feel that > it is too much to handle. Nobody requires anyone to answer to all > threads..... > Nevertheless I still have to thank Alex for his story on Plato and the studetn who questioned the validity of studying geometry before philosophy (in "reverse Jython" thread). maurice From graham.fawcett at gmail.com Tue Nov 2 15:44:52 2004 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 2 Nov 2004 12:44:52 -0800 Subject: Python needs a CPyAN References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: <1099428292.622129.83160@f14g2000cwb.googlegroups.com> A.M. Kuchling wrote: > And it should be noted I can already install Python packages with > dependencies by running a command such as "apt-get install > python2.3-gnome2", for example. Great point. Collectively, apt-get, yum et. al. and the underlying package models will get far more development time, more polishing and more real-world use than a PyPAN ever would. Perhaps what Python needs is for Win32 to grow a working apt-get...;-) -- G From hungjunglu at yahoo.com Mon Nov 15 06:12:08 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 15 Nov 2004 03:12:08 -0800 Subject: simple recursion help References: <1gm4uqv.nmgjbj1vt0spjN%aleaxit@yahoo.com> <8ef9bea6.0410231916.450f67d@posting.google.com> Message-ID: <8ef9bea6.0411150312.a2bdc5d@posting.google.com> Thorsten Kampe wrote: > * Hung Jung Lu (2004-10-24 04:16 +0100) > > (1) "Variation" is the same as "permutation". > > Sorry, no. Sorry, yes. Just to add some more information, see also: (1) http://en.wikipedia.org/wiki/Combinatorics (2) Download user manuals from any major scientific calculator maker (HP, Casio, Texas Instruments, Sharp, etc.), and you will find them all using the term "permutation" instead of "variation". E.g.: http://www.hp.com/calculators/docs/guides/33sProbFact.pdf You can promote your preferred term ("variation") as much as you want, but to ignore the fact that the majority of people use the term "permutation" is a bit strange, to say the least. Hung Jung From mrjean1ATcomcastDOTnet at no.spam.net Sun Nov 7 21:01:05 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Mon, 08 Nov 2004 02:01:05 GMT Subject: interning strings References: <418e1e69$0$15438$afc38c87@news.optusnet.com.au> <418eab10$0$13356$afc38c87@news.optusnet.com.au> Message-ID: <071120041801483184%mrjean1ATcomcastDOTnet@no.spam.net> A while ago, we faced a similar issue, trying to reduce total memory usage and runtime of one of our Python applications which parses very large log files (100+ MB). One particular class is instantiated many times and changing just that class to use __slots__ helped quite a bit. More details are here /Jean Brouwers ProphICy Semiconductor, Inc. In article <418eab10$0$13356$afc38c87 at news.optusnet.com.au>, Mike Thompson wrote: > [snip very useful explanation] > > > > > By the way, why would you want to mess with these implementation details? > > Use the == operator to compare strings and be happy ever after :-) > > > > '==' won't help me, I'm afraid. > > I need to improve the speed and memory footprint of an application which > reads in a very large XML document. > > Some elements in the incoming documents can be filtered out, so I've > written my own SAX handler to extract just what I want. All the same, > the content being read in is substantial. > > So, to further reduce memory footprint, my SAX handler tries to manually > intern (using dicts of strings) a lot of the duplicated content and > attributes coming from the XML documents. Also, I use the SAX feature > 'feature_string_interning' to hopefully intern the strings used for > attribute names etc. > > Which is all working fine, except that now, as a final process, I'd like > to understand interning a bit more. > > From your explanation there seems to be no language rules, just > implementation accidents. And none of those will be particularly > helpful in my case. > > However, I still think I'm going to try using the builtin 'intern' > rather than my own dict cache. That may provide an advantage, even if it > doesn't work with unicode. > > -- > Mike From zach at cs.uni-bonn.de Mon Nov 8 07:48:36 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 8 Nov 2004 12:48:36 GMT Subject: generic way to access C++ libs? References: Message-ID: > Looked at boost::python? Thanks a lot! That's a very neat tool (like everything from Boost ;-) ), and pretty close to what I was envisioning, except that one still has to sort of manually transform header files into BOOST_PYTHON_MODULE declarations ... Cheers, Gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From robin at reportlab.com Mon Nov 8 06:42:46 2004 From: robin at reportlab.com (Robin Becker) Date: Mon, 08 Nov 2004 11:42:46 +0000 Subject: pep 8 converter? In-Reply-To: References: <418F503F.9050409@chamonix.reportlab.co.uk> Message-ID: <418F5BB6.3000807@chamonix.reportlab.co.uk> Gerhard Haering wrote: > On Mon, Nov 08, 2004 at 10:53:51AM +0000, Robin Becker wrote: > >>Is there a tool that checks/imposes PEP 8 (ie the right core coding >>style?). It seems that bugfix patches which miss on style are rejected out >>of hand. [...] > > > I doubt that's the case. Care to provide an example? > > -- Gerhard Date: 2004-11-07 14:32 Sender: ******* Logged In: YES user_id=31392 The formatting of this patch is wrong. There is a long line (>80 chars) and missing whitespace around commas, operators, etc. -- Robin Becker From rkern at ucsd.edu Sat Nov 20 11:24:28 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 20 Nov 2004 08:24:28 -0800 Subject: stopping the sound server in PySol code -- how? In-Reply-To: References: Message-ID: Lynn wrote: > Lynn wrote: > > >>Robert Kern wrote: > > >>It is via an RPM. I think it's the one that came with SuSE 9.1. It >>installed pysolsoundserver.so. I renamed that file to see if not finding >>it would be enough. But the script failed because it couldn't find it. >> >>I will try uninstalling the rpm and getting the PySol source. >> > > > Nope. If I run from the src (grabbed frm www.pysol.org) I get this stack > trace: > File "pysol.py", line 47, in ? > from main import main > File "/data/apps/pysol-4.82/src/main.py", line 48, in ? > from app import Application > File "/data/apps/pysol-4.82/src/app.py", line 54, in ? > from images import Images, SubsampledImages > File "/data/apps/pysol-4.82/src/images.py", line 47, in ? > from pysoltk import tkversion, loadImage, copyImage, createImage > File "/data/apps/pysol-4.82/src/pysoltk.py", line 81, in ? > exec "from " + m + " import *" > File "", line 1, in ? > File "/data/apps/pysol-4.82/src/tk/soundoptionsdialog.py", line 44, in ? > from pysolaudio import pysolsoundserver > File "/data/apps/pysol-4.82/src/pysolaudio.py", line 44, in ? > import pysolsoundserver > ImportError: No module named pysolsoundserver > > If I strip out every instance of importing that module, it eventually dies > with a tk box alerting me thatg the global pysolsoundserver is not defined. > > I'm farther along than I've ever been though. :) My version has try: from Pysol import pysolsoundserver except ImportError: pysolsoundserver = None -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ianb at colorstudy.com Wed Nov 17 17:41:49 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 17 Nov 2004 16:41:49 -0600 Subject: thread, threading; how to kill a thread? In-Reply-To: References: Message-ID: <419BD3AD.1040908@colorstudy.com> David Bolen wrote: > Ian Bicking writes: > > >>(...) >>Even if it messes things up and I have to restart the process at the >>soonest possible time to clean up the problems, it would be nice to be >>able to exit the process. (...) > > > I'm not positive, but os._exit() may at least let you get the process > exited regardless of any thread states. Indeed, sir, you are right! Thanks. I whipped up something to try to do the right thing (sys.exit), unless things go badly, then do the wrong thing (os._exit): http://svn.colorstudy.com/home/ianb/thread_die.py In Webware we usually run the server so that if it exits with an error code of 3, the server gets restarted. (In other setups you might always restart the server.) Anyway, this way we could actually test if there were wedged threads, and restart the whole server if so. At the same time, most resources should be properly freed. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From aleaxit at yahoo.com Mon Nov 1 15:13:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 1 Nov 2004 22:13:49 +0200 Subject: saved sys.path References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> Message-ID: <1gmlelr.q7q1rz5rc37oN%aleaxit@yahoo.com> Eric S. Johansson wrote: ... > one of the things I've been bothered with using Python for larger > applications is path manipulation. For example, how does one create the > search path necessary to find your own modules if you do not wish > pollute site-packages with your private code. > > the path file looks like this might be a good solution in preference to > modifying sys.path in your code. Are there any scope or limitation > rules for this path modifier? Can this modification be made specific to > an application or is the new path visible to the entire world (which > reintroduces the namespace pollution problem). The modifications to sys.path performed by .pth files are visible to all applications. A single application may (however it chooses to do so) find out or determine a path it wants only for its own imports, and prepend it to sys.path, during its startup (entry-point script). On Windows the popular choice is to stick stuff in the registry; on most Unix-like systems "run-command files" are usually preferred. The Mac (Mac OS X) has an extra possibility, since "an application" is a directory (with extension .app) and the Mac has its own conventions about what is where inside that directory. Python is not particularly different, from the point of view of "where does an app find its own configuration information", from most other languages. Alex From tim.peters at gmail.com Tue Nov 2 14:24:08 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 2 Nov 2004 14:24:08 -0500 Subject: Why is heapify linear? In-Reply-To: <4186e5f9$1@nntp0.pdx.net> References: <4186cb77$1@nntp0.pdx.net> <4186e5f9$1@nntp0.pdx.net> Message-ID: <1f7befae04110211241f3173b9@mail.gmail.com> [Scott David Daniels] > I stupidly took a simple look before posting, and a better look > immediately after posting. I feel really stupid for that and > deserve the big clue stick whack. I don't know -- it's not obvious that heapification can be done in worst-case linear time, and indeed that wasn't realized at first. > The "hand wave" on dict building is because I am still stuck in the > sad old world where, when we said O(1), we meant "worst case linear." > I am sure you remember those times. The "expected-case" or "amortized- > time" silent, rather than stated, still bothers me, not so much in an > irritated way, as in a "my mind still doesn't notice" way. I don't recall much consistency about this no matter how far back we look, For example, quicksort was always always described as an N log N sorting method in my experience, despite that its worst case is quadratic. So I've always qualified O() claims with the intended measure, unless min, max and mean are the same. For example, finding the smallest element in a list is O(n) regardless. Since just finding a minimum is O(n) on its own, it's initially surprising that heapification is also O(n)! From deetsNOSPAM at web.de Sat Nov 6 09:28:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 06 Nov 2004 15:28:08 +0100 Subject: Python OS References: Message-ID: Richard Blackwood wrote: > Is it possible to prototype an operating system in Python? If so, what > would such a task entail? (i.e. How would one write a boot-loader in > Python?) There have been lengthy discussions on this subject in this group - google is your friend. Generally spaeking, its not possible - as there is a fair amount of low-level stuff to be progammed for interrupt routines and the like that can not be done in python. -- Regards, Diez B. Roggisch From grahamd at dscpl.com.au Sun Nov 21 16:46:07 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 21 Nov 2004 13:46:07 -0800 Subject: Python with Apache 2.0 References: <89cc6e1f.0411190632.2976b3e1@posting.google.com> Message-ID: changli_to at hotmail.com (Chang LI) wrote in message news:<89cc6e1f.0411190632.2976b3e1 at posting.google.com>... > Does python support threads safely along with Apache 2.0 in web applications. Yes, but the latest version of mod_python (3.1.3) has a couple of bugs in it in relation to threads which can cause problems when using a threaded MPM with Apache. No indication has been given as to when they will be fixed so you should patch the bugs yourself for now. You can find some details and the patches at: http://www.dscpl.com.au/projects/vampire/PATCHES There is a discussion on the mod_python mailing list archives at: http://www.modpython.org/pipermail/mod_python/2004-October/thread.html Look for the thread starting with "Udate python modules without restarting Apache". It is this discussion which lead to the uncovering of the bugs. From peter at engcorp.com Fri Nov 12 22:48:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Nov 2004 22:48:59 -0500 Subject: problem with "setup.py bdist --formats=zip" In-Reply-To: References: Message-ID: Humpdydum wrote: > I would like to create a "binary" distribution for Windows, but in zip > format, since the installer requires root access. Not sure what you mean here. Windows doesn't have a "root" user, though it has "Administrator". Is that what you meant? I believe you'll find that the installer has an option to install for the current user only, so that you don't have to be an Administrator to do it. -Peter From exarkun at divmod.com Thu Nov 25 21:30:42 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 26 Nov 2004 02:30:42 GMT Subject: Subclassing complex with computed arguments In-Reply-To: Message-ID: <20041126023042.17481.666337864.divmod.quotient.5906@ohm> On 25 Nov 2004 14:30:18 -0800, pcolsen at comcast.net (Peter Olsen) wrote: >I want to define a class "point" as a subclass of complex. > > When I create an instance > > sample = point() > > I want "sample" to "be" a complex number, but with its real and > imaginary parts computed in point()'s __init__ function with their > values based on the arglist. I want to compute with point instances > as though they were native complex numbers, but I want to be able to > define some new methods and over-ride some of complex's existing ones. Something like this? >>> class simple(complex): ... def __new__(cls, real=0, imag=0): ... return super(simple, cls).__new__(cls, real + 1, imag + 1) ... >>> simple(3, 4) (4+5j) >>> The trick is that since complex instances are immutable, you need to change the initialization parameters before the instance is ever created. __new__ is the hook for that. Jp From fake at not-real.bogus Tue Nov 9 23:48:54 2004 From: fake at not-real.bogus (Matt Garman) Date: Wed, 10 Nov 2004 04:48:54 GMT Subject: saving curses screen state (putwin() and getwin() again) Message-ID: I'm working on a curses-based application in Python. I've implemented what I call a "Chooser" (a fancy name for a menu): ---> 1. Choice 1 <--- 2. Choice 2 3. Choice 3 So the user can use the arrow keys to change choices. When he hits enter, the screen is re-drawn with a new interface. When that interface is quit, the screen should return to the Chooser, exactly as it was left. So my strategy is to call putwin() before going to the new interface, and call getwin() after returning from the previous interface. This works as described the *first* time, but subsequent calls to getwin() return the window that was saved with the first call to putwin(). I.e., it's as though only the first call to putwin() has any effect. Any thoughts? Thanks! Matt -- Matt Garman email at: http://raw-sewage.net/index.php?file=email From f.geiger at vol.at Sat Nov 20 10:37:36 2004 From: f.geiger at vol.at (F. GEIGER) Date: Sat, 20 Nov 2004 16:37:36 +0100 Subject: wxPython: how to update a panel content/layout according to a variable content References: <27a5ac50.0411190819.3ad36f15@posting.google.com> Message-ID: wxWindow has Update and Refresh methods. You can override the one of your wxPanel, where you can call all its children to update/refresh themselves. wxPanel's update could be triggered by a timer event, mouse event or whatever. I do such things preferably in timers owned by the widgets themselves. HTH Franz GEIGER "Lo?c Mah?" schrieb im Newsbeitrag news:27a5ac50.0411190819.3ad36f15 at posting.google.com... > Hello > > I have a problem to update the content of a wx.Panel already displayed > after changing a variable, used to define the wx.Panel content. > > I have the following elements in my code: > > DataList: is a list containing some data > > CustomPanel: is a derived class of wx.Panel, > it contains one sizer which contains a smaller panel for each > element of the DataList list > > > After having displayed CustomPanel on the screen, the elements in > DataList change (after a user action like clicking on button) > > I would like to refresh the CustomPanel to take into account the > changes of the DataList list > Is there a kind of Refresh/Update function which could update the > CustomPanel so > that evry sizers and panles contained by this CustomPanel are redrawn > according to the current value of DataList ? > or do you have to write your own update/refresh method for Panel and > Windows objects ? > and are you obliged to detroy the CustomPanel object and re-create a > new one? > > > I would appreciate any hint/reference to do this, and also a code > sample if possible. > > Thanks. > > Lo?c From hungjunglu at yahoo.com Fri Nov 19 09:33:44 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 19 Nov 2004 06:33:44 -0800 Subject: returning unordered keyword arguments from a function (WAS: Are multiple return values really harmful?) References: <30001hF2ptnqcU1@uni-berlin.de> <8ef9bea6.0411180831.e44ae56@posting.google.com> Message-ID: <8ef9bea6.0411190633.4da78912@posting.google.com> Steven Bethard wrote: > Fernando Perez wrote: > > Steven Bethard wrote: > >>>>> r = object(year=2004, month=11, day=18) > > Given that the necessary class is literally a 3-liner, ... > Even at 3 lines, do you really want to rewrite those every time you need > this functionality? I have written the one-liner "class Generic: pass" all too many times. :) Generic objects can be used to represent hierarchical data in tree fashion. As I said, generic objects are also good for pickling/serialization. We are talking about communication between multiple applications, across time and/or space. Other representations include dictionaries or XML. But you can tell that when it comes to compactness and ease of use, generic objects are the way to go. In fact, most common hierarchical data structures only need: (1) the generic object, (2) list, (3) basic types (numbers and strings.) It seems odd that there is no standard generic object in Python. Actually, if one thinks outside Python, in prototypish languages, generic objects are more fundamental. They are the building block of everything else. You don't build your 3-liner generic object from something else... all on the contrary, you build everything else from your generic object. The syntax "object(year=2004, month=11, day=18)" certainly is nice. I wouldn't be surprised that somewhere, someone has already written some programming language that uses this syntax for their fundamental generic object. > On the other hand, I usually find that in the few places where I have > used a record like this, I eventually replace the struct with a real > class... This is true for single programs. It's true for function arguments or outputs. In those places, generic objects are good as the quick and easy way of using hierarchical data structure without the need of formally defining a class. Once things deserve to be replaced by real classes, they are replaced. This is not true for pickling/serialization purpose. When you have pickled data, you don't want to have to search for the definition of the classes, which you or someone else may have written years ago. You want to be able to unpickle/unserialize your data and use it, without the need of class definition. Yes, dictionary can be used, but you: (a) either use mydata['a']['b']['c']['d'] instead of mydata.a.b.c.d, or (b) have a class to convert dictionary-based back to object-based (hence we come back to the problem: where is that code file of the class that some guy wrote 7 years ago?) If I have avoided anything more complicated than "class Generic: pass", it's because this is a one-liner that I can remember how to type anytime. :) Now, if in the language there is something standard, even this trick won't be necessary. From all what I can see, "class Generic: pass" will stay as the preferred choice for many people, for a long time to come. Simplicity counts. Hung Jung From rganesan at myrealbox.com Tue Nov 16 23:39:10 2004 From: rganesan at myrealbox.com (Ganesan R) Date: 17 Nov 2004 10:09:10 +0530 Subject: Rounding curiosity References: <20041116182254.6cb5a603.bartley9@pacbell.net> Message-ID: >>>>> "Tim" == Tim Peters writes: > What's wrong is that you haven't yet read the Python tutorial's > appendix on floating-point issues. That much is easily repaired > : > http://docs.python.org/tut/node15.html IMHO the documentation for round() function is misleading in this respect. It reads ==== round(x[, n]) Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0). ==== Something like, "Note that, since the floating point values cannot represent decimal fractions exactly, the rounding will not be exact." should help. Ganesan From sam at three60.com Tue Nov 2 16:28:22 2004 From: sam at three60.com (Sam) Date: 2 Nov 2004 13:28:22 -0800 Subject: Should I learn Python? Message-ID: <624a388a.0411021328.5ac41f4c@posting.google.com> Hi, I have been developing sites and cms's for the past few years using PHP and mysql. I've been interested in learning a new language and was considering Python. I have a pretty decent grasp of OOP concepts (i know, you're skeptical since I mentioned PHP). I don't have a formal programming background, just learning as I go. So, with that being said, here are some dumb questions. 1. What can I do with Python that I can't do with php? 2. Do you use both PHP and Python in conjunction with each other? 3. In what way could I utilize Python to compliment existing sites or apps built with PHP? Thanks for any help. From timh at zute.net Wed Nov 17 04:08:42 2004 From: timh at zute.net (Tim Hoffman) Date: Wed, 17 Nov 2004 17:08:42 +0800 Subject: psSerial: how to write a single byte value to the serial port? In-Reply-To: <5a050156.0411170057.6c27a6a4@posting.google.com> References: <5a050156.0411170057.6c27a6a4@posting.google.com> Message-ID: <419b151b$1@news.highway1.com.au> SoftwareTester wrote: > http://pyserial.sourceforge.net/ > example shows how to write string to serial port. > > > #Open port 0 at "9600,8,N,1", no timeout > > >>>>import serial >>>>ser = serial.Serial(0) #open first serial >>>>ser.write("hello") #write a string >>>>ser.close() #close port > > > how do i write a single byte value to the serial port? mystring = "hello" ser.write(mystring[0:1]) or ser.write("h") or ser.write(chr(i)) # where 0<=i<=255 Is that what you where asking for ? T From jeff at ccvcorp.com Fri Nov 26 17:52:37 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 26 Nov 2004 14:52:37 -0800 Subject: network programming without goto (refactoring) In-Reply-To: References: Message-ID: <10qfcmta665kbeb@corp.supernews.com> Roy Smith wrote: >What you want to do is refactor this into a number of smaller functions, >each one encapsulating one piece of the puzzle. To start, I'd build a >function which handled the multiple connection attempts to a given host. >Maybe something like this: > ># ># Untested code -- this is just to give you some ideas ># and get you thinking in the right direction ># >def connectWithRetries (host, port, retryLimit): > attempts = 0 > while attempts < retryLimit: > try: > connection = zoom.Connection (host, port) > return connection > except ConnectionError: > attempts += 1 > throw ConnectionError > > IMO, Roy's advice here is spot-on, with one minor technical detail. In Python, exceptions use 'raise', not 'throw'... Jeff Shannon Technician/Programmer Credit International From autismuk at autismuk.muralichucks.freeserve.co.uk Tue Nov 30 09:51:01 2004 From: autismuk at autismuk.muralichucks.freeserve.co.uk (Paul Robson) Date: Tue, 30 Nov 2004 14:51:01 +0000 Subject: weird behaviour of "0 in [] is False" References: Message-ID: Sylvain Thenault wrote: >>>> l = [] >>>> 0 in (l is False) (l is False) is not a tuple or list, it's a boolean value. > Traceback (most recent call last): > File?"",?line?1,?in?? > TypeError: iterable argument required >>>> (0 in l) is False > True 0 in l is False becuase l is empty, so it's False is False which is true, (except in Intercal probably and Visual C++) >>>> 0 in l is False > False l is False is False because l is not the value false though it has a false value (err.....) Okay. l != False because it's not the displayed value false but if not l would evaluated to true because [] is a false equivalent. 0 in False .... okay.... this should be an error ..... something to do with the equivalence confusion of what False is ? From exarkun at divmod.com Mon Nov 15 10:22:41 2004 From: exarkun at divmod.com (Jp Calderone) Date: Mon, 15 Nov 2004 15:22:41 GMT Subject: Will python ever have signalhandlers in threads? In-Reply-To: Message-ID: <20041115152241.20649.1215409062.divmod.quotient.5880@ohm> On 15 Nov 2004 11:44:31 GMT, Antoon Pardon wrote: >Op 2004-11-15, Peter Hansen schreef : > > Antoon Pardon wrote: > >> AFAIU the Queue module doesn't block on a full/empty queue when > >> a timeout is specified but goes in a loop sleeping and periodically > >> checking whether place/items are available. With signals that > >> can be sent to a thread the queue could just set an alarm and > >> then block as if no timeout value was set and either unblock > >> when place/items are available or get signalled when the timeout > >> period is over. > > > > I'm fairly sure that the Queue uses an internal Event > > (or REvent?) to signal when space or a new item is > > available, so I believe your description (and possibly > > conclusion) above is wrong. There should be no > > "periodical check", as that would imply polling. Check > > the source if you're interested. > > I did check the source, I just didn't study it carefully > and got my understanding mostly from the comments. > But anyway here is the relevant part and IMO we have > a polling loop here. > You are correct, but why does it matter? The Queue class works. Why should Python be changed in a difficult and complex way to... make the Queue class continue to work? If you can give other examples of the uses you have in mind, that might help convince people of the value of this change. But be sure you give examples of things that don't already work. Jp From ossix at ossix.net Sat Nov 13 19:20:35 2004 From: ossix at ossix.net (steven alyari) Date: Sat, 13 Nov 2004 17:20:35 -0700 Subject: IMAP4 example in docs causes memory error for me (OS X 10.3, Message-ID: <0142BE46-35D3-11D9-800B-000A95DBE2DA@ossix.net> John, I have the same problem with OS X and Python 2.3 standard. the code: import getpass, imaplib M = imaplib.IMAP4("mail.host") M.login(getpass.getuser(), getpass.getpass()) M.select( ) typ, data = M.search(None, 'ALL') mydir = "./msgs" i = 0 for num in data[0].split( ): print str(i) + " ..." typ, data = M.fetch(num, '(RFC822)') w = file(mydir + "/" + str(i) + ".msg","w") w.write(data[0][1]) w.close( ) i+=1 M.logout( ) one the 115th message i get this error: *** malloc: vm_allocate(size=4755456) failed (error code=3) *** malloc[1471]: error: Can't allocate region Traceback (most recent call last): File "imap.py", line 13, in ? typ, data = M.fetch(num, '(RFC822)') File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 417, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 1000, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 830, in _command_complete typ, data = self._get_tagged_response(tag) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 931, in _get_tagged_response self._get_response() File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 893, in _get_response data = self.read(size) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/imaplib.py", line 231, in read return self.file.read(size) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/socket.py", line 301, in read data = self._sock.recv(recv_size) MemoryError Thanks, Steven Alyari > > > I am running the IMAP4 example in the documentation: > > http://www.python.org/doc/lib/imap4-example.html > > with two small changes (different username, comment out print > statement). The inbox I am accessing is 42 MB and has 80-someodd > messages, so the messages are fairly big (all of them have > attachments). When I run this program, I get a malloc error. Now, I'm > really new to python programming, but it was my understanding that > memory management was not something I had to explicitly do. I'd > appreciate some help in understanding what I've done wrong. > > If I watch memory usage via "top", the memory usage (vmem) goes up to > 3.5 GB, drops back down to a few tens of megabytes, then rises to 3.5 > GB or so again, then crashes. (Backtrace is appended at the end of > this message.) It seems odd to me that python should require GB of > memory to read a 40 MB mailbox. > > I also installed python 2.3.3 via fink and was able to reproduce the > error in the same way. > > Machine / python information: > > [JDO:~/Documents/src/vm2imap] jowens% uname -a > Darwin JDO.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 > 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power > Macintosh powerpc > [JDO:~/Documents/src/vm2imap] jowens% python -V > Python 2.3.3 > > JDO > > == > > *** malloc: vm_allocate(size=7426048) failed (error code=3) > *** malloc[17319]: error: Can't allocate region > Traceback (most recent call last): > File "minimal.py", line 8, in ? > typ, data = M.fetch(num, '(RFC822)') > File "/sw/lib/python2.3/imaplib.py", line 417, in fetch > typ, dat = self._simple_command(name, message_set, message_parts) > File "/sw/lib/python2.3/imaplib.py", line 1000, in _simple_command > return self._command_complete(name, self._command(name, *args)) > File "/sw/lib/python2.3/imaplib.py", line 830, in _command_complete > typ, data = self._get_tagged_response(tag) > File "/sw/lib/python2.3/imaplib.py", line 931, in > _get_tagged_response > self._get_response() > File "/sw/lib/python2.3/imaplib.py", line 893, in _get_response > data = self.read(size) > File "/sw/lib/python2.3/imaplib.py", line 231, in read > return self.file.read(size) > File "/sw/lib/python2.3/socket.py", line 301, in read > data = self._sock.recv(recv_size) > MemoryError -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 4659 bytes Desc: not available URL: From len-1 at telus.net Wed Nov 24 13:04:03 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Wed, 24 Nov 2004 18:04:03 GMT Subject: Microsoft Patents 'IsNot' References: <30ijkhF31dg9sU1@uni-berlin.de> Message-ID: Greg Ewing writes: > Lenard Lindstrom wrote: > > So Delphi is definitely not BASIC-derived. It is BASIC-like in that various > > basic dialects, including QBasic, came to support the structured programming > > that Pascal was designed from the beginning to teach. > > So it would be more accurate to say that those Basic > dialects are, in those respects, Pascal-like... > By saying Delphi is BASIC-like I just mean that many languages have come to resemble each, having adopted many of the same features. But it was definitely Basic that did most of the adopting. So yes, more precisely, Basic has become more Pascal-like. I was just giving the patent applicants a minor benefit of a doubt. Lenard Lindstrom From mrjean1ATcomcastDOTnet at no.spam.net Wed Nov 17 23:43:38 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Thu, 18 Nov 2004 04:43:38 GMT Subject: Custom memory manager References: Message-ID: <171120042044309678%mrjean1ATcomcastDOTnet@no.spam.net> We have done some experiments with the memory manager in Python 2.3+. Not to replace it but to obtain more detailed and accurate statistics for the memory usage. One thing to keep in in mind is that not all memory in a Python application is managed by the Python memory manager. Objects may be allocated by direct calls to malloc() and then passed to the Python memory manager to be freed. The Python memory manager handles that scenario properly. While replacing the Python manager is possible, be prepared for some surprises. It all depends on the actual modules used in your Python application and how those modules allocate objects. /Jean Brouwers ProphICy Semiconductor, Inc. In article , Carl Bevil wrote: > Hello all. If I want to use a custom memory manager to, say, track memory > allocations in Python, what's the best way to do this? I seem to remember > there being a way in version 1.5 (or so -- been a while since I used it). I > didn't see anything in the documentation, but I may have missed it. > > I've got the Python source code (v2.3.3) embedded in my application (which is > in C++), and would like to somehow override Python's default memory > allocators. Is there an easy or "accepted" way to do this? > > Thanks! > > Carl > > -- > Remove "NOSPAM" to reply in e-mail > From 2002 at weholt.org Wed Nov 17 18:11:39 2004 From: 2002 at weholt.org (Thomas) Date: Thu, 18 Nov 2004 00:11:39 +0100 Subject: Watermark images using PIL Message-ID: <6emnp01vff4atv9jto62vtp9t9srndnntf@4ax.com> I've searched google for this topic and found a few examples, but I need an example of how to create a semi-transparent, non-intrusive watermark for images using PIL, something that takes into account the background of the image when choosing color for the text. Making a huge white box or just putting a single-color text across the entire image looks just bad, so if there is a way to create a more professional looking watermark I'd be happy for any hint or tip you might have to offer. Best regards, Thomas From tim.peters at gmail.com Tue Nov 16 11:19:58 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 16 Nov 2004 11:19:58 -0500 Subject: Zope 3.0, and why I won't use it In-Reply-To: References: <41985663$0$272$edfadb0f@dread12.news.tele.dk> <4198cc5f$0$258$edfadb0f@dread12.news.tele.dk> <4198e036$0$289$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae0411160819544b3950@mail.gmail.com> [Tim Peters] >> Ya, I sure agree it's not obvious what to do on Windows! There have >> been detailed Windows instructions since X3 alpha 1, but subsequent >> release pages didn't point to them. I see Jim updated the 3.0.0-final >> release page to include them now: >> [Fred Pacquier] > Huh, thanks for that pointer ! Sure makes a lot more sense that way, and a > lot less to guess at, even for a developer release :) Yup -- it's essential. > If only the lower part of that page had figured in a prominent > WINDOWS_INSTALL_README.TXT or some such in the Windows > installer, there'd been much less bitchin' here :-) Ah, but where would you put this file? In a *tarball* distribution, it's easy: you stick README_FILES_WITH_SCREAMING_NAMES in the root of the distribution, and then they're easy to find. But this is a Windows *installer*, and every file it installs is "hiding" under some subdirectory of your pre-existing Windows Python installation. Where could the X3 Windows installer put WINDOWS_INSTALL_README.TXT where a new user is likely to find it? I don't believe such a place exists. It would be anti-social to clutter the root of the Python installation with package README files, and I doubt most users would think to look there anyway. And that's the "most obvious" place I can dream up. Doing something other than that (for example, maybe popping up a README file in Notepad at the end of installation) would require changes to distutils, since X3's Windows installer is built by distutils. The point of that isn't that changing distutils makes it impossible, the point is that since distutils *today* doesn't have such abilities, no distutils-built installer built today (whether X3's or any other Python project's) can do such things. From dave at pythonapocrypha.com Thu Nov 18 09:40:39 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 18 Nov 2004 07:40:39 -0700 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: References: <30001hF2ptnqcU1@uni-berlin.de> <419bbf2a.319309032@news.oz.net> Message-ID: <419CB467.70109@pythonapocrypha.com> Jeremy Bowers wrote: > You take every example mentioned to date, which is largely: > > * OS code trying to be as thin as possible (stat, socket) > * math-type code where the tuple really is the class, as you suggest > * more-or-less contrived one- or two-liner code > > and you've still got way, way, way less than 1% of the code of the vast > majority of programs. > > Like any other code smell, there are times to use it. But I say it's a > *smell*, and those of you implicitly reading that to mean "Returning > tuples is *never* a good idea" are doing me a disservice; please go look > up "code smell" and the word "generally". Well, the first page I found that listed the term "code smell" also mentioned "code wants to be simple", and having scanned through a good sized chunk of Python code looking to see where multiple return values were used, I am now of the opinion that, not only are multiple return values _not_ automatically code smell, but they are one of the key ingredients to avoiding monolithic functions (and thus they help keep code simple). The code I looked through had about 4500 return statements. Of those, roughly 350 were returns with multiple values. Of those, 26 had 4 or more return values - if code smell is a hint that something _might_ be wrong, I'd say those 26 have code smell, but the remaining 320 or so do not automatically raise concern (I inspected those 26 in detail and saw only 4 or 5 cases that'd be removed next time the code got refactored). > If you use it every once in a while where it is the right solution, great. > I do too. If you're using it every other function in a module, and it > isn't a thin wrapper around some other library, you've got a code smell. I found that multiple return values were not often used in "public" functions (those meant to be accessible from outside the module). Instead the most common use case was between functions that had been separated to divide the problem into smaller, testable code chunks (i.e. - rather than having a huge function to parse a log line, perform computations, and send the results to output, there was a function that'd take the raw data, call a helper function to parse it, call another helper to compute the result, and call another to send the results off for output) Without the ability to return multiple values, it would be much more cumbersome to split the code into small, easily understood chunks because for any non-trivial task, each logical "step" in that task often has multiple inputs as well as multiple outputs. After reviewing the code, I think that the use of multiple return values is, in and of itself, _almost never_ a good hint of a problem - way too many false positives (a better rule of thumb would be that code that returns BIG tuples has code small). > (It's probably a class or two trying to get out.) No, at least not in the code I looked at - in the vast majority of the uses of multiple return values, the coupling between the functions was already very tight (specialized) and the callee-caller relationship was one-to-one or one-to-few (the function returning multiple values was called by one or very few functions), and the data didn't move around between function as a unit or group, such that making a class would have been pure overhead like many C structures - never reused, and used only to cross the "bridge" between the two functions (immediately unpacked and discarded upon reception). > You've got a *big* code > smell if you are unpacking those return values many times, because now > you've hard coded the size of the tuple into the code in many places. Yes, this was mentioned previously. -Dave From mj-usunto at tkb.pl Wed Nov 10 07:14:10 2004 From: mj-usunto at tkb.pl (Marcin Jurczuk) Date: Wed, 10 Nov 2004 12:14:10 +0000 (UTC) Subject: How to find MAC address and uids? References: Message-ID: On 2004-11-10, Daniel T. wrote: > 1) How can I programatically find the MAC address of the machine? Is it > stored in a file I can look into? (MacOS X) What is syntax of this file ?? > 2) If I have a user name in a string how do I get his UID? >>> import pwd >>> pwd.getpwnam('spock') ('spock', 'x', 100, 101, '', '/export/home/spock', '/bin/bash') >>> pwd.getpwnam('spock')[2] 100 >>> -- Marcin Jurczuk, NIC-HDL: MJ1679-RIPE From carribeiro at gmail.com Wed Nov 17 14:40:22 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 17 Nov 2004 17:40:22 -0200 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: <30001hF2ptnqcU1@uni-berlin.de> References: <30001hF2ptnqcU1@uni-berlin.de> Message-ID: <864d370904111711406225d37@mail.gmail.com> On Wed, 17 Nov 2004 16:49:03 +1300, Greg Ewing wrote: > Jeremy Bowers wrote: > > Generally, returning a tuple is either a sign that your return value > > should be wrapped up in a class, or the function is doing too much. > > While I suspect you may be largely right, I > find myself wondering why this should be so. We > don't seem to have any trouble with multiple inputs > to a function, so why should multiple outputs be > a bad thing? What is the reason for this asymmetry? If there is an assymetry, it is in *favor* of returning tuples for multiple outputs. Using a tuple removes some of the coupling between the caller and the function. Note that the function signature defines names for its internal use, and the caller is not required to know the internal names (unless kw parameter passing is used). Forcing names on the output introduces *more* coupling, and makes the design less flexible. In practical terms, it's important to note that generic utility functions often do not return a "full class", but just a bunch of results that may or not be stored into a single class. Requiring that a class to be defined just to return a bunch of data is overkill. Finally, I assume that it's considered standard practice in Python to use tuples to store arbitrary collections of data, pretty much like C structs. The only difference is that the members are not named (and thus loosely coupled). This should not be a big deal for *most* situation. The structure of the return tuple can be documented in the doc string. For complex structures, returning a dict is good possibility (although in this case the fact that the names are defined introduces some degree of coupling). Of course, if the case is complex enough, declaring a class is the way to go, but then, it's a design decision. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From arkham at gmail.com Wed Nov 24 12:00:05 2004 From: arkham at gmail.com (Rob Snyder) Date: Wed, 24 Nov 2004 17:00:05 GMT Subject: teaching OO References: Message-ID: Neil Benn wrote: > > >>As for the interesting C++ issues, those same students were able to pick >>those concepts up quickly in their later classes. "Overloading", for >>example, was a pretty simple concept to grasp for people who had >>previously spent a whole semester heads down learning OO. >> >>Rob >> >> > Hello, > > Just out of interest, did the students get confused between > polymorphism acheived through duck-typing and polymorphism acheived > through inheritence. Obviously not all OO languages have duck typing > and they are subtly different concepts which may confuse a learner. > > Just a question, I'm not in education so I wouldn't know the best > way to perform structured education (my teacher friends remind me of > this all the time!!). > > Cheers, > > Neil > Neil - At first, yes. What I found quite interesting was that most students seemed to naturally think that duck typing was the only "sensible" way things should work, and later, when faced with C++, they did often stumble. I am more careful now to seperate the Python way of doing things from the general theory behind inheritance, interfaces, and class types, and I try to cover up front how a lot of the rest of the world works. Regards, Rob From craig at postnewspapers.com.au Fri Nov 19 16:14:16 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 20 Nov 2004 05:14:16 +0800 Subject: Question about thread In-Reply-To: References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> <1100879122.755150@eng-ser4> Message-ID: <1100898855.13953.1.camel@rasputin.localnet> On Sat, 2004-11-20 at 04:56, Jarek Zgoda wrote: > Are you sure? I keep observing that child threads continue its execution > until completion even if I do nothing in main thread. Consider this example: Well, I'm very far from an expert, but I've also experienced the poster's reported behaviour even with quite simple programs. I'm surprised to hear that the initially described behaviour isn't always the case, and would be interested in knowing more about when it is, and is not, generally encountered. -- Craig Ringer From Florian.Wilhelm at web.de Tue Nov 9 17:54:37 2004 From: Florian.Wilhelm at web.de (Florian Wilhelm) Date: Tue, 09 Nov 2004 23:54:37 +0100 Subject: Problems with user input Message-ID: I have some easy questions, but I cant figure them out: I want to read exactly one char from stdin, there should be no need to hit enter. import sys print "Input: (y/N) ", input = sys.stdin.read(1) print "Your input:", input This code has following problems: 1) I need to hit enter, although I read only one char?!? 2) The complete output is: Input: (y/N) y Your input: y Why does the whitespace char appear in front of "Your input..."? I guess it has something to do with not causing a linebreak after "Input: (y/N) ", but I want no linebreak... Any suggestions? Regards, Florian From theller at python.net Fri Nov 5 07:13:44 2004 From: theller at python.net (Thomas Heller) Date: Fri, 05 Nov 2004 13:13:44 +0100 Subject: Python for 8/16 Bit MSDOS ( 486 / 586 / K5 / K6/ Beck-IPC ) processors. References: <418B6158.3C7BD9B1@iee.lu> Message-ID: Manfred Schwab writes: > Hi there, > which versions of python are usable under MS-DOS 5.0 oder 6.22 or Dr. > DOS. > > I want to use it under a industrial environment to collect measuring > data like temperature, moist and signalconditions with a Beck industrial > PC. Did somebody try this already ? Is there a certain URL where i can > get further information. I severely doubt the Beck-IPC has enough memory for that. Thomas From none at none.com Wed Nov 17 20:53:16 2004 From: none at none.com (Larry) Date: Thu, 18 Nov 2004 01:53:16 GMT Subject: ODBC Select Message-ID: I am trying to connect to my MySQL database using python and ODBC. Here is what I am doing. >>> import dbi,odbc >>> conn=odbc.odbc("dsn=facs") >>> cursor=conn.cursor() >>> cursor.execute("select * from data") 0 >>> Notice I get the "0" after the select statement. Problem is, there are 20 records in the database. In fact I can do this >>> cursor.execute("insert into data (facility) values ('AAA')") 1 >>> and then I can do this >>> cursor.execute("delete from data where id > 20") 1 >>> but when I do >>> cursor.execute("select * from data") 0 >>> Anyone seen this and can maybe tell me why this is occuring. I have full privileges as I can log on and query with the DSN from other programs. Thanks, Larry From peter at engcorp.com Mon Nov 22 20:25:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Nov 2004 20:25:53 -0500 Subject: Identifying exceptions that can be raised In-Reply-To: <545cb8c2.0411221645.442bb88a@posting.google.com> References: <6Rknd.6671$%M4.4203@trndny08> <545cb8c2.0411221645.442bb88a@posting.google.com> Message-ID: Jim Hefferon wrote: > Peter Hansen wrote .. > >>The usual approach is to have a caller catch exceptions >>*which it is capable of dealing with appropriately*, and >>ignore others. In some cases it's necessary to have a >>"generic" exception handler, such as at the top level of >>a thread, to catch and log all exceptions, but that's >>relatively rare. > > I wonder if perhaps you don't write different kinds of programs than I > do. I certainly do. I don't, for example, ever do CGI... > For instance, I have a cgi program. One routine will get an id from a > httpd parameter, use it to reach into a database and fetch some xml, > and then pull information out of the xml for display. That I can > tell, there are about 100 exceptions that could be raised ... ...but were I faced with this situation, I would follow my above advice about "in some cases it's necessary...". This is exactly such a situation. I would always wrap such a program** at the top level with a generic exception handler and a call to traceback.format_exception() (or whatever it's called), turning any errors into visible results, or at the very least logging them somewhere for analysis. ** I don't think of CGI calls as independent _programs_, mind you, any more than I think of individual threads as programs, but I'm not sure this is affecting my opinion here vis-a-vis exception handling. -Peter From ncoghlan at email.com Thu Nov 25 09:10:24 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Fri, 26 Nov 2004 00:10:24 +1000 Subject: Python Function pointer in C In-Reply-To: References: Message-ID: <41a5e7ce$0$25788$5a62ac22@per-qv1-newsreader-01.iinet.net.au> David Gilbert wrote: > I'm trying to maintain the interface to KQueue for FreeBSD. At one > point, the C module stores an opaque object in a C structure such that > the opaque pointer can be used later by the application. In this case, a Py_IncRef/DecRef pair is definitely required - the 'borrowed' reference from the Python function call only lasts until the function returns. You need your own reference if you're going to hang on to the pointer. > How do I define "udata" such that I can stuff the lambda reference in > there? PyObject* should be fine so long as the references are handled correctly. > Now... I've wondered if this is a reference counting issue --- but > this still happens when I use the name of a module global function as > udata. I'd suggest adding the IncRef/DecRef pair and trying it out again. I can't see anything else obviously wrong in the fragments you've posted. If that was the sole problem though, I would have expected the same as you - for the module global function to work correctly. Sorry I can't be more help. . . Cheers, Nick. From deetsNOSPAM at web.de Mon Nov 8 12:18:46 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 18:18:46 +0100 Subject: generic way to access C++ libs? References: <1gmxizh.3rip5na92f0nN%aleaxit@yahoo.com> <1gmxn7d.19o8q51jt2gu5N%aleaxit@yahoo.com> Message-ID: >> Conveniently, COM objects can be wrapped on the fly be the >> python win32 extensions. > > Yes, but only Dispatch interfaces. ctypes is able to wrap native > interfaces by constructing the vtable at runtime, by using a manually > written or generated interface definition. COM is espacially designed to allow for this - language interoparability. So its not to surprising that its easily wrapped. But one can draw _no_ conclusions from that about C++ - as COM is a binary standard defined in terms of C. The fact that VStudio integrates it nicely with C++ has nothing to do with that. > I mean, for example, code like this (from MS' GdiPlusTypes.h): > > class CharacterRange > }; I know, I meant that code too. -- Regards, Diez B. Roggisch From greg at cosc.canterbury.ac.nz Tue Nov 16 22:49:03 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 17 Nov 2004 16:49:03 +1300 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: References: Message-ID: <30001hF2ptnqcU1@uni-berlin.de> Jeremy Bowers wrote: > Generally, returning a tuple is either a sign that your return value > should be wrapped up in a class, or the function is doing too much. While I suspect you may be largely right, I find myself wondering why this should be so. We don't seem to have any trouble with multiple inputs to a function, so why should multiple outputs be a bad thing? What is the reason for this asymmetry? Perhaps it has something to do with positional vs. keyword arguments. If a function has too many input arguments to remember what order they go in, we always have the option of specifying them by keyword. But we can't do that with the return-a-tuple- and-unpack technique for output arguments -- it's strictly positional. Maybe things would be better if we had "dict unpacking": a, c, b = {'a': 1, 'b': 2, 'c': 3} would give a == 1, c == 3, b == 2. Then we could accept outputs by keyword as well as inputs... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From steve at holdenweb.com Tue Nov 9 08:26:43 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Nov 2004 08:26:43 -0500 Subject: psycopg, transactions and multiple cursors In-Reply-To: References: Message-ID: <5G3kd.13457$931.7749@lakeread01> Alban Hertroys wrote: > Diez B. Roggisch wrote: > >>> AFAIK, you can't open a transaction w/o using a cursor; You need a query >>> that says "BEGIN;". >>> You can commit a connection object, however. It would be nice to be able >>> to start a transaction on a connection object, but then you still could >>> only have one transaction per connection... :( >> >> >> >> thats actually the case for all DBs I know including e.g. oracle with >> jdbc - >> so the abstraction layers usually use connection pooling to speed up >> opening a connection thus the app doesn't suffer so much. > Yes, most database connections will generate an implicit transaction the first time a change is made to the database (in the absence of autocommit). > > Ok, that means I won't get away with a single connection object (unless > psycopg puts a connection pool in a single connection object). > >> No idea why thats happening - on jdbc, one can set an "autocommit" >> connection property that will do exactly that: enforce a commit if a >> statement was successful. Maybe psycopg has that too? > > > Yes, it does have autoCommit, and thankfully it can be turned off (which > I did, of course). > It certainly isn't too useful if you occasionally need to roll things back. Structural changes to the database will frequently cause an automatic commit anyway, though - you aren't modifying the database structure at all, I take it? >>> I know PostgreSQL can do transactions on nested cursors, I have used >>> that now and then in stored procedures (pl/pgsql). > > >> I didn't find much on nested cursors on google, so I don't know how they >> work - but I assume if they are part of psycopg, they somehow have to be >> created using an existing cursor, as otherwise how should psycopg know >> that >> what you want is a nested and not a new cursor. > > > Actually, nesting of cursors is something that PL/PgSQL can do. And so > can PL/SQL in Oracle. > It's something that's possible on a low database API level, and (to my > understanding) the DBAPI 2.0 uses them for queries. It's one of Pythons' > advantages over eg. PHP, and one of the reasons I chose to use Python > for this project. > Nested cursors aren;t nested transcations, though, right? >> So is there something on cursor objecst to get a new cursor, or at >> least the >> connection so you can get a cursor on the very same connection? > > > A cursor is comparable to an iterator over a result set (where the > cursor fetches one record from the database at a time). > B e careful that you don;t confuse the DB API curosrs with the cursors you get with DECLARE CURSOR in PL/SQL, for example. The two aren;t necessarily the same thing (and I've always felt that "cursor" was, for that reason, not the best possible terminological choice for the DB API). > You use one for every query, and it can often be reused for the next > query as well. > > However, if you loop through a result set (with a cursor) and you need > to do a query based on the record that the cursor is currently > positioned at, you can't use the same cursor again for that query, but > need to open a new cursor. That's what I meant by "nesting cursors". > Bear in mind, though, that it will often be *much* more efficient to do a fetchall() from the cursor and iterate over that result. This typically avoids many round-trips by fetching all the data at once, though it's less practical if data sets become huge. There's sometimes a middle ground to be found with repeated calls to fetchmany(). In that way the curosr can be reused with impunity once the data has been fetched. > That shouldn't matter for the state of a transaction, though... > > Maybe there's a difference between database level cursors and DB API 2.0 > level cursors in Python? > As I mentioned above, there often is. I think we've already agreed that the psycopg cursors aren't DB API compliant anyway, precisely because of the way they handle transactions. An API-compliant library shares transaction state across all cursors generated from the same connection, which (IMHO) gives the flexibility one needs to to handle complex database interactions. > The number of questions is increasing... Well, the number of answers is, too, but it seems to me you *are* kind of wanting to have your cake and eat it. In previous threads you've suggested that the psycopg cursor behavior is what you want, but now that very behavior might (?) be biting you. Anyway, you couldn't be talking to a better bunch of guys to try and solve this problem. c.l.py is sometimes persistent beyond all reasonable limits. Good luck! regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From ianb at colorstudy.com Mon Nov 1 12:42:15 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 01 Nov 2004 11:42:15 -0600 Subject: ruby on rails ... python on ? In-Reply-To: References: Message-ID: <41867577.4010409@colorstudy.com> flab ba wrote: > The pragmatic programmers (Dave & Andy) are spreading a good word about > RubyOnRails. I was wondering if there are any Python programmers who are > /also/ familiar with Rails - and if they could recommend something in the > Python world that is comparable. I've looked a little at Rails. It's not super special. Well, it *is* compared to things like Java; dynamic languages *are* quite superior for rapid development of websites, and Ruby and Python are similar languages in that way. Rails is really a whole stack that works well together. People have been writing this sort of thing in Python for a long time; which isn't to say they always have gotten it right, or that those efforts have had the right perspective to be strategic successes (i.e., become popular). Lessee... Rails seems to have: * A simple object publisher. There's a ton of these in Python. It also perhaps includes some sort of MVC system, where the object picks up a template automatically if it exists. These exist as well, though I think MVC efforts can become overly ambitious or overly restrictive fairly easily. * An object-relational mapper. I'd say this is close to SQLObject, though SQLObject is in some ways more powerful. * A templating system. Looks like ASP. There's lots of templating languages in Python; the simplest (e.g., embed Python code) can be problematic because of Python's significant whitespace. But anyway, we have lots and lots of these, and there are real reasons for why there's multiple templating languages. Spyce is probably the closest to Rails. All three of these pieces fit together really well in Rails, which is perhaps what it offers that Python doesn't have. Well, I'm sure some framework out there has this, but it's hard to say, there's so damn many. But, while this is really compelling when you show off the creation of a simple system, I suspect it becomes a fair amount more complicated later on. At least, that is my experience with Python projects of similar ambition. It's neat to setup a database and have it work instantly, complete with the standard CRUD forms. But this only works for "leaf" tables, and even then no so well. How do you deal with joins? How do you deal with complex requirements on input, or actions on updates? Eventually you'll need to tweak a generated form just a *little*, does that mean you have to throw away all the automated aspects and code it by hand? I don't mean to criticize Rails with these questions; it's not that Python frameworks solve these wonderfully either, these are just hard problems. But for realistic web applications these are inevitable issues, and I suspect Rails isn't quite as compelling when you take them into account. OTOH, I'd love to see something in Python that is just as tight as Rails, but uses all the pieces we've already developed. It's really just a question of sticking pieces together; but that's a surprisingly difficult operation. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From adalke at mindspring.com Tue Nov 9 15:03:48 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 09 Nov 2004 20:03:48 GMT Subject: Summary: strong/weak typing and pointers In-Reply-To: <41905f33@news.highway1.com.au> References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> <2vaj5oF2jl25lU1@uni-berlin.de> <41905f33@news.highway1.com.au> Message-ID: Tim Hoffman wrote: > Oops now that we are on the slippery slope of metaphors ;-) do we class > super cooled liquid types as ones that can be co-oerced but just take a > very long time ;-) Or perhaps since supercooled fluids have all particles in the lowest quantum state, the metaphor is that everything gets treated as the root Object type? Andrew dalke at dalkescientific.com From tim.peters at gmail.com Sun Nov 21 01:02:17 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 21 Nov 2004 01:02:17 -0500 Subject: Will python ever have signalhandlers in threads? In-Reply-To: References: Message-ID: <1f7befae041120220268ec5cf7@mail.gmail.com> [Antoon Pardon] > I'm talking about PyThreadState_SetAsyncExc only as a throw in > response to your previous remark. The main subject is signals. OK. ... > Well wether the work is done or not hardly seems to matter. The > documentation as worded now seems to make it clear, this isn't > going get into the language. But you're still talking about PyThreadState_SetAsyncExc here, right? Explained last time that it can't possibly "get into the language" in the state it's in now. The people who orginally did the work got everything they wanted at the time: the C API function, and the then-new thread.interrupt_main() function in Python. They didn't ask for more than that, and they didn't work on more than that. Doing more work is a necessary prerequisite if people want more than that in the language. Making the case that it should be in the language is part of that work, but, if you haven't noticed, PEPs that have working implementations fare much better than PEPs that don't. Indeed, no PEP without an implementation has ever been released . ... > As I understand the doc, one doesn't plan to begin working on a > Python-level feature and even if someone else implements it, it > has no chance of getting in the language. Sorry, couldn't make sense of that sentence. > As I read the docs it is not so much a question of the feature not > being ready for the langauge, but a question of Guido not wanting the > feature to be in the language. You're still talking about PyThreadState_SetAsyncExc? I haven't asked Guido about it, and I can't find any design discussion of that function anywhere. I think it got added during a European sprint. If you want to know what he thinks, ask him. If you want a definitive ruling, write a PEP. > This just to show that having someone implement it, is not > the biggest hurdle as your prevous remark seemed to suggest > to me. An implementation is prerequisite to release, but isn't necessarily sufficient. I explained in detail last time why the current C code has no claim to being "an implementation" of a *Python*-level spelling of this functionality, so neither a suitable implementation nor the necessary design discusiion have been done in this case. If this is something you want, but you also want guaranteed acceptance in advance of doing more than writing about it, that won't work. If you ask Guido, and he can make time to answer, you may get guaranteed rejection in advance -- or you may not. A PEP would be a good thing to have in *either* case. ... > Although you can't help me with my main question, I like to express > my appreciation for your responses. They have been very insighfull > and I'll be sure to use them to my advantage. My fondest hope is that you'll be able to use them to crush Guido into submission . From tzot at sil-tec.gr Thu Nov 18 09:24:14 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 18 Nov 2004 16:24:14 +0200 Subject: PIL for Python 2.4? References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> Message-ID: On Thu, 18 Nov 2004 14:17:50 +0100, rumours say that Gerhard Haering might have written: >> Has anyone built PIL (1.1.4 or 1.1.5) for Python 2.4? If yes, >> please let me know, [...] > >I haven't. But it would have been useful if you had mentioned which >platform ;-) Windows? Oh, yes, Windows... On Linux I built it myself. I just don't have access to a MS compiler on Windows. Sorry for not being clear. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From vze4rx4y at verizon.net Mon Nov 8 14:47:34 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 08 Nov 2004 19:47:34 GMT Subject: yet another recipe on string interpolation References: <4edc17eb.0411032219.659c1824@posting.google.com> <4edc17eb.0411080106.71d4f3d4@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:4edc17eb.0411080106.71d4f3d4 at posting.google.com... > Peter Otten <__peter__ at web.de> wrote in message news:... > > As of 2.4b2, the modulo operator is not (not yet, or no longer?) defined, so > > I had to use substitute() instead. > > I have downloaded Python 2.4b2 today and looked at the source code for > the Template class. There is no __mod__ method, in contraddiction with > PEP 292. Is there somebody who knows what happened and the rationale > for the change? Should PEP 292 be updated? It was updated a good while ago: http://www.python.org/peps/pep-0292.html The PEP STATES that the API is through the substitute() and safe_substitute() methods. Also, it notes that __mod__ is easily aliased to one of the those via a Template subclass. By using named methods instead of the % operator: * we avoid the precedence issues associated with % * we avoid confusion as to whether a tuple is an acceptable second argument * we avoid confusion with "%s" style inputs. * we enable keyword arguments: mytempl.substitute(weather="rainy") * we get something more documenting than punctuation. Raymond Hettinger > > Michele Simionato From PeterMayne at ap.spherion.com Wed Nov 10 22:42:18 2004 From: PeterMayne at ap.spherion.com (Mayne, Peter) Date: Thu, 11 Nov 2004 14:42:18 +1100 Subject: Pre-built SWIG binaries for Graphviz Message-ID: <5E9DE07827946946A62B84765DE84D7402532A68@s-f003004.cbr.cpg.com.au> I'm looking for pre-built SWIG binaries for Python 2.3 so I can call the Graphviz (graphviz.org) libraries directly, rather than using os.popen2 (which doesn't work on Windows 9x) to call the executable. Any pointers to binaries + instructions? I've exhausted the Google/AltaVista routes. Thanks. PJDM -- Peter Mayne Technology Consultant Spherion Technology Solutions Level 1, 243 Northbourne Avenue, Lyneham, ACT, 2602 T: 61 2 62689727 F: 61 2 62689777 The information contained in this email and any attachments to it: (a) may be confidential and if you are not the intended recipient, any interference with, use, disclosure or copying of this material is unauthorised and prohibited; and (b) may contain personal information of the recipient and/or the sender as defined under the Privacy Act 1988 (Cth). Consent is hereby given by the recipient(s) to collect, hold and use such information and any personal information contained in a response to this email, for any reasonable purpose in the ordinary course of Spherion's business, including forwarding this email internally or disclosing it to a third party. All personal information collected by Spherion will be handled in accordance with Spherion's Privacy Policy. If you have received this email in error, please notify the sender and delete it. (c) you agree not to employ or arrange employment for any candidate(s) supplied in this email and any attachments without first entering into a contractual agreement with Spherion. You further agree not to divulge any information contained in this document to any person(s) or entities without the express permission of Spherion. -------------- next part -------------- An HTML attachment was scrubbed... URL: From premshree_python at yahoo.co.in Thu Nov 11 15:24:35 2004 From: premshree_python at yahoo.co.in (Premshree Pillai) Date: Thu, 11 Nov 2004 20:24:35 +0000 (GMT) Subject: Py2exe help for beginner In-Reply-To: Message-ID: <20041111202435.92276.qmail@web8503.mail.in.yahoo.com> --- Martin Franklin wrote: > On 8 Nov 2004 04:08:30 -0800, PeterFI > wrote: > > > Howdy folks, > > > > I?m taking my first steps in a world of python and > I start from the > > end:) > > > > I have this little application written in python > and I need to convert > > it to Finnish. Modifications to the source code > are ready and now I > > need to compile it to exe. It is only one py file, > Iterator.py. > > > > my setup.py looks like this > > > > from distutils.core import setup > > import glob,os,sys > > import py2exe > > > > > > setup(name='MyIterator', > > version='0.2', > > author='P.P', > > py_modules=["Iterator"]) > > Tried this? from distutils.core import setup import py2exe setup(name = "package_name", scripts = ["path/to/script.py"], ) --Premshree > > it runs nicely but no exe is created? What am I > missing? > > > What does the output of the 'python setup.py py2exe' > command look like > exactly? > > -- > http://mail.python.org/mailman/listinfo/python-list > ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From jerry at jerrysievers.com Mon Nov 29 11:07:48 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 29 Nov 2004 11:07:48 -0500 Subject: PyQt on a Server References: Message-ID: Bob Parnes writes: > I have an application importing qt on a linux server and am missing > something in trying to run it from a workstation via nfs. The > workstation has the server /usr directory mounted to its own /usr > directory, so it can access the necessary files. The error I get is > > Traceback (most recent call last): > File "/demo/revenues.py", line 24, in ? > from qt import * > File "/usr/lib/python2.3/site-packages/qt.py", line 24, in ? > import libsip > ImportError: libXrender.so.1: cannot open shared object file: > No such file or directory > > I can see the file in /usr/X11R6/lib. So maybe there is a path variable > that qt.py uses and that has to be set on the workstation. If so, I don't > know how to find it. Thanks for any help. LD_LIBRARY_PATH=/usr/X11R6/lib or if the LD_LIBRARY_PATH exists already, append to it; LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/X11R6/lib then export LD_LIBRARY_PATH Now try running your Python script and see if this helps. If so, read about ld.config and add that lib to the standard config on the workstation if you plan on having that NFS mount all the time. You might also check to insure that the lib that you are "seeing" is actually a file and not a symlink to nowhere and that the file has appropriate perms for a shared lib r-x is typical. HTH > > Bob > > -- > Bob Parnes > rparnes at megalink.net -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From aleaxit at yahoo.com Sun Nov 7 04:30:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 Nov 2004 10:30:34 +0100 Subject: PEP new assert idiom References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> <1gmvgit.vzj5g4hv9dsrN%aleaxit@yahoo.com> Message-ID: <1gmvm6b.131yfhfvdcrzpN%aleaxit@yahoo.com> F?bio Mendes wrote: > > So follow PEP 8's recommendation instead: > > > > assert ( > > exp1 and > > exp2 and > > ... > > expn > > ), 'Errormsg' > > > I didn't know this would work for 'and/or' operators (even I've read the > style guide PEP!), sorry. It's not super beautiful, but I could live > happy with that :) It works for the parentheses -- what operators are inside the parentheses, including none at all, doesn't matter. A logical line isn't finished until all kinds of parentheses are balanced. > > I don't see the parentheses (which clarify the syntax issue you > > mentioned in your first post) and 'and' as any uglier than the commas. > > And having commas mean line continuation is out of the question. > > I never said that commas should mean line continuation (as a backslash). > It CAN be used as implicit line continuations in lot cases, (like > function arguments, for instance. This would be just one more case. Nope, comma can never be used as implicit line continuation in Python (that's different from some other languages). The opened and yet unclosed parentheses are what cause several physical lines to be part of the same logical line -- not commas, nor other operator or punctuation. Consider for example: print ( 'some text' 'and some more' 'and yet more' ) look, ma: no commas (nor other punctuation nor operators, yet three physical lines merge into just one logical line -- thanks to the parentheses. This will print some textand some moreand yet more because adjacent string literals merge into one string literal (in Python just like in C). If you put commas there WITH the parentheses, you'd be printing out a tuple. With the commas and WITHOUT the parentheses, syntax error. You may be associating "commas continue lines" with "function arguments" because function definitions and calls DO use parentheses, and separate arguments with commas. But it's really not an ideal mental model. Alex From max at alcyone.com Fri Nov 19 19:00:43 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Nov 2004 16:00:43 -0800 Subject: Global variables in modules/functions In-Reply-To: References: Message-ID: Aaron Deskins wrote: > I'm trying to write program with a main.py and several functions > distributed in auxiliary *.py files. I've looked through the archives on > the 'global' keyword, but I'm still not sure how to get this right. I > want to be able to have some variables that can be accessed/changed by > many modules/functions. Globals aren't common to all modules. You can think of globals as module-specific. That is, the global n is not shared between your two modules. It will be in one of the modules, and the other module can then reference it explicitly. Something like (untested): main.py ------- import change change.n = 1 change.change_n() print change.n change.py --------- n = 0 # here's the actual global def change_n(): global n n = 2 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis They have rights who dare defend them. -- Roger Baldwin From timothy.grant at gmail.com Wed Nov 10 13:20:06 2004 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 10 Nov 2004 10:20:06 -0800 Subject: ANN: PyQt-Mac installer available In-Reply-To: <5Vlkd.1069$yk5.385@fe37.usenetserver.com> References: <5Vlkd.1069$yk5.385@fe37.usenetserver.com> Message-ID: On Wed, 10 Nov 2004 05:17:36 -0500, Kevin Walzer wrote: > > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > PyQt-Mac is a binary installer of the various components of Qt and PyQt > for Mac OS X. Included are the following: > ? > * A complete build of Qt/Mac with QScintilla support. > ? > * A compiled binary of Sip, the application that converts Qt's C++ base > into Python bindings. > ? > * PyQt. > ? > * Eric 3, an integrated development environment (IDE) for Python written > with the PyQt toolkit. > > These packages include both compiled binaries and complete source code. > > For more information, http://www.wordtech-software.com/pyqt-mac.html. > > > > - -- > Kevin Walzer, PhD > WordTech Software--Open Source Applications and Packages for OS X > http://www.wordtech-software.com > http://www.smallbizmac.com > http://www.kevin-walzer.com > mailto:sw at wordtech-software.com > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (Darwin) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFBkeqzJmdQs+6YVcoRApnZAJ4pc/sP2NmybJ6JOb3kSXUaGoBBygCcCHPx > 6upq87BzVyaXLpQnyMztv2I= > =57qD > -----END PGP SIGNATURE----- > > -- > http://mail.python.org/mailman/listinfo/python-list > This is a huge blessing! Thank you so much. That said I'm having a bit of difficulty. I believe I followed the instructions correctly including all the symlinks that were suggested. However, I get an error. (timothygrant at bastard%) pythonw ~ Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import qt Traceback (most recent call last): File "", line 1, in ? ImportError: Failure linking new module: libqt-mt.3.dylib: dyld: /System/Library/Frameworks/Python.framework/Versions/2.3/Resources/Python.app/Contents/MacOS/Python can't open library: libqt-mt.3.dylib (No such file or directory, errno = 2) >>> Any tips? Thank you. -- Stand Fast, tjg. From bokr at oz.net Wed Nov 24 12:33:36 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 24 Nov 2004 17:33:36 GMT Subject: How to get an item from a simple set? References: Message-ID: <41a4bbce.908273778@news.oz.net> On Wed, 24 Nov 2004 15:40:30 GMT, Steven Bethard wrote: >Pete Forman wrote: >> I have a set that contains one item. What is the best way of getting >> at that item? Using pop() empties the set. Here is what I've tried. > >This is what tuple unpacking is for: > > >>> s = set(['foo']) > >>> item, = s > >>> item >'foo' > >>> [item] = s > >>> item >'foo' > >It's up to you whether you like the tuple or list syntax better. =) > Thanks. I didn't realize a list format could be used to specify target names like that. My intial reaction is a bendy feeling in my list expression syntax recognizer, though. I'm not sure I like that on the left hand side. It feels too much like __setitem__ on some implied object. The tuple syntax on the left hand side is only for unpacking (unless you want to imagine invoking an implied unnamed function, but that's a stretch IMO), so it doesn't trigger that near-miss syntax recognition feeling. Regards, Bengt Richter From tifredman at free.fr Sun Nov 7 17:59:22 2004 From: tifredman at free.fr (bwani) Date: Sun, 07 Nov 2004 17:59:22 -0500 Subject: installing ppgplot (using OS X 10.3 / gcc 3.4 / python 2.3b) References: Message-ID: Ok, I found my error... the one missing was -lg2c and all works fine again :) But i still don't understand the errors in pgplot compilation Here are the 2 commands i typed for ppgplot: # Compilation gcc -fno-strict-aliasing -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/System/Library/Frameworks/Python.framework/Versions/2.3/include/python2.3/Numeric -I/usr/local/pgplot/ -I/System/Library/Frameworks/Python.framework/Versions/2.3/include/python2.3 -c src/_ppgplot.c -o build/temp.darwin-7.5.0-Power_Macintosh-2.3/src/_ppgplot.o # Linking !! DON'T FORGET -lg2c !!!!! gcc -framework Python -lcpgplot -lpgplot -L/usr/X11R6/lib/ -L/usr/local/pgplot -L/usr/local/lib -lg2c -lX11 -lm -bundle -Wl,-framework -Wl,AppKit build/temp.darwin-7.5.0-Power_Macintosh-2.3/src/_ppgplot.o -o build/lib.darwin-7.5.0-Power_Macintosh-2.3/ppgplot/_ppgplot.so then copy the _ppgplot.so to pythonpath, and use it! Fred From sjmachin at lexicon.net Wed Nov 10 21:17:34 2004 From: sjmachin at lexicon.net (John Machin) Date: 10 Nov 2004 18:17:34 -0800 Subject: Announce: csv_xs.py References: Message-ID: Christian Meissner wrote in message news:... > > Can you explain what you liked about Perl's csv_xz package and/or didn't > > like about Python's csv module that motivated you to write your own class? > > > > I'm a native perl speaker, but at my last work i had to learn python, to > edit some zope thinks (quite difficult). > > Now i wanna learn python for me and i often work with csv files with perl > but now i wanna develop some python programs for csv file working. > In this task i would extend the csv module for my needs What are your needs, that are not covered by Python's csv module? You have this comment near the beginning of your source file: "This File contains classes, which enable you to get mor efficient access to csv - files." How do you define efficiency? Speed of reading files? Last time I looked, the guts of the Python csv module was written in C. Memory footprint? Try sucking in a file with a few million records with your module and check the memory usage. > but there i get any > errors, What errors did you get when you tried to use the Python module? > so it was easier for me to develop a class which is like the perl > one. > > hope it is ok Istvan has already covered this topic. > Chris From gh at ghaering.de Tue Nov 2 18:13:00 2004 From: gh at ghaering.de (Gerhard Haering) Date: Wed, 3 Nov 2004 00:13:00 +0100 Subject: Python needs a CPyAN In-Reply-To: <41880b1a$0$19736$626a14ce@news.free.fr> References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> <41880b1a$0$19736$626a14ce@news.free.fr> Message-ID: <20041102231300.GA15162@mylene.ghaering.de> On Tue, Nov 02, 2004 at 11:41:18PM +0100, bruno modulix wrote: > Michael Str?der a ?crit : > >Peter Hickman wrote: > > > >> > >>Just today we required a module that was not installed on our system. > >> > >>sudo perl -MCPAN -e 'install Data::Pager' > >> > >>And it was installed with all it's dependencies. > > > > > >I'd rather call that a security and maintenance nightmare... > > > We had some program (can't remember if it was spamassassin or an > antivir, I'm not the sysadmin !-) gone mad and all our customers mails > blocked for a full day because of such a wonderfull update of a perl > module... > Well, could have happened with a Debian [*] or *BSD, etc. update as well, right? -- Gerhard [*] -testing or -unstable -- A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From felciano at ingenuity.com Fri Nov 19 19:47:03 2004 From: felciano at ingenuity.com (Ramon Felciano) Date: 19 Nov 2004 16:47:03 -0800 Subject: Pythonic list to bitflag mapping Message-ID: <76c29906.0411191647.4b135e06@posting.google.com> Hi -- I have a list of integers that I'd like to convert to a bitflag or 1D matrix format: a = [3,4,6] b = [0,0,0,1,1,0,1,0,0,0] # a 1 for each position in the a list The specifics of the resulting representation is irrelevant; it could be ' ' and 'X' characters. Eventually this will be printed in a grid format, so the key is converting those numbers to an appropriate positional flag in the result list. I can do this with loops etc, but was curious if there isn't a python one-liner or list comprehension way of doing it. What I'd like to write is something like the following: [1 if x in a else 0 for x in range(10)] Any tips? Thanks! Ramon From pythongnome at hotmail.com Wed Nov 24 08:09:31 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 24 Nov 2004 13:09:31 GMT Subject: instant messenging In-Reply-To: <5c861a71.0411231758.30c5d37c@posting.google.com> References: <2004112108293216807%craig@yumaca> <5c861a71.0411231758.30c5d37c@posting.google.com> Message-ID: craig wrote: > > >>>http://www.yuma.ca/wordpress/index.php?p=118 >>> >>>It's not remotely close to a good release, and the code isn't error >>>checked very well, but my bot (yumatito) has been up about 7 days now on >>>AIM without crashing, that's a good sign :P His torrent download >>>ability doesn't work yet, the code is there, but broken, as I haven't >>>completely grasped how the btdownload code works yet.. feel free to fix >>>that for me :P >>> >>>Hope this helps, >>>Craig >>> >> >>Ah, could you possibly have a zip file?? I looked on your site and >>downloaded the BZ2 file, but I'm not sure how to extract it. I have >>Cygwin for another application, but I don't know how to get the files >>out the BZ2. So either a ZIP file or instructions on extracting files in >> BZ2 files would be greatly appreciated. > > > http://www.yuma.ca/wordpress/index.php?p=118 > All done, there is a ZIP file there. I tried to email you off list, > but it seemed to not go so well, so I'm posting here. Thank you. It's much appreciated. From roland.heiber at web.de Thu Nov 25 07:35:27 2004 From: roland.heiber at web.de (Roland Heiber) Date: Thu, 25 Nov 2004 13:35:27 +0100 Subject: redirecting stderr In-Reply-To: <4edc17eb.0411250410.6b460253@posting.google.com> References: <4edc17eb.0411250410.6b460253@posting.google.com> Message-ID: Michele Simionato wrote: > Maybe it is something obvious, but what is going on with this code? > > import sys > myerr = file("myerr.txt", "w") > sys.stderr = myerr > try: > raise Exception, "some error" > finally: > myerr.close() > sys.stderr = sys.__stderr__ > > I would expect the error message to be written into "myerr.txt", instead > it is displayed on the console, on regular stderr (?) and "myerr.txt" is > empty. I guess I misunderstood something ... > > Michele Simionato Hi, os.close(2) os.dup2(myerr.fileno(), 2) Works, but is dirty ... HtH, Roland From alban at magproductions.nl Mon Nov 8 10:07:21 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 08 Nov 2004 16:07:21 +0100 Subject: psycopg, transactions and multiple cursors In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: >>AFAIK, you can't open a transaction w/o using a cursor; You need a query >>that says "BEGIN;". >>You can commit a connection object, however. It would be nice to be able >>to start a transaction on a connection object, but then you still could >>only have one transaction per connection... :( > > > thats actually the case for all DBs I know including e.g. oracle with jdbc - > so the abstraction layers usually use connection pooling to speed up > opening a connection thus the app doesn't suffer so much. Ok, that means I won't get away with a single connection object (unless psycopg puts a connection pool in a single connection object). > No idea why thats happening - on jdbc, one can set an "autocommit" > connection property that will do exactly that: enforce a commit if a > statement was successful. Maybe psycopg has that too? Yes, it does have autoCommit, and thankfully it can be turned off (which I did, of course). >>I know PostgreSQL can do transactions on nested cursors, I have used >>that now and then in stored procedures (pl/pgsql). > I didn't find much on nested cursors on google, so I don't know how they > work - but I assume if they are part of psycopg, they somehow have to be > created using an existing cursor, as otherwise how should psycopg know that > what you want is a nested and not a new cursor. Actually, nesting of cursors is something that PL/PgSQL can do. And so can PL/SQL in Oracle. It's something that's possible on a low database API level, and (to my understanding) the DBAPI 2.0 uses them for queries. It's one of Pythons' advantages over eg. PHP, and one of the reasons I chose to use Python for this project. > So is there something on cursor objecst to get a new cursor, or at least the > connection so you can get a cursor on the very same connection? A cursor is comparable to an iterator over a result set (where the cursor fetches one record from the database at a time). You use one for every query, and it can often be reused for the next query as well. However, if you loop through a result set (with a cursor) and you need to do a query based on the record that the cursor is currently positioned at, you can't use the same cursor again for that query, but need to open a new cursor. That's what I meant by "nesting cursors". That shouldn't matter for the state of a transaction, though... Maybe there's a difference between database level cursors and DB API 2.0 level cursors in Python? The number of questions is increasing... From duncan.booth at invalid.invalid Sun Nov 21 07:00:04 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Nov 2004 12:00:04 GMT Subject: arrays References: <87ekinsawp.fsf@sinken.local.csis.hku.hk> Message-ID: Isaac To wrote: >>>>>> "Rahul" == Rahul Garg writes: > > Rahul> Hi. Is there someway i can get something similar to > Rahul> multi-dimensional arrays in python.I dont want to use > Rahul> Numarray. > > Is an array of array sufficient? Thinks like [[0]*5]*3. > You were right to call that an array of array (singular): what you suggested creates a list containing 3 references to the same list. I suspect the OP is much more likely to want an array of arrays (plural). The cleanest way these days is to use a list comprehension for all but the innermost list (provided the initial value is immutable): [[0]*5 for i in range(3)] or, if you want something mutable or more complex for an initial value you can just use list comprehensions throughout e.g.: [ [(i*100+j) for i in range(5)] for j in range(3) ] From steven.bethard at gmail.com Thu Nov 4 15:34:16 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 20:34:16 +0000 (UTC) Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> <1gmqqa3.r7hg5g17qatxkN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > [snip description of using integer parts of float representation] > > Although the details were more antiquated, that was elementary stuff > taught in electronic engineers' first-year computing courses back in the > '70s, just in case we ever needed to code our own transcendentals (in > Fortran, of course -- you weren't expected to master machine code unless > you took computing electives in 3rd and later years, much less exoterica > such as Pascal, Lisp or APL). Is it considered advanced or specialized > these days?! I'm obviously upsetting you, and I can see that we're still not quite understanding each other. I have to assume that you're not the only one I'm upsetting through these misunderstandings, so for the sake of the list, I'll stop responding to this thread. Thanks everyone for a good discussion! Steve P.S. If anyone would like to know my response to the float representation example, please contact me directly instead. From hancock at anansispaceworks.com Tue Nov 23 19:13:15 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 23 Nov 2004 18:13:15 -0600 Subject: Integrating w/ distutils, hooks? Message-ID: <200411231813.15006.hancock@anansispaceworks.com> Some time ago, I got the idea that I wanted to build image resources from vector graphic originals, instead of marshalling hundreds of tiny little icon images by hand. I wrote "BuildImage" to do this for me, and so far, it works very well, so I'm trying to make it easier to use and available to more developers. There is a brief (and somewhat dated) tutorial explaining what BuildImage itself does at: http://www.anansispaceworks.com/Documentation/BuildImage """ In as few words as I can put it: "BuildImage is a build system for image resources." That is to say, it attempts to do for image resources what make does for programs. """ So now, I'm looking for the best way to integrate the BuildImage package with distutils to make it the least painful for developers to use in their own distutils' packages. And I really feel this is something I should be talking to distutils-sig about. This is a little long -- but the idea is to spark some discussion about how I ought best to do this: I originally tried making my interface look more like distutils' interface -- providing a "setup" function, etc. I was thinking perhaps I might be able to drop in BuildImage scripts instead of distutils scripts in image resource sub-packages of some kind. But the end-user is unlikely to have BuildImage installed, and I really want 'build' and 'install' targets of the containing distribution to go without a hitch with or without BuildImage (assuming the images are already built, that is), while the developer targets "sdist" and "bdist" should use BuildImage to create image resources and include them in the distribution. Also, I'm probably starting to duplicate distutils functionality, which is wasteful. Perhaps, emulating distutils is somewhat misguided -- I certainly don't want to replace distutils, I just want to work with it in a way that will be intuitive for the developer. What I really want are hooks to attach to within distutils. *Ideally*, BuildImage would run at the time you would normally run Bison/Flex code -- i.e. it actually is a "pre-source" operation: you run it to complete your source distribution, then you compile C/C++ code, THEN you install Python modules, etc. I don't really see that distutils has this concept as yet, but it's probably a reasonable compromise to run it at the same time as C/C++ builds. (?) If that's the right path, then "sdist" should simply include all the necessary files for BuildImage, and the installer will simply need to have BuildImage installed in their Python site-packages in order to build the package. If not, then maybe 'sdist' should build the images, but certainly include all the BuildImage sources so they can be re-built. (?) OTOH, "bdist" should go ahead and build the images, store them in the correct location in the distribution tree, and tell distutils that it should install them along with the sources. (Pretty sure of this) Is it conventional for 'bdist' to *also* include the source files (i.e. in an open-source built distribution)? I'm a little confused about HOW to tell distutils what and where to install: it seems that I might want to use the "data_files" option to setup, or perhaps I want to update the MANIFEST or MANIFEST.in files (can I somehow get my code called after processing MANIFEST.in to MANIFEST so I can then add my additional instructions?). Modifying "MANIFEST.in" seems a little ugly, since the idea is that MANIFEST.in is human-edited source, while "MANIFEST" is machine-generated. But I don't know how I can get my code called to work on MANIFEST *after* it has been generated, but *before* it is used to install files. Currently, I visualize a typical setup.py module using BuildImage as something like this: """ # setup.py using BuildImage import distutils try: # We don't want to fail if BuildImage is not available, # because we are also run by the end user import BuildImage BuildImage.setup( ... options for BuildImage ... ) except: print """ You don't have BuildImage installed, so only distutils operations will be supported. """ distutils.setup( ... options for distutils ... ) """ So, when the end-user runs the setup script, they will see a message warning them that BuildImage targets won't work, but distutils will be able to do its job. OTOH, when the developer runs the script to build the images, that will work too, and BuildImage will do its thing. Obviously, though, BuildImage.setup() has to be able to tell distutils the things it needs to know, such as what to do with the images after they are built (typically they will be in a resource directory under the source tree? But in a distribution that insists on a filesystem standard, like Debian, they should be under /usr/share/images or perhaps /usr/share/pixmaps, etc). Since BuildImage won't be run at 'build' or 'install' time, these things have to already be prepared for distutils' installer. But BuildImage could be made aware of the requirements for 'bdist', 'bdist_rpm', 'bdist_deb', etc., and alter what it tells distutils accordingly. Anyway, thanks for your time -- any recommendations would greatly be appreciated, including references to previous discussion or online resources I should be reading. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at ferg.org Fri Nov 19 13:58:37 2004 From: steve at ferg.org (Stephen Ferg) Date: 19 Nov 2004 10:58:37 -0800 Subject: Events References: Message-ID: > Are there any really obvious things I should be doing with this code You might want to think about defining an event class. There's a cookbook recipe that addresses this kind of thing. It is at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286136 I've been playing with a little program that I'm going to use in a paper on event-driven programming. It uses an event-class. Also uses a set rather than a list to hold the list of observers/subscribers/listeners: *************************************************************** import sets class Dispatcher: def __init__( self ): # initialize a set of observers # each observer includes the event-type that # it wants to observer self.myEventHandlers = sets.Set() def registerHandler( self, argEventHandler, argEventType ): self.myEventHandlers.add( (argEventHandler, argEventType) ) def eventArrival(self, argEvent): # dispatch the event to the registered handlers self.notifyEventHandlers(argEvent) def notifyEventHandlers( self, argEvent): for anEventHandler, anEventType in self.myEventHandlers: if anEventType == argEvent.myEventType: # if the observer is registered for this type of event... anEventHandler.handle(argEvent) # ...send the event to it class Event: def __init__(self, argEventType, argEventSource): self.myEventType = argEventType self.myEventSource = argEventSource class EventHandler: def __init__(self, argHandlerName): self.name = argHandlerName def handle(self, argEvent ): # for this simple example, all we do to handle # the event is print information about it print self.name , "is handling a", argEvent.myEventType, \ "event from" , argEvent.myEventSource # create a dispatcher demoDispatcher = Dispatcher() # create some event handlers demoHandler1 = EventHandler("Larry") demoHandler2 = EventHandler("Moe ") demoHandler3 = EventHandler("Curly") # define an event type demoEventType = "LeftMouseDoubleClick" # register the event handlers for that type of event demoDispatcher.registerHandler( demoHandler1, demoEventType ) demoDispatcher.registerHandler( demoHandler2, demoEventType ) demoDispatcher.registerHandler( demoHandler3, demoEventType ) # generate an actual event demoEvent = Event(demoEventType, "mouse") # "mouse" is the event source # send the event to the dispatcher demoDispatcher.eventArrival(demoEvent) **************************************************************** From exarkun at divmod.com Mon Nov 15 21:04:15 2004 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 16 Nov 2004 02:04:15 GMT Subject: nonblocking read() In-Reply-To: Message-ID: <20041116020415.27631.1019852699.divmod.quotient.125@ohm> On Mon, 15 Nov 2004 16:08:00 -0800, Peter Ammon wrote: >I would like to read from a pipe in which data may arrive slowly. From > experimenting, it looks like os.read() will block until it returns the > maximum amount of data you asked for, in the second parameter to read(), > or until it hits EOF. I cannot find a way to return only the data that > the file object has immediately available. > > If no data is available, blocking is OK. > > The only workaround I can think of is to call select() in a loop, > reading and storing one byte each time, and then returning them when > select() indicates that the pipe is not ready for reading. > > Are there better approaches? Thanks, > You can read all available bytes (up to the given limit, n) like this (taken from Twisted): def setNonBlocking(fd): """Make a fd non-blocking.""" flags = fcntl.fcntl(fd, FCNTL.F_GETFL) flags = flags | os.O_NONBLOCK fcntl.fcntl(fd, FCNTL.F_SETFL, flags) Calling os.read(fd, n) after passing fd to setNonBlocking will return between 1 and n bytes, or raise an exception if no bytes are available. Jp From riko.wichmann at remove-this.desy.de Tue Nov 30 04:55:37 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Tue, 30 Nov 2004 10:55:37 +0100 Subject: comment out more than 1 line at once? In-Reply-To: References: Message-ID: I'm using emacs (with python-mode) to do most of my editing. also tried IDLE from python already, which is nice but an old dog doesn't like to learn new tricks :) Maybe I just don't know to comment out whole blocks using editor commands. Probably the trick Marc mentions in the following post will do the job. I use it to test pieces of a modules which usually is imported from another. For testing different parts, I usually have different __main__ sections in the file .... Cheers, Riko Aaron Bingham wrote: > Riko Wichmann wrote: > >> Dear all, >> >> is there a way in Python to comment out blocks of code without putting >> a # in front of each line? Somethings like C's >> >> /* >> block of code here is commented out >> */ > > > No. Why do you want this? Any good programmer's editor will have a > comment/uncomment feature to make it easy to comment out whole blocks of > code at a time using the hash character ('#'). > > Aaron > From davidf at sjsoft.com Thu Nov 25 03:30:59 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 25 Nov 2004 10:30:59 +0200 Subject: Newbie requires help me on how to use the ZipFile module please. In-Reply-To: <8cf64c3d.0411241601.feca1f7@posting.google.com> References: <8cf64c3d.0411241601.feca1f7@posting.google.com> Message-ID: <41A59843.8030301@sjsoft.com> Ian Cook wrote: > Hi, > Can someone PLEASE shed some light on using the ZipFile module > correctly. > I'm new to python so please excuse me if this is a 'dumb' question. > > If I use mode='a' then what happens is the zip file just gets bigger > and bigger as the SAME file is appended to the zipfile. > > If I use mode='w' then what happens is the zip file is erased before > adding files to it. Therefore I lose the files that were in the > original file zipfile. > > What I want is to use the ZipFile module to UPDATE an existing zip > file, rather than append, or create a new zip file. The zip file then > contains my original files and any updated files. > > Does anyone know how this can be done with the Zipfile module? > > This is a snippet of the code I have now.. > > try: > zf = zipfile.ZipFile(zfname,mode='a') > except: > zf = zipfile.ZipFile(zfname,mode='w') > > for name in cutflist: > fp = os.path.join(root,name) > print "adding ",fp,"...", > compresstype = zipfile.ZIP_DEFLATED > if zipfile.is_zipfile(fp): > compresstype = zipfile.ZIP_STORED > zf.write(fp,compress_type=compresstype) > print 'done.' > > > > Thanks in advance. > > Ian Cook Curious, I posted a reply to the similar question you posted a week or two ago, but it doesn't show up in google groups... even though I got it from my nntp server... So I'll post it again and Cc you :-) Instead of attaching the file, you can get it here: http://cvs.sourceforge.net/viewcvs.py/*checkout*/translate/src/translate/misc/zipfileext.py?rev=1.3 > > This is the module translate.misc.zipfileext from translate.sourceforge.net > I use it to do updating of zip files (it adds some stuff on top of the normal zipfile class that I should really submit as a patch :-) ) > Can't recall all the details but I think even so its a bit hairy. > For an example you could look at http://cvs.sourceforge.net/viewcvs.py/translate/src/translate/storage/xpi.py?rev=1.33&view=auto > > The key method being this: > def overwritestr(self, zinfo_or_arcname, bytes): > """writes the string into the archive, overwriting the file if it exists...""" > if isinstance(zinfo_or_arcname, zipfile.ZipInfo): > filename = zinfo_or_arcname.filename > else: > filename = zinfo_or_arcname > if filename in self.NameToInfo: > self.delete(filename) > self.writestr(zinfo_or_arcname, bytes) > self.writeendrec() > > Basically you need to delete existing files before you write to them if you want to replace them. > > (This became more tricky) tricky as I was modifying zip files within zip files and trying to get them to store correctly, I ended up cloning the zip file objects, catching close events etc) > Anyway maybe you can find something there that will help you. > > David From tdelaney at avaya.com Mon Nov 22 23:56:34 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 23 Nov 2004 15:56:34 +1100 Subject: Python and generic programming Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE72120C@au3010avexu1.global.avaya.com> And now a version that works with multiple arguments ... import itertools def generic (genfunc): speclist = [] def wrapf (*args): typs = tuple(type(arg) for arg in args if not isinstance(arg, type)) assert len(args) == len(typs) for specfunc, specs, typs in speclist: if len(args) != len(typs): continue for arg, spec, typ in itertools.izip(args, specs, typs): if isinstance(spec, type): if not isinstance(arg, typ): break elif (arg != spec) or (not isinstance(arg, typ)): break else: return specfunc(*args) return genfunc(*args) wrapf.wrappedfunc = genfunc wrapf.speclist = speclist wrapf.func_name = genfunc.func_name return wrapf def specialised (genf, *specifiers): try: genf = genf.genfunc except AttributeError: pass assert len(specifiers) == genf.wrappedfunc.func_code.co_argcount def spd(specf): assert len(specifiers) == specf.func_code.co_argcount typs = [] for s in specifiers: if isinstance(s, type): typs.append(s) else: typs.append(type(s)) typs = tuple(typs) genf.speclist[:0] = [(specf, specifiers, typs)] return specf spd.genfunc = genf return spd # For my US friends ;) specialized = specialised @generic def some_function (arg): print "generic - %r" % (arg,) @specialised(some_function, int) @specialised(some_function, long) def some_specific_function(arg): print "int-specific - %r" % (arg,) @specialised(some_function, float) def some_specific_function(arg): print "float-specific - %r" % (arg,) @specialised(some_function, 1) @specialised(some_function, 1.0) @specialised(some_function, 1L) def some_specific_function(arg): print "one-specific - %r" % (arg,) @generic def other_function (arg1, arg2): print "generic - %r, %r" % (arg1, arg2) @specialised(other_function, 1, object) def other_specific_function (arg1, arg2): print "1/object - %r, %r" % (arg1, arg2) @specialised(other_function, int, float) def other_specific_function (arg1, arg2): print "int/float - %r, %r" % (arg1, arg2) @specialised(other_function, 1, float) def other_specific_function (arg1, arg2): print "1/float - %r, %r" % (arg1, arg2) @specialised(other_function, 1, 2.0) def other_specific_function (arg1, arg2): print "1/2.0 - %r, %r" % (arg1, arg2) if __name__ == '__main__': some_function('abc') some_function(itertools) some_function(123) some_function(123L) some_function(123.0) some_function(1) some_function(1.0) some_function(1L) print other_function(2, 2) other_function(1, 2.0) other_function(1, 1.0) other_function(2, 2.0) other_function(1, 2) In cases where more than one specialisation would match, the most recently added will be used i.e. in the above, for other_function(1, 1.0) will use (int, float) even though (1, object) would also match. So it's important to create functions in the correct order. This is starting to get recipe-worthy - but I want to see what happens with methods first ... Tim Delaney From ville at spammers.com Tue Nov 30 06:31:09 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Nov 2004 13:31:09 +0200 Subject: Python on Nokia Phones ? References: <8d851104.0411300047.1ea17809@posting.google.com> Message-ID: >>>>> "Mark" == Mark Doukidis writes: Mark> An exciting prospect when I first heard of Nokia's proposal. Mark> I thought there would be a few more postings here since the Mark> idea first surfaced around Jan 2004. Do realize that giants like Nokia move slow and make a minimum amount of noise about what they are doing. They (Nokia) seemed pretty excited about the prospects back in the June workshop: http://www.forum.nokia.com/main/0,,4_22,00.html I think I'll try to check out whether they have come up with a new version. There are lots of changes happening with S60 / Symbian OS in general ATM, so I wouldn't be surprised if they chose to delay Python a little bit, at least as far as shipping it with the phones goes. -- Ville Vainio http://tinyurl.com/2prnb From dave.benjamin at gmail.com Thu Nov 4 03:03:21 2004 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Thu, 04 Nov 2004 01:03:21 -0700 Subject: pep 336: Make None Callable In-Reply-To: References: Message-ID: The Eternal Squire wrote: > > None should be a callable object that when called with any > arguments has no side effect and returns None. > This is how ActionScript works, and to be honest I strongly dislike this behavior. It hides bugs, and to make things worse, the null often bubbles up someplace entirely different from where the error initially occurred. This makes debugging a pain in the ass. I'd prefer to just write a NullObject if I need one. Otherwise, I like Python's behavior, which is more fail-fast and less error-prone. IMHO. But thanks for putting the idea out. I think Objective C does something similar--is this the case? It does have the convenient effect of allowing you to pass null as an event listener if you just want to ignore events from a GUI object, for instance, but it's just not worth the price. Dave From programmer.py at gmail.com Mon Nov 1 09:57:21 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 1 Nov 2004 08:57:21 -0600 Subject: Arugument list too long on Linux System In-Reply-To: References: Message-ID: If your python script processed '*.jpg' files, then you could probably get away with using the glob module -> import glob files_to_process = glob.glob( "/path/to/files/*.jpg" ) for f in files_to_process: tar_it.add(f) Something like that ought to be close to what you need. I'm not sure what the limitation is to commandline arguments, so I can't be much help there :(. jw tar_it = tarfile.open("%s.tar" %real_time, "w") for root, dirs, files in os.walk(path): > for f in files: > jpg = os.path.splitext(f) > ## If the file has a '.jpg' extension add it to the tar file. > if jpg[1] == '.jpg': > tar_it.add(f) On Mon, 01 Nov 2004 09:45:22 -0500, Brad Tilley wrote: > I was using Python to tar up some files each day in a directory by > calling os.popen("/bin/tar.......). > Everything was working well until the app that generated the files was > set to generate a file every two seconds for nine hours each day (16,200 > files each day). After this I began getting this error: > > "Argument list too long" > > This would happen from the script or from the command line invoking tar > natively. So, I wrote my way around this by using this code: > > tar_it = tarfile.open("%s.tar" %real_time, "w") > for root, dirs, files in os.walk(path): > for f in files: > jpg = os.path.splitext(f) > ## If the file has a '.jpg' extension add it to the tar file. > if jpg[1] == '.jpg': > tar_it.add(f) > > But, I don't understand why I got this error in the first place. I use a > rather robust Debian GNU\Linux system (3.2GHz proc, 2GB DDR400 RAM, 15K > SCSI drives) what causes this type of error? This is not really a Python > issue, but I thought some knowledgeable users on the list might be > willing to explain it. > > Thanks, > > Brad > -- > http://mail.python.org/mailman/listinfo/python-list > From deetsNOSPAM at web.de Sat Nov 27 08:06:02 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 27 Nov 2004 14:06:02 +0100 Subject: executable from python cod References: <77969915.0411241036.553c3da3@posting.google.com> <77969915.0411261142.1bcca34c@posting.google.com> Message-ID: > No i need it help. > I created small compiler(real, not packer - like py2exe) to compile > basic python code(to work compiled program - not need it python??.dll > or *.pyd files). Simple py programs, after compiling has size 1-3,4 > kb. But i don't know if it need... That's why i ask you. When it works - sure, I bet a lot of people are interested. -- Regards, Diez B. Roggisch From andrea.valle at unito.it Wed Nov 3 02:56:22 2004 From: andrea.valle at unito.it (andrea valle) Date: Wed, 3 Nov 2004 08:56:22 +0100 Subject: pickling a dict In-Reply-To: References: <783d0f8c.0411012330.4172d1d4@posting.google.com><20041102083027.F7CC.JCARLSON@uci.edu> Message-ID: > First of all, your posting shows up as part of the "Newbie question" > thread > and not as a new thread. You probably replied or followed up to a > posting > in that thread and you only changed the subject line. Please don't do > that. > Yes, it's true. I'm really sorry. I didn't know about this fact. (Where is these info about thread recorded??) > BTW, does your save( ) function also take minutes? If it takes much > less > than the open( ) function, my guess would be that pickle is not the > problem. You're guessing fine: it takes much less. So effectively it should depend on my other functions. I hadn't considered that. Thanks a lot for your help. Best -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From jdadson at yahoo.com Sat Nov 20 02:09:52 2004 From: jdadson at yahoo.com (Jive Dadson) Date: Sat, 20 Nov 2004 07:09:52 GMT Subject: Python and generic programming References: <1gm17og.ctwoqv17vkctxN%aleaxit@yahoo.com> Message-ID: <419EEEAA.D3C1046F@yahoo.com> Alex Martelli wrote: > > Roman Suzi wrote: > > > I wonder, does Python support generic programming paradigm, and to what extent > > It appears to me to support generics at least as well as C++ does. I > just write normal code (no typechecks) and voila, the equivalent of C++ > templates (at least). What do you think is missing? > > Alex How about specialization? I'm relatively new to Python. I ask for information, not to be argumentative. If you have, for example, several data-types for matrices, how do you write code that will automatically find the right routine for quickly multiplying a vector by a diagonal matrix represented as a vector, and automatically call the right code for multiplying by a sparse matrix represented by some sparse coding, etc? From zach at cs.uni-bonn.de Tue Nov 2 05:23:12 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 2 Nov 2004 10:23:12 GMT Subject: strong/weak typing and pointers References: Message-ID: > printf("value is %d", f); This seems a very good example to me. Note that this is also an example showing that C++ does contain a little bit of dynamic typing, too, isn't it? Cheers, gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From steven.bethard at gmail.com Sun Nov 21 18:55:48 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 21 Nov 2004 23:55:48 GMT Subject: generic object implementation Message-ID: <8W9od.373195$wV.310530@attbi_s54> So I'm trying to get a prototype implementation of the 'generic object' type. (I'm currently calling it 'bunch', but only because I can't really think of anything better.) I'd like some feedback on what methods it needs to support. Ideally I'd keep this as minimal as possible... Remember that the goal of the 'generic object' type is to allow the programmer to make the design decision that attribute-style access is more appropriate than []-style access. Given that, my feeling is that the 'generic object' type should *not* support __(get|set|del)item__ , though I'm still undecided on __len__, __iter__, __contains__, items, keys, values, etc. Here's what I have currently: import operator as _operator class bunch(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __eq__(self, other): if not isinstance(other, bunch): return False attrs = set(self.__dict__) if attrs != set(other.__dict__): return False for attr in attrs: if not getattr(self, attr) == getattr(other, attr): return False return True def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join('%s=%r' % (k, v) for k, v in self.__dict__.items())) def update(self, other): self.__dict__.update(other.__dict__) @classmethod def frommapping(cls, mapping, getkeys=iter, getitem=_operator.getitem): result = bunch() for key in getkeys(mapping): value = getitem(mapping, key) try: value = bunch.frommapping(value) except TypeError: pass setattr(result, key, value) return result From ch.pingel at web.de Mon Nov 22 16:06:53 2004 From: ch.pingel at web.de (Christoph Pingel) Date: Mon, 22 Nov 2004 22:06:53 +0100 Subject: crash when loading a lib on OS X Message-ID: Can anybody tell me what's going on here (or give me a pointer where to start looking): Nov 22 18:05:03 localhost crashdump: Unable to determine CPSProcessSerNum pid: 1230 name: python This is form python.crash.log ------ Command: python Path: /usr/bin/python Version: ??? (???) PID: 1230 Thread: 0 Exception: EXC_BAD_ACCESS (0x0001) Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000004 Thread 0 Crashed: 0 org.python.python 0x10094c4c PyErr_NewException + 0x18c (errors.c:544) 1 orange.so 0x020223b8 makeExceptionClass(char*, char*, _object*) + 0x94 2 orange.so 0x021c8c74 initorange + 0x30 3 org.python.Python.framework 0x95fc1bc4 _PyImport_LoadDynamicModule + 0xcc 4 org.python.Python.framework 0x95fbf7a4 PyImport_ExecCodeModuleEx + 0x17b8 5 org.python.Python.framework 0x95fc08c4 PyImport_ImportModuleEx + 0x930 6 org.python.Python.framework 0x95fc02e0 PyImport_ImportModuleEx + 0x34c 7 org.python.Python.framework 0x95fbfe00 PyImport_ImportModule + 0xc8 8 org.python.Python.framework 0x95fbffd4 PyImport_ImportModuleEx + 0x40 9 org.python.Python.framework 0x95f9cbf0 _PyUnicodeUCS2_IsAlpha + 0x90 10 org.python.Python.framework 0x95f4a8d0 PyObject_Call + 0x30 11 org.python.Python.framework 0x95fa91ec PyEval_CallObjectWithKeywords + 0x100 12 org.python.Python.framework 0x95fa6984 PyEval_EvalCode + 0x2280 13 org.python.Python.framework 0x95fa7e30 PyEval_EvalCodeEx + 0x850 14 org.python.Python.framework 0x95fa4734 PyEval_EvalCode + 0x30 15 org.python.Python.framework 0x95fc85f0 PyRun_FileExFlags + 0xe4 16 org.python.Python.framework 0x95fc7354 PyRun_InteractiveOneFlags + 0x1f0 17 org.python.Python.framework 0x95fc713c PyRun_InteractiveLoopFlags + 0x10c 18 org.python.Python.framework 0x95fc6fd4 PyRun_AnyFileExFlags + 0x54 19 org.python.Python.framework 0x95fd1ec0 Py_Main + 0x7cc 20 python 0x00003c78 start + 0x1bc 21 python 0x00003aec start + 0x30 ------ I'm afraid that something's wrong with my system, but I had a hard time googling for getCPSProcessSerNum: it returned 0 results. Same at Apple's site... What does CPS mean? Thanks for any input, best, Christoph From jepler at unpythonic.net Tue Nov 9 13:37:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 9 Nov 2004 12:37:40 -0600 Subject: Concise idiom to initialize dictionaries In-Reply-To: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> References: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> Message-ID: <20041109183738.GF3567@unpythonic.net> The documentation (docs.python.org, not help(locals)) makes it clear that this is not intended to work: locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Perhaps you want a dict of dicts. d = dict([(s, {}) for s in 'abc...z']) now refer to d['a'][key] instead of a[key] Python has good reasons to forbid the modification of locals(). The most important may be that for each function, static analysis determines whether a particular name is local or not: A name is local if it is assigned and there is no 'global' statement for that name. The following code would treat x as global, because it is never assigned: def f(): locals()['x'] = 3 return x Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ncoghlan at email.com Tue Nov 30 06:18:26 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Tue, 30 Nov 2004 21:18:26 +1000 Subject: slicing, mapping types, ellipsis etc. In-Reply-To: References: Message-ID: <41ac5701$0$25761$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Jerry Sievers wrote: > Fellow Pythonists; > > I am totally puzzled on the use of slicing on mapping types and It's generally not supported (since slices are designed to work with the numerical indices of a sequence, not the arbitrary keys of a mapping). The results of d.keys(), d.values() & d.items() can all be sliced like any other sequence, though. > especially unsure on use of the Ellipsis... and slicing syntax that > has two or more groups seperated by comma. Others have explained these - one point that may not have been entirely clear is that none of the classes in the standard library make use of these (although the point may have been implied by the references to PyNumeric as the place to look for more exact documentation. Python's own documentation of the slice() builtins makes reference to Numeric!). Cheers, Nick. From wgshi at namao.cs.ualberta.ca Thu Nov 25 14:37:54 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Thu, 25 Nov 2004 19:37:54 +0000 (UTC) Subject: dictionary initialization References: <41a62df4.1003031613@news.oz.net> Message-ID: Hi, In article <41a62df4.1003031613 at news.oz.net>, Bengt Richter wrote: > On Thu, 25 Nov 2004 18:38:17 +0000 (UTC), wgshi at namao.cs.ualberta.ca > (Weiguang Shi) wrote: >You wrote it, so you have to "justify" it ;-) I guess :-) >While I agree that ++ and -- are handy abbreviations, and creating a >key by default makes for concise notation, a[i]++ means you have to >make some narrow assumptions ... Right, though generalization can be painful for the uninitiated/newbie. >You can certainly make a dict subclass that behaves that way if you >want it: > ... This is nice even for someone hopelessly lazy as me. > >Otherwise the usual ways are along the lines of >... I would happily avoid them all. Thanks a lot, Weiguang From koko9991 at compuserve.de Sun Nov 7 04:10:10 2004 From: koko9991 at compuserve.de (Konrad Koller) Date: Sun, 07 Nov 2004 09:10:10 GMT Subject: New Python Books? References: <1099427406.763633.285680@z14g2000cwz.googlegroups.com> Message-ID: <418de5e2.75659078@news.compuserve.de> On 2 Nov 2004 12:30:06 -0800, ryan at ryankaskel.com wrote: >I love reading books on Python and have almost all of them. However, it >seems that there aren't any new ones currently being written that >aren't for beginners. Does anyone know of any plans for future Python >books that cover specific topics like wxPython or mod_python (like >O'reilly's mod_perl and also their book on PerlTk). Thanks. > >Ryan Kaskel > I recommend: H.P.Langtangen: Python Scripting for Computational Science. Excellent! Konrad Koller From newsgroups at jhrothjr.com Tue Nov 30 15:30:16 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Nov 2004 14:30:16 -0600 Subject: weird behaviour of "0 in [] is False" References: Message-ID: <10qpm2qpsphal6e@news.supernews.com> "Paul Robson" wrote in message news:coi1hc$9go$1 at news8.svr.pol.co.uk... > Sylvain Thenault wrote: > >>>>> l = [] >>>>> 0 in (l is False) > > (l is False) is not a tuple or list, it's a boolean value. > >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: iterable argument required >>>>> (0 in l) is False >> True > > 0 in l is False becuase l is empty, so it's False is False which is true, > (except in Intercal probably and Visual C++) > >>>>> 0 in l is False >> False > > l is False is False because l is not the value false though it has a false > value (err.....) > > Okay. > > l != False because it's not the displayed value false > > but if not l would evaluated to true because [] is a false equivalent. > > 0 in False .... okay.... this should be an error ..... something to do > with > the equivalence confusion of what False is ? It's not an error. As one of the first responders said, check the language definition. That defines both 'in' and 'is' as equality operators, and defines exactly what a chain of equality operators means. In this case, it means: (0 in l) and (l is False) The and short circuits, giving the result of False without ever doing the final comparison. Granted, that's not exactly obvious... John Roth > > > From tom at tompurl.com Mon Nov 8 15:17:19 2004 From: tom at tompurl.com (Tom Purl) Date: Mon, 08 Nov 2004 14:17:19 -0600 Subject: Mixing Python And Bash Message-ID: I just wrote a Python script that is going to be called from bash script. If the Python script fails, I want the bash script to also stop running. Unfortunately, I can't seem to get that to work. Here's the script so far: # custom python script /usr/bin/python /home/username/Dev/Python/packZODB.py \ -s"gsgmc.sigma.zettai.net" -b 7 # next program /usr/bin/someOtherProgram I don't want the second program to run if the first program fails. Isn't that the default in bash? If someone could please point me in the right direction regarding this problem, I would really appreciate it. Thanks in advance! Tom Purl From theller at python.net Fri Nov 5 12:31:39 2004 From: theller at python.net (Thomas Heller) Date: Fri, 05 Nov 2004 18:31:39 +0100 Subject: py2exe 0.5.4 released References: <4pulo0tjm2se1p10apth81sn4p6a9mh6g8@4ax.com> <4qk4wq6k.fsf@python.net> <554no051vbnq7os9hs0b1kov9p2a9c60g7@4ax.com> Message-ID: Mark A. Munza writes: > On Fri, 05 Nov 2004 11:22:43 +0100, Thomas Heller wrote: > >>There seems a problem with the mirrors. One (the only one?) that works >>is optusnet mirror in australia. >> >>http://prdownloads.sourceforge.net/py2exe/py2exe-0.5.4.win32-py2.3.exe?use_mirror=optusnet >> >>Thomas > > If you have the py2.3 version could I trouble you to email a copy to me? Doesn't the above link work for you? Thomas From tjordah at start.no Fri Nov 26 04:24:04 2004 From: tjordah at start.no (Lars Moastuen) Date: 26 Nov 2004 01:24:04 -0800 Subject: Extending classes written in C++ using SWIG References: <99efe53b.0411250614.1f0c0e3c@posting.google.com> Message-ID: <99efe53b.0411260124.34f36ff@posting.google.com> Thx for your replies. It seems I have created an example I thought were equal to my problem, but it turned out that wasn't the case. I'm trying to figure out what the difference is, but I find the classes quite similar to the example below (too big to post here)... However, this problem can be solved by using "directors" (http://www.swig.org/Doc1.3/Python.html#directors), mine cannot... Im currently testing if Boost.Python does the job better, but seems I run into the same problem... I suspect it has something to do with STL list or something, but I'm not sure yet... Will post if I manage to create an example or if I find a solution. "Phil Thompson" wrote in message news:... > > tjordah at start.no (Lars Moastuen) writes: > > > >> class Bar > >> { > >> public: > >> Bar() {}; > >> ~Bar() {}; > >> virtual char* DoBar() const { return "Bar"; }; > >> }; > >> > >> class Foo > >> { > >> public: > >> Foo() {}; > >> ~Foo() {}; > >> virtual void DoFoo(Bar* someBar) { cout << someBar->DoBar() << endl; > >> }; > >> }; > > >> class ExtendedBar(Bar): > >> def __init__(self): > >> Bar.__init__(self); > >> > >> def DoBar(self): > >> return "ExtendedBar"; > >> > >> bar = ExtendedBar(); > >> foo = Foo(); > >> foo.DoFoo(bar); > > >> I now expect to get "ExtendedBar" as output from UseFoo.py (since I've > >> declared DoBar() as virtual, but I get "Bar" > > >> Can anyone tell me why? > > > > Because "someBar->DoBar()" uses the vtable of the C++ dynamic type to > > decide which actual DoBar method to call. Unfortunately there is no > > C++ type corresponding to your ExtendedBar, there is no vtable for > > your ExtendedBar type in C++. C++ only knows about C++ types; it is > > unaware of the existence of Python types. Inside your Python instance > > of ExtendedBar you are holding on to an instance of a C++ Bar. > > > >> Is there a way to remedy this?? > > > > I don't know whether SWIG provides a boxed solution for this sort of > > problem. One approach is to override the DoBar method in a subclass of > > Bar in C++, and make that method pass the 'dispatch request' up into > > Python. Then you expose the wrapper class in Python, rather than Bar > > itself. > > > > It looks something like this: > > > > struct PseudoBar : public Bar { > > PyObject* self; // the Python instance wrapping this C++ instance > > void DoFoo () { > > PyObject_CallMethod(this->self, "DoFoo", ""); > > } > > }; > > > > Of course, you'll need to augment this with checks to ensure that > > there really is something overriding the method, otherwise you'll end > > up in an infinite loop ... but hopefully you get the idea. It's all a > > bit tedious. > > If SWIG really requires you to do this by hand (I'm surprised) then you > might want to look at SIP (http://www.riverbankcomputing.co.uk/sip/). SIP > generates code that does exactly what you suggest so that bindings behave > as the OP was expecting. > > Phil From kent3737 at yahoo.com Fri Nov 26 00:06:59 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 26 Nov 2004 00:06:59 -0500 Subject: Subclassing complex with computed arguments In-Reply-To: References: Message-ID: <41a6b8a3$1_2@newspeer2.tds.net> Jp Calderone wrote: > On 25 Nov 2004 14:30:18 -0800, pcolsen at comcast.net (Peter Olsen) wrote: > >>I want to define a class "point" as a subclass of complex. >> >>When I create an instance >> >>sample = point() >> >>I want "sample" to "be" a complex number, but with its real and >>imaginary parts computed in point()'s __init__ function with their >>values based on the arglist. I want to compute with point instances >>as though they were native complex numbers, but I want to be able to >>define some new methods and over-ride some of complex's existing ones. > > Something like this? > >>>>class simple(complex): > > ... def __new__(cls, real=0, imag=0): > ... return super(simple, cls).__new__(cls, real + 1, imag + 1) > ... Unfortunately operations on 'simple' objects will return 'complex' results. This is probably not what the OP wants. >>> class point(complex): ... def __new__(cls, x, y): ... return complex.__new__(point, x*2, y*2) ... >>> p=point(1,2) >>> p (2+4j) >>> type(p) >>> p2=p+1 >>> p2 (3+4j) >>> type(p2) I don't know if there is an easy way around this. A brute force approach might be to override __add__(), etc to return point objects instead of complex - though I haven't been able to figure out how to do this. I tried: def __add__(self, *args, **kwds): val = complex.__add__(self, *args, **kwds) return point(val) but val is NotImplemented instead of the desired sum ?? I had more luck with a delegation-based approach: class point(object): def __init__(self, *args, **kwds): if len(args) == 1 and isinstance(args[0], complex): self.c = args[0] if len(args) == 2: self.c = complex(args[0]*2, args[1]*2) else: self.c = complex(*args, **kwds) def __add__(self, y): val = self.c+y return point(val) def __repr__(self): return 'point' + self.c.__repr__() p=point(1,2) print p p1 = p+1 print p1 prints: point(2+4j) point(3+4j) I was hoping that the special methods of point could delegate to the corresponding special method of complex, so the delegation could be automated, but again I couldn't get this to work. Maybe someone else can explain this? For example if c is a complex number, why does c.__add__(1) return NotImplemented? I tried adding a delegating __coerce__() to class point but it is never called... Call me confused... Kent > >>>>simple(3, 4) > > (4+5j) > > > The trick is that since complex instances are immutable, you need to change the initialization parameters before the instance is ever created. __new__ is the hook for that. > > Jp From behnel_ml at dvs1.informatik.tu-darmstadt.de Mon Nov 8 07:15:19 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Mon, 08 Nov 2004 13:15:19 +0100 Subject: Import Python Class/methods into C++ In-Reply-To: References: Message-ID: Keith Moore schrieb: > Can anyone show me an example of how to import a python class into a C++ > program? > I am able to use PyImort_ImportModule to import a module, and > PyObject_GetAttrString to import the function from the module. > Now I converted that module to a class. I need to import methods from that > class into my C++ program. Have you tried elmer? http://elmer.sourceforge.net/ Stefan From zanesdad at bellsouth.net Thu Nov 4 15:08:59 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 04 Nov 2004 15:08:59 -0500 Subject: Storing objects in dictionary In-Reply-To: <8C53AAFA2050EE40BDCDB9455DA7D6340C6266@sw720ex020.visa.com> References: <8C53AAFA2050EE40BDCDB9455DA7D6340C6266@sw720ex020.visa.com> Message-ID: <418A8C5B.20508@bellsouth.net> Feghhi, Jalil wrote: >I get an error storing an object in a dictionary. The dictionary and the object are both provided by mod_python. One is the session object (which is just a dictionary) and one is a FieldStorage object (I think it is a class but displays as a dictionary). My question is what is the requirement for an object to be able to store it in a dictionary? I am sure there is documentaion somewehre but I couldn't find it. > >Regards, > >-Jalil > > Are you trying to use the session object as a key in the dictionary or a value of a key? What error are you getting? You should be able to put anything into a dictionary (AFAIK) as a key, but only hashable objects can be put in as keys. Jeremy Jones From walter at livinglogic.de Fri Nov 5 04:59:43 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Fri, 05 Nov 2004 10:59:43 +0100 Subject: Extract Title from HTML documents In-Reply-To: References: Message-ID: <418B4F0F.4020707@livinglogic.de> Nickolay Kolev wrote: > Hi all, > > I am looking for a way to extract the titles of HTML documents. I have > made an honest attempt at doing it, and it even works. Is there an > easier (faster / more efficient / clearer) way? You might try XIST (http://www.livinglogic.de/Python/xist): --- from ll.xist import parsers, xfind from ll.xist.ns import html e = parsers.parseFile("test.html", tidy=True) print unicode(xfind.first(e//html.title)) --- (This uses libxml2's HTML parser internally). Bye, Walter D?rwald From sxanth at ceid.upatras.gr Sun Nov 14 03:55:12 2004 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Sun, 14 Nov 2004 00:55:12 -0800 Subject: [PATCH] Some new stuff Message-ID: Hi all. Basically, I'd like to use python as my system shell. It's not suitable for a general purpose shell but since it is very programmable it can eventually do whatever bash does and even more. One thing I'd like python to do is: attach the *python code* of a function to a function object. The same for class. This can be done in python as it is but it doesn't feel very right. I think it should be the job of the parser. So there is a patch vs 2.3.4 at: http://students.ceid.upatras.gr/~sxanth/ISYSTEM/python-PIESS.tar.bz2 With this patch when the command line option -P is passed to python, all functions and classes have an extra member __pycode__ which is the code of the thing! This is very exciting because if combined with a function 'save()' which looks for all the functions/classes in globals(), takes their __pycode__ and saves it to a file (along with it's own code: save.__pycode__) can lead to a really fun Python Incremental Expert System Shell. Such a sample system is also included in the tar file. For example we can say: lsfunc() # lists all functions pr (lsfunc) # prints definition of lsfunc ed (pr) # edits the function 'pr' save () # saves all and we go to sleep Cheers Stelios From aleaxit at yahoo.com Thu Nov 4 03:36:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 Nov 2004 09:36:01 +0100 Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> Message-ID: <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> Steven Bethard wrote: > Alex Martelli yahoo.com> writes: > > > > Steven Bethard gmail.com> wrote: > > > > > On the other hand, I haven't really seen any good > > > cases for wanting weak-typing in a statically-typed language either. > > > > How would an operating system's filesystems store arbitrary sequences of > > bytes (which might be floats, int, whatever -- only the application > > knows) into disk pages (blocks of, say , 4096 bytes each) otherwise? > > Valid point of course. But the OS doesn't really take advantage of > weak-typing here if it takes an arbitrary sequence of bytes and stores an > arbitrary sequence of bytes. I haven't written much OS code (just a > prototype system back in undergrad), but I never cast one type of struct > to another -- to and from void*, but never between types. Is the OS going to be able to read something from disk and *USE* it? > Of course, I'm sure there're are a number of good reasons to do so -- my > claim was only that I hadn't seen them. I'd be grateful if you could > point me to an example. =) Suppose for example that you would like your OS to be able to load executable code from disk into memory and execute it. Suppose you would like it to be able to read some configuration parameters from disk and set its own internal data structures accordingly. At one level, as it goes to disk or comes back from there, you have arrays of bytes. But in memory, you want functions that can be called appropriately (a device driver residing in a module) or data structures which, differently from an array of byte, DO have structure -- for example, a partition table for a disk, with information to specific filesystem drivers as to what partition is to be treated in what way. I don't understand how you can have failed to see a zillion more examples of operating systems actively _using_ data read from disk, since it's such a widespread phenomenon nowadays. > > Even if you design a new OS based on a filesystem whose files are all > > "strongly typed" > > You really do think I'm satan, don't you? ;) I'm old enough to have fought my way through filesystems more strongly typed than plain streams of bytes, sure -- Unix was already around but not all-pervasive yet. I remember peripherals which wanted streams, but streams of _SIX_-bit "bytes" -- so you had to have somewhere a pack-and- unpack routine that could take (e.g.) a block of 48 8-bit bytes and reinterpret it as a block of 64 6-bit bytes, or viceversa. I hope there aren't any more of _those_ around -- but in exchange we have, for example, pervasive issues of unicode vs byte streams and encodings. It's not just files, either. We have memory sliced up into pages, and a page is, say, a well defined object of 4096 bytes. But we want to be able to store all different kinds of stuff into those bytes - we HAVE to, in fact, because that is all the memory we have... all pages... If your point is that all you need is, not to "overlay" different structures onto the same address, but "just" to overlay "look at this as raw bytes" upon any structure and viceversa -- can't you see you're doing exactly the same thing with just one conceptual extra step? Instead of struct foo* p = ...; struct bar* q = (struct bar*) p; you're thinking struct foo* p = ...; void *v = (void *) p; struct bar* q = (struct bar*) v; but it's just the same thing, and v can be optimized away. Above the lowest levels, you can get away with (at least conceptually) copying stuff in order to be able to reinterpret bits, as you can do in Python with x = struct.unpack(f1, struct.pack(f2, y)) -- you can do plenty of bit-level reinterpretation but not *in-place*, only via copying. But you can't generally afford that luxury when you dig deep enough -- copying bits around when you only need to reinterpret them is paying a real cost in memory and CPU and bus bandwidth, after all. It doesn't have to be OS-level: any virtual machine has similar issues. So, look at the CPython interpreter sources, for example... what performance price would it have to pay if it couldn't cast pointers but rather had to copy bits around each time it now does a cast? Alex From hancock at anansispaceworks.com Wed Nov 3 08:59:15 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 3 Nov 2004 07:59:15 -0600 Subject: Wrapping or converting Perl module? Message-ID: <200411030759.15909.hancock@anansispaceworks.com> Hi all, Suppose you have found a really nice module that does what you want (or will do, it still being in development), and you don't want to waste a lot of duplicated effort, but this module is in Perl rather than Python (and yes, the author is not open to conversion -- already tried that ;-) ). If it were written in C, I'd have a couple of answers, such as wrapping the module with a Pyrex module, or one of the other means of adapting C modules to use with Python. But I don't know what to do with Perl. For starters, should I be thinking in terms of a wrapper (as with C), or would it be smart to try to automatically translate the code. I'm willing to do a little bit of development work on this, but as I said, the original code is still being developed, and I hate to waste a lot of effort by reinventing what my colleague is doing. I'm willing to go as far as collaborating with this person, and I'm pretty sure we can share his work on the MySQL code embedded in his module, but I'd like to be able to convert his logic, too. (In fact it's http://www.disobey.com/noos/LibDB/ , which is an FRBR compliant library for cataloging books and media. Not to be confused with "libdb", which IIRC is the C library for accessing the "Berkeley Database", I've been meaning to point out the name collision to the author). And if I do have to manually translate his code, is there such a thing as a "Perl to Python" HOWTO or something along those lines to help me do it? Thanks for comments, (and BTW, nice to be back, I tried using Usenet for awhile, but I don't seem to have a news server anymore after switching ISPs, *sigh*). Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From iketo2 at netscape.net Mon Nov 1 20:44:26 2004 From: iketo2 at netscape.net (Isaac To) Date: 02 Nov 2004 09:44:26 +0800 Subject: Why is heapify linear? References: <4186cb77$1@nntp0.pdx.net> Message-ID: <87hdo9t479.fsf@sinken.local.csis.hku.hk> >>>>> "Scott" == Scott David Daniels writes: Scott> I am sorry, but in the Python 2.4 description of "heapify", Scott> I find the description of "Transform list x into a heap, Scott> in-place, in linear time," unbelievable. I understand the Scott> hand-wave that makes dictionary building linear (though I Scott> have a hard time with even that). Could somebody tell me Scott> what twist of logic makes "heapify" linear, except in the Scott> sense that linear is coming to mean "very fast?" I'll try to illustrate the idea without any complex maths, but instead with real ugly ascii art. The basic building block of "heapify" is a simple procedure which I'd call "heapify_node". It looks at a node that is not a leaf, and among that non-leaf node and its two children, which is largest. Then it swap that largest node to the top, so that the node becomes the largest among the three---satisfy the "heap property". Clearly, constant time. To heapify the whole tree, we will heapify it from the bottom (so "bottom up"). Heapifying a node at the "bottom" (i.e., next to a leaf) is trivial; heapifying a node that is not bottom might cause the heap property of nodes below to be violated. In that case we will have to heapify the node below as well, which might cause a node one more level below to violate heap property. So to heapify a node at level n, we might need to call heapify_node (height-1) times. Now we show that a whole run of heapify of a tree with n=2^k-1 nodes will never call heapify_node more than n times. We do it by finding a way to charge the calls to heapify_node so that each node is never charged more than once. Note that we simplify things by always considering full binary trees (otherwise, the claim has to be a bit more complicated). Let's consider the bottom layer. To heapify a node with two children, we need one call to heapify_node. It is charged to left leaf. So we have this: After heapify O / \ X O where O shows a node that is not charged yet, and X show a node which is already charged. Once all the next-to-bottom nodes have been heapified, we start to heapify the next-to-next-to-bottom nodes. Before heapifying a node there, we have Before heapify O _/ \_ O O / \ / \ X O X O To heapify this node, we might need two calls to heapify_node. We charge these two calls to the two uncharged nodes of the left subtree. So we get: After heapify O _/ \_ X O / \ / \ X X X O So none of the nodes is charged more than once, and we still have some left for the next level, where before heapify the picture is: Before heapify O ____/ \____ O O _/ \_ _/ \_ X O X O / \ / \ / \ / \ X X X O X X X O Heapifying at this level requires at most 3 calls to heapify_node, which are charged again to the left branch. So after that we get After heapify O ____/ \____ X O _/ \_ _/ \_ X X X O / \ / \ / \ / \ X X X X X X X O We note a pattern: the path towards the right-most leaf is never charged. When heapifying a level, one of the branches will always have enough uncharged nodes to pay for the "expensive" heapify at the top, while the other branch will still be uncharged to keep the pattern. So this pattern is maintained until the end of the heapify procedure, making the number of steps to be at most n-k = 2^k - k - 1. This is definitely linear to n. Regards, Isaac. From valinor at linuxmail.org Tue Nov 2 07:01:52 2004 From: valinor at linuxmail.org (foten) Date: 2 Nov 2004 04:01:52 -0800 Subject: Array of textboxes in Tkinter Message-ID: Hi guys, I thinking of creating a Tkinter gui for a script I'm using to do bit manipulation. The idea is for the user, using the mouse to toggle (0 or 1) the 32 bits seen below in my ascii representation of the gui. I need advice on how to create the 32-bitarray (i.e. four separate ones), what widget to use? Can someone shed some light on this or perhaps point me to an example? 57005 ---------- ___0 00000000 ___0 ___0 00000000 _222 11011110 _57005 _173 10101101 Hex: DEAD Octal: 157255 //Fredrik From valkyrie at cuhk.edu.hk Fri Nov 19 09:50:17 2004 From: valkyrie at cuhk.edu.hk (Valkyrie) Date: Fri, 19 Nov 2004 22:50:17 +0800 Subject: Question about thread In-Reply-To: <1100875373.911763@eng-ser6> References: <1100875373.911763@eng-ser6> Message-ID: <1100875819.430462@eng-ser6> To be more precise, what I want to do is to have a threaded program to handle some jobs concurrently (while those jobs are fetching information from the Internet, so threading could speed up the process if the network is slow) start | (blahblahblah...) v +-----+-----+-----+-----+ | | | | | --+-- --+-- --+-- --+-- --+-- | | | | | | | | | | | A | | B | | C | | D | | E | | | | | | | | | | | --+-- --+-- --+-- --+-- --+-- | | | | | +-----+-----+-----+-----+ | (blahblahblah...) v finish! While process A-E will access the shared variables within the same program, and each of those processes will have to parse a document on its own. Valkyrie wrote: > Refering to the following codes I found, there is nothing displayed in the > console, may I ask why? > > def thrd(param): # the thread worker function > print "Received",param > > import thread > for i in range(5): # start five threads passing i to each one > thread.start_new_thread(thrd,(i,)) > > Thanks in advance From deetsNOSPAM at web.de Tue Nov 9 18:35:48 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 10 Nov 2004 00:35:48 +0100 Subject: unicode string literals and "u" prefix References: <418fed14$0$156$9b622d9e@news.freenet.de> Message-ID: Hi, > Working for an insurance company, most of our data contain french > accented characters. > So, we are condemned to work essentially with unicode strings. > In fact, it is hard to find examples where plain ascii strings would > be useful in our case. > Even data we retrieve from databases are returned to us as unicode > strings. This statement looks as if you confuse utf-8 and unicode. They are not the same. The former is an encoding of the latter. > A way of defaulting all string literal as unicode would have been a > relief. I can understand that wish, but it certainly would break too much existing 3rd-party-code. But I wonder if a tool as pychecker could be enhanced to issue warnings on python code if string literals are not prefixed by an u. -- Regards, Diez B. Roggisch From insert at spam.here Wed Nov 17 11:10:00 2004 From: insert at spam.here (Doug Holton) Date: Wed, 17 Nov 2004 10:10:00 -0600 Subject: Zope 3.0, and why I won't use it In-Reply-To: <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Jim Fulton wrote: > > >>> Guido has repeatedly stated that a future version of Python will > > include static type support. The Zope project has driven numerous past > changes to Python. What's funny about this? > >>For the record, I'm against static typing for Python, although, >>if Guido decides he wants it, I have an open mind. :) > > > Glad to hear that. As for me, I'd love it if function arguments, only, > could bear an 'as' clause (making 'as' a keyword is long overdue): > > def x(y as foo, z as bar): > I know many people here already know about this, but you can use this syntax in boo: def foo(y as int, z as bool) as bool: You can also use attributes (similar to decorators): def foo([required(value > 3)] value as int): pass http://boo.codehaus.org/ If anyone here familiar with Zope, mod_python, etc. ever tries out boo and ASP.NET (or Mono's XSP/mod_mono), I'd appreciate you sharing any notes about it on the boo mailing list to help others getting started. From f.geiger at vol.at Tue Nov 9 13:53:07 2004 From: f.geiger at vol.at (F. GEIGER) Date: Tue, 9 Nov 2004 19:53:07 +0100 Subject: Umlauts, encodings, sitecustomize.py References: <4190ED09.3010503@skynet.be> Message-ID: "Helmut Jarausch" schrieb im Newsbeitrag news:4190ED09.3010503 at skynet.be... > Try the line > # _*_ coding: latin1 _*_ > > at the very beginning (or at least after a #! line on Unix) > This works under Linux, at least. > Thank you, Helmut, I had already added # -*- coding: iso-8859-1 -*- to the scripts in question. Kind regards Franz GEIGER From jzgoda at gazeta.usun.pl Sun Nov 21 12:00:17 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 21 Nov 2004 18:00:17 +0100 Subject: Gnome version of Idle? In-Reply-To: <1101051295.435416.307320@c13g2000cwb.googlegroups.com> References: <992f396f.0411202018.1edbc6d0@posting.google.com> <1101051295.435416.307320@c13g2000cwb.googlegroups.com> Message-ID: Sridhar R wrote: > If you ask me, aliased fonts are better for coding. I second this statement. Recently I had to install Slackware 10.0 on my new box. By default, Qt and GTK2 (so KDE, GNOME and XFce in consequence) use Xft/freetype2 antialiased fonts -- all my editors was broken, even Vim was compiled with GTK2. Unfortunately, simple switching antialiasing for sizes smaller than 16pt resulted in ugly looking fonts, no less. Of course, freetype was compiled without TrueType hinting, as one may expect from software coming from US of A, where "truetype bytecode interpreting" is patented. Fortunately for me, this was matter of uncommenting one DEFINE and recompilation of freetype2. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From glenfant-nospam at bigfoot.com Mon Nov 1 16:37:46 2004 From: glenfant-nospam at bigfoot.com (Gilles Lenfant) Date: Mon, 1 Nov 2004 22:37:46 +0100 Subject: question de bonne doc References: <418505b9$0$3662$8fcfb975@news.wanadoo.fr> <1gmkhbc.yxlo8f10l5uq5N%aleaxit@yahoo.com> <4186179a$0$31207$8fcfb975@news.wanadoo.fr> <1gmkp2e.o08a66kodcjxN%aleaxit@yahoo.com> Message-ID: <4186b186$0$3612$8fcfb975@news.wanadoo.fr> "Alex Martelli" a ?crit dans le message de news: 1gmkp2e.o08a66kodcjxN%aleaxit at yahoo.com... > orionlux wrote: > [...] > > Essayez alors http://fr.diveintopython.org/index.html, "Plongez au coeur > de Python", peut-?tre vous le trouverez satisfaisant. Bonjour, diveintopython.org n'est pas pour les newbies. Et encore moins "Thinking in Python" de Bruce Eckel comme je l'ai lu dans un autre post. -- Gilles > > > Alex From rkern at ucsd.edu Wed Nov 10 23:08:30 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 10 Nov 2004 20:08:30 -0800 Subject: distutils and Debian In-Reply-To: References: <4192AD69.5040707@sympatico.ca> Message-ID: Istvan Albert wrote: > Robert Kern wrote: > >> only depend on the main python package. Most packages that need Python >> *don't* need distutils or the C headers or the static library. > > > The *devel* branch in my interpretation means the distribution > that contains the files used during the development of the > application itself. For example the C headers > that you mention. But in Debian's consistent interpretation, it means "for development *with* the library/interpreter/whatever." If I want to compile a C program, I need to install libc6-dev. If I want to *develop* glibc, I get the source. Similar strategies are employed by other free Unices' package systems. > But it should not mean removing support > for installing new scripts for the runtime > application! If I want to compile a non-Debian program that uses libpng, I install libpng-dev. If I want to install a non-Debian Python package, I install python-dev. > Distutils is primarily about installing and distributing > python programs and it has little to do with developing > python itself. And as I said, your interpretation has nothing to do with the way Debian and other Linux/BSD/what-have-you distributions use the suffix in their package names. > Some packages will not > be installable without the devel branch but removing > distutils to head off that situation seems very odd. > > Istvan. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From someone at microsoft.com Wed Nov 24 15:28:12 2004 From: someone at microsoft.com (Jive) Date: Wed, 24 Nov 2004 20:28:12 GMT Subject: Python's annoyance. References: Message-ID: Your message showed up just as I finished typing my own screen. Yours is better, but having put all that wear and tear on my fingerprints, I'm going to post mine anyway. So there. "Steven Bethard" wrote in message news:<_V4pd.386875$wV.330416 at attbi_s54>... > > While I'm not a fan of the decorator syntax or the $syntax in > string.Template, you're not forced to use either of these: > I don't know anything about the specific features you are discussing, but in general, "You aren't forced to use it," is not a sound argument for difficult features, or feature creep in general. Why? Because frequently you ARE forced to use it! Firstly, a novice does not know which bits he would best skip over. While not literally forced to use a feature, he does not know he probably should not. If there are pitfalls, he is at the mercy of whatever learning material he is using to keep him from stepping in them. Better not to dig the pits in the first place. Secondly, in the the real world, one seldom has the luxury of writing code from scratch. If I need to repair, augment, or integrate with existing code, I am indeed FORCED to deal with whatever difficulties and obscurities it may present. One of Python's big selling points is its clarity and ease of use. Okay, that's two selling points. I am not arguing against improving functionality. I do believe that in the future the Python wranglers would do well to be more circumspect when adding features. Generators are pretty cool, but weren't there more general constructs that might have been added instead? And why is the syntax so utterly inscrutible? Something that looks like a function should act like a function, and vice versa. Why do I have to read the body of the, uh, thing, in order to determine that it even *is* a generator rather than a function? Someone who does not know that generators even exist, and specifically does not know about the magic properties of the world "yield", would be thoroughly and hopelessly confused. He would be hard pressed to figure it out from the source code. From steve at holdenweb.com Thu Nov 18 10:14:40 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Nov 2004 10:14:40 -0500 Subject: SQL Server stored prcedures with output parameters In-Reply-To: References: Message-ID: <419CBC60.60405@holdenweb.com> Tim Golden wrote: > Well, this is not much more than "me, too" kind of > information, but just in case... > > The Object Craft MSSQL module which I use every day > for SQL stuff doesn't have a working callproc method, > something which has never bothered me before, but which > would have been useful now. > Yes. A lot of DB API modules have just punted on callproc, which is damned annoying when you need it :-( I haven't used the MSSQL module, but adodbapi seems like the most complete interface. > The pymssql module -- which seems a bit underdeveloped -- > doesn't have a callproc at all. > I have tried that briefly, but saw no compelling reason to adopt it. > What I do to get things out of a stored proc is to > select out at the end and let Python pick it up as > a result set. Just in case you're unfamiliar with the > technique (and apologies if I'm teaching my granny...): > > > CREATE PROCEDURE test @i INT AS > SELECT @i > GO > > > > # Uses Object Craft module, but should work > # with other interface modules. > import MSSQL > db = MSSQL.connect ("VODEV1", "", "", "EVODEV") > q = db.cursor () > q.execute ("EXECUTE test 1") > print q.fetchone () > > > Not much help, I know, but I'm afraid I have about 3 hours less > experience in ADO than you. > No apologies necessary. Unfortunately these are somebody else's stored procedures, and the suggestion that they change them to accommodate the weaknesses of the Python interface wouldn't be well received. These procedures have output parameters, and that's where I'll have to get the results from. I'm probably going to have to work around it for now by duplicating the SQL, but that has bad maintenance problems long term. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From rparnes at megalink.net Mon Nov 29 09:18:45 2004 From: rparnes at megalink.net (Bob Parnes) Date: Mon, 29 Nov 2004 14:18:45 -0000 Subject: PyQt on a Server Message-ID: I have an application importing qt on a linux server and am missing something in trying to run it from a workstation via nfs. The workstation has the server /usr directory mounted to its own /usr directory, so it can access the necessary files. The error I get is Traceback (most recent call last): File "/demo/revenues.py", line 24, in ? from qt import * File "/usr/lib/python2.3/site-packages/qt.py", line 24, in ? import libsip ImportError: libXrender.so.1: cannot open shared object file: No such file or directory I can see the file in /usr/X11R6/lib. So maybe there is a path variable that qt.py uses and that has to be set on the workstation. If so, I don't know how to find it. Thanks for any help. Bob -- Bob Parnes rparnes at megalink.net From imbosol at aerojockey.com Mon Nov 8 14:28:25 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 8 Nov 2004 11:28:25 -0800 Subject: remove assert statement (Was: Re: PEP new assert idiom) References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> <7xy8hep325.fsf@ruckus.brouhaha.com> Message-ID: <60dfb6f6.0411081128.78cff0b1@posting.google.com> Gerrit wrote in message news:... > Paul Rubin wrote: > > "Raymond Hettinger" writes: > > > Why do you need a statement for this? > > > IMO, a plain function will do the trick: > > > > I do write such functions sometimes, but using a statement is more > > natural. That's why the assert statement exists, for example. > > I think 'assert' being a statement is on Guido's regrets list. exec and > print are on his regrets list: both should have been a function. I > think the same holds for assert, although I'm not sure. I don't recall seeing assert on that list. Unlike print and exec, what assert does can't be done by a function. > > statement is very great, and I find myself doing it all the time > > thinking I'll clean it up later. So I think having a statement for > > runtime checking would be in the correct spirit. > > In my opinion, assert is almost useless. It can sometimes be useful for > debugging purposes, but beyond that, it isn't. The exception raised by > 'assert' is always AssertionError. That is a major disadvantage, because > it's not specific. Actually it is, if you use assert correctly. I'll get to that. > If a method I'm calling would raise an AssertionError > is some cases, and I want to catch it, I'm catching too much. Creating a > new exception-class and raising that one is better because of this. If you use assert correctly, you either wouldn't want to catch AssertionError, or you'd want to catch it at a rather high level and print a message about a bug in the program. > I don't see the use of a statement like > "assert isinstance(message, basestring)". [snip] Generally speaking, this is an incorrect use of assert. I don't approve of this use of assert. The proper use of assert is to declare that a certain condition is impossible. That is, if the program is bug-free, this condition will never happen. An assertion error should never be raised unless there's a bug in the program. Here's a ridiculous, and incorrect, but illustrative, example of its proper use: def f(y): x = y*y assert x >= 0 As we know, multiplying a real number by itself always produces a positive number (for the sake of argument, let's ignore the fact that y could be a complex number). Thus, is it impossible for x to be negative. Impossible, that is, unless there's a bug. The assert statement declares this to be an impossible condition. If this condition does not hold, it can't be bad input. It's a bug. Obviously, this is a silly example, but real world examples aren't so silly. Because it's an "impossible" condition, it only needs to be checked in debugging builds. This is where the magic of the assert statement comes in: in an optimized build, the assertion is not checked. Thus it's an optimiztion. If you change assert into a function, Python can no longer optimize the assertion away, because the function argument is always evaluated. This however, raises a question: is it a premature optimization? I would say yes and no. For simple assertion, like assert x >= 0, the optimization is premature and probably not worth justifying an assert statement. However, I still like having it, just to document that the condition being checked is intended to be an impossible condition, as opposed to bad input or an operating system error. However, there are some impossible conditions that are simply not premature optimizations by anyone's definition. Let me show you an example: def some_public_function(tree1, tree2): assert one-to-one(tree1,tree2) ... In this case, I have two tree heirarchies which the program is to keep 1:1 at all time (i.e., for every node in tree1, there is a corresponding node in tree2). There are hundreds of functions operating on both trees, and all of them have to make sure to update both hierarchies. If there is any exit point of a public function where these trees are not one-to-one, then it's a bug. The problem is, checking the whole hierarchy every time you call a public function is simply too expensive for production code. An assert statement lets you optimize this call away, and very conveniently. I feel that power justifies the existence of assert. Assert statements have found many, many bugs in my larger projects, so I would be very sad to see them go away. HOWEVER, in the end, I could easily live without it. Simple assertions don't cost much to check in production code. Expensive assertions I usually put in a function anyways, so I can optimize it away by simply not calling it unless a debug flag is set. > In my opinion, assert should be deprecated and then removed in Py3K: > assertions are redundant, unspecific, and conflict with the philosophy > of duck typing and EAFP. > > What do others think of this? I don't want to see it disappear because it has valid uses. I think it would be wise to discourage the use of assert for purposes it wasn't intended for, such as the example you gave. IMO, the best way to do this is to have assertion OFF by default. The way Python is set up now is to have a default mode and optimized mode, the optimized mode not running asserts. I would change that. I suggest that Python should instead have a default mode and a debugging mode, and that assertions should only be checked in debugging mode. Ordinary Python runs, without a -g flag, would simply ignore assert statements. -- CARL BANKS From steven.bethard at gmail.com Tue Nov 2 12:35:28 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 17:35:28 +0000 (UTC) Subject: strong/weak typing and pointers References: <96F3EC4BDF504540BB9715CBE9DACB8B0FA6012C@pa-mail1.legato.com> Message-ID: Michael Pyle emc.com> writes: > Perhaps he is refering to the ability to change the class of an instance at > runtime. If you can't do that in Smalltalk (all other things being equal), I'd > say that would indicate weaker typing. This seems to confuse strong/weak typing with static/dynamic typing. If we think about an object as an allocated block of memory, changing the class of an Python object does not change how that block of memory is interpreted[1]. It changes the value of one field of that object, namely the field that determines where to look for the class object[2]. The memory block is still interpreted in the same way, it just happens that some of the fields in that block may have changed. The point here is that changing the class of an object does not change how the block of memory representing that object is interpreted; it only changes how the class (and class methods) are looked up for that object. Steve [1] To be clear on what I mean by "how that block of memory is interpreted", you may want to refer to my example of weak-typing in C: http://mail.python.org/pipermail/python-list/2004-November/248983.html [2] This may actually be changing several fields in the object's memory block (I don't know Python's implementation well enough) but the idea is still the same. From walter at livinglogic.de Thu Nov 25 10:07:06 2004 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Thu, 25 Nov 2004 16:07:06 +0100 Subject: import can't find xml.sax.saxlib from PyXML In-Reply-To: References: Message-ID: <41A5F51A.5000807@livinglogic.de> Stefan Behnel wrote: > Hi! > > I'm using PyXML 0.8.3 on a number of machines. When I now run > > import xml.sax.saxlib > > python touches both the python/xml/sax and python/site-packages/_xmlplus > modules but not _xmlplus/sax (I see that from strace), and then only > searches for saxlib in python/xml/sax, i.e. in stdlib. I therefore get > an ImportError though saxlib exists in _xmlplus/sax. > > I know that it worked before, but I can't tell what changed on the > systems during new installations of new python versions. I tried it with > 2.3 (which worked before but somewhat surprisingly doesn't work any > more) and 2.4 (where I never managed to make this work). > > Does anyone have a hint what I could try? xml/__init__.py from python 2.4 contains: _MINIMUM_XMLPLUS_VERSION = (0, 8, 4) so currently Python 2.4 will always fall back to the builtin xml module. A quick fix would be to change this back to: _MINIMUM_XMLPLUS_VERSION = (0, 8, 3) (Or hope that a PyXML 0.8.4 will be released before Python 2.4 final) Bye, Walter D?rwald From wgshi at namao.cs.ualberta.ca Thu Nov 25 17:30:38 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Thu, 25 Nov 2004 22:30:38 +0000 (UTC) Subject: dictionary initialization References: Message-ID: I see. Thanks Weiguang From deetsNOSPAM at web.de Thu Nov 18 10:09:07 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 18 Nov 2004 16:09:07 +0100 Subject: SPARK v.s. PLY References: Message-ID: > If you know the parsing stuff well, could you briefly tell me the > pros. and cons. of those packages? (or some others you find good too) I use spark and am very satisfied. Its usage is quite natural, and the power of the earley parsing method ensures the grammars can be easy to write and understand (close to bnf), as you don't have to care about left-factoring and the like. In badly designed grammars, it can get quadratic (or even worse I think, but I'm to lazy now to think about that thorougly..) in runtime - but I never expirienced any real trouble with that. The algorithms that afterwards run on the AST are usually complex themselves, shadowing the parsing complexity. And as I said - only ambigue grammars produce that overhead at all. I can't say anything about other parsers though - didn't use them. At least not in python. -- Regards, Diez B. Roggisch From fredrik at pythonware.com Mon Nov 22 05:09:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Nov 2004 11:09:49 +0100 Subject: PIL for Python 2.4? References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com><419d002e$1@nntp0.pdx.net> Message-ID: David Fraser wrote: > I tried building PIL with mingw recently and had some failures I can't remember ... if you don't report your build problems, they will never get fixed (the image-sig is the right forum for this, and the best place to get answers to PIL-related questions). > It *did* make me think "I wish there was some Pure Python image-handling code". It seems like the > C linkage is mainly required for image formatting handling - I couldn't find any JPEG > reading/writing code in Pure Python ... would be nice :-) and incredibly slow. PIL uses C for a reason. From richardblackwood at cloudthunder.com Sun Nov 7 14:12:56 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 07 Nov 2004 14:12:56 -0500 Subject: Python OS In-Reply-To: References: Message-ID: <418E73B8.6030002@cloudthunder.com> Diez B. Roggisch wrote: >>Do you mean that there are no entirely C OSs? >> >> > > >Now one can argue if that is still C, as it's written in a cpp-file thats >run through a compiler - but if that really counts as C, then of course you >can write anything in python (or VB or whatever languague you choose) by >simply writing out hexdigits to a file.... > > Looks like a Hybrid. > > >>Understood, however, note the terms prototype and virtual. Perhaps I >>could create virtual hardware where needed, and play around with the >>timing issues in this manner (emulate them and create solutions >>prototyped in Python). >> >> > >In you first post, you didn't mention virtual - only prototype. And >prototyping an OS for whatever hardware can't be done in pure python. Thats >all that was said. > >Writing a virtual machine for emulation can be done in python of course. But >then you can't write a OS for it in python as well (at least not in >CPython )- as your virtual machine must have some sort of byte-code, memory >model and so on. But the routines you write for the OS now must work >against that machine model, _not_ operate in CPython's execution model >(which is based on an existing os running on real hardware) > > > All of that can be virtually emulated (virtual memory and so forth). >But creating a VM only leverages that work to the next level, retaining the >initial problems. If you don't do it that way, you don't prototype anything >like an OS nor implement a machine model but instead meddle some things >together by creating a machine model that is so powerful (e.g. has an >built-in notion for lists, dicts and the like) that it can't be taken >seriously as educational for writing an OS - at least to me, as the virtue >of writing an OS is to actually _deal_ with low-level matters, otherwise >there is no challenge in it. > > *laugh* Now that is hilarious. >I don't say that this is not a worthy project to undertake for educational >purposes - but I wouldn't call it an OS, as it does not teach what creating >an OS from scratch is supposed to teach. > > Understood. >For example you can't write a OS for the JAVA VM, as there is no such things >like interrupts defined for it - instead IO happends "magically" and is >dealt with on the low level with the underlying OS. The VM only consumes >the results. > > > This has been done as well, there are Java operating systems were IO is handled by Java and not magic, or so I understand. From sw at wordtech-software.com Tue Nov 9 16:52:18 2004 From: sw at wordtech-software.com (Kevin Walzer) Date: Tue, 09 Nov 2004 16:52:18 -0500 Subject: Help on installing PyQt on MacOSX 10.3 needed In-Reply-To: <2vcc6oF2i91ltU1@uni-berlin.de> References: <2vcc6oF2i91ltU1@uni-berlin.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Svenn Are Bjerkem wrote: | | you are perfectly right. I went back to the documentation and paid a bit | more attention and with your information in mind, I now see that it is | talking about a selfcontained python with pyqt. I guess that I want to | use the qt bindings *dynamically*. That means that I have to find a way | to tell Python where to find the pyqt that I installed. | | In tcl I would either have installed into a directory in auto_path or I | would have extended auto_path. How is this done in Python? | PyQt is installed in the site-packages directory on OS X--there's nothing special you need to do, it "just works" and loads up fine. - -- Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBkTwRJmdQs+6YVcoRAj0rAJ9bRjtLXWTYZV5jFeyVBESisqbasgCdFwwa lW+8v04/KiAWzKM6glr3PVE= =ZpPs -----END PGP SIGNATURE----- From rtilley at vt.edu Thu Nov 4 18:49:04 2004 From: rtilley at vt.edu (Brad Tilley) Date: Thu, 04 Nov 2004 18:49:04 -0500 Subject: win 2003 server Message-ID: Does Python run on Windows Server 2003? http://www.python.org/download/download_windows.html only lists the following: Python for Windows 95, 98, NT, 2000, ME, XP From drew at gremlinhosting.com Thu Nov 18 17:43:17 2004 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 18 Nov 2004 22:43:17 +0000 Subject: TPG error when using 't' as the first letter of a token In-Reply-To: References: Message-ID: <1100817797.30315.20.camel@odin> Paul, Thanks for your detailed response. I've read through the PyParsing site and I'm considering using it for further development of my project - wish I'd found it before! I noted your comments about my last test case; the syntax of the language I'm implementing is closely related to XPath and the [] at the end of the query are intended to contain metadata criteria. I have since revised my parsing rules (see below) and they now parse both the original test queries and arbitrarily complex boolean expressions. I'm just about to post a new message with a description of what the language is aimed at doing and asking for any improvements - I would value your opinion if you have the time. # Tokens separator space '\s+'; token Num '\d+(.\d+)?'; token Ident '[a-zA-Z]\w*'; token CharList '\'.*\''; token CatUnOp '~'; token CatOp '[/\^]'; token MetaOp '[=\+\-!]'; token Date '\d\d-\d\d-\d\d\d\d'; token FileID '(\w+\.\w+)'; token EmptyLine '^$'; # Rules START -> CatExpr ('\[' MetaExpr '\]')? | FileID | EmptyLine ; CatExpr -> CatUnOp CatName | CatName (CatOp CatExpr)* ; CatName -> Ident | '\(' CatExpr '\)' ; MetaExpr -> MetaCrit (',' MetaCrit)* ; MetaCrit -> Ident MetaOp Value ; Value -> CharList | Num | Date ; parseTests = ( "simple", "this/is/a/simple/test", "a/test/with/metadata[author='drew',date=10]", "music/mp3/~jackson/michael", "docs/latex/~(computer^science)", "media/video/((comedy/action)^thriller)" ) Regards, Andrew From peter at engcorp.com Tue Nov 30 10:37:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Nov 2004 10:37:17 -0500 Subject: Struggling with struct.unpack() and "p" format specifier In-Reply-To: <6b26402d.0411300657.d575d75@posting.google.com> References: <6b26402d.0411300657.d575d75@posting.google.com> Message-ID: Geoffrey wrote: > I am trying to read data from a file binary file and then unpack the > data into python variables. Some of the data is store like this; ... > As I read the documentation the "p" format string seems to address > this situation, where the number bytes of the string to read is the > first byte of the stored value but I keep getting this error. > > Am I missing something ? > Can the "p" format character be used to unpack this type of data ? I've tried experimenting with "p" and cannot get any meaningful results. In all cases pack() returns '\x00' while unpack() with anything other than a one-byte string returns an exception (unpack str size does not match format) while with a one-byte string it always returns ('',). I would be inclined to say that the "p" format in struct (using Python 2.4rc1 or Python 2.3.3) does not act as documented on Windows XP SP2, at least... I hope we've both just missed something obvious. -Peter From deetsNOSPAM at web.de Mon Nov 22 11:10:51 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 22 Nov 2004 17:10:51 +0100 Subject: pyKDE tutorial References: Message-ID: Search for boudewijn rempts book on pyqt. And there are other resources online. Generally speaking, you can use whatever C++ tutorial you find, as the bindings usually are so close that you can tranlate examples line-by-line. -- Regards, Diez B. Roggisch From fumanchu at amor.org Thu Nov 11 12:54:15 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 11 Nov 2004 09:54:15 -0800 Subject: pickle: huge memory consumption *during* pickling Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32451BD@exchange.hqamor.amorhq.net> Hans Georg Krauthaeuser wrote: > I have a long running application (electromagnetic compatibility > measurements in mode-stirred chambers over GPIB) that use pickle > (cPickle) to autosave a class instance with all the measured > data from > time to time. > > At the beginning, pickling is quite fast but when the data > becomes more > and more pickling slows down rapidly. > > Today morning we reached the situation that it took 6 hours to pickle > the class instance. The pickle file was than approx. 92 MB > (this is ok). > During pickling the memory consuption of the python proccess > was up to > 450 MB (512 MB RAM -> machine was swapping all the time). > > My class use data types taken from a c++ class via swig. > Don't know if > that is important... > > My feeling is that I'm doing something wrong. But my python > knowlegde is > not so deep to see what that is. > > Is there an other way to perform an autosave of an class > instance? Shelve? Shelve just uses pickle: try: from cPickle import Pickler, Unpickler except ImportError: from pickle import Pickler, Unpickler ...but it might help if the bottleneck is in your file-handling. Robert Brewer MIS Amor Ministries fumanchu at amor.org From bogus@does.not.exist.com Thu Nov 4 23:02:46 2004 From: bogus@does.not.exist.com (Mark) Date: Thu, 04 Nov 2004 23:02:46 -0500 Subject: py2exe 0.5.4 released References: Message-ID: <4pulo0tjm2se1p10apth81sn4p6a9mh6g8@4ax.com> On Fri, 22 Oct 2004 21:06:18 +0200, Thomas Heller wrote: >**py2exe 0.5.4** released >=================================== >*SNIP* >Download from the usual location: > > > Am I the only one having problems downloading this latest release??? -- Best regards, Mark From lynn at crazedimaginations.net Sat Nov 20 00:15:54 2004 From: lynn at crazedimaginations.net (Lynn) Date: Fri, 19 Nov 2004 21:15:54 -0800 Subject: stopping the sound server in PySol code -- how? Message-ID: I have a SuSe 9.1 linux box (although this isn't a new issue) with reasonably up to date everything. When I run PySol, it grabs the sound system in a rude and complete way. I don't listen to sound and I NEED my sound system available even if PySol is running. Does anyone have a simple way of ripping the sound functionality our of PySol? I've not enough of a python programmer to deal with this. Everything I've tried has just generated a ton of errors. -- Peace, Love and Absolute Pleasure Crazed Imaginations RHPS cast www.crazedimaginations.net From steven.bethard at gmail.com Tue Nov 2 17:18:34 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 22:18:34 +0000 (UTC) Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> Message-ID: Christophe Cavalaria free.fr> writes: > > One could say that the common definition of weakly typed languages cannont > apply for a dynamicaly type language. Let's face it, once you've > implemented a dynamicaly typed language, it seems very hard to use one > piece of data as the wrong type. While I agree that it would be kind of foolish to implement a dynamically typed language that wasn't strongly-typed (PL theory definition), there's no reason you *couldn't* -- your language would just need to provide some sort of 'cast' function that did the conversion at runtime. For example, say the memory block for an object instance was allocated like: [0] pointer to class object [1] pointer to dictionary object (holding variables) Then maybe you could do something like: int1, int2 = cast(object(), list(int)) Given, I can't see any use for such behavior, but you *could* do it if you had a weakly-typed dynamic language and you knew how it allocated objects. At some level, you always have bits -- whether it makes any sense to reinterpret them depends on exactly what the bits originally meant. > What we can do is extend the definition of weakly typed language to something > like : "A weakly typed language is a language that often uses incorectly some > piece of data by applying to it the wrong type" Such definition would include > any language that is too liberal with the type coertion like php. Don't get me wrong -- I do understand your point. In every case I can think of, there is no reason to want weak-typing (PL theory definition) in a dynamically-typed language. On the other hand, I haven't really seen any good cases for wanting weak-typing in a statically-typed language either. Note that PHP doesn't fit your definition above anyway. When PHP allows: "a" + 10 == 10 it's not incorrectly using "some piece of data by applying to it the wrong type". It's doing exactly what it tells you it'll do. This is *correct* response given the PHP language definition. In addition, you *can* create a statically-typed language that is strongly typed (PL theory definition) but also very liberal with type coercion. What would you call such a language? Since being liberal with type coercion and allowing bit reinterpretation are orthogonal, why not keep the two separate terms? My issue here is that I don't think we should confuse an already easily confused term by giving it a second meaning. If there aren't any dynamically typed languages that are also weakly-typed, that's ok -- it doesn't mean we should change the meaning of "weakly-typed" for these languages. Steve From follower at gmail.com Fri Nov 12 17:22:24 2004 From: follower at gmail.com (Follower) Date: 12 Nov 2004 14:22:24 -0800 Subject: Iterating over PDF documents References: Message-ID: <3c18c08f.0411121422.6e405b04@posting.google.com> Would this Python/PDF handling library be useful to you: I don't think it specifically handles re-writing, but it might be a useful starting point. --Phil. From nun at example.com Mon Nov 15 17:02:56 2004 From: nun at example.com (Mitja) Date: Mon, 15 Nov 2004 23:02:56 +0100 Subject: Set like feature References: <1100552512.672456.317420@c13g2000cwb.googlegroups.com> Message-ID: On 15 Nov 2004 13:01:52 -0800, Hari Pulapaka wrote: > Hi, > > I have a list of space delimited strings ending in a newline. > Eg: a = ['a sfds sdf s df 34 ew\n', 'df sdf s f s ssf\n'] > > Now inside each row, I have a space delimited list of fields. > > Now I want to compare the fields in each row of the array and see which > fields do not match. > > Think of it as a 2 dimensional array of size mn, and comparing each > each element on a column by column basis. > > I am using python2.2 so no sets. Can anyone think of an efficient way > to do this? If I understand the problem correctly, splitting the lines up and sorting them before comparison _is_ much better than a naive approach, though I don't know if that's what's best. -- Mitja From aleaxit at yahoo.com Sat Nov 6 17:35:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 Nov 2004 23:35:05 +0100 Subject: PEP new assert idiom References: Message-ID: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> F?bio Mendes wrote: ... > This elegant syntax is NOT equivalent to python's not so ellegant: > > >>> erromsg = 'Errormsg' > >>> assert statement 1, errormsg > >>> assert statement 2, 'errormsg > >>> (...) > >>> assert statement n, errormsg Why isn't this equivalent? Apart from the fact that you keep, here and elsewhere, using 'statement' where you hopefully mean 'expression' -- you cannot assert a statement, you can only assert an expression. > In Ruby, the Assertion error is raised if executing statement 1, then 2, > then 3... etc raises an error. This is a subtle thingm the error COULD > NOT be raised if each statement is executed alone, as each statement may > have side effects which make the order of execution relevant. To Can you give one Python example where the sequence of asserts would behave differently from what you propose? I cannot see any. > suceccefully emulate this behaviour, the python programmer have to > resort to a even more cumbersome solution: > > >>> foo = lambda : (statement 1) and (statement 2) ... (statement n) > >>> assert foo, 'Errormsg' I assume you mean to call foo, because if you don't, it will surely be true and the assert will just never trigger. Now, calling expressions expressions, rather than very confusingly statements, can you explain how the semantics of this, with foo being called, would differ from those of assert exp1 and exp2 and exp3 ... and expN, 'errormsg' ??? > My proposal is to add the following syntax to the language: > > >>> assert (statement 1), (statement 2), ... (statement n), 'Errormsg' Again: can you explain how the semantics of this, would differ from those of: assert exp1 and exp2 and exp3 ... and expN, 'errormsg' ??? > Or, if the user prefers, the traditional comma rules also applies: There is no such "traditional" rule (or rules) in Python. Both a statement and an expression can perfectly well end in a comma; the comma does NOT imply any kind of continuation. Alex From franck.lepoutre at caramail.com Fri Nov 19 06:50:02 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Fri, 19 Nov 2004 12:50:02 +0100 Subject: persistent CGI pattern at google.com (was why python?) References: <1gndypu.1e28rl1cgo8nsN%aleaxit@yahoo.com> Message-ID: <419ddb81$0$27395$79c14f64@nan-newsreader-06.noos.net> Hi all, > Google itself is a python success story - for example this here: > https://adwords.google.com/support/bin/topic.py?topic=102 Sure, it looks like google.com is using some kind of cgi process to run python code. Kind of good news for those selling python-based stuff. I expect google use some sort of persistency layer (mod_python, fastcgi ...) to run their python cgi code effectively. Anyone knows the way their python code is delivered at adwords ? Fran?ois From wh2005 at web.de Wed Nov 24 07:03:41 2004 From: wh2005 at web.de (wolfgang haefelinger) Date: Wed, 24 Nov 2004 12:03:41 GMT Subject: read(1) returns string of length 2 Message-ID: Greetings, I'm trying to read (japanese) chars from a file. While doing so I encounter that a char with length 2 is returned. Is this to be expected or is there something wrong? Basically it's this what I'm doing: import codecs f = codecs.open("ident.in",'rb','Shift-JIS') ## japanses codecs installed c = f.read(1) while c: if len(c)==1: print hex(ord(c)), else: print "{", for x in c: print hex(ord(x)), print "}", c = f.read(1) This is my input (file is also attached): $ od -tx1 ident.in 0000000 8d 87 8c 76 8e 9e 8a d4 3b 0d 0a 0000013 This is what I'm getting: $ python ident.py ## python 2.3.4 on Windows 0x5408 0x8a08 0x6642 0x9593 { 0x3b 0xd } 0xa "Python" believes that there are 6 chars on the stream while there are actually 7 chars. My naive assumption was that f.read(1) returns always a char of length 1 (or zero). Remark: The input is believed to be "SJIS" but I haven't found a Python codecs for this. Therefore I'm using Shift-JIS. Of course this could be the problem. Note that when feeding Java with my input "correct" using SJIS, chars are spit out: c=21512 c=35336 c=26178 c=38291 c=59 c=13 c=10 : 7 char(s) References: I downloaded Japanese codecs from here (version: 1.4.10) http://www.asahi-net.or.jp/~rd6t-kjym/python/ Thanks for any hints, Wolfgang. begin 666 ident.in +C8>,=HZ>BM0[#0H` ` end From Scott.Daniels at Acm.Org Sun Nov 7 20:43:18 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 07 Nov 2004 17:43:18 -0800 Subject: Stop spaces from appearing when printing to file In-Reply-To: <418ec9ff$1_2@newspeer2.tds.net> References: <418ec9ff$1_2@newspeer2.tds.net> Message-ID: <418ee25a$1@nntp0.pdx.net> Kent Johnson wrote: > Brad Tilley wrote: > >> I'm printing some info into a txt file that will be uploaded into a >> MySQL DB. I use ';' as field separaters. How can I stop spaces from >> appearing on both sides of the ';' > > > The spaces are a feature of print. To avoid them, use string formatting > to create a single output string. > >> print >> x,';',object,";",AN_string,";",ascii,";",sum > > > Try > print >> x, ';%s;%s;%s;%s' % (object, AN_string, ascii, sum) or even: print >>x, ';'.join([str(v) for v in (object, AN_string, ascii, sum)]) -Scott David Daniels Scott.DanielsAcm.Org From python-url at phaseit.net Mon Nov 22 18:08:03 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 22 Nov 2004 23:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 22) Message-ID: QOTW: "[W]riting C code is typically the least time-consuming part of any language feature." Tim Peters "Best way to discourage visual basic knock offs, is to try and use visual basic, in my opinion." Eddie Parker You can use no-cost compilers to build extensions for 2.4 under Windows in a reasonably standard way. http://www.vrplumber.com/programming/mstoolkit/ Ipython's so desirable people (all but) abandon zsh and allied *sh. http://groups.google.com/groups?frame=right&th=1831549887c79e Comp.lang.python has been talking about decorators for months. A C++ perspective through templates (notice Diez B. Roggisch's example of how C++ creates pain) leads back to decorators and generics. http://groups.google.com/groups?frame=left&th=fe2717900f2a9312 Is there value in lighter-weight syntax checking than, say, pycheck provides? In any case, Ian Bicking shows that it's at hand now. http://groups.google.com/groups?frame=left&th=eaef717078406f39 Exceptions are IMPORTANT. Peter Hansen, Roy Smith, Andrew Dalke, and others help those coming from outside Python to think clearly about exceptions. http://groups.google.com/groups?frame=left&th=96be282f14e5d437 Python defines signal-handling in a way that makes correct behavior relatively easy to maintain. Tim Peters explains that painful experience has taught the wisdom of this approach (and avoidance of HP-UX "features", incidentally). Along the way, he gives stylistic advice on threads, queuing, ... http://groups.google.com/groups?frame=left&th=d56763f5f3d9823f ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From news5 at bennymo.ch Fri Nov 19 10:03:10 2004 From: news5 at bennymo.ch (Benny Mohr) Date: Fri, 19 Nov 2004 16:03:10 +0100 Subject: elegante zuweisung gesucht Message-ID: Hallo ihr Cracks, ich habe eine einfache Funktion def myFunc(a,b): pass und eine Liste myList = [1,2] und m?chte gerne auf diese Weise aufrufen: myFunc(myList) Geht leider nicht - gibt es Alternativen ohne myFunc zu ?ndern? Besten Dank Benny From roy at panix.com Tue Nov 2 19:44:23 2004 From: roy at panix.com (Roy Smith) Date: Tue, 02 Nov 2004 19:44:23 -0500 Subject: Should I learn Python? References: <624a388a.0411021328.5ac41f4c@posting.google.com> <418807d0$0$19691$626a14ce@news.free.fr> Message-ID: bruno modulix wrote: > > 3. In what way could I utilize Python to compliment existing sites or > > apps built with PHP? > a cgi is a cgi, whatever the language (php, perl, python, bash, C, > COBOL, assembly....). But there's a lot more to web applications than CGI. From skip at pobox.com Wed Nov 17 11:24:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Nov 2004 10:24:44 -0600 Subject: seeking a new host for the "Python Grimoire" In-Reply-To: References: Message-ID: <16795.31564.254323.753340@montanaro.dyndns.org> Gerrit> I didn't know this resource. It looks nice. Why take it down? It Gerrit> looks valuable as is. Maybe you should add a warning that it is Gerrit> no longer maintained and that volunteers are welcomed at the Gerrit> top? Or convert it to a wiki and let the community as a whole maintain it? If you want to go that route I'd be happy to host the wiki on the Mojam server. Skip From valkyrie at cuhk.edu.hk Fri Nov 19 10:45:21 2004 From: valkyrie at cuhk.edu.hk (Valkyrie) Date: Fri, 19 Nov 2004 23:45:21 +0800 Subject: Question about thread In-Reply-To: <306ic5F2svtsdU1@uni-berlin.de> References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> Message-ID: <1100879122.755150@eng-ser4> When I do it line by line in python's console, I have similar result to youl. But when I try to run it in a file, say: python demo.py It just returns me nothing. I have no idea on this right now... Russell Blau wrote: > "Valkyrie" wrote in message > news:1100875373.911763 at eng-ser6... > >>Refering to the following codes I found, there is nothing displayed in the >>console, may I ask why? >> >>def thrd(param): # the thread worker function >> print "Received",param >> >>import thread >>for i in range(5): # start five threads passing i to each one >> thread.start_new_thread(thrd,(i,)) > > > You may ask, but when I tried your code, here is what happened: > > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>def thrd(param): # the thread worker function > > ... print "Received",param > ... > >>>>import thread >>>>for i in range(5): # start five threads passing i to each one > > ... thread.start_new_thread(thrd,(i,)) > ... > 1960 > 836 > 232 > 2864 > 3692 > >>>>Received 0 > > Received 1 > Received 2 > Received 3 > Received 4 > > Note that the numbers 1960, etc., appear to be the return values of the > thread.start_new_thread() function. > > From mrovner at propel.com Fri Nov 5 16:23:55 2004 From: mrovner at propel.com (Mike Rovner) Date: Fri, 05 Nov 2004 13:23:55 -0800 Subject: sh: test: argument expected and /etc/passwd In-Reply-To: <200411041256.iA4CuZ9q002858@relay.uva.es> References: <200411041256.iA4CuZ9q002858@relay.uva.es> Message-ID: Iv?n Cabria wrote: > Hi, > > thanks to Mike Rovner for the answer. > I did grep loginname /etc/passwd to confirm I was using bash, and the line I > got ended with > > :/usr/bin/bash If the error doesn't go away try to locate shell invocation inside script. Also try "which sh" and "ls -l $(which sh)". On my system that points to bash as well. If it isn't on yours, you can simulate it (if python script doesn't call sh bu full path like /bin/sh) by placing "sh" symlink to /usr/bin/bash early in your PATH: mkdir ~/bin PATH=~/bin:$PATH ln -s /usr/bin/bash ~/sh and try to run your script again from there. HTH, Mike From strombrg at dcs.nac.uci.edu Tue Nov 9 20:37:46 2004 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Wed, 10 Nov 2004 01:37:46 GMT Subject: html parsing? Or just simple regex'ing? Message-ID: I'm working on writing a program that will synchronize one database with another. For the source database, we can just use the python sybase API; that's nice and normal. For the target database, unfortunately, the only interface we have access to, is http+html based. There's same javascript involved too, but hopefully we won't have to interact with that. So, I've got Basic AUTH going with http, but now I'm faced with the following questions, due to the fact that I need to pull some lists out of HTML, and then make some changes via POST or so, again over HTTP: 1) Would I be better off just regex'ing the html I'm getting back? (I suppose this depends on the complexity of the html received, eh?) 2) Would I be better off feeding the HTML into an HTML parser, and then traversing that datastructure (is that really how it works?)? 3) When I retrieve stuff over http, it's clear that the web server is sending some kind of odd gibberish, which the python urllib2 API is passing on to me. In a packet trace, it looks like: Date: Wed, 10 Nov 2004 01:09:47 GMT^M Server: Apache/1.3.29 (Unix) (Red-Hat/Linux) mod_perl/1.23^M Keep-Alive: timeout=15, max=98^M Connection: Keep-Alive^M Transfer-Encoding: chunked^M Content-Type: text/html^M ^M ef1^M ^M ^M ^M ...and so on. It seems to me that "ef1" should not be there. Is that true? What -is- that nonsense? It's not the same string every time, and it doesn't show up in a web browser. Thanks! From caleb1 at telkomsa.net Thu Nov 25 20:59:54 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 25 Nov 2004 20:59:54 -0500 Subject: network programming without goto References: Message-ID: On Thu, 25 Nov 2004 06:53:53 -0800 (PST), kent sin wrote: > > for host in hostlist: > try: > # sometimes the host may fail > conn =zoom.Connecton(host.ip, host.port) > except: > continue # Next host? But How to give it some > chance? 3 times? > ... Roy really posted the definitive answer here, but there is something else you may find it interesting to try: recursive functions. I played around with this for a random POV-Ray texture generator I made a while ago (anyone interested? It's decent :) - nesting levels were somewhat flexible, and I made the number of nesting levels in different sections (texture maps, normal maps, etc.) randomised as well. You do something like *** def funnyWalk(stuff, NUMBER_OF_THIS_TRY, NESTING_LEVEL) if NUMBER_OF_THIS_TRY > NESTING_LEVEL: # We're done. break # Is this valid??? I confuse pascal and python easily :( NailParrotsFeet() if NEED_ANOTHER_CALL == true: funnyWalk(stuff,NUMBER_OF_THIS_TRY+1) NESTINGLEVEL = 3 funnyWalk(stuff,1,NESTINGLEVEL) *** And "NailParrotsFeet()" function will get run 3 times. From jerf at jerf.org Thu Nov 25 00:54:20 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 25 Nov 2004 00:54:20 -0500 Subject: Python's annoyance. References: Message-ID: On Wed, 24 Nov 2004 10:47:11 -0800, caroundw5h wrote: > Serioulsy, one of python's main selling points is its elegant syntax, non > perl like, non C like. If it can't live up to it. I guess i might as well > use perl or ruby or server side javascript. There's a rather large difference between @require_int @dynamic_dispatch('add', int) @author("Steven Q. Dude") @whack_a_hacka_ding_dong(with_fruit=True, sledgehammer=5) @register(zodb & mysql_storage) def increment(i): return i + 1 and @require_int def advanceCounter(index): objToAdvance = objStorageArray[index] obj.prep(prepType = ADVANCE) try: obj.advance(1) except IOError: obj.lazyAdvance(1) return obj One guess which is the more common case. I can make any language look bad by focusing on the nasty cases. I mean, why not complain about p=lambda n,s=2,np=lambda s,f:reduce(lambda x,y:x and y,map(lambda x,y:x%y,[s+1]*(s/2),range(2,s/2+2)))and s+1or f(s+1,f ):n>0and[s]+p(n-1,np(s,np))or[] (http://groups.google.com/groups?hl=en&lr=&c2coff=1&frame=right&th=5c8439bf5fa72cde&seekm=000001bd7a3a%24f205cc40%2418472399%40tim#link3) Obviously, any language that allows that isn't clean. You have to take the gestalt of real code written in the language, not contrive cases focusing on the worst part of the language. Python's near the top of the heap. Javascript would fare better if so many inexperienced programmers weren't bashing away in it, and if so many extant programs in it weren't bogged down by browser checking code brought on by wildly divergent DOMs. If you insist on using such faulty metrics, though, hie thee hence to Perl, that epitome of elegant syntax and more power to you. I leave you with this closing benediction in honor of the might syntactical cleanliness of Perl: @==sort@$=map$_.shift@=,@@for@@=/\pL|,/g;$_=@$[$_] (http://perlgolf.sourceforge.net/cgi-bin/PGAS/post_mortem.cgi?id=11) (http://perlgolf.sourceforge.net/TPR/0/6/) From lbates at syscononline.com Fri Nov 19 12:40:49 2004 From: lbates at syscononline.com (Larry Bates) Date: Fri, 19 Nov 2004 11:40:49 -0600 Subject: Building a word list from multiple files In-Reply-To: References: <3oqdnVtPVOyFMgHcRVn-rA@comcast.com> Message-ID: With email messages they should be small enough so reading them into memory isn't an issue so line-by-line processing isn't indicated here. Email messages have LOTS of punctuation in the other than witespace between words. Just look at your email message below. It contains: > greater than symbol ) parenthesis . periods ? question marks , commas Even text like: "html.So no line.." Periods with no whitespace will be a problem string split would return "html.So" as a word. I really think you are going to need to use regex to split this into "words" and even then the words may be of questionable origin. See another response for an example regex expression that might work. Constructs like e.g. will return two words "e" and "g" (which might be ok for your application). Hope feedback at least helps. Larry Bates Manu wrote: > hi, > >>1) How large are the files you are reading (e.g. can they >>fit in memory)? > > > The files are email messages. > I will using the the builtin email module to extract only the content > type which is plain text or in html.So no line by line processing is > possible unless > i write my own parser for email. > > >>2) Are the words in the file separated with some consistent >>character (e.g. space, tab, csv, etc). > > > in the case of html mail i only extract the text and strip of the > tags. > Since this is regular text i expect no special seperators and as i > understand split() by default takes any whitespace character as > delimter.This will work fine for my purposes. > > > >>If not, preprocess the files and use shelve to save a >>dictionary that has already been processed. When you > > > This is what i was planning to do.Once the processing is done for a > set of files they are never processed again.I was going to store the > dict as a string in a file and then use eval() to get it back. > > > Thanks > Manu From bokr at oz.net Wed Nov 10 05:17:27 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 10 Nov 2004 10:17:27 GMT Subject: range and wx co - ords References: Message-ID: <4191dc09.80425295@news.oz.net> On 9 Nov 2004 17:07:12 -0800, mj.clift at virgin.net (Malcolm Clift) wrote: >Hi All, > >I have now got something approaching what I need. Could someone please >show me how to define the 'line', so rather than just the first 50 >items being printed over and over it goes through the text >incrementally? > > > line = text1[:50] > for i in range(1000): > dc.DrawText(line, 100, 100 + (i//2)*100) > I don't think you want to do 1000 DrawText calls to display 50 characters ;-) I can't tell what you really want to do, but if you just want to spread characters evenly to make an array of characters with 50 per row of some width and a box of some height, I would just walk through the characters and bump coordinates as I went. If you are tyring to spread _words_ into the space, you might want to keep the characters in words more together than what overall average spacing will give. I.e., insert extra space between words, but none or some mild effect between characters. This also depends on what font you are using, which gets into font metrics. Also how persnickety you are about precise inclusion within the box area of characters on the right. An '!' is going to be narrower than an 'M'. Also, do you want to ignore word boundaries and likely break words between lines? If you just want to walk through 20 lines of 50 characters taken successively from text1, you can write something like (untested!!) cpl = 50 # chars per line totlines = 20 top = 100; left = 100 # top left pixel position width = 500; height = 400 # box pixel(?) dimensions cleantext = ' '.join(text1.split()) # change all whitespace to single spaces?? for linestart in xrange(0, cpl*totlines, cpl): line = cleantext[linestart:linestart+cpl] for ix, c in enumerate(line): # compute position iy = linestart//cpl # might want to add 1 if top is not baseline pos x = int(left + width*ix/float(cpl)) y = int(top + height*iy/float(totlines)) dc.DrawText(c, x, y) But this is not normal word flowing to fit _words_ in a box justified to both sides, if that's what you really want. If you want that, you should probably output words whose characters are not separated as much, and put extra space between words, and not break words at line ends. Also, if your text has real newlines ('\n') or tabs etc. in it, you may want to change them to spaces (but not necessarily a single space for each separation as I did in cleantext above). HTH and that the bug is not too bad (untested, there's bound to be one ;-) Regards, Bengt Richter From ca765 at earthlink.net Fri Nov 19 21:09:11 2004 From: ca765 at earthlink.net (Charles Allen) Date: 20 Nov 2004 02:09:11 GMT Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> Message-ID: I suggest that someone quickly file an application for the "IsToo" operator. Skeptics may doubt that this is patentable, to which I say... Is Too! Is Not! Is Too! Is Not! ... -- Charles Allen From peter.mosley at talk21.com Mon Nov 22 12:33:31 2004 From: peter.mosley at talk21.com (Peter) Date: 22 Nov 2004 09:33:31 -0800 Subject: [Beginner] delete items of [] also from memory References: Message-ID: <72c8d50d.0411220933.203ca8f0@posting.google.com> "Birgit Rahm" wrote in message news:... > Hello newsgroup, > > I am a beginner, so I am asking maybe immoderate questions. > I want to delete a [] variable, after filling it with complex objects. How > should I do it? > e.g. > AAA = [] > AAA = [B, C, D, E, F] > Can I > 1) AAA = [] > 2) del AAA[0:] > 3) ? > whats about the computers memory, will it get free? Or will it get more and > more while Python is running? I too am a novice, so am prepared to be corrected if this is wrong. I don't think you need to worry - Python handles memory allocation automatically. Names are not specifically allocated to memory, and when the last reference to a name is deleted all the associated memory is freed. From carribeiro at gmail.com Thu Nov 18 06:49:27 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 18 Nov 2004 09:49:27 -0200 Subject: Idiom for default values when unpacking a tuple In-Reply-To: References: Message-ID: <864d37090411180349675aef7b@mail.gmail.com> On Thu, 18 Nov 2004 03:34:42 GMT, Steven Bethard wrote: > Well, it doesn't quite exist in itertools, but it's there with just a > simple composition: > > >>> def iterfixed(seq, times, defaultitem=None): > ... return it.islice(it.chain(iter(seq), it.repeat(defaultitem)), times) > ... After I posted the previous recipe I polished it up a little bit more and renamed it as "iunpack". It now returns the remaining part of the tuple as the last item. As it is, it's a good candidate for itertools -- it's way more convenient than the composition option, and judging by how many times the issue was brought up here, it's a relatively common problem. > >>> tuple(iterfixed((1,2,3,4), 3)) > (1, 2, 3) > >>> tuple(iterfixed((1,2,3,4), 6)) > (1, 2, 3, 4, None, None) > >>> a,b,c = iterfixed((1,2,3,4), 3) > >>> a,b,c > (1, 2, 3) > >>> a,b,c,d,e,f = iterfixed((1,2,3,4), 6) > >>> a,b,c,d,e,f > (1, 2, 3, 4, None, None) > > > The only catch is that, if you have only one parameter, then all you > > will get is the generator itself. But that's a corner case, and not > > the intended use anyway. > > Not exactly sure what you mean here. If you only have one item in your > unpack tuple, I believe things still work, e.g.: > > >>> a, = iterfixed((1,2,3,4), 1) > >>> a > 1 > > But I'm probably just misunderstanding your statement... No -- it's that you remembered to include the comma. My example was to assign it it one item only, which really isn't tuple unpacking; but this is a easy mistake to do in this case. Anyway, it should work as intended. BTW, I never saw it mentioned before that iterators can be used at the right side of an assignment with the tuple meaning. Nice side effect, I think. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From kent3737 at yahoo.com Sat Nov 20 21:23:08 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 20 Nov 2004 21:23:08 -0500 Subject: CGI email script In-Reply-To: References: Message-ID: <419ffad3$1_3@newspeer2.tds.net> bojanraic at gmail.com wrote: > I'm trying to write a basic Python email CGI script to send email > through HTML email form. > I've seen a lot of examples out there, but nothing I tried so far > seemed to work. So I would like to know what I am doing wrong. > #!/usr/bin/python > > import cgitb > cgitb.enable() > import cgi > import smtplib > > print "Content-type: text/html\n" This line should be inside main() so it is printed each time the script runs (OK maybe for a CGI it doesn't matter...), and it should have two \n - you need a blank line between the HTTP headers and the body. > > def main(): > form = cgi.FieldStorage() > if form.has_key("name") and form["name"].value != "": > fromaddress = form["email"].value > toaddress = my at email.com > message = form["comment"].value > > server = smtplib.SMTP('localhost') > server.set_debuglevel(1) > server.sendmail(fromaddress, toaddress, message) Strangely enough, the message actually has to include the from and to addresses as well. Try something like this: msg = '''From: %s To: %s Subject: Test %s ''' % (fromaddress, toaddress, message) server.sendmail(fromaddress, toaddress, message) > server.quit() > > print "Sent" > print "

", > print "

Your message has been sent!" > print "" > > if __name__ == '__main__': main() > > > > Of course, I change the email address to my own. > I keep getting the premature end of script headers error. > > Several questions: > > 1. server = smtplib.SMTP('localhost') should return the name of the > server, right? I don't need to explicitly name it, or do I? You should pass the name of the SMTP server, is that on your local machine? Kent > 2. cgitb.enable() - shouldn't that give me a trace back if something > goes wrong so I can debug the code? It doesn't seem to give me > anything... > 3. What am I doing wrong here? How can I fix the errors and make it > work? From and-google at doxdesk.com Sun Nov 14 05:14:52 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 14 Nov 2004 02:14:52 -0800 Subject: get element text in DOM? References: Message-ID: <2c60a528.0411140214.9ed8e57@posting.google.com> Manlio Perillo wrote: > for n in node.childNodes: > if n.nodeType in (dom.Node.TEXT_NODE, dom.Node.CDATA_SECTION_NODE): (Aside: node.TEXT_NODE would probably be better here. Can't guarantee that a DOM's implementation of the 'Node' interface is available as a class called 'Node' inside its module.) > L.append(n.data) > else: > if not recursive: > return None Surely 'continue'? This will exit the function (returning None instead of the expected empty string) the first time a non-Text node is met. Incidentally, DOM Level 3 Core defines the property 'textContent' to return pretty much exactly this (although it removes the ignorable whitespace). Not in minidom yet, but... -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From amanjit.gill at gmx.de Wed Nov 17 15:49:43 2004 From: amanjit.gill at gmx.de (Amanjit Gill) Date: Wed, 17 Nov 2004 21:49:43 +0100 Subject: Arbitrary errors with c++, python, and simple mapi - basically c/c++ specific In-Reply-To: References: Message-ID: Thomas Zehbe wrote: > Everything works fine until I did the first call to a function in the > mapi32.dll. The loading of the dll doesn?t matter, but any call to the mapi, > i.E. MAPLogon, leads to arbitrary errors calling the Py-API. [..] Hi, - I suppose you should first check if your heap is still ok - perhaps your usage of that specific DLL caused heap corruption. Then the py-API screwed up. You should try the following standard heap check from win32 (, _DEBUG versions) _CrtCheckMemory() // to check all of the heap _CrtIsValidPointer(..) // to check a specific memory region for r/w doing _CrtCheckMemory() before and after a call can reveal alot. - It is very important to use the same runtime library in your projects, this is another common cause for failure. - MAPI is a COM library. You might try this straight c++ wrapper class first and see if the simplest example works for you: http://www.codeproject.com/internet/mapadmin.asp#xx708710xx. Or you may aswell try the more simplistic CMC Common messaging calls first (Platform SDK). Sorry for being _UnPythonic(); _________________________ Amanjit Gill Medical and Bioinformatics Gynecology and Obstetrics University Clinic Charite Berlin, Germany amanjit.gill at charite.de From deetsNOSPAM at web.de Tue Nov 16 11:53:20 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 16 Nov 2004 17:53:20 +0100 Subject: Idiom for default values when unpacking a tuple References: Message-ID: You can always have a try/exept clause around unpacking. That you could fator out into a function that always returns the right sized tuples. Like this: def unpack(t): try: a,b,c = t d = None except ValueError: a,b,c,d = t return a,b,c,d -- Regards, Diez B. Roggisch From gandalf at geochemsource.com Mon Nov 29 15:08:42 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 29 Nov 2004 21:08:42 +0100 Subject: httplib question In-Reply-To: <001e01c4d64e$3f2be150$0e8b18ac@stuartxplaptop> References: <883978369.20041129203018@geochemsource.com> <001e01c4d64e$3f2be150$0e8b18ac@stuartxplaptop> Message-ID: <1795433759.20041129210842@geochemsource.com> Hello Stuart, Monday, November 29, 2004, 8:59:57 PM, you wrote: > Laszlo, > The "request" method call expects a "body" parameter that defaults to None > as the 3rd method parameter. You will either need to pass in an empty > string as the body parameter, or assign the headers property by named > assignment. Python interprets your call as passing the dictionary into the > body parameter. > Stuart I'm a real Lama. :-) From davidb at mcs.st-and.ac.uk Thu Nov 18 19:18:08 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 18 Nov 2004 16:18:08 -0800 Subject: [PyQt] How to get the QRect of a QMenuBar (QPopupMenu) item ? References: Message-ID: <4de76ee2.0411181618.59a90abd@posting.google.com> Erwan Adam wrote in message news:... > I try to introduce tooltips in my application written > in PyQt (more precisly, in the menubar of my application) > but I can't find a way to get the QRect instance > associated to a QMenuBar item (neither a QPopupMenu item) You need to call the itemGeometry method on your QPopupMenu object with the index of the menu item you want to examine. Something like this should work for popup menus: # popup is a QPopupMenu containing several items rect = popup.itemGeometry(2) # for the third item in the menu It may be a little more difficult to get this information out of QMenuBar because it looks like PyQt can't access the itemRect function when the menu bar is created by a C++ object, such as a QMainWindow. > I need the QRect 'cause I followed the tooltip.py file > given with pyqt to do the job with a re-implementation > of "maybeTip( self, pos )". Are you trying to implement tooltips on menu items? You may find that regulars on the PyQt/PyKDE mailing list can give you more detailed advice: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde Good luck! David From tim.peters at gmail.com Wed Nov 24 18:32:12 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 24 Nov 2004 18:32:12 -0500 Subject: Python 2.4 and Visual C++ Express In-Reply-To: References: <9APod.4998157$ic1.468025@news.easynews.com> <30ji62F31ppn0U1@uni-berlin.de> Message-ID: <1f7befae041124153249a0b892@mail.gmail.com> [Jive] ... > In any case, I think it would be a Good Thing if the Pythonistas > provided a download of 2.4 compiled under VC++ 6.0, in addition to > the 7.1 one. That requires someone who cares enough to volunteer the work, or to fund the work (presuming someone exists who could be convinced to do the work for pay). For various reasons I, and later Raymond Hettinger, cared enough to keep the MSVC 6 project files working with Python 2.4, but nobody voluntered to produce a Windows installer for 2.4 based on MSVC 6. There's no policy against that, but Pythons don't grow on trees. From Scott.Daniels at Acm.Org Thu Nov 11 09:44:59 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Nov 2004 06:44:59 -0800 Subject: re.compile.match() results in unicode strings - why? In-Reply-To: <2vh2mlF2lbkrdU1@uni-berlin.de> References: <2vh2mlF2lbkrdU1@uni-berlin.de> Message-ID: <41938e20$1@nntp0.pdx.net> Axel Bock wrote: > .... I match a string with > exp = re.compile(blah) > m = exp.match(string) > a,b,c,d = m.groups() > now a,b,c,d are all string variables, This shows a misunderstanding. Python does not have typed variables. a,b,c,d = 'a', 'b', 'c', 'd' a = 4.5 b = 3+5j c = u'\N{LATIN CAPITAL LETTER D WITH STROKE}one' d = repr is perfectly legal. > ... and [a,b,c,d] all come out as unicode > strings (u"xxx"). The example is not concrete enough to reproduce. Please give particular examples for blah and string. -Scott David Daniels Scott.Daniels at Acm.Org From jzheng at jpl.nasa.gov Fri Nov 12 15:59:04 2004 From: jzheng at jpl.nasa.gov (Jason Zheng) Date: Fri, 12 Nov 2004 12:59:04 -0800 Subject: popen help In-Reply-To: References: Message-ID: Jason Zheng wrote: > exarkun at intarweb.us wrote: > >> On Fri, 12 Nov 2004 11:29:46 -0800, Jason Zheng >> wrote: >> >>> I'm trying to open a subshell to run some csh commands, and I want to >>> connect the stdout of the subshell to the main stdout: >>> >>> sub = Popen4('csh -f') >>> sub.tochild.write('source source.me\n') >>> sub.tochild.write('runthis\n') >>> sub.tochild.close() >>> >>> for x in sub.fromchild.readlines(): >>> print x >>> >> >> >>>>> import os, time >>>>> for x in iter(os.popen('for x in `seq 3`; do echo $x; sleep 1; >>>>> done').readline, ''): >> >> >> ... print time.time(), x, >> ... 1100290304.55 1 >> 1100290305.56 2 >> 1100290306.56 3 >> >> The difference is that readline() returns one line whereas >> readlines() returns all of the lines. Since you cannot know what all >> the lines are until you have read all of the data, it cannot return >> until the child process exits. >> >> Jp > > Jp, > > I doubt that's gonna resolve the problem I have tho. Suppose I send one > command which doesn't not have the 'sleep' but prints some output line > periodically, wouldn't I have to wait till the end of the execution to > see any output? > > Can I just connect sys.stdout to the stdout of the subshell? > > jz Nevermind, I think I understand now... I thought that the close() call was blocking executation. Thanks! From NutJob at gmx.net Thu Nov 18 11:47:06 2004 From: NutJob at gmx.net (Markus Kemp) Date: 18 Nov 2004 08:47:06 -0800 Subject: Need function to test if EFFECTIVE UID has read-access to a file. References: <9b96ed1.0411170915.2b88da0e@posting.google.com> Message-ID: <9b96ed1.0411180847.17d4f7af@posting.google.com> Oh, and another reason why I can't use the method suggested by you is that I'm dealing with directories, not files. Then again .... I guess I could do something like: try: os.listdir( strPathname ) except: print "No read access to pathname", strPathname, "!" Problem is, I don't wanna catch __everything__. Does anyone know what kind of exception is.listdir() throws if it fails to read a directory? From wolfgang.keller.nospam at gmx.de Tue Nov 2 12:19:25 2004 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Tue, 2 Nov 2004 18:19:25 +0100 Subject: JMS for CPython via JPype? Message-ID: <1b2k1czwwox4i$.ae466jlsmeu2$.dlg@40tude.net> Hello, sorry for the potentially dumb question, but - would JPype make it possible for a CPython program to use JMS? It seems that JMS is going to become a standard for (java-based) MOM, so as an excellent middleware language it should be possible for CPython to somehow "talk" (and understand) JMS... TIA, Best regards Wolfgang Keller From kayschluehr at gmx.de Sat Nov 27 07:23:12 2004 From: kayschluehr at gmx.de (Kay Schluehr) Date: Sat, 27 Nov 2004 13:23:12 +0100 Subject: Protecting Python source Message-ID: <41A871B0.4000308@gmx.de> You can passwort-protect Your zip-files, but how will the passwort ( private keys ) be protected? As Alex Martelli stated: one option is a client-server / webservice application which is only used but by Your customer but not owned by him. Another option is the usage of secure hardware i.e. smartcards and a PKI infrastructure. But this requires probably additional appropriate hardware. If You simply want to fool Your customer You can embed the Python interpreter into a C-program, then zip Your scripts into a file "custom.zip" and rename it to "custom.dll" or "custom.ocx" or something else. At least the cracker should have fun, puzzling this out. But also this "solution" will never be more secure than a compiled C-source. Same with all the Pyrex, py2exe and py-2-don't-know-what solutions. Ciao Kay From cme at lampcoders.net Wed Nov 10 15:15:50 2004 From: cme at lampcoders.net (Christian Meissner) Date: Wed, 10 Nov 2004 21:15:50 +0100 Subject: Announce: csv_xs.py References: Message-ID: > What you do is not csv parsing! > > You are just splitting the rows by > the separator character (a triviality). > But this character may be inside the field > enclosed within quotation characters. > > > Istvan. atm it is work in progress, so i will extends it if it is nessesary ... From mauriceling at acm.org Sun Nov 7 01:04:01 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 07 Nov 2004 17:04:01 +1100 Subject: Newsgroup mood [was] why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> Message-ID: <418DBAD1.70702@acm.org> > 3) Links to threads that answer common questions > Yes, there is an FAQ and yet people still ask why Python gets division > wrong. But I've often seen people dig up links to threads for questions > perhaps not so common to be written up in an FAQ, but perhaps common > enough to merit linking on a wiki page. I'm not under the illusion that > it would solve the problem on its own, but it might well head some > repeat questions off. For those it doesn't, it would give an easy way to > answer. > This may be useful but it will certainly bring us a new set of questions then, in the form of "is this still holds for ?" Although computer science stems from mathematics, it had lost an important aspect of mathematics, that is, "once proven true is forever true." maurice From aleaxit at yahoo.com Sun Nov 28 19:46:13 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 29 Nov 2004 01:46:13 +0100 Subject: Is there a consensus on how to check a polymorphic instance? References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> Message-ID: <1gnzok5.1ewvjgm9it36pN%aleaxit@yahoo.com> Dan Perl wrote: > I have a question here, as we are discussing now protocol interfaces vs. > inheritance. Is using a class that implements a protocol without inheriting > from a base class still "polymorphism"? ``still'' is inappropriate here. It is _fully_ polymorphism, of course. It's known as signature-based polymorphism. C++ has it in templates, only, where it's the basis of the whole power of the standard library containers, algorithms, iterators, etc. Python has it everywhere, except where some coder breaks everything with 'isinstance' or the like. > There are probably many definitions > for polymorphism and probably all those definitions can be interpreted in > such a way that they accept also protocols. But what I would like to hear Otherwise they're very broken and useless definitions. > is what is the general opinion of people who use python. I am biased > because I come from a C++ and Java background and I am still used to a > certain practical meaning for "polymorphism". One that doesn't apply to C++ templates?! > But it's beginning to dawn on > me that it is only a bias and polymorphism does apply also to python > protocol interfaces. Is that generally accepted? Yep. Alex From chazen at gmail.com Wed Nov 24 22:20:57 2004 From: chazen at gmail.com (Charlie DeTar) Date: Wed, 24 Nov 2004 22:20:57 -0500 Subject: Embedding Python in MaxMSP In-Reply-To: References: Message-ID: Oh, in case anyone out there cares or had the same problem at some point: I was able to fix this by adding "-lpython2.3" to the ld command list. Probably something to do with "Python.h" not corresponding to "libpython.a"? Maybe there ought to be links (libpython.a->libpython2.3.a), so that embedded applications don't depend on particular versions of python? cheers, Charlie Charlie DeTar wrote: [snip] > /usr/bin/gcc-3.3 -o "/Users/tc1/Sources/MaxMSP-SDK/Mach-O > Development/nyptho/build/nyptho.mxo/Contents/MacOS/nyptho" > "-L/Users/tc1/Sources/MaxMSP-SDK/Mach-O Development/nyptho/build" > "-L/sw/lib/python2.3/config/" "-F/Users/tc1/Sources/MaxMSP-SDK/Mach-O > Development/nyptho/build" "-F/Library/Frameworks" -filelist > "/Users/tc1/Sources/MaxMSP-SDK/Mach-O > Development/nyptho/build/nyptho.build/nyptho.build/Objects-normal/LinkFileList" > "-framework" "Carbon" "-framework" "MaxAPI" "-arch" "ppc" "-bundle" > "-ldl" > ld: Undefined symbols: > _PyEval_InitThreads > _PyRun_SimpleFile > _PyRun_SimpleString > _PySys_SetArgv > _Py_Finalize > _Py_Initialize [snip] From donn at drizzle.com Sat Nov 27 12:16:23 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 27 Nov 2004 17:16:23 -0000 Subject: protocols, inheritance and polymorphism References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> <786dnYZkrq-ieT7cRVn-tw@rogers.com> <1101273995.954137@yasure> <41a6340f$0$307$636a15ce@news.free.fr> Message-ID: <1101575782.366954@yasure> Quoth Jacek Generowicz : [ ... re C++ casting to subtype ] | Yes, you can "easily" do the work that the absent dynamic type system | should be doing for you (and Turing equivalence tells us that that we | can implement a decent dynamic type system as well). The fact remains | that the objects *are* *dynamically* typed, even though the language | claims to be statically typed. The fact that statically typed | languages feel the need to introduce dynamic typing (however poorly | supported it may be) in order to support OOP, points to the fact that | static type systems DO have problems with OOP, which is what the | question was about. | | Specifically, dynamic polymorphism is impossible without dynamic | typing. Given a model for polymorphism that means smuggling an object around wrapped in some degree of mystery about its type, elegant and sound static typing does seem unlikely. But C++ and its descendents have always been easy targets. Would you happen to know something about how Objective CAML's OO system approaches this? I see in the on-line documentation this paragraph: Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of colored points would remain unchanged and thus still be a subtype of points. http://caml.inria.fr/ocaml/htmlman/manual005.html I'm thinking that this might be more or less typical of academic ideas about OO typing, and it seems conceptually appealing. I don't know the details though. Donn Cave, donn at u.washington.edu From deets.nospaaam at web.de Tue Nov 2 07:22:30 2004 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Tue, 02 Nov 2004 13:22:30 +0100 Subject: strong/weak typing and pointers References: Message-ID: <2upcg9F2ca8muU1@uni-berlin.de> > Note that this is also an example showing that C++ does contain a little > bit of dynamic typing, too, isn't it? On a related note: c++ _can_ have some dynamic type information - when not disabled with -fno-rtti (gcc) you get "real time type identification". That allows for (guess why there called that way...) dynamic casts. -- Regards, Diez B. Roggisch From fperez528 at yahoo.com Fri Nov 12 19:40:20 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 12 Nov 2004 17:40:20 -0700 Subject: Will python ever have signalhandlers in threads? References: <121120041606297367%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: Jean Brouwers wrote: > > Fernando, > > Just curious, does 'gtk/WX' in your message below mean wxPython? Yes. > If so, does this signal handling code actually work with wxPython?> It does, but not in a generic manner: this is code for ipython to support matplotlib's WX backend in an interactive shell. It allows you to type into ipython plotting commands which cause matplotlib to open a WX plotting window, and the interactive terminal continues to function. You can have multiple WX plotting windows open, and the command line keeps on chugging. But this relies on a special collaborative hack between matplotlib and ipython. matplotlib, in its WX and GTK backends (Tk doesn't need this) has a special flag to indicate who is in control of the mainloop. In standalone scripts, everything works in the typical manner. But if ipython comes in, it will set this flag, telling matplotlib to keep off the mainoop. It's pretty hackish, but it works in practice pretty well. here's the relevant matplotlib WX code (trimmed of docstring): def show(): for figwin in Gcf.get_all_fig_managers(): figwin.frame.Show() figwin.canvas.realize() figwin.canvas.draw() if show._needmain and not matplotlib.is_interactive(): wxapp.MainLoop() show._needmain = False show._needmain = True When ipython starts up, it sets show._needmain to False, so that the Mainloop() call is never made. You can look at the whole code from ipython if you wish, it's in IPython/Shell.py. best, f From digital_ant2 at yahoo.com Fri Nov 5 02:06:15 2004 From: digital_ant2 at yahoo.com (digital_ant2) Date: Fri, 05 Nov 2004 07:06:15 -0000 Subject: Script Generation, help! Message-ID: I'm new to python, so I'll be at detailed as I can be. I need to generate a script where each line is like this: Spam=(x) Spam=(y) Spam=(z) each entry being on their own line, Spam is a string of text and x,y,and z are random numbers, I also need it to be exported to a text file with a specified extension.... being completely NEW to python I push in the right direction would be really helpfull! Thanks, Pat From cjw at sympatico.ca Wed Nov 10 19:08:09 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 10 Nov 2004 19:08:09 -0500 Subject: distutils and Debian Message-ID: <4192AD69.5040707@sympatico.ca> The distutils download page has: -------------------------------------------------------- Current stable release The current stable release is Distutils 1.0.2; you can download it as: * Distutils-1.0.2.tar.gz (source distribution) (233k) * Distutils-1.0.2.zip (source distribution) (274k) * Distutils-1.0.2.win32.exe (Windows installer) (187k) If you are running Python version 1.6 or later, you do not need to download the Distutils: they're included with Python. However, if you have a Distutils more recent than your Python, you might want to install it: see the Distutils README.txt file. Version 1.0.2 is identical to the version included in Python 2.1. --------------------------------------------------------- With Debian, it seems that distutils is not included for Python 2.2 or 2.3. Should this be reported as a Debian bug? Colin W. From pwatson at redlinepy.com Thu Nov 18 22:32:52 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 18 Nov 2004 21:32:52 -0600 Subject: ping-based network monitoring GUI? References: Message-ID: <3057rfF2s8jdtU1@uni-berlin.de> "Count L?szl? de Alm?sy" wrote in message news:mailman.6519.1100737717.5135.python-list at python.org... > Greetings, > > I'm in need of a simple GUI application that "monitors" a range of > hosts using ping and reports on their status by changing the panel > color for that host (i.e, green for pingable, red for unreachable). > > Does anyone know of any existing opensource program that does this? > Preferably Python so I can extend it easily. > > If not, what tools would you recommend I write this kind of app in? > Ping doesn't seem to be supported by Python out of the box, and the > modules I've looked at seem sketchy. I looked at Expect, and see > there's a Pexpect module available. Once I have the core > functionality nailed down, I'll probably wrap it with Tkinter. > > Thanks for any advice. You might want to take a look at Big Brother. http://www.bb4.org/ It provides a web interface. While it is not written in Python, you can add tests in any language, including Python. If you only want 'ping' to be used, you can remove many of the default monitoring reports. From fperez528 at yahoo.com Wed Nov 10 22:29:38 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 10 Nov 2004 20:29:38 -0700 Subject: tkinter gnuplot References: <1100137324.13730.3.camel@localhost.localdomain> Message-ID: F?bio Mendes wrote: > Or even scipy. It's a great scientific library and I think it uses > gnuplot as one of the graphical frontends (http://scipy.org) . I'm not > sure if it allows you to pass arbitrary gnuplot commands, but if you > want to build such a thing, surely the source could be helpful. The gnuplot support in scipy is more or less deprecated, as scipy has a new framework (Chaco) coming down the pipe, and much of today's scipy user base is moving over to matplotlib. For the diehard gnuplot users (a group I happen to still belong to), Gnuplot.py offers a pretty clean interface. IPython (http://ipython.scipy.org) adds a fair amount of functionality to make interactive gnuplot work much more efficient, as well as simplifying some common tasks with a better syntax. But again, the problem is that gnuplot was not meant to be embedded as a Tk widget, which was the OP's intent. The tkcanvas terminal type is an intriguing option, but I have no idea how hard (if it's even possible) it would be to use that in a Python/Tkinter application. Best, f From greg at cosc.canterbury.ac.nz Wed Nov 24 00:13:50 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 24 Nov 2004 18:13:50 +1300 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: Message-ID: <30ijkhF31dg9sU1@uni-berlin.de> Lenard Lindstrom wrote: > So Delphi is definitely not BASIC-derived. It is BASIC-like in that various > basic dialects, including QBasic, came to support the structured programming > that Pascal was designed from the beginning to teach. So it would be more accurate to say that those Basic dialects are, in those respects, Pascal-like... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Mon Nov 1 04:58:23 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 01 Nov 2004 09:58:23 GMT Subject: List problem References: <1gmiyon.jvyq1w1ob9r59N%aleaxit@yahoo.com> <41853d5f.1278687054@news.oz.net> <1gmjqh9.oialil1r1xwffN%aleaxit@yahoo.com> <41858eaa.1299498379@news.oz.net> <1gmkg86.1nzf8g91e7yby5N%aleaxit@yahoo.com> Message-ID: <418603c1.1325873395@news.oz.net> On Mon, 1 Nov 2004 09:46:09 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Bengt Richter wrote: > ... >> >def delsome_am(n=1000000, todel=[2]): >> > a = range(n) >> > a = [x for x in a if x not in todel] >> ^-- shud be a[:] ;-) >> (I think the missing return a is in the noise ;-) > >Right, sorry. > >> >kallisti:/tmp alex$ python -mtimeit -s'import br' 'br.delsome_br()' >> >10 loops, best of 3: 4.44 sec per loop >> >kallisti:/tmp alex$ python -mtimeit -s'import br' 'br.delsome_am()' >> >10 loops, best of 3: 3.92 sec per loop >> > >> I thought you had 'way faster machines than mine. Neither time is an >> improvement over delsome_br for 2.3.2 on my old box. I wonder what's up. > >I ran these on an 800 MHz laptop, the one I invariably use for netting >-- best ergonomics. OK, I'll try with faster machines when I get a >chance -- I'm surprised you measure almost a 1:2 ratio with _br faster. > Maybe the listcomp optimizations were introduced in 2.3.4? Or even 2.4.x? I have Python 2.3.2 on an old 300 MHz P2 with 320 MB RAM and NT4 as OS, so the mystery deepens ;-) Regards, Bengt Richter From __peter__ at web.de Wed Nov 17 03:17:44 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Nov 2004 09:17:44 +0100 Subject: inserting bracketings into a string References: Message-ID: Steven Bethard wrote: > I'm trying to insert some bracketings in a string based on a set of > labels and associated start and end indices.??For?example,?I'd?like?to > do something like: > >>>> text = 'abcde fgh ijklmnop qrstu vw xyz' >>>> spans = [('A', 0, 9), ('B', 6, 9), ('C', 25, 31)] >>>> insert_bracketings(text, spans) > '[A abcde [B fgh]] ijklmnop qrstu [C vw xyz]' Not tested beyond what you see: text = 'abcde fgh ijklmnop qrstu vw xyz' spans = [('A', 0, 9), ('B', 6, 9), ('C', 25, 31)] def insert_bracketings(text, spans): inserts = [(s, "[%s " % r) for (r, s, t) in spans] inserts.extend([(t, "]") for (r, s, t) in spans]) inserts.sort() inserts.reverse() text = list(text) for (r, s) in inserts: text.insert(r, s) return "".join(text) assert ('[A abcde [B fgh]] ijklmnop qrstu [C vw xyz]' == insert_bracketings(text, spans)) Peter From thorsten at thorstenkampe.de Sun Nov 14 08:23:05 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 14 Nov 2004 14:23:05 +0100 Subject: simple recursion help References: <1gm4uqv.nmgjbj1vt0spjN%aleaxit@yahoo.com> <8ef9bea6.0410231916.450f67d@posting.google.com> Message-ID: * Hung Jung Lu (2004-10-24 04:16 +0100) > Steven Bethard wrote: >> Does anyone know what this operation is called? It's not permutations or >> combinations as I understand them since permutations and combinations do >> not allow repetition. I assume there was already a solution for this >> somewhere, but I didn't know what term to google for. > --------------------------------------------------- > aleaxit at yahoo.com (Alex Martelli) wrote: >> There's been a recent thread where the OP called them 'permutations', >> somebody commented they're 'variations'. In that thread you'll find a >> bazillion solutions, recursive and non, with or without itertools, &c. > --------------------------------------------------- > > (1) "Variation" is the same as "permutation". Sorry, no. > It's matter of semantics. It's a matter of definition and the definitions of both don't have anything in common. > Some people use the notation V(n, k), some people use the notation > P(n, k). For people that use the term "variation", the term > "permutation" is reserved for the special case V(n, n). That's misleading: the special case of a variation without repetition of the nth degree is the same as a permutation without repetition of that set. But the definitions of both are very different. Variations /with/ repetition are also equal to the "cartesian product" of the set with itself. But that doesn't mean that "cartesian product" and variation (with repetition) are the same. Let me explain: In combinatorics there are two distinct kinds of "operations": permutations and combinations[1]. PERMUTATIONS ____________ A permutation is a "bijective mapping on itself" which means that each permutation has the same length and consists of all elements of the original set. Permutations are divided into * permutations without repetition = n! * permutations with repetition = n! / (s1! * ... * sr!) For instance: [11, 22, 33, 44, 55, 66, 77] has 7! = 5040 different permutations (without repetition) [11, 22, 22, 33, 44, 44, 44] has 7! / (2! * 3!) = 420 different permutations (with repetition) COMBINATIONS ____________ A combination is a subset of the original set (also sometimes described as "ball picking". "Repetition" is sometimes called "putting back"). Combinations are divided into * unordered combinations without repetition * unordered combinations with repetition * ordered combinations without repetition * ordered combinations with repetition Of course that was too difficult to remember even for a mathematician so it was decided (about one hundred years ago) that ordered combinations should now be called "variations" and unordered combinations should now be called "combinations". So since then there are: * combinations without repetition = n! / (k! * (n - k)!) * combinations with repetition = (n + k - 1)! / ((n - 1)! * k!) * variations without repetition = n! / (n - k)! * variations with repetition = n ** k And this is where the confusion starts: * the binomial coefficient "(n over k) = n! / (k! * (n - k)!)" is sometimes called C(n, k). * "n! / (n - k)!" is sometimes called P(n, k) So you can also give the number of different combinations and variations like this: * combinations without repetition = C(n, k) * combinations with repetition = C(n + k - 1, k) * variations without repetition = P(n, k) Thorsten [1] For a quick overview have a look at http://www.eco.uc3m.es/stefan/phd-sum/probl2004.pdf From rogerb at rogerbinns.com Wed Nov 3 01:53:24 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 2 Nov 2004 22:53:24 -0800 Subject: HTML to Text renderer References: <3A81C87DC164034AA4E2DDFE11D258E324510E@exchange.hqamor.amorhq.net> Message-ID: <9acm52-st1.ln1@home.rogerbinns.com> Ian Bicking wrote: > Right. And word wrapping too. Some other tags would also be > interesting:

,
, 
, ,  , and something > to control alignment (e.g.,

). Usually I resort to using one of the text based browsers (eg lynx/links/w3m) which all have a mode to dump plain text out formatted in that way. Roger From steve at holdenweb.com Tue Nov 23 09:09:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Nov 2004 09:09:42 -0500 Subject: Filling Forms ( What is the best way to Print on Forms) In-Reply-To: References: Message-ID: Alex wrote: > Please advice: I have some DMV forms that I would like to print on to > fill the answers, is there any good software to do this with? Any free > software to do this? I need to align it so the prints go on the > designated response areas! > > Thanks a Million! > > Alex > 11-23-04 > ------------------------------------------------------------------------------ Take a look at www.reportlab.org - the open source toolkit should do what you want. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From alanmk at hotmail.com Mon Nov 8 06:20:51 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 08 Nov 2004 11:20:51 +0000 Subject: SAX parse string to Handler?? In-Reply-To: References: Message-ID: [Juliano Freitas] > here is my pythn code that's handle a xml file: Juliano, I think you're better off using the standard sax parsing facilities than those inside saxexts, etc. Try this code #================================================== import xml.sax class swdbHandler(xml.sax.handler.ContentHandler): def __init__(self): self.flag = 0 def startElement(self, name, atts): if name == "swml": print "enter" def endElement(self, name): if name == "swml": print "exit" xml_string="" xml.sax.parseString(xml_string, swdbHandler()) #================================================== HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From beps at email.it Wed Nov 24 03:30:24 2004 From: beps at email.it (beps) Date: Wed, 24 Nov 2004 09:30:24 +0100 Subject: Text widget - insert line References: <41a21527$0$8170$8fcfb975@news.wanadoo.fr> <30emukF2u6uf7U2@uni-berlin.de> <2KGod.2017$QR.1630@lakeread01> Message-ID: as you have written you I return to the problem begins them, that is the customers do not go to new line. I must recover the index of the last column of the data. -- questo articolo e` stato inviato via web dal servizio gratuito http://www.newsland.it/news segnala gli abusi ad abuse at newsland.it From Python at IvoNet.nl Wed Nov 10 10:08:11 2004 From: Python at IvoNet.nl (Ivo Woltring) Date: Wed, 10 Nov 2004 16:08:11 +0100 Subject: ConfigParser - MyConfigParser.py (0/1) References: Message-ID: <0jb4p096ot0dchcm7gdr7u25g3agi5e6s8@4ax.com> On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo wrote: >Regards. > >Since sections in CongiParser files are delimited by [ and ], why >there is not an escape (and unescape) function for escaping >&, [, and ] characters to &, [ and ] ? > > > > >Thanks Manlio Perillo Next try with attachment MyConfigParser.py Just save and run to see Cheerz, Ivo. From peter at designtheory.org Sat Nov 13 21:24:04 2004 From: peter at designtheory.org (Peter Dobcsanyi) Date: 14 Nov 2004 02:24:04 GMT Subject: numarray memory leak Message-ID: Calling the following function with a large enough 'n' causes memory leak. import numarray as N def loop(n, m=100): for i in xrange(n): a = N.zeros((m,m)) N.matrixmultiply(a, a) If the matrixmultiply line is commented out, there is no leak, the program has a stable memory size. I am using numarray 1.1, the result is the same with Python 2.3.4 and 2.4b2. Peter From danb_83 at yahoo.com Tue Nov 23 08:00:55 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Nov 2004 05:00:55 -0800 Subject: is int(round(val)) safe? References: Message-ID: "Russell E. Owen" wrote in message news:... > I realize this probably a stupid question, but...is it safe to > round to the nearest integer by using int(round(val))? > > I suspect it is fine, but wanted to be sure that weird floating point > representation on some platform might make it unsafe there (i.e. get the > wrong value due to the floating point value being an approximation) and > if so, is there a Better Way). Yes, int(round(val)) is safe. The only concern is avoiding errors in "val" itself. For example, >>> val 3.4999999999999996 # Should have been exactly 3.5 >>> int(round(val)) 3 # Should have been 4 From carribeiro at gmail.com Tue Nov 16 11:54:42 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 16 Nov 2004 14:54:42 -0200 Subject: adaptation In-Reply-To: <419A16CE.3050907@bellsouth.net> References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> <1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com> <1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> <419A16CE.3050907@bellsouth.net> Message-ID: <864d370904111608547c94c7c9@mail.gmail.com> On Tue, 16 Nov 2004 10:03:42 -0500, Jeremy Jones wrote: > Bryan wrote: > > > alex, > > > > you've mentioned several times the concept of adapting parameters to a > > method. but i'm not able to understand your few examples. can you go > > more into depth (and with simpler examples) on this topic? > > > > thanks, > > > > bryan > > Bryan, > > Thanks for asking this. You aren't alone in wanting to know more. > > Jeremy Well, my name is not Alex, and my answer will probably fall short of a comprehensive definition :-) But let's see if I can help here... Adaptation is the act of taking one object and making it conform to a given protocol (or interface). Adaptation is the key to make dynamic code that takes parameters from arbitrary types work in a safe, well behaved way. The basic concept underlying adaptation is the "protocol", also called "interface" in some implementations. For all purposes of this discussion, and for simplicity reasons, we can safely assume that protocols and interfaces are equivalent. A protocol is a set of primitives that is supported by a given object. For example: the iterator protocol defines the following primitives: __iter__ and next() (as documented in http://docs.python.org/lib/typeiter.html). Any object from any class that implement these methods, regardless of its ancestors, is said to support the iterator protocol. Any object that supports the iterator protocol can be used whenever an iterable is acceptable. This includes for loops and list comprehensions. The biggest advantage of adaptation comes when one realize how flexible this design is, specially when compared with old-style type checking. In a old-style type checking environment, parameters to a given routine must conform to the declared type of the arguments. For iterators, it would mean that only objects descending from some abstract class (let's say, "Iterable") would be accepted. Now, even with multiple inheritance, this design is severely limited. Now, back to Python world. In many situations, there is no need for adaptation; the object itself supports the protocol, and can be supplied directly. But there are situations when the object itself can't be immediately used; it has to be adapted, or prepared, to support the protocol. Another situation is when an object is passed to a routine that *doesn't* support the required protocol; this is an error, that can be catched by the adapt() framework in a superficially similar but fundamentally different approach from type checking (and that's whats Alex has been pointing out). The adapt protocol (as presented on PEP246 - http://www.python.org/peps/pep-0246.html) defines a very flexible framework to adapt one object to a protocol. The result of the adaptation (if possible) is an object that is guaranteed to support the protocol. So, using adapt(), we can write code like this: def myfunc(obj): for item in adapt(obj, Iterable): ... Finally, one may be wondering, is there any situation when an object needs to be "adapted"? Why don't just check for the availability of the interface? There are many reasons to use the adapt framework. The protocol checking is one of the reasons -- it allows errors to be catched much earlier, and at a better location. Another possible reason is that complex objects may support several protocols, and there may be name clashes between some of the methods. One such situation is when an object support different *versions* of the same protocol. All versions have the same method names, but semantics may differ slightly. The adapt() call can build a new object with the correct method names and signatures, for each protocol or version supported by the object. Finally, the adaptation method can optionally build an opaque "proxy" object, that hides details of the original methods signature, and it's thus safer to pass around. Well, that's a broad overview of the subject. There is a lot of stuff to learn, and using adaptation properly is something that takes some time. Hope it helps. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From rays at blue-cove.com Tue Nov 30 19:37:25 2004 From: rays at blue-cove.com (RayS) Date: Tue, 30 Nov 2004 16:37:25 -0800 Subject: Running External Programs from Within Python In-Reply-To: References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: <5.2.1.1.2.20041130162358.0225fd60@blue-cove.com> At 10:50 PM 1/31/2004 +0100, Nuff Said wrote: >On Sat, 31 Jan 2004 11:23:42 -0800, Bob=Moore wrote: If anyone is interested, I used the following non-threaded code; I tried pipedream.py, but had apparent timing issues with the threads that I couldn't clear up. I usually use wxPython. An *NIX version would be interesting as well (hint). The external .exe is an interactive DOS-menu'd program in FORTRAN. ================== snip ============================= import os import time from wxPython.wx import * import win32pipe def getDataFrom(pipe): done = False timeout = 4 ## seconds start_time = time.time() data = '' error = None while not done: try: ## check to see if the 'file' has any data, using stat() #print os.fstat(input.fileno())[6], if(os.fstat(pipe.fileno())[6]!=0): ## this will read up to a large amount data = os.read(pipe.fileno(), 2**16) elif(len(data)): ## if the read was done on the last loop, we can quit done = True #print 'read all' elif((time.time() - start_time) > timeout): ## something went wrong done = True print 'Error; read timed out' else: ## might be starting up the remote process... time.sleep(.01) except (IOError, OSError): print '(IOError, OSError)',(IOError, OSError) done = True return [error, data] def driveRemote(stdinput, stdoutput, resp): """ takes pipes and a string to send always gets the current DOS output first... """ timeOut, result = getDataFrom(stdoutput) if timeOut: print 'timedOut resp', result return timeOut print "remote:'%s'" % result[-60:], if (result==('' or None)): dlg = wxMessageDialog(parent, "resp not received!"+"\nGot '"+result+"'", 'Error', wxOK | wxICON_INFORMATION) try: dlg.ShowModal() finally: dlg.Destroy() pgDlg.Destroy() ## check for errors if (string.find(result, 'run-time error')>-1): print resp, '\n' dlg = wxMessageDialog(None, result, 'Error!', wxOK | wxICON_INFORMATION) try: dlg.ShowModal() finally: dlg.Destroy() return 'error: '+result if resp!=None: try: print resp, '\n' os.write(stdinput.fileno(), resp+'\n') except IOError, e: print 'error; resp, reslt:', resp, result print "IOError %s" % e return result ## actually start, text mode stdinput, stdoutput = win32pipe.popen4("FV4R.EXE", 't') ## go through a list of actions for resp in actionList: result = driveRemote(stdinput, stdoutput, resp) ================ snap ======================= > > Can I run (call? exec? eval?) an external program from inside a Python > > program? > > > >Check out os.popen (in all it's variants); e.g. something like >the following will do what you want: > > import os > > stdin, stdout, stderr = os.popen3('your program goes here') > output = stdout.read() > errors = stderr.read() > stdin.close(); stdout.close(); stderr.close() > > ... do something with 'output' and 'errors' ... > >HTH / Nuff > >-- >http://mail.python.org/mailman/listinfo/python-list From deetsNOSPAM at web.de Thu Nov 4 13:17:48 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 04 Nov 2004 19:17:48 +0100 Subject: New configuration module released References: <2e37dc1.0411030650.ff44840@posting.google.com><4d2dnXe5XY7bmxTcRVn-rw@rogers.com> <2uv9goF2f3161U1@uni-berlin.de> Message-ID: > I'm currently using YAML for configuration syntax. I don't need object > references as in the OP's module, so I'm happy with it. afaik yauml supports these, too. And it even carries type information, which can be nice but sometimes sucks if you want your config file invariant of class names or actual layout. > It's also easy to change for users. Yes, and there exist bindings for different languages. It also tries to be clever about data types. -- Regards, Diez B. Roggisch From alikakakhel3 at hotmail.com Thu Nov 4 14:16:41 2004 From: alikakakhel3 at hotmail.com (Ali) Date: 4 Nov 2004 11:16:41 -0800 Subject: How to use python in matlab References: <8f17f4bc.0410291738.2f3708b8@posting.google.com> Message-ID: <8f17f4bc.0411041116.8655ce2@posting.google.com> John Hunter wrote in message news:... > >>>>> "Ali" == Ali writes: > > Ali> How to use python in matlab? -- > > Could you be more explicit about what you want to do - do you want to > call a python script from within a matlab shell? > > Note that python offers many tools which enable you to *replace* > matlab with python. See > > Numeric - array package with many matlab element wise operations and > functions - http://numpy.sourceforge.net/ > > numarray - the same but with enhanced indexing, better support for > large arrays and > more. http://www.stsci.edu/resources/software_hardware/numarray > > matplotlib - 2D plotting with matlab syntax - > http://matplotlib.sourceforge.net/ > > scipy - a vast collection of numeric tools, including support for > loading and saving mat files - http://www.scipy.org > > and much more.... > > JDH ok so is there a thing I can download that will do the symbolic stuff that matlab can do? From kent3737 at yahoo.com Sun Nov 7 20:25:04 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 07 Nov 2004 20:25:04 -0500 Subject: Stop spaces from appearing when printing to file In-Reply-To: References: Message-ID: <418ec9ff$1_2@newspeer2.tds.net> Brad Tilley wrote: > I'm printing some info into a txt file that will be uploaded into a > MySQL DB. I use ';' as field separaters. How can I stop spaces from > appearing on both sides of the ';' The spaces are a feature of print. To avoid them, use string formatting to create a single output string. > print >> x,';',object,";",AN_string,";",ascii,";",sum Try print >> x, ';%s;%s;%s;%s' % (object, AN_string, ascii, sum) Kent > > My file looks like this: > > ;12345 ; 23456 ; [1,2,3,4,5] ; 15 > > I need it to look like this to make the DB happy: > > ;12345;23456;[1,2,3,4,5];15 From exarkun at divmod.com Thu Nov 11 10:05:00 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 11 Nov 2004 15:05:00 GMT Subject: sockets: How to know when your data is sent In-Reply-To: Message-ID: <20041111150500.20649.129828770.divmod.quotient.2707@ohm> On 11 Nov 2004 06:46:45 -0800, mederis at hotmail.com (Marc Ederis) wrote: >Richie Hindle wrote in message news:... > > If you want to ensure that all the data has been sent before *closing* the > > socket, which sounds like Marc's requirement, you can use > > setsockopt(SO_LINGER): > > > > SO_LINGER > > Sets or gets the SO_LINGER option. The argument is > > a linger structure. > > > > struct linger { > > int l_onoff; /* linger active */ > > int l_linger; /* how many seconds to linger for */ > > }; > > > > When enabled, a close(2) or shutdown(2) will not > > return until all queued messages for the socket > > have been successfully sent or the linger timeout > > has been reached. Otherwise, the call returns imme??? > > diately and the closing is done in the background. > > When the socket is closed as part of exit(2), it > > always lingers in the background. > > > > (from the GNU manpages). I don't believe that's true for shutdown() on > > all platforms, but I do believe it's true for close() / closesocket(). > > Calling it from Python is a bit of a chore involving the struct module, > > and is left as an exercise for the reader. 8-) > > SO_LINGER... Interesting, I'll keep that in mind for the future. In > the end, acknowledging receipt of the data, as it was arriving at the > server, turned out to be the best solution for me. I wanted to be able > to show a progress bar (at the client) of the data being sent. > All this talk of fun socket options is neat, but I'd like to suggest you stick with your current instinct, as you decided for now and in the future. SO_LINGER only lets you know that the peer has ACK'd your data. This means, typically, that it reached a kernel buffer. It says nothing about the application level, and the application level is all you really care about. Doing application-level ACKs is the only really reliable way to know if your data was received. Jp From kent3737 at yahoo.com Sun Nov 28 11:36:59 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 28 Nov 2004 11:36:59 -0500 Subject: [ANN] rpncalc-1.0 RPN Calculator For Python In-Reply-To: References: Message-ID: <41a9fd4e$1_3@newspeer2.tds.net> Ray Buvel wrote: > Module that adds an interactive Reverse Polish Notation (RPN) > interpreter to Python. This interpreter allows the use of Python as > an RPN calculator. You can easily switch between the RPN interpreter > and the standard Python interpreter. > > Home page: http://calcrpnpy.sourceforge.net/ The .tar.gz file seems to be corrupt, opening it with WinZip it uncompresses the .gz then I get "Error reading header after processing 0 entries." Kent From jcarlson at uci.edu Thu Nov 11 14:55:47 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 11 Nov 2004 11:55:47 -0800 Subject: Simple thread pools In-Reply-To: <4190CBE9.5050801@holdenweb.com> References: <4190CBE9.5050801@holdenweb.com> Message-ID: <20041109234944.F8A3.JCARLSON@uci.edu> Steve Holden wrote: > > Josiah Carlson wrote: > > > Steve Holden wrote: [another snip] > > I had initially planned to create a listening socket, and generate a > > bunch of local sockets, then I remembered os.pipe and said to myself, "to > > hell with it, pipes should be faster, they bypass the network stack". > > > Of course the example is then all running on the one machine, which > might influence elapsed times in a way that having servers remote > wouldn't, but it was a neat example just the same. Certainly, it all but removes the latency between sending and receiving data. It also keeps the TCP/IP stack out of it. The main desire was to test the threads+system call slowdown theory, and it corroborated my slowdown statement. > > As they sometimes say, "there is more than one way to skin a cat", > > though let us hope that there isn't any cat skinning. > > > > If your processor spends time maxed out by your script, then you may do > > better by reducing threads (processor limited, and not bandwidth/latency > > limited). As thread count increases, you spend more processor handling > > overhead. If it isn't maxed out, and you are running at the file handle > > limit and/or the bandwidth limit, congrats. > > > Well I'm happy to say I don't appear to be running at *any* limit just > at the moment. But clearly when you are CPU-limited then there's a > balance to be struck between thread-handling overhead and applications > processing. Considering that your application is pushing emails out as fast as possible, and mine is getting emails as fast as possible, then anything can be the bottleneck. The real question one should ask themselves when writing a process that handles (arguably) too much data is "why is it finishing in X minutes instead of X/2?" Then again, as long as the client is happy, it doesn't much matter. > > Now, just because you are using fewer threads, doesn't mean that you > > can't get equivalent throughput. Heck, using a heavily modified variant > > of asyncore, we've been able to handle 50,000 POP3 account checks (login, > > stat, and if necessary: list, uidl, download email, delete email, > > disconnect) every 15 minutes from a laptop. Our biggest issue is > > latency of our connection, but even then, we do well considering that > > this is all with a single thread. > > > The owner of that laptop needs to be given some work. Even *I* don't > check my mail every second :-) It is an automated system, meant to check hundreds of thousands of email accounts every 15 minutes (multiple processors/machines check 50k accounts each processor every 15 minutes or so). > I see we were indeed at cross purposes. The load I'm talking about is > bursty in the extreme - I am communicating with the MX hosts for each of > the receiving domains, and it takes less than 100ms to send some mails. We don't do mx lookups, and our traffic can be bursty, though we use dynamic scheduling to reduce/remove burstiness. Some of our accounts do complete fast, but others are on machines accross the world with low bandwidth and high latency. > For others I have to try several MX hosts to get any response at all > (each one with a 20-second timeout), and the reason I went to the > multi-threaded solution int he first place was to avoid having the whole > process wait on a single recalcitrant MX host. Such things are not necessary. If you keep records of socket instantiation time, last data received time, last data sent time, data transferred, etc., you can poll to disconnect on poor quality of service. We check every 5 seconds for timed out connections, and have found the results to be quite satisfactory. No need to wait on a socket, use select to multiplex. > The client is very happy, as we've seen in increase in reliability and a > 48-fold speed up in elapsed time as a result of the (rather painful) > transition to multi-threading. This is clearly justification for using > 200 parallel threads, as on many threads the dominant factor in the > elapsed time is the remote server response (or absence thereof). I am glad that your client is happy and that threading has been a good solution for you. All I'm saying is that you can get the same kinds of concurrency, same kinds of throughput, same kinds of elapsed times, etc., with an asynchronous approach and a single thread. I suppose 'whatever floats [our] boats' and 'whatever implementation presents itself in the most timely manner'. There is one really nice thing about client programming...you don't need to worry as much about a denial of service attack, as you control the number of threads/forks/sockets/etc. Well...except in the case of a cruel server. > The cases you are taking about may well require a more careful > consideration of threading overhead. There are various reasons we went with an asynchronous approach, among them being gross scalability (thousands of sockets with a Python recompile). - Josiah From devries at idolstarastronomer.com Mon Nov 22 11:44:21 2004 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 22 Nov 2004 08:44:21 -0800 Subject: configure and make for distutils Message-ID: <1101141861.220259.138590@c13g2000cwb.googlegroups.com> The predominant operating system in my workplace is Solaris, with a bit of Linux and MacOS X thrown in. As such people expect to install new software with the sequence: ./configure make make install I've written some python modules and scripts which I packaged as a source distribution with distutils and sent it to some of my colleagues so they could use the software, but despite the fact that I included instructions on how to install the software (namely: type "python setup.py install") I still heard back from several of them asking, "Where is the configure script?" or "How do you compile this thing?" Usually python is installed on their computers, but they have no experience installing python packages and do not seem to read installation instructions. In order to make installation seem more familiar for unix users I have written a configure script that checks the path for python, optionally checks the python version number, and checks to see if distutils is installed. It will optionally check if other modules are installed by trying "import" on them. The configure script is written in shell script and works under Linux and Solaris (though it uses echo -n which means no newline on Linux and apparently nothing under Solaris). It writes a Makefile which will run the appropriate distutils functions. Now unix users can run ./configure make make install without realizing that distutils and python are running under the hood. The script is available from my rarely used blog at http://miyu.idolstarastronomer.com:8080/cgi-bin/cgiwrap/devries/blosxom.cgi/2004/11/22#pyconfig Parts of the configure file where copied from an autoconf generated configure file. The section that checks for a program in the PATH and handles arguments and help are directly copied from a configure script. Please let me know if you think this script is useful and I will be happy to accept any edits anyone might have. Chris From use at reply.to Mon Nov 1 13:29:29 2004 From: use at reply.to (Beretta Vexée) Date: 01 Nov 2004 18:29:29 GMT Subject: question de bonne doc References: <418505b9$0$3662$8fcfb975@news.wanadoo.fr> <1gmkhbc.yxlo8f10l5uq5N%aleaxit@yahoo.com> <4186179a$0$31207$8fcfb975@news.wanadoo.fr> <1gmkp2e.o08a66kodcjxN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) ecrivait dans news:1gmkp2e.o08a66kodcjxN%aleaxit at yahoo.com: > Ah, je vois, merci. Oui, la s?rie O'Reilly "en Concentr?", m?me que > la s?rie "in a Nutshell" en Anglais, c'est plus pour reference, avec > peux d'examples de code. Le "Cookbook" c'est l'envers, mais je ne > croix pas qu'il ait ?t? traduit, malheuresement. Chez le m?me editeur il y a aussi "Apprendre a programmer avec Python" qui s'addresse plus aux debutant en programations qui a juste ce qu'il faut d'exemple et "Python pr?cis & concis" qui sert vraiment de m?mo de commandes et des fonctions classique. > Essayez alors http://fr.diveintopython.org/index.html, "Plongez au > coeur de Python", peut-?tre vous le trouverez satisfaisant. Perso je trouve toujours la doc papier plus pratique et plus agreable. -- Les fautes d'orthographes sus-cit?es sont d?pos?es aupr?s de leurs propri?taires respectifs. Aucune responsabilit? n'est engag? sur la lisibilit? du message ou les ?ventuelles dommages qu'il peut engendrer. Beretta Vex?e [utilisez l'addresse Reply-to, SVP] From bearophileHUGS at lycos.com Tue Nov 30 04:40:03 2004 From: bearophileHUGS at lycos.com (bearophile) Date: 30 Nov 2004 01:40:03 -0800 Subject: Few things References: <5c882bb5.0411251641.6177ee9d@posting.google.com> <41a756c6$0$25782$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <5c882bb5.0411300140.6ebd9d17@posting.google.com> Thank you for the comments and answers, and sorry for my answering delay... Josiah Carlson: >Decorators can do this without additional syntax. Think @accepts and @returns.< The purpose of those pre-post is to write something simile and very *clean* that states what inputs and outputs must be. This is an example of a pre-post conditional for a sorting function taken from that site (all this is inside the docstring of the function): pre: # must be a list isinstance(a, list) # all elements must be comparable with all other items forall(range(len(a)), lambda i: forall(range(len(a)), lambda j: (a[i] < a[j]) ^ (a[i] >= a[j]))) post[a]: # length of array is unchanged len(a) == len(__old__.a) # all elements given are still in the array forall(__old__.a, lambda e: __old__.a.count(e) == a.count(e)) # the array is sorted forall([a[i] >= a[i-1] for i in range(1, len(a))]) Surely such things can be passed (at least as strings) to the @accepts and @returns decorators (using a "decorate" identifier instead of @ is probably nicer, because the @ makes Python look more like Perl, but I've seen that lots of people have already discussed such topic). Such testing performed by such decorators can be "switched off" with a global boolean flag when the program is debugged and tested. So now someone can write and let standardise a couple of good @accepts and @returns decorators/functors :-] >Having a 'faq' for permutation and combination generation would be 99% of the way there.< Uh, I'm sorry, but I don't understand :-] Aren't such functions quite well defined? >[Fixed] Quickselect, really, doesn't gain you a whole lot. Sure, it's a log factor faster to select a median, but many algorithms involving selecting medians (at least the ones that I run into in CS theory) end up repeatedly (logn times) selecting the 'kth' smallest element (varying k's), where sorting would actually run slightly faster.< I've done some tests with a Quickselect that I have essentially translated and adapted to pure Python from "Numerical Recipes" (it seems a bit faster than the Quickselect coded by Raymond Hettinger that can be seen in the cookbook). I have seen that on my PC, on random sequence of FP numbers, a *single* Quickselect (to find just the median) is faster than the standard sort for lists longer than about 3 million elements. So it's often useless. But using Psyco, that Quickselect becomes 5-6 times faster (for long lists), so it beats the (good) standard Sort for lists longer than 600-3000 elements. If the Quickselect works in place (as the sort) then it returns a partially ordered list, and you can use it to quickly select other positions (so for close positions, like the computing of the two central values for the median, the complexity of the second select is nearly a constant time). So coding the Quickselect in C/Pyrex can probably make it useful. If you are interested I can give the Python Quickselect code, etc. >Raymond Hettinger< I have already seen that this person is working a lot on Python, often in the algorithmic parts. Nick Coghlan>I believe the OP was objecting to the spelling of "this integer literal is hex" and "this integer literal is octal".< Right. Josiah Carlson>Regardless, I also don't believe the "I don't like this" without "this is the way it should be" will result in anything.< You are right, I was mostly afraid of saying silly things... Here is: Such syntax can be like: number (Putting at the beginning of the number is probably worse and it goes against normal base representation in mathematics, where you often subscript the base number). cannot be "B" or "b" (that stands for "base") because number can be a Hex containing B too... So can be "_" (this is the Subscript in TeX markup, so this agrees with normal representation of the base) can be: 1)just an integer number representing the base (similar to the second parameter of "int", this also allows to specify any base). 2) a symbol to represent a smaller class of possibilities, like 0=2, 1=8, 2=10, 3=16, 4=64. Instead of such digits a letter can be used: a=2, b=8, c=10, etc. I think the first option is better. So integer numbers can be written like: 1010100111011_2 154545_10 777_8 afa35a_16 Fi3pK_64 Thank you to Carlos Ribeiro for your development of such doc string ideas, I appreciate them :-] Bear hugs, Bearophile From bearophileHUGS at lycos.com Mon Nov 1 11:35:32 2004 From: bearophileHUGS at lycos.com (bearophile) Date: 1 Nov 2004 08:35:32 -0800 Subject: Few questions Message-ID: <5c882bb5.0411010835.5a409600@posting.google.com> Hello, I have few more things to say/ask (left from a discussion in another Python Newsgroup). Is it possibile (and useful) to write few small sub-sections of the Python interpreter in Assembly for Pentium (III/IV)/AMD, to speed up the interpreter for Win/Linux boxes running on those CPUs? (Such parts don't replace the C versions, kept for compatibilty). I think the HLA (High Level Assembly) language can be fit for this purpose, it's a cute language: http://webster.cs.ucr.edu/AsmTools/HLA/index.html -------- I've done a little comparison of the speed of Python lists and arrays: # speed_test.py from time import clock import sys def array_test(): from array import array v = array("l", [0] * n) t = clock() for i in xrange(len(v)): v[i] = i print "Timing:", round(clock()-t,3), "s" def list_test(): v = [0] * n t = clock() for i in xrange(len(v)): v[i] = i print "Timing:", round(clock()-t,3), "s" n= 3*10**6 if str(sys.argv[1]) == "1": print "List test, n =", str(n) + ":" list_test() else: print "Array test, n =", str(n) + ":" array_test() On a old Win2K PC it gives: C:\py>speed_test 1 List test, n = 3000000: Timing: 2.804 s C:\py>speed_test 2 Array test, n = 3000000: Timing: 3.521 s Python lists are arrays of pointers to objects, I think (a test shows that here they use about 16 bytes for every number). And the Python Arrays are packed: every number here uses 4 bytes. Why do lists are faster here? ------ Memory cleaning: in the last script I've added some calls to a Win version of the small "pslist" program, and I've put a "del v" command after the timings. And I've seen: C:\py>speed_test 1 List test, n = 3000000: 1) Process size: 1408 KB. 2) Process size: 48928 KB. 3) Process size: 37204 KB. C:\py>speed_test 2 Array test, n = 3000000: 1) Process size: 1416 KB. 2) Process size: 13152 KB. 3) Process size: 1416 KB. 1 is at the start of the script before v creation, 2 is after its inizialization loop, and 3 is after the "del v" command, like this: used_mem(1) from array import array v = array("l", [0] * n) for i in xrange(len(v)): v[i] = i used_mem(2) del v used_mem(3) The garbage collector removes at once the array (this is easy, it's just a lump of memory with little extra things), but the memory used by the list isn't free even a little time later. (I think that to understand how/when such such garbage collector works, I have to read the Python C sources...) Thank you, bearophile From rtilley at vt.edu Fri Nov 5 21:40:04 2004 From: rtilley at vt.edu (Brad Tilley) Date: Fri, 05 Nov 2004 21:40:04 -0500 Subject: Python for Reverse Engineering Message-ID: A friend of mine wrote an algorithm that generates strings. He says that it's impossible to figure out exactly how the algorithm works. That may be true, but I think if I had enough sample strings that I could write a program to identify patterns in the strings and then produce strings with similar patterns. He disagrees with me. He gave me 100 strings to analyze. I wrote a script to read each string and build a list of characters present. I've discovered that he only uses 20 alpha/numeric chars to generate the strings and that each string sums up to a value between 1000 and 1200 when I assign each char in the string its ASCII value. What else might I do to analyze these things? As it stands now, I can generate an acceptable string on ever 100th attempt or so, but I'd like to do better than this. -b From fperez528 at yahoo.com Mon Nov 15 17:03:36 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 15 Nov 2004 15:03:36 -0700 Subject: determining the number of output arguments References: <1gnb7hi.1hwbltbftm6c1N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Fernando Perez wrote: > >> suspect that by playing very nasty tricks with sys._getframe(), the dis >> and the inspect modules, you probably _could_ get to this information, at >> least if the caller is NOT a C extension module. But I'm not even 100% >> sure this works, and it would most certainly the kind of black magic I'm >> sure you are not asking about. But given the level of expertise here, I >> better cover my ass ;-) > > Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's > recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd > edition (which I'm supposed to be working on right now -- deadline > closing in, help, help!-). Well, I feel pretty good now: I didn't see Jp's mention of this, and just guessed it should be doable with those three tools. I just looked it up, and it seems it's exactly what I had in mind :) Cute hack, but I tend to agree with Scott Daniels' comment that this kind of cleverness tends to promote rather unreadable code. Maybe I just haven't seen a good use for it, but I think I'd rather stick with more explicit mechanisms than this. Anyway, is it true that this will only work for non-extension code? If you are being called from a C extension, dis & friends are toast, no? Cheers, f From adalke at mindspring.com Wed Nov 10 03:44:00 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 10 Nov 2004 08:44:00 GMT Subject: unicode string literals and "u" prefix In-Reply-To: <4191c722$0$158$9b622d9e@news.freenet.de> References: <418fed14$0$156$9b622d9e@news.freenet.de> <4191c722$0$158$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > If you really need a way of declaring all string literals as Unicode, > on a per-module basis, then > > from __future__ import string_literals_are_unicode Were it to be done, would that also introduce new syntax for generating a byte string? Perhaps b"" as in s = b"\N{LATIN" ? Andrew dalke at dalkescientific.com From riko.wichmann at remove-this.desy.de Tue Nov 30 05:49:14 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Tue, 30 Nov 2004 11:49:14 +0100 Subject: comment out more than 1 line at once? In-Reply-To: References: Message-ID: Ha! have just discover C-c # myself (sometimes it helps to actually look at the emacs menus, even if you are used to using the key-bindings :) Better yet works "Meta-;" as Bernhard suggested, because it comments and un-comments marked line! Thanks for all the helpful tips! - Riko > > Riko, > > if you are using emacs, try C-c # to comment out a block of code. > Unfortunally Uncomment is not bound to a key by default. > Do a key-binding for it by yourself. > > Uwe From kent3737 at yahoo.com Fri Nov 12 08:59:34 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 12 Nov 2004 08:59:34 -0500 Subject: Accessing an instance via its memory address (instance at ...) In-Reply-To: References: Message-ID: <4194c25e$1_2@newspeer2.tds.net> simon.alexandre at cetic.be wrote: > Hi > > I have a list containing several instance address, for example: > > [, , > ] > > I'd like to invoke a method on each of these instance but I don't know : > > 1. if its possible Certainly > 2. how to proceed lst = ... # your list # Call method() for each instance in l for instance in lst: instance.method() # Call method() for a particular instance in lst lst[0].method() Kent From fake at example.com Sat Nov 27 22:32:51 2004 From: fake at example.com (charliek) Date: Sat, 27 Nov 2004 21:32:51 -0600 Subject: mod_python 2.7.10 - publisher References: <41a8fb2d$0$85022$a1866201@visi.com> Message-ID: <41a9471a$0$85026$a1866201@visi.com> > I was wondering if there was a default function in mod_python 2.7.10. > > If not, is there any reasons why I should not add one? Other than the > fact that the current implementation is well tested. > I looked at the source code for the publisher handler and it looks like the 2.7.x version of mod_python does not default to anything. I just added a couple of lines to make it default to the index function. Got to love open source! Thanks, Charlie From urner at alumni.princeton.edu Thu Nov 4 18:03:56 2004 From: urner at alumni.princeton.edu (Kirby Urner) Date: Thu, 04 Nov 2004 15:03:56 -0800 Subject: MySQL blobs confusion Message-ID: <3mclo05un9qh2ojufh02ic8me6o7c2mh11@4ax.com> I've been testing the Cookbook example 8.6 (2002 edition) re using cPickle to insert and retrieve BLOBs from mySQL, using Python's MySQLdb module. When I try to cPickle.loads(blob), I get an error telling me that loads wants a string, not type array.array. So I go cPickle.loads(blob.tostring()) instead and it works. My question is: has something changed in the Python API since this example was written? Here's my version of the code (change commented): import MySQLdb, cPickle def cookbook(): connection = MySQLdb.connect('','root','xxxx','test') cursor = connection.cursor() cursor.execute("CREATE TABLE justatest (name TEXT, ablob BLOB)") try: # Prepare some BLOBs to insert in the table names = 'aramis', 'athos', 'porthos' data = {} for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum, 1) # Perform the insertions sql = "INSERT INTO justatest VALUES (%s, %s)" for name in names: cursor.execute(sql, (name, MySQLdb.escape_string(data[name])) ) # Recover the data so you can check back sql = "SELECT name, ablob FROM justatest ORDER BY name" cursor.execute(sql) for name, blob in cursor.fetchall(): print name, cPickle.loads(data[name]), \ cPickle.loads(blob.tostring()) # note conversion finally: # Done, Remove the table and close the connection cursor.execute("DROP TABLE justatest") connection.close() if __name__ == '__main__': cookbook() Kirby From bokr at oz.net Mon Nov 29 17:14:42 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 29 Nov 2004 22:14:42 GMT Subject: unicode question References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> <41A061E1.8050203@v.loewis.de> <41a0ab62$0$151$9b622d9e@news.freenet.de> <41a1d80d.718896828@news.oz.net> <41a27514$0$179$9b622d9e@news.freenet.de> <41a28c3d.765024687@news.oz.net> <41A33A7D.7090506@holdenweb.com> <41a39160$0$192$9b622d9e@news.freenet.de> Message-ID: <41ab8637.1353306531@news.oz.net> On Tue, 23 Nov 2004 20:37:04 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >Steve Holden wrote: >> Am I the only person who found it scary that Bengt could apparently >> casually drop on a polynomial the would decode to " L?wis"? Well, don't give me too much credit, though I admit enjoying a little unearned flattered-ego buzz ;-) But it's not a big deal if you had recently implemented an automatic lambda-printer-outer to solve for a polynomial function f such that f(0)==k0, f(1)==k1, .. f(n)==kn. For a single number k0 that will be lambda x: k0 and for two numbers k0, k1 will be lambda x: k0 + x*(k1-k0) etc. It's a matter of solving some simultaneous equations for the coefficient values, which I had done in response to a previous thread. For that, I happened to have had some experience from the '60s writing variations on an equation solver (back when we congratulated ourselves on getting all (software-implemented) floating point ops other than divide to execute in under a millisecond ;-) Here I was using an exact decimal module I happened to have (also built in response to previous thread discussion ;-), so I didn't even have to look for maximum abs pivot elements in the matrix for this one. And it didn't have to be fast. So it was kind of a fun exercise. But anyway, it was all ready to go at this point, so all I had to was do was run coeffsx.py with the character ord values as args on the command line. The opportunity to use it in a fun way to fake casual wizardry was just dumb luck ;-) > >I'm not scared, but honored, of course. > A bit late responding, but I couldn't think of a clever followup to that ;-) But Just to play fair, print ''.join([chr((lambda x: ( -6244372133*x**31 +3013910052086*x**30 -695396351572920*x**29 +102105752307741620*x**28 -10715303804974659632*x**27 +855734314951919397204*x**26 -54067713339116101354860*x**25 +2774121296568607137441900*x**24 -117725625258165396333623970*x**23 +4187405270602160539007125440*x**22 -126060225187601954901807327900*x**21 +3234908736910295469078183101700*x**20 -71121878980966418114205095297640*x**19 +1344268902923717571167117226451980*x**18 -21886601404074660751245403749948900*x**17 +307180698948793841846368910776059300*x**16 -3714719218772170154406066269371644945*x**15 +38641327091060849304069885597725238090*x**14 -344757809926306996671359721670334393500*x**13 +2627069115710241704477921121071756668600*x**12 -16998869426095431823754237370045113150352*x**11 +92697362475995606001274610327169882407584*x**10 -421837211162827653880286870838716820642880*x**9 +1581695033356657201434736494281105646218880*x**8 -4805817748883837636614530805204695373091328*x**7 +11572394080794032785251889126742747327087616*x**6 -21417820944419013080374525134500006003159040*x**5 +29141767437911436346798089144038222112768000*x**4 -27186086428826094346108431447644781404160000*x**3 +15339943556592952236643053124047771402240000*x**2 -3882253738078295379102517100266822041600000*x +230239482316981838896315760640000000) /2740946218059307605908520960000000 )(x)) for x in xrange(32)]) Not-ready-to-be-mythologized-though-plenty-flatterable-ly y'rs Regards, Bengt Richter From rstephens at vectron.com Sat Nov 20 15:16:23 2004 From: rstephens at vectron.com (Ron Stephens) Date: 20 Nov 2004 12:16:23 -0800 Subject: Python Tutorials, about 100 and sorted by Topic or Category Message-ID: I have updated my Python Tutorials page with quite a few new ones, and eliminated a few dead links. More importantly, I have now created a clickable menu sorting them by topic and category, as below: Table of Contents New Tutorials (13) For Beginners (11) General and Advanced (13) GUI Programming (21) HTML and XML (7) CGI and Server-Side Programming (4) Windows (4) Database (5) Math, Science, Physics and Bioinformatics (7) Mac (4) Advanced Specific Topics including Idle, Sorting, Unicode, Threads, NumPy, RE, Sockets, Curses, and Boost C ++ (16) Reference (7) I am always interested in finding even more quality tutorials to add this page. LL> missing. I imaging the patent is intended to protect Visual Basic.NET > LL> rather than restrict unrelated languages like Delphi and Python > LL> anyways. > > If it would be applied to Python there would be enough prior art anyway. It is not whether or not Python has prior art but rather what the cost would be to defend a patent infringement lawsuit. But honestly, I believe that is a remote possibility. > And they forgot to put the word 'invention' between quotes. > How stupid can they become? I do not know what the proper form of a US patent application should be. But on my first read of this claim I did find a typo in part 12 of the FIELD OF THE INVENTION section. So this application was not carefully proofread. It needs at least one revision. Besides, many other assertions are plainly wrong. The constructs in parts 3-5 of the above section are not Basic. They are Microsoft's own additions to the language. And to the claim Basic hid pointer arithmetic (part-2) remember PEEK and POKE. No, the scope of this patent will have to be narrowed to VISUAL BASIC-derived languages, which is a very narrow scope indeed. Lenard Lindstrom From alan.gauld at btinternet.com Sun Nov 7 08:56:23 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Nov 2004 13:56:23 +0000 (UTC) Subject: ANN: Updated beginner's tutorial References: Message-ID: On Sun, 7 Nov 2004 12:53:05 +0000 (UTC), Alan Gauld > Enjoy, and as ever send that feedback to me. > > Alan G. > http://www.freenetpages.co.uk/hp/alan.gauld/ > > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 Oops! I forgot to change the .sig! The top one is the correct url for the new tutor. The bottom one is now defunct and was the draft version... Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From deetsNOSPAM at web.de Thu Nov 4 18:08:57 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 05 Nov 2004 00:08:57 +0100 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> Message-ID: I'd suggest using ZODB instead of directly pickling - then every cgi can open the database with its own connection. ZODB will manage concurrency issues. -- Regards, Diez B. Roggisch From tjreedy at udel.edu Thu Nov 11 13:38:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Nov 2004 13:38:07 -0500 Subject: Questions pending - please help References: <200411111110.00909.philippecmartin@sbcglobal.net> Message-ID: "Philippe C. Martin" wrote in message news:200411111110.00909.philippecmartin at sbcglobal.net... > 2) Is there a rule of thumb to follow when writing a c extention which > will > ensure backward compatibility with earlier python versions: The C API changes slowly but it does change. So don't use API functions which have been added or which have changed since the earliest version you want to support. For future compatibility, don't use functions which are deprecated (or which will be ;-). I think changes are documented for each version, but I do not know of any master summary. If there is not one, an info PEP (or web site page) on C API changes would probably be accepted should someone write and submit one. Terry J. Reedy From marc at zeroc.com Wed Nov 24 08:59:58 2004 From: marc at zeroc.com (Marc Laukien) Date: Wed, 24 Nov 2004 08:59:58 -0500 Subject: ANNOUNCE: Ice 2.0 released In-Reply-To: References: Message-ID: Ville Vainio wrote: >>>>>>"Marc" == Marc Laukien writes: > > > Marc> Ice is free software, available with full source, and > Marc> released under the terms of the GNU General Public License > Marc> (GPL). Commercial licenses are available for customers who > Marc> wish to use Ice for closed-source software." > > So, unlike with currently available Python CORBA implementations (and > implementations for other languages as well), you can't use ICE in a > closed source system without paying a fee. Just wanted to point this > out so that nobody got the wrong idea. This *is* a big deal with > middleware / library that would quite probably be adopted in > commercial systems where the managers will feel uneasy about giving up > the control of their "precious" source. That is correct. I thought what I wrote about licensing above was already clear enough, but if you have the need to clarify it even further, that's of course fine :) From mefjr75 at hotmail.com Sun Nov 7 12:31:10 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 7 Nov 2004 09:31:10 -0800 Subject: Color schemes References: <41838c6e$0$7153$d5255a0c@news.wanadoo.nl> <18282ecb.0410301418.1ee469f5@posting.google.com> <418c2006$0$34293$cd19a363@news.wanadoo.nl> <18282ecb.0411061242.7deceef3@posting.google.com> Message-ID: <18282ecb.0411070931.34508476@posting.google.com> "Neil Hodgson" wrote in message > There is a bit of inheritance here: many environments that use Scintilla > start with the default colour scheme used by SciTE which was based on > PythonWin, and I think that PythonWin got the basics (blue keywords and > green comments) from Visual C++. Isn't PythonWin now based on Scintilla too? Circular refrences ;) > It is not just the waste of ink. Most printers are very poor at printing > black or dark backgrounds, with ink bleeding into characters or light > streaks and other marks on laser printers. > > Neil Good point, the one time I did print light on dark it looked horrible...streaks. While I am at it i want to THANK YOU for your work. I benefit from it every day. Scintilla is awesome, and so are you, thanks Neil! M.E.Farmer From mauriceling at acm.org Fri Nov 5 00:58:09 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 05 Nov 2004 05:58:09 GMT Subject: why python is slower than java? Message-ID: <418b166f$1@news.unimelb.edu.au> This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice From aleaxit at yahoo.com Tue Nov 16 02:14:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 16 Nov 2004 08:14:16 +0100 Subject: int literals and __class__ References: <4197c013$1_1@newspeer2.tds.net> Message-ID: <1gnc423.db0wo1mts12dN%aleaxit@yahoo.com> Steven Bethard wrote: > Dan Bishop yahoo.com> writes: > > You don't have to ask *that* nicely. > > > > >>> 1 .__class__ # notice the space > > > > Why does this work? Or, perhaps my real question is why *doesn't* it work > without the space? Pointers to the appropriate point in the docs would be > fine... I assume it's something about making parsing easier...? It's to make lexing more predictable: it's known as maximal-much lexing (without backtracking: backtracking in lexical analysis would really but really be bad). '1.' (no space) is a token (stands for a float literal). So, '1.__class__' is two tokens: float '1.' followed by identified '__class__'. Alex From ville at spammers.com Wed Nov 3 12:28:37 2004 From: ville at spammers.com (Ville Vainio) Date: 03 Nov 2004 19:28:37 +0200 Subject: Python needs a CPyAN References: Message-ID: >>>>> "Steve" == Stephen Ferg writes: >> Hell, people rarely even mention Perl these days Steve> ----------------------------------------- Steve> location number of hits for Steve> Python Perl Steve> ----------------------------------------- Steve> Monster.com 18 552 ... etc. This does not take away the fact that a few years ago, it was felt that Python is in a bloody fight over popularity with Perl. It was felt that Perl still had this or that over Python; this doesn't seem to be the case anymore. Python is no longer the obscure up-and-coming scripting language. It is used in several high-profile places, while Perl usage seems to be mostly going down in popularity. In the Open Source world, Python aleady seems to have a higher profile than Perl. The popularity of Python is already big enough to not be an impediment for the company to switch over - it may be that there is still a need to switch over in the first place, but that's just a refreshing challenge ;-). Hence, I wouldn't be too worried about competing with Perl. Decision to use a library requires some thinking already, it's not a big additional hurdle to download it from SF/whatever and add it to the company version control system. I wouldn't mind a CPANish system, but the lack of it isn't the bottleneck in Python adoption. -- Ville Vainio http://tinyurl.com/2prnb From danperl at rogers.com Fri Nov 26 00:33:06 2004 From: danperl at rogers.com (Dan Perl) Date: Fri, 26 Nov 2004 00:33:06 -0500 Subject: Subclassing complex with computed arguments References: Message-ID: <99CdncSdrOaJXTvcRVn-og@rogers.com> I need a clarification. Does "sample" have to be an instance of complex or can it be a subclass of complex? So can it be an instance of point as long as point is a subclass of complex? If "sample" has to be an instance of complex and not of a subclass, I think you need to subclass point from complex and override the __new__() method to return an instance of complex and override __init__() to use all your arglist. In that case you also need yet another method to actually create instances of point. If "sample" can be an instance of a subclass of complex, I think you can just subclass point from complex and override only __init__(). There is more in the details I guess, but I would like to first see an answer to the above questions. Dan "Peter Olsen" wrote in message news:a86143fb.0411251430.50665acf at posting.google.com... >I want to define a class "point" as a subclass of complex. > > When I create an instance > > sample = point() > > I want "sample" to "be" a complex number, but with its real and > imaginary parts computed in point()'s __init__ function with their > values based on the arglist. I want to compute with point instances > as though they were native complex numbers, but I want to be able to > define some new methods and over-ride some of complex's existing ones. > > This is probably very simple, but it hasn't been simple to me. > > Please feel free to flame me with RTFM as long as you also tell me > where in TFM to R. > > If you respond, please send a copy directly to me. I seldom have > access to this group. (My primary network isn't connected to the > internet.) > > Peter > pcolsen-at-comcast.net From tony.ha at philips.com Mon Nov 29 05:15:35 2004 From: tony.ha at philips.com (Tony Ha) Date: Mon, 29 Nov 2004 10:15:35 GMT Subject: Python Design Patterns Message-ID: Hello I am learning Python for in the pass ten months, and have brought a few books about Python. Most of them are good books by its only right, and all of them only teach you how to write Python programs using Python syntax and Python ways, but no one single Python book explicitly teaches you on how to analyst your application, and structure your programmes in a way, so that, it is easy to maintain, easily to reuse, (i.e. use loosely couple), and easily to extend or add new features (programming to Interface instead of Implementation) without introduce bugs into your existing working codes. I recently brought a book called "Head First Design Patterns" published by O'reilly. This book is simply a gem. It shows you how to use and apply Design Patterns to analyst and structure your code, so that, the programs can be easy maintains, reuse, modify and extend. (It is the books I have been looking for a long time while I am learning Python, but cannot find one). The only caveat about this book is that the authors use Java (not Python) in the examples. I wonder, can any Python guru out there translate the Java examples in the book into Python examples, or write a similar book in Python, perhaps called "Head First Design Patterns in Python". I think, this will be a great addition to Python books, and a great benefit to Python community. P.S. I am not sure is this the right news group to post this request. From martin at v.loewis.de Tue Nov 23 14:35:21 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 23 Nov 2004 20:35:21 +0100 Subject: unicode question In-Reply-To: <41a28c3d.765024687@news.oz.net> References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> <41A061E1.8050203@v.loewis.de> <41a0ab62$0$151$9b622d9e@news.freenet.de> <41a1d80d.718896828@news.oz.net> <41a27514$0$179$9b622d9e@news.freenet.de> <41a28c3d.765024687@news.oz.net> Message-ID: <41a390fa$0$192$9b622d9e@news.freenet.de> Bengt Richter wrote: >>Because print invokes str() on its argument, unless the argument is >>already a byte string (in which case it prints it directly), or a > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- effectively an assumption that > bytestring.decode('some_unknown_encoding').encode(sys.stdout.encoding) > has already been done, it seems (I'm not arguing against). Not really. sys.stdout really is a byte string, which may or may not *have* an encoding. Python tries to guess, and refuses to in the face of ambiguity: e.g. if sys.stdout is a file, resulting from python mkimage.py > image.gif then sys.stdout really does not *have* an encoding - but it still is a byte stream. So copying the bytes to stdout is a straight-forward thing to do. Of course, "print" should only be used if the stream is meant to transmit characters, and then the bytes written to the stream should use the stream's encoding. This is indeed the assumption - but one that the application author needs to make. > So how about changing print so that it doesn't blindly use str(y) On the C level, this is already possible, through tp_print. Whether or not this should be exposed to the Python level (or whether doing so would just add to the confusion), I don't know. > but instead > first tries to get y.__str__() in case the latter returns unicode? > Then print y can succeed the way print y.__str__() does now. As yet another alternative, print could invoke unicode(), if there is a stream encoding. This would try __unicode__first, then fall back to call __str__. Patches in this direction would be welcome - but the code implementing print is already quite involved, so a redesign (with a PEP and everything) might also be in order. In P3k, this part of the issue will go away, as str() then will return Unicode strings. > I.e., str doesn't know that printing and '%s' can use unicode to good effect > if it available, so for print and str.__mod__ blindly to use str() intermediately > throws away an opportunity to do better ISTM. That is true. Of course, there is already so much backwards compatibility in this that any change to behaviour (such as trying unicode() before trying str()) might break things. Regards, Martin From syd.diamond at gmail.com Wed Nov 3 11:00:15 2004 From: syd.diamond at gmail.com (syd) Date: 3 Nov 2004 08:00:15 -0800 Subject: general class functions References: <4187d1b6$1_2@newspeer2.tds.net> Message-ID: > Instead of > return self.__dict__[name] > you need > raise AttributeError, name Booyah, Kent! This works. For posterity, I'll dump a working code: #!/usr/bin/python class Library(object): def __init__(self,list=None): self.list=list def __getattr__(self,name): if name.startswith("get_"): attrname = name[4:] def filter(value): library=Library() for nation in self.list: if getattr(nation,attrname) == value: library.add(nation) return library return filter else: raise AttributeError,name def add(self,nation): try: self.list.append(nation) except: self.list=[nation] def defineNation(self,name,continent,size): nation=Library.Nation() nation.name=name nation.continent=continent nation.size=size self.add(nation) def getNameList(self): outList=[] for nation in self.list: outList.append(nation.name) return outList class Nation(object): def __init__(self,name=None,continent=None,size=None): self.name=name # eg, Spain self.continent=continent # eg, Europe self.size=size # eg, medium library=Library() library.defineNation('Spain','Europe','medium') library.defineNation('USA','NorthAmerica','large') library.defineNation('Luxembourg','Europe','small') library.defineNation('Portugal','Europe','medium') print library.getNameList() print library.get_continent('Europe').getNameList() From dave at didnt.freeserve.co.uk Fri Nov 5 03:38:21 2004 From: dave at didnt.freeserve.co.uk (Dave Sellars) Date: Fri, 05 Nov 2004 08:38:21 +0000 Subject: py2exe sf.net hosed??? Message-ID: <418b3bf9$0$17580$afc38c87@news.easynet.co.uk> I cannot download py2exe from the sourceforge site, the download page just keeps refreshing but the d/l never starts... http://sourceforge.net/project/py2exe then choose 'Files' --tried with firefox and IE (on windows), no cigar... Anyone else having the same problem, or am I doing something *really* dumb? ;-) From eparker at mail.kickingdragon.com Thu Nov 11 20:44:50 2004 From: eparker at mail.kickingdragon.com (eparker at mail.kickingdragon.com) Date: Thu, 11 Nov 2004 20:44:50 -0500 Subject: Multiple running parsers, different threads, embedded in C++..? Message-ID: <124000-220041151214450865@M2W026.mail2web.com> Hello! I'm new to this list, so please be gentle. :) I've been scouring the net for an answer to this, as well as trying to get a little demo running, but to no avail, so I'm going to plead some help from the court, about a multithreading C++, which embeds Python parsers.. Hopefully I'm dumb, and it's an easy answer. :) So, here goes: I'm trying to embed a Python parser into C++, and so far, it works beautifully (I thought there could be nothing sexier then Python, and then Boost.Python came along too. I could cry, I'm so happy). Now, I want to embed this into an application that is serving web pages (required to be standalone server), however I keep reading about the GIL and how Python is not reentrant. However, it's locking scenario sounds like it try's to make the best of it, and it sounds like other applications make their way around it just fine.. even mod_python (or is that forking, happening?). I'm curious if this restriction will have me wallowing in pain, as it might severely slow down the server? Does anyone know if this will be a huge issue? (I'm grasping at straws here: Python & Boost.Python does EVERYTHING else I need/want. :)) I'm also trying to do a demo app, to test the speed, but I'm actually having problem GETTING threading going.. Perhaps it's my lack of knowledge with the system, but I was wondering if I could solicit some advice? I'm getting errors like the following: Fatal Python error: PyThreadState_Get: no current thread Fatal Python error: PyThreadState_Get: no current thread And as for what my code looks like (as of now, anyways: it's been through more surgery then Michael Jackson, today), it's at the bottom of this message. Is there anything I'm doing horribly wrong? I don't claim to be an expert on threading, but YOU could change this. :) Thanks so much.. Please don't break my heart and tell me I can't use Python. :) -e- unsigned __stdcall ExecutePython(void *) { const char *kFileName = "TestFile.py"; PyObject *pPyFileObject = PyFile_FromString(const_cast(kFileName), "r"); PyRun_SimpleFile(PyFile_AsFile(pPyFileObject), kFileName); Py_DECREF(pPyFileObject); return 0; } int main(void) { Py_Initialize(); PyEval_InitThreads(); const unsigned int kNumThreads = 2; HANDLE hThreads[kNumThreads]; unsigned int threadIDs[kNumThreads]; PyThreadState *tstate = PyEval_SaveThread(); for(unsigned int i = 0; i < kNumThreads; ++i) { PyEval_RestoreThread(tstate); hThreads[i] = (HANDLE)(_beginthreadex(NULL, 0, &ExecutePython, NULL, 0, &threadIDs[i])); tstate = PyEval_SaveThread(); } for(unsigned int i = 0; i < kNumThreads; ++i) { cout << "Waiting for thread #" << i << endl; WaitForSingleObject(hThreads[i], INFINITE ); CloseHandle(hThreads[i]); } PyEval_RestoreThread(tstate); Py_Finalize(); // Python interpreter has ended. return 0; } -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From square690410 at yahoo.com.tw Mon Nov 29 00:36:48 2004 From: square690410 at yahoo.com.tw (Leon) Date: Mon, 29 Nov 2004 13:36:48 +0800 Subject: how to drop all thread ?? Message-ID: if class A( use threading,thread module ) to produce 100 thread,how to drop its (100 thread) when its running From roy at panix.com Mon Nov 8 08:14:28 2004 From: roy at panix.com (Roy Smith) Date: Mon, 08 Nov 2004 08:14:28 -0500 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <1gmw2us.eerwmfbnb899N%aleaxit@yahoo.com> <87vfcgkd3e.fsf@pop-server.bigpond.net.au> Message-ID: In article <87vfcgkd3e.fsf at pop-server.bigpond.net.au>, Israel Raj T wrote: > Roy Smith writes: > > > mention that I know what the program drum is used for on an 029 card > > punch. I am however typing this from my wireless PowerBook :-) > > I hate to say this, but my kids have had 802.11g on their notebooks since > the age of 12 ( ie : nearly 2 years now). That's OK. I once went for a job interview that really made me feel antiquated. The kid who was interviewing me looked at my resume, saw that I had started using Unix in 1977, and said, "Wow, you've been doing Unix longer than I've been alive!". The key to avoiding becoming a dinosaur is to keep learning. If you don't learn something major (a new language, operating system, etc) every year, it won't be too long before you start to sink into the tar pits. From DesertLinux at netscape.net Wed Nov 17 09:32:43 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 17 Nov 2004 14:32:43 GMT Subject: Newbie: Python & ADFGVX Cipher Cracking? Message-ID: Hello, I am working on building a program that cracks "ADFGVX" ciphers. However, I have run into a minor problem, is has to do with figuring out the different potential character re-arrangement combinations. See example below for clarification: The characters "ABC" can be re-arranged in several different possible ways: 1) ABC 2) BAC 3) BCA 4) ACB 5) CAB 6) CBA Is there a python function in which I can sent a string of characters to -- and it will provide me with a list of all possible combinations available? example function call: possCharList = allCombinations("ABC") Any help SINCERELY appreciated!! Byron --- From adalke at mindspring.com Fri Nov 12 18:50:04 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 12 Nov 2004 23:50:04 GMT Subject: regular expressions and internationalization (WAS: permuting letters...) In-Reply-To: References: <67lld8kr76.fsf@aster.homelinux.net> <34Skd.24295$KJ6.17501@newsread1.news.pas.earthlink.net> <4195217c$1@nntp0.pdx.net> <3B8ld.24947$KJ6.15770@newsread1.news.pas.earthlink.net> Message-ID: Steven Bethard wrote: > I looked again at the re module, and it seems that \w and \W do have > internationalization support... Is there any way to match \w but not \d? Maybe > something like: > r'[^\d\W]{4,}' > > This seems to work (maybe?): Yeah, I tried that originally but noticed that digits and '_' are included, which ruined the idea of the scramble. So I opted with the OP's choice and hard-coded just the letters. >>>>p = re.compile(r'[^\d\W]{4,}', re.UNICODE) Nice way to do it. I would also put '_' in that exclude list. > I don't know how to check how this works in different > locales though... I think I don't understand locales well enough either. It looks like I need to use re.UNICODE more often. >>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> import re >>> pat = re.compile(r"[^\d^\W]{4,}", re.UNICODE) >>> GOT = u"G\N{LATIN SMALL LETTER O WITH DIAERESIS}teborg" >>> print GOT.encode("utf8") G?teborg >>> pat.search(GOT).group(0) u'G\xf6teborg' >>> pat = re.compile(r"[^\d^\W]{4,}") >>> pat.search(GOT).group(0) u'teborg' >>> >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'C' >>> So you can see that re.UNICODE uses the Unicode definition of what is a letter despite the locale being C. Therefore, I think your approach is better. Andrew dalke at dalkescientific.com From drew at gremlinhosting.com Sun Nov 28 09:06:30 2004 From: drew at gremlinhosting.com (Andrew James) Date: Sun, 28 Nov 2004 14:06:30 +0000 Subject: Psycopg2 mirror availability Message-ID: <1101650790.7679.3.camel@odin> All, I'd like to be able to use psycopg2's new features for my development work with postgresql, but unfortunately the init.d site seems to be broken and I can't get to the repository there. Does anyone know: a) Why init.d is down, and when it might be back up b) Where I might be able to find a psycopg2 mirror, and c) Whether there's a Gentoo ebuild available? Any help would be much appreciated, Regards, Andrew -- Andrew James From kent3737 at yahoo.com Wed Nov 10 11:10:08 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 10 Nov 2004 11:10:08 -0500 Subject: [development doc updates] In-Reply-To: <41923be3$1_2@newspeer2.tds.net> References: <41923be3$1_2@newspeer2.tds.net> Message-ID: <41923db8$1_2@newspeer2.tds.net> Kent Johnson wrote: > Using Firefox 1.0 and Firefox 1.0PR on Win2K, the tables are missing the > left and right borders. and top. For example in Section 2.3.6, the table of > operations for sequence types, in the 2.3.4 docs I have a black border > on left, right top > and bottom; in the dev docs it is only on the bottom. Also the borders under the header and at the bottom are heavier in the new docs; my guess is that is intentional... Kent From ianb at colorstudy.com Fri Nov 5 18:20:55 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 05 Nov 2004 17:20:55 -0600 Subject: executing python code In-Reply-To: References: Message-ID: <418C0AD7.2090603@colorstudy.com> Darren Dale wrote: > Some time ago I asked about executing a python program or script. For > windows, I was informed that the .py extension could be added to some list > of executable extensions, and then I could just type "mycode" instead of > "python mycode.py". Great advice, worked like a charm. > > I recently jumped ship, and have been running Gentoo Linux for about two > months. Is it possible to get the same behavior on Linux? I thought it > would have something to do with adding the #!/usr/bin/env python line to my > code, but I'm not sure what this is supposed to do (it didnt work, that > much I know.) chmod +x mycode.py ./mycode.py Note: . (the present directory) probably isn't in your $PATH, so you have to use ./ to tell the shell to look in the present directory. Do "echo $PATH" to see where you can put it where it's always accessible. You also have to include the extension. If you want, you can rename it to leave off the extension, and that will work fine. You can also make a symlink, like (as root): cd /usr/local/bin ln -s /path/to/mycode.py mycode ~/bin is also often in the $PATH, instead of putting it in /usr/local/bin. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From ncoghlan at email.com Mon Nov 22 09:14:04 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Tue, 23 Nov 2004 00:14:04 +1000 Subject: Import problem In-Reply-To: References: Message-ID: <41a1f42b$0$25786$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Achim Domma (Procoders) wrote: > Achim Domma (Procoders) wrote: > >> Seems like I'm mixing up something in a very bad way, but I have no >> idea what I'm doing wrong!? > > > I have moved the calculation of VERSION to a module _Version.py which > contains a function Version(), which is imported by __init__.py and > _C.py. That works and is much cleaner, but I would still be happy if > somebody could explain we, what's going wrong. Not an explanation, but even developers on the Python core can't always follow the twists and turns the import logic can go through when importing a package: http://sourceforge.net/tracker/index.php?func=detail&aid=992389&group_id=5470&atid=105470 Cheers, Nick. From eternalsquire at comcast.net Thu Nov 4 00:23:51 2004 From: eternalsquire at comcast.net (The Eternal Squire) Date: Wed, 03 Nov 2004 22:23:51 -0700 Subject: pep 336: Make None Callable Message-ID: In article , The Eternal Squire wrote: >> >>Title: Make None Callable No, *no*, *NO*, and *HELL NO*. OTOH, once the BDFL Pronounces, we can return to laughing and pointing the next time this comes up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing Why not? From bdp003 at hotmail.com Mon Nov 1 04:01:47 2004 From: bdp003 at hotmail.com (Bengt dePaulis) Date: Mon, 01 Nov 2004 09:01:47 GMT Subject: saved sys.path Message-ID: <%Xmhd.29071$g4.544104@news2.nokia.com> I have a local directory that I want to include in my sys.path How to save it permanently? Regards /Bengt From ianb at colorstudy.com Wed Nov 3 00:36:43 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 02 Nov 2004 23:36:43 -0600 Subject: HTML to Text renderer In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E324510E@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E324510E@exchange.hqamor.amorhq.net> Message-ID: <41886E6B.3070903@colorstudy.com> Robert Brewer wrote: > Ian Bicking wrote: > >>Does anyone know of a module that can render HTML to text? Just a >>subset of HTML, really; I'd like to compose emails using

tags and >>whatnot, fill in all the values in the email template, then >>apply word >>wrapping and other formatting. Also, it'll make using Zope Page >>Templates with email easier. >> >>Even if all it supports is

and
that would be enough, but I'm >>hoping there's something even more complete out there. I don't need >>something as general as, say, Lynx; these templates would be written >>with a specific renderer in mind. > > > To clarify: you don't want the HTML tags merely stripped; you want to > replace e.g. br with a line break and p with, say, two line breaks? Right. And word wrapping too. Some other tags would also be interesting:

,
, 
,
,  , and something to control alignment (e.g.,

). -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From Chris at Sonnack.com Tue Nov 2 18:56:03 2004 From: Chris at Sonnack.com (Programmer Dude) Date: Tue, 02 Nov 2004 17:56:03 -0600 Subject: scripting languages vs statically compiled ones References: <3064b51d.0410280904.55f2fa4@posting.google.com> Message-ID: John writes: > Believe it :-). VB5 and VB6 can be compiled to native code and has > more or less identical performance to equivalent C code. And why > should not it? VBA implementation in VB is statically typed, well > optimized and not even as expressive as C. There is no kind of > developer productivity overhead like you see in Python :-). If your VB > code is running slower in VB6, chances are you are using variants and > other less optimizable features. > > VBA in MS Office is interpreted (not even p-code) and your C dll will > improve performance a lot, but not much in VB5/VB6. > > I actually benchmarked this 4 years ago. VB4 code ran 30 times slower > compared to when using a C dll. VB5 code ran at about the same speed > as C. Concur. A while back I thought I could speed up a VB app that had a lot of bit-twiddle operations by writting a C-based DLL for it. Turns out it ran slower that way! Having used the VC++ debugger to step through compiled VB code, I can attest to it being compiled down to native. Ratio is much higher than with, say C or C++... I'd WAG it at about 10:1 or slightly more. From joel at rosdahl.net Fri Nov 19 07:46:20 2004 From: joel at rosdahl.net (Joel Rosdahl) Date: Fri, 19 Nov 2004 13:46:20 +0100 Subject: ANN Python IRCD In-Reply-To: (Joseph T. Bore's message of "Wed, 17 Nov 2004 23:32:47 GMT") References: Message-ID: <87mzxe2ehv.fsf@fluff.rosdahl.net> jbore at tjtech.com (Joseph T. Bore) writes: > I would like to let everyone know about, and release onto the world, > my python IRCD. > > The goals of it were to be small and light, not a full IRC protocol > implementation. To that end, it's under 500 lines of code and just > one file. > > It's stable, and seems ready for others to use, I'll probably spend > the next few releases working on more comments and adding a few more > basic functions. > > I Hope others find it useful.. > > http://pyircd.sf.net Oh. Your project seems very similar to my miniircd (http://joel.rosdahl.net/projects/#miniircd). Maybe we could share efforts? Regards, Joel -- Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From steve at holdenweb.com Mon Nov 1 07:19:00 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 01 Nov 2004 07:19:00 -0500 Subject: OT: Ruby programmers use Python In-Reply-To: <1gmkh2e.14hbem8agi1ieN%aleaxit@yahoo.com> References: <1gmkh2e.14hbem8agi1ieN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > A.M. Kuchling wrote: > ... > >>can just write plain vanilla HTML, being sure to put DIV elements and ID >>attributes in the right places, and then style the pages with CSS. Quixote >>is betting that pure HTML + CSS is the way of the future. > > > Sounds like a pretty safe bet to me, in general terms. I'm not quite > sure how fully a 'plain vanilla HTML' page can be controlled, > looks-wise, with CSS only, but no doubt as generations of CSS succeed > each other the trend is up (though I don't think it's asymptotically > going to 100%, but that's a different issue;-). > > > Alex If you take a look at the Zen garden (http://csszengarden.com/) you will realize that Quixote's bet is probably a good one. I was pleasantly surprised how the recent re-work of www.holdenweb.com made the programming for the site (it's static HTML produced from a database) much less dependent on look-and-feel issues thanks to input from a good designer. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From bartley9 at pacbell.net Tue Nov 16 21:22:55 2004 From: bartley9 at pacbell.net (PyBo) Date: Wed, 17 Nov 2004 02:22:55 GMT Subject: Rounding curiosity Message-ID: <20041116182254.6cb5a603.bartley9@pacbell.net> What's wrong with this picture? >>> x = 500000000.0 >>> y = x / (1024 * 1024) >>> y 476.837158203125 >>> z = round(y, 2) >>> z 476.83999999999997 I have tried this and get the same result using different CPU's and operating systems. Obviously, '476.83999999999997' is not rounded to two decimal places. Or am I doing something wrong? From danperl at rogers.com Sun Nov 21 21:27:43 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 21 Nov 2004 21:27:43 -0500 Subject: Small Database Needed References: Message-ID: "Michael J. Fromberger" wrote in message news:Michael.J.Fromberger-95B81B.20470421112004 at localhost... > Meet a couple of helpful friends: > > http://shorl.com/ > http://tinyurl.com/ > > I hope this helps! Thanks! Never felt the need for tools like that before, but with 3 long URLs they come in real handy! Dan From caleb1 at telkomsa.net Thu Nov 25 22:45:59 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 25 Nov 2004 22:45:59 -0500 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: <41A5EFA9.5030907@arcor.de> Message-ID: Wow, yeh, that's actually much better. I got into python back when map, filter & lambda were still fashionable. The list comprehension is sweeter than the map, that's for sure. > My solution would be: > >>>> keywords = ['my','is'] >>>> sentence = 'hi there my name is caleb' >>>> lsen = sentence.split() >>>> def myfunc(kw,word): > ... if word in kw: > ... return '*%s*' % word > ... else: > ... return word > ... >>>> ans = [ myfunc(keywords, word) for word in lsen ] >>>> ans > ['hi', 'there', '*my*', 'name', '*is*', 'caleb'] >>>> newSentence = ' '.join(ans) >>>> newSentence > 'hi there *my* name *is* caleb' > > Kind Regards > Berthold From jerry at jerrysievers.com Tue Nov 30 09:04:58 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 30 Nov 2004 09:04:58 -0500 Subject: comment out more than 1 line at once? References: Message-ID: Uwe Grauer writes: > Riko, > > if you are using emacs, try C-c # to comment out a block of code. > Unfortunally Uncomment is not bound to a key by default. > Do a key-binding for it by yourself. In Emacs, you can have the comment-region command do uncomment by typing C-u first; C-c # comment region C-u C-c # uncomment region >From the Emacs online help for plain comment-region'. you are probably invoking py-comment-region which is just a python tailored version; Comment or uncomment each line in the region. With just C-u prefix arg, uncomment each line in region. Numeric prefix arg ARG means use ARG comment characters. If ARG is negative, delete that many comment characters instead. Comments are terminated on each line, even for syntax in which newline does not end the comment. Blank lines do not get comments. ...Curiosly, I tried the numeric prefix arg to see it use 2 or more comment chars or delete as many and I get 2x the number of the prefix arg. C-u 2 C-c # and I get; ####def foo(): HTH -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From caleb1 at telkomsa.net Sat Nov 27 21:49:46 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Sat, 27 Nov 2004 21:49:46 -0500 Subject: dictionary initialization References: Message-ID: Peter, Right :) I was trying to kill off (with kindness) a thread that just wasn't making sense. The other respondents gave pretty good technical explanations regarding the dynamic typing rules, but I suspect the OP's assertion was just what I described in the simplest terms I could. Which doesn't make sense as a critical language feature/flaw. thx Caleb On Sat, 27 Nov 2004 12:59:00 -0500, Peter Hansen wrote: > Caleb Hattingh wrote: >> IF this is the point you are making, and the awk functionality >> demostrated in this particular example is a really significant feature >> for you in your specific problem domain, then I must concede that awk >> is probably right for you, and you shouldn't waste your time with >> Python. > > Unfortunately for the logic, if one finds something like > that to be a "really significant feature ... [in a] specific problem > domain", then with Python you can of course create your own > custom data type which behaves exactly as desired. And in fact > it is likely that there is additional behaviour that could be > added that would make the Python approach to the problem *even > simpler than the awk approach*, but maybe that's getting too > much of a good thing... > > Of course, this capability prevents one from whining about how > wonderful a specialized limited-purpose tool is compared to > that waste of space called Python, but if it weren't for people > like that Usenet would have no traffic and we'd all have lives > instead. > > -Peter From theller at python.net Thu Nov 18 10:44:15 2004 From: theller at python.net (Thomas Heller) Date: Thu, 18 Nov 2004 16:44:15 +0100 Subject: PIL for Python 2.4? References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> <419CB9D2.2030504@chamonix.reportlab.co.uk> Message-ID: <1xerqi0g.fsf@python.net> Robin Becker writes: > Christos TZOTZIOY Georgiou wrote: >> On Thu, 18 Nov 2004 14:17:50 +0100, rumours say that Gerhard Haering >> might have written: >> >>>>Has anyone built PIL (1.1.4 or 1.1.5) for Python 2.4? If yes, >>>>please let me know, [...] >>> >>>I haven't. But it would have been useful if you had mentioned which >>>platform ;-) Windows? >> Oh, yes, Windows... On Linux I built it myself. I just don't have >> access to a MS compiler on Windows. >> Sorry for not being clear. > well I have old MS VC++ 6 and building with setup.py Python 2.4b2 > gives an error related to the compiler; :( I guess I need MSVC++ 7. > > I have MSDN subscription, but no idea whether I can get 6 & 7 to coexist. You need 7.1, not 7.0. Aka named Visual Studio .NET 2003. And it coexists with 6.0. Thomas From fuzzyman at gmail.com Fri Nov 12 04:20:19 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 12 Nov 2004 01:20:19 -0800 Subject: ZIP files References: <808f000f.0411100805.7bff7e5d@posting.google.com> Message-ID: <6f402501.0411120120.3f5147d6@posting.google.com> Mike Meyer wrote in message news:... > Ivo Woltring writes: > > > On 10 Nov 2004 08:05:28 -0800, oriana.falco at thalesesec.com (Oriana) > > You might wish to try using a larger buffer than 8192 bytes. BTW, > > note that Python automatically closes the files since the file objects > > are released when the function returns. > > This behavior of file objects isn't guaranteed and doesn't happen in > Jython. It's better - and more pythonic - to explicitly close files. > > After all, explicit is better than implicit. > > <69cbbef2.0411041513.120fc039@posting.google.com> <1gmrrsj.7ljqd6f3sgkfN%aleaxit@yahoo.com> Message-ID: <1gms4py.c7p5cjeee3clN%aleaxit@yahoo.com> Dan Sommers wrote: ... > > "Spawning an external editor and waiting until the user is done using it > > before proceeding" is an important architectural pattern (well examined > > and analyzed in Raymond's "Art of Unix Programming", like many others). > > Tty based Unix programs, yes; modern GUIs, no. The usual parent-child > relationship between application and editor is nowhere to be found these > days. Consider this scenario: And yet, as a user, I vastly prefer those apps which, even if they have their own GUIs, still let me edit stuff with my text-editor of choice, say GVIM or Emacs, even when that editor, too, is a "modern GUI" app. Yes, the process relationship may be murkier and therefore it can be harder for the driving app to find out when the user is done editing that file -- nevertheless, I can be SO much more productive with my editor of choice than with whatever the driving app may choose to use for text editing, that, as a user, I still consider that important. > 1. The application requests that Mac OS launch TextEdit and that > TextEdit edit the given file. > > TextEdit starts (or maybe TextEdit was already running) and > opens the document (or maybe the document was already open). > The appliction neither knows nor cares about either of those > details. > > 2. In any event (pun intended), the user edits the file, and maybe > even saves it once or twice just in case there's a crash, and > ponders the configuration before committing to it. > > 3. The user is distracted by, for example, Software Update (which > is very annoying, but it happens), and attends to that matter. > It could be a printer failure, or new email, or anything that > causes the user to start working in another application. > > 4. While Software Update is thrashing, the user remembers that the > configuration file is open but has already been saved, and > closes it by clicking on its window's dimmed close button. > TextEdit processes the event and closes the window without > further ado. > > At which point does the application know that the user is finished > editing the file? The application should somehow be notified after point (4); any earlier time would be inappropriate. > With vi-as-a-child-of-the-application, even if the user spawns a > subshell (and, for that matter, an entire nested X server/session), the > termination of vi is still a well-defined. As is the closing of a document by an app. Whether another app has an easy time or a hard time finding out is another issue, connected with how well designed is the OS/desktop manager/window manager/... that is responsible for coordinating communication between the apps. > > Ideally it should be the external editor of choice for the user; > > foisting vi on poor innocent machistas just because it's easy to wait > > for THAT and hard to wait for TextEdit would seem mean;-)... > > Speaking as a long time Unix hacker *and* long time Mac user, Forcing > machistas to use a text editor instead of a GUI to edit config files > would seem mean. ;-) Speaking as a long time Unix lover who's reasonably recently falled in love with the Mac, just like _many_ others these days, *because* MacOSX *is* now a Unix -- I'd rather keep the option of editing textfiles with a text editor, not be forced to use somebody else's idea of how that particular file should be edited, thankyouverymuch. It's exactly the concept that I _couldn't_ work the way I liked, with a commandline and text editors, that kept my interest in the Mac hovering around 0 for about 19 years. Then, suddenly, I found out that it had become an excellent BSD *plus* a neat GUI layer -- now, *that* was interesting! Developers of Mac apps, mostly -- and therefore developers of infrastructure that runs on Macs to help apps -- apparently haven't yet caught on to this reasonably-new bunch of users, me included, who see MacOSX as just what it IS today -- a BSD with a neat GUI on top (and a Mach underneath, sure, but that's hardly ever relevant;-). Fine, I guess we'll stick with fink and darwinports and the like. But (unless I'm being paid for it) I'm not going to write an application that I would never want to use myself. So, if the only way to shell out to an editor is to write commandline apps instead of GUIs, and use /usr/bin/vi (which IS, after all, one editor Apple that is bundling, to which we can easily shell out), then that's going to be what we do -- until and unless shelling out to TextEdit or BBEdit or whatever is just as easy. Sure, Windows and Linux DEs make it easier because they do preserve the traditional process relationship -- I can start another process running (whatever program, GUI or not) and wait for that process to terminate, rather than having to reuse an existing process that already happens to be running that program. But, since the event I need is "done processing that specific file", I should be able to wait for that, just as easily as I can wait for process termination. Alex From pinard at iro.umontreal.ca Thu Nov 11 08:48:29 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 11 Nov 2004 08:48:29 -0500 Subject: Status of BaseHTTPServer In-Reply-To: <41934512.2060302@sweetapp.com> References: <4e4a11f8.0411110023.52526404@posting.google.com> <41934512.2060302@sweetapp.com> Message-ID: <20041111134829.GA28743@alcyon.progiciels-bpi.ca> [Brian Quinlan] > Patches, bugs, etc. should be done through Sourceforge: > http://sourceforge.net/projects/python They do not offer an email interface. This list does! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From adurdin at gmail.com Tue Nov 2 20:39:44 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 3 Nov 2004 12:39:44 +1100 Subject: scripting languages vs statically compiled ones In-Reply-To: References: <3064b51d.0410280904.55f2fa4@posting.google.com> Message-ID: <59e9fd3a041102173920bb72ec@mail.gmail.com> On Tue, 02 Nov 2004 17:56:03 -0600, Programmer Dude wrote: > > Concur. A while back I thought I could speed up a VB app that had > a lot of bit-twiddle operations by writting a C-based DLL for it. > > Turns out it ran slower that way! > > Having used the VC++ debugger to step through compiled VB code, I > can attest to it being compiled down to native. Ratio is much higher > than with, say C or C++... I'd WAG it at about 10:1 or slightly more. On the other hand, I had to do base64 decoding of a string in a VB app; I got a very significant speed increase by rewriting that portion with a C DLL. So YMMV I guess :) From fredrik at pythonware.com Mon Nov 22 05:22:20 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Nov 2004 11:22:20 +0100 Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> <16798.19563.729805.103774@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > >> My guess is Microsoft hopes to discourage Visual Basic knock-offs. Claim > >> 2 clearly seems to restrict the scope to BASIC. > > Neal> Doesn't Python (along with probably every other language ever > Neal> invented) display prior art here? > > Sure, but maybe there is no such prior art in the BASIC arena. IIRC, the "inventor" mentioned on his weblog that he didn't come up with the idea himself; it was suggested by customers. In other words, the solution clearly wasn't obvious to the "inventor" himself, since he didn't invent it. And if it's not obvious, it can be patented, right? As chewbacca would say, if it doesn't make sense, you must patent! I need coffee. From lbates at syscononline.com Wed Nov 24 18:23:18 2004 From: lbates at syscononline.com (Larry Bates) Date: Wed, 24 Nov 2004 17:23:18 -0600 Subject: GCJ equivalent for Python? In-Reply-To: References: Message-ID: On Windows I use py2exe. It isn't REALLY compiled but the problem you describe doesn't sound like you necessarily want compilation but rather a way to create an easy to distribute program of just a few files. After that I use Inno Installer to create a single setup.exe file that self installs. You didn't say what platform you were on, so this may or may not be helpful to you. When user installs they to have no idea it is "interpreted" Python that is running. Larry Bates Ed Suominen wrote: > I have been programming Python for a year or so and like everything about it > except for the difficulty of distributing programs to someone who doesn't > have the 10MB+ interpreter package downloaded installed. > > I'm a frequent user of pdftk, a Java-based PDF-manipulation program that > runs natively (no JVM required) because it is compiled with gcj. It's > plenty fast and you really never know that it was written in Java unless > you try to build it. > > So, the question naturally arises, why isn't there something like the gcj > compiler for Python? > > Ed Suominen > Registered Patent Agent > Open-Source Software Author (yes, both...) > Web Site: http://www.eepatents.com From vinay_sajip at yahoo.co.uk Wed Nov 3 09:50:17 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 3 Nov 2004 06:50:17 -0800 Subject: ANN: New configuration module released Message-ID: <2e37dc1.0411030650.ff44840@posting.google.com> I've just made available the first general release of a configuration module for Python. It has grown out of the need to make configuration easier and more powerful (for developers and end users) than ConfigParser. It's one of the implementations which could be considered in the ConfigParser shootout, mentioned on the Python Wiki at http://www.python.org/moin/ConfigParserShootout What Does It Do? ================ The config module allows you to implement a hierarchical configuration scheme with support for mappings and sequences, cross-references between one part of the configuration and another, the ability to flexibly access real Python objects, facilities for configurations to include and cross-reference one another, simple expression evaluation and the ability to change, save, cascade and merge configurations. This module has been developed on python 2.3 but should work on version 2.2 or greater. A test suite using unittest is included in the distribution. A very simple configuration file (simple.cfg): # starts here message: Hello, world! #ends here a very simple program to use it: from config import Config cfg = Config(file('simple.cfg')) print cfg.message results in: Hello, world! Configuration files are key-value pairs, but the values can be containers that contain further values A simple example - with the example configuration file: messages: [ { stream : `sys.stderr` message: 'Welcome' name: 'Harry' } { stream : `sys.stdout` message: 'Welkom' name: 'Ruud' } { stream : $messages[0].stream message: 'Bienvenue' name: Yves } ] a program to read the configuration would be: from config import Config f = file('simple.cfg') cfg = Config(f) for m in cfg.messages: s = '%s, %s' % (m.message, m.name) try: print >> m.stream, s except IOError, e: print e which, when run, would yield the console output: Welcome, Harry Welkom, Ruud Bienvenue, Yves The above example just scratches the surface. There's more information about this module available at http://www.red-dove.com/python_config.html Comprehensive API documentation is available at http://www.red-dove.com/config/index.html As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. From fredrik at pythonware.com Mon Nov 29 05:03:52 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Nov 2004 11:03:52 +0100 Subject: Building web graphics with Python References: Message-ID: Steven Feil wrote: >I am wondering if there is a light weight Python library for producing > web graphics on-the-fly. There is a C-language library called gd that > can be used in a CGI program to produce gif images. The Library can > be used to produce graphics images that are dynamically generated. I > was wondering if there is something similar for Python. here's one such library: http://www.pythonware.com/products/pil/index.htm if you insist on using GD itself, use the gdmodule: http://newcenturycomputers.net/projects/gdmodule.html From ivy at doramail.com Tue Nov 2 01:51:14 2004 From: ivy at doramail.com (ivy) Date: Tue, 2 Nov 2004 14:51:14 +0800 Subject: How to use Data Structure (such as Tree,link list) by Python? References: Message-ID: Python has built-in list and search tree. If you like , you can write it by yourself. From pete.forman at westerngeco.com Wed Nov 24 11:16:42 2004 From: pete.forman at westerngeco.com (Pete Forman) Date: 24 Nov 2004 16:16:42 +0000 Subject: How to get an item from a simple set? References: Message-ID: Skip Montanaro writes: > Pete> I have a set that contains one item. What is the best way of > Pete> getting at that item? Using pop() empties the set. > > If you just want to grab one arbitrary (though not random) item from the > set, try: > > elt = iter(s).next() I actually wanted to append the single item to a string, Steven's solutions work for assignment. So this looks like my best bet. I'll probably use join instead of += in my code. >>> line = 'bar ' >>> line += iter(s).next() >>> line 'bar foo' -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- opinion of Schlumberger, Baker http://petef.port5.com -./\.- Hughes or their divisions. From Andrew at ferndale.net.nz Sun Nov 21 15:20:08 2004 From: Andrew at ferndale.net.nz (Andrew A. Cox) Date: Mon, 22 Nov 2004 09:20:08 +1300 Subject: Floating point -> string conversions Message-ID: <9DA3F6A6D39A8045848BC9F128D093CDCCC1@silver.ferndale.net.nz.local> I disagree with '%d' you have explicitly requested that the number be turned into an integer for use as a string, so you expect that as long as you feed it a number (be it int, long or float) that it changes to a string representation of an integer. Now it may be nice to have a flag that says how you want to round it. -----Original Message----- From: John Fouhy [mailto:jfouhy at paradise.net.nz] Sent: Friday, 19 November 2004 2:47 p.m. To: python-list at python.org Subject: Re: Floating point -> string conversions Steve Holden wrote in message news:... > The fact that %s coerces things makes us expect more of other format > tokens, but what would you expect %d to do with 2147483648.5? I'd expect it to give me "2147483648", since that would be consistent with its other behaviour :-) (eg: eval('"%d" % 1.5') == '1') I guess what annoys me is that python encourages you to not worry about the difference between ints and longs (which is great) (unless you're doing high performance computing), but then something like this can cause code to stop working just because you've passed a border which is almost invisible. (of course, this means that one solution which I would be happy with is for python to reject any non-integer/long arguments to "%d" :-) ) -- John. -- http://mail.python.org/mailman/listinfo/python-list From philippecmartin at sbcglobal.net Fri Nov 12 09:18:08 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 12 Nov 2004 08:18:08 -0600 Subject: Questions pending .... Not anymore Message-ID: <200411120818.08021.philippecmartin@sbcglobal.net> Thank you all for your answers: 1) I will generate binaries and use as few as possible python calls in my extentions: 2) doing a set_next in overwritten bdb user_line (instead of set_step) + useing set_break instead of handling it myself did speed things up greatly. Appreciate the help. Philippe From jcarlson at uci.edu Wed Nov 3 19:27:09 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 03 Nov 2004 16:27:09 -0800 Subject: threads and exception in wxPython In-Reply-To: <10ois9flj489d5e@corp.supernews.com> References: <10ois9flj489d5e@corp.supernews.com> Message-ID: <20041103161001.F7F5.JCARLSON@uci.edu> Jeff Shannon wrote: > > Josiah Carlson wrote: > > >Zunbeltz Izaola wrote: > > > > > >>If I put some code after the .start() method the queue will be > >>empty. Do I need to insert a infinite loop to see when the exception > >>is raised? > >> > >> > > > >In your main thread (the one handling the GUI), you can set up a > >wx.Timer() whose bound event checks the queue every second or so. > > > >As another poster mentioned, you can also post events to the GUI, which > >can either say "there is an exception traceback in the queue" or "here > >is the exception traceback". > > > > > > Another possibility is to check the queue in an idle-event handler. > When you place something in the queue, you can call wx.WakeUpIdle() to > ensure that the main thread will do idle processing at its soonest > opportunity. The only ugly part about idle handling is that idle handlers are called quite often (at least in the wxPython versions I've run). Specifically, whenever I move my mouse over a wxPython app window, idle events are streamed to the idle event handler at 30-60 events/second. Not really a big deal, but something people should know about none the less. - Josiah #source I used, lack of new namespace the result of copy/paste from #wxPython wiki from wxPython.wx import wxPySimpleApp, wxFrame, EVT_IDLE import time class myframe(wxFrame): def __init__(self, *args, **kwargs): wxFrame.__init__(self, *args, **kwargs) self.t = None EVT_IDLE(self, self.idle_handler) def idle_handler(self, evt): if self.t is None: self.t = time.time() else: print round(time.time()-self.t, 3), self.t = time.time() evt.Skip() app = wxPySimpleApp() frame = myframe(None, -1, "Ugly Idle Handling") frame.Show(1) app.MainLoop() #output on win2k, Python 2.3.2, wxPython 2.4.2.4 while wiggling my #mouse over the window... C:\Temp>test_idle.py 1.828 0.016 0.015 0.032 0.015 0.016 0.015 0.032 0.031 0.016 0.406 0.547 0.031 0. 016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.01 6 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0. 015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.016 0.01 6 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0. 016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.01 6 0.015 0.016 0.015 0.016 0.016 0.015 0.016 0.016 0.015 0.016 0.015 0.016 C:\Temp> From steven.bethard at gmail.com Tue Nov 23 14:00:30 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 23 Nov 2004 19:00:30 GMT Subject: itertools.islice and slice objects Message-ID: Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 = slice(2, 10) >>> s3 = slice(10) >>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) [2, 4, 6, 8] >>> list(itertools.islice(r, s2.start, s2.stop, s2.step)) Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required >>> list(itertools.islice(r, s2.start, s2.stop, s2.step or 1)) [2, 3, 4, 5, 6, 7, 8, 9] >>> list(itertools.islice(r, s3.start, s3.stop, s3.step)) Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required >>> list(itertools.islice(r, s3.start or 0, s3.stop, s3.step or 1)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Of course, I can get (start, stop, step) tuples with slice.indices, but only if I know the length of the iterable, which kinda defeats the purpose of using itertools... >>> list(itertools.islice(r, *s2.indices(10))) [2, 3, 4, 5, 6, 7, 8, 9] >>> list(itertools.islice(r, *s3.indices(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Steve From zach at cs.uni-bonn.de Mon Nov 8 07:36:34 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 8 Nov 2004 12:36:34 GMT Subject: generic way to access C++ libs? References: Message-ID: > The layout is also modified by various compiler options. really? that would mean that c++ libs themselves are not binary compatible among each other? (You are not talking of that insane issue with M$'s libs when compiled with or without debug info, are you?) > I believe that, > with symbolic debugging information, this feature could be implemented but > it would be a large amount of work. i can believe that. but it would tremendously foster Python's spreading. cheers, gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From steven.bethard at gmail.com Tue Nov 30 02:22:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 30 Nov 2004 07:22:47 GMT Subject: keyword argument for min/max Message-ID: So I've been playing around with trying to add a keyword argument to min and max that works similarly to the one for sorted. It wasn't too hard actually, but it does raise a few questions about proper handling of keyword arguments. Currently, help(max) gives: max(...) max(sequence) -> value max(a, b, c, ...) -> value With a single sequence argument, return its largest item. With two or more arguments, return the largest argument. Now, if 'key' is to be added as an argument, it cannot be accepted as a positional argument because the second form of max tells us that, as a positional argument, the function is just another item to be compared: >>> d = dict(a=3, b=2, c=1) >>> max(d, d.__getitem__) {'a': 3, 'c': 1, 'b': 2} As you can see, the current implementation compares the dict 'd' and its __getitem__ method, and determines that 'd' is larger. For backwards compatibility then, 'key' cannot be accepted as a positional argument. It is possible to allow 'key' only as a keyword argument, and not as a positional argument. This is what my current implementation does: >>> d = dict(a=3, b=2, c=1) >>> max(d) 'c' >>> max(d, d.__getitem__) {'a': 3, 'c': 1, 'b': 2} >>> max(d, key=d.__getitem__) 'a' Notice the different behavior when d.__getitem__ is specified as a keyword argument and when it is specified as a positional argument. My question is, is this a reasonable approach? It's the only one I could think of that seems to guarantee backwards compatibility, but it's a little counterintuitive to me that max(d, d.__getitem__) and max(d, key=d.__getitem__) don't produce the same thing. Steve From jarrodhroberson at yahoo.com Sat Nov 6 14:39:31 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 6 Nov 2004 11:39:31 -0800 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> Message-ID: Maurice LING wrote in message news:... > > Interestingly enough, I sort of share your perception -- and I have > > noticed the same thing, and seen it remarked upon by others, in other, > > completely unrelated newsgroups as well, such as it.comp.macintosh. > > > > It's not, I think, about newbies in general: people who come and post > > help requests, without giving the information that's quite obviously > > indispensabile to let us help them, keep getting treated with > > unreasonable amounts of friendliness and courtesy even after many > > requests for more info go unheeded, for example. > > > > However, newbies who are clueless enough to come blasting in with the > > usual whines we've heard a zillion times -- Macs cost too much, Python > > is too slow, there's no apps for Macs, Python must absolutely add > > feature X or it will die, Apple's gonna go broke tomorrow, etc, etc -- > > do appear to get on our collective nerves worse than their essentially > > indistinguishable precursors did last year, two years ago, &c. > > > > The accusation of being a troll often follows, breaking the old advice > > to "Never attribute to malice what can be adequately explained by > > incompetence". Maybe it's a case of the corollary to that old advice, > > "Sufficiently advanced cluelessness is indistinguishable from malice". > > But why that should be so this year more than last year, say, is not > > clear to me... > > > > > > Alex > > I've already said the following and was not noticed: > > 1. it is a disk intensive I/O operation. > 2. users delay is not in the equation (there is no user input) > 3. I am not interested in the amount of time needed to develop it. But > only interested execution speed. > > Thanks maurice this is still not enough information to give an answer to. and as for "disk intensive" all languages handle disk i/o about the same since they have to rely on the underlying Operating System, its drivers. From donn at drizzle.com Wed Nov 10 00:50:38 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 10 Nov 2004 05:50:38 -0000 Subject: Problem flushing stderr in embedded python References: Message-ID: <1100065836.697971@yasure> Quoth "Farshid Lashkari" : | I don't understand it from a C perspective either. I poked around the source | code for python and found where it is flushing the file. It is simply | calling fflush on the FILE handle. Also, I'm somewhat bewildered as to why | running the string "sys.stderr.flush()" is different than directly calling | the flush method of the stderr object. Oh well, I guess some things are | better left unknown. It could be different if the stderr object - i.e., PySys_GetObject("stderr") - is actually not sys.stderr. I don't understand why, but am not familiar with PySys_*, so I offer that as a hypothesis you might be able to test. By the way, since as you observed it's only calling fflush(), I think you could leave Python out of it altogether and do this with just fflush(stdout); fflush(stderr); Donn Cave, donn at u.washington.edu From tim.golden at viacom-outdoor.co.uk Mon Nov 22 04:39:23 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 22 Nov 2004 09:39:23 -0000 Subject: clear screen / locate cursor Message-ID: peter.mosley at talk21.com] | I am just trying to learn python, to use for some fairly basic command | line utilities which will run in either Windows/DOS or Linux. I cannot | find a platform neutral way of manipulating the screen. | | It seems that under Linux the curses module will do all this and more | (though I haven't tried it), but despite Python documentation curses | does not seem to be available under DOS. A quick google for: Python win32 curses turned up http://flangy.com/dev/python/curses/ as the first hit. Any use? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From levub137 at wi.rr.com Sun Nov 28 12:21:55 2004 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 28 Nov 2004 17:21:55 GMT Subject: [ANN] rpncalc-1.0 RPN Calculator For Python In-Reply-To: <41a9fd4e$1_3@newspeer2.tds.net> References: <41a9fd4e$1_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Ray Buvel wrote: > >> Module that adds an interactive Reverse Polish Notation (RPN) >> interpreter to Python. This interpreter allows the use of Python as >> an RPN calculator. You can easily switch between the RPN interpreter >> and the standard Python interpreter. >> >> Home page: http://calcrpnpy.sourceforge.net/ > > > The .tar.gz file seems to be corrupt, opening it with WinZip it > uncompresses the .gz then I get "Error reading header after processing 0 > entries." > > Kent This is a problem I have encountered with WinZip before. The compressed tar file was created with Python's tarfile module with the 'w:gz' mode. The resulting file works fine with a number of archive packages under Linux and with the tar command in the MKS toolkit under Windows. If I get around to it, I may make a .zip file available for Windows. Until then, I suggest you use Python's tarfile module or something other than WinZip to read it on a Windows platform. Sorry for the inconvenience but I develop on Linux :-) From sean at buildingonline.com Mon Nov 8 15:33:48 2004 From: sean at buildingonline.com (Sean Berry) Date: Mon, 8 Nov 2004 12:33:48 -0800 Subject: Determining combination of bits References: Message-ID: <8KQjd.121796$hj.4674@fed1read07> Just to set everyone's mind at ease... I haven't had a homework assignment for about four years now. I am using two database tables. One will have some options and a code (power of 2). Then, someone will check off checkboxes and submit. The number will be added and saved in a cookie. Then, later, I want to be able to redisplay their choices by reading the value from the cookie. I expect the values will get no bigger than 2^32 = 4294967296. Is this getting too big??? "Terry Reedy" wrote in message news:mailman.6124.1099945664.5135.python-list at python.org... > > "Sean Berry" wrote in message > news:x3Qjd.121786$hj.41260 at fed1read07... >> and I am given some numbers, say 22, 25, and 9. I want to determine the >> keys, powers of 2, that comprise the number. >> How do I get these keys? > > if n%2: print 'has a positive one bit' > > n//2 == n>>1 deletes that bit > > keep track of divisions/shifts and stop when n == 0 > > Terry J. Reedy > > > From cpl.19.ghum at spamgourmet.com Sat Nov 6 04:39:24 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 6 Nov 2004 09:39:24 +0000 (UTC) Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <878y9gbkh7.fsf@pop-server.bigpond.net.au> Message-ID: Israel Raj T wrote in news:878y9gbkh7.fsf at pop- server.bigpond.net.au: > On the updated version at http://shootout.alioth.debian.org/craps.php, > Python beats at least two java implementations. Very interesting link, great ressource!!! What really is disturbing: within the test "hash access" perl2 comes out first compared with java. A know that Python dictionaries are the most heavily used datastructure (because it is allways used within Python itself), and from looking at the sourcecode there is the line "with help from Raymund Hettinger"; so I am very sure it is probably THE optimal coding. So... string processing, regular expression, blablabla no problem; but why second to perl2 in Hash-access ??? Harald From eddie at replicon.com Tue Nov 16 13:57:54 2004 From: eddie at replicon.com (Eddie Parker) Date: Tue, 16 Nov 2004 11:57:54 -0700 Subject: .pyc files... In-Reply-To: Message-ID: <20041116185807.16EB81E4006@bag.python.org> No, I'm not, not always. Doesn't preclude Cygwin, or http://unxtools.sourceforge.net, however... Some days I wish Windows was more like Linux.. Some days I wish Linux was more like Windows.. Ah well, that's the way she goes. :) Thanks for everyone's help on this. ;) Looks like there might be forward movement on this, if not just right yet.. Wish I had time to pick up the patch myself! :) -e- [Assuming OP = Original Poster]. :) -----Original Message----- From: python-list-bounces+eddie=replicon.com at python.org [mailto:python-list-bounces+eddie=replicon.com at python.org] On Behalf Of Jorgen Grahn Sent: November 16, 2004 11:24 AM To: python-list at python.org Subject: Re: .pyc files... On Sun, 14 Nov 2004 16:48:51 -0600, Mike Meyer wrote: > "Simon John" writes: > >> Stephen Waterbury wrote: >> >>> > OK, stupid question, but it's been bothering me for ages.. J >>> > >>> > I love Python to bits, but .pyc files always litter my source tree, >> and >>> > they've always bothered me. ... >> >>> One solution (on unices, at least): >>> >>> alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" >> or with backticks: rm -rf `find . -name '*.pyc'` > > Better with $(: rm -rf $(find . -name '*.pyc'). Yeah, but then you're bash-specific. Or at least that rules sh, csh and tcsh. My weapon of choice would be find . -name '*.pyc' | xargs rm but on the other hand .pyc files don't bother me much ... /Jorgen (who wonders if the OP really was on a Unix system) -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 From niels_bohr at uol.com.br Sat Nov 6 20:50:14 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sat, 06 Nov 2004 23:50:14 -0200 Subject: PEP new assert idiom In-Reply-To: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> Message-ID: <1099792214.8551.19.camel@localhost.localdomain> > > >>> erromsg = 'Errormsg' > > >>> assert statement 1, errormsg > > >>> assert statement 2, 'errormsg > > >>> (...) > > >>> assert statement n, errormsg > > Why isn't this equivalent? Apart from the fact that you keep, here and > elsewhere, using 'statement' where you hopefully mean 'expression' -- > you cannot assert a statement, you can only assert an expression. There is only the conceptually subtle difference that in the 1st you asserts the whole block of expressions, the second you assert each expression. They're likely to be the same, probably they will be equivalent in all cases but I can't backup the truth or falsity of that statement. The pythonic counterpart involves too much typing and is more error prone. > Now, calling expressions expressions, rather than very confusingly > statements, can you explain how the semantics of this, with foo being > called, would differ from those of > > assert exp1 and exp2 and exp3 ... and expN, 'errormsg' This is very similar to what I'm proposing, with the only inconvinience that is uglier to type: assert \ exp1 and \ exp2 and \ ... expn, 'ErrorMsg' Instead of: assert \ exp1, exp2, ... expn, 'Errormsg' Well, I realize I didn't expressed my thoughts very clearly and that it's indeed a very minor change in python's syntax. It won't let anyone does anything new, IFAIK, but it makes a common pattern of code a little more beautiful, (and why not? more expressive). If one consider the fact that it won't break old code (only in one very unlikely case) I don't see it as a completely unreasonable suggestion. Other people may think differently though. Thanks, Fabio From eddie at replicon.com Fri Nov 19 16:24:18 2004 From: eddie at replicon.com (Eddie Parker) Date: Fri, 19 Nov 2004 14:24:18 -0700 Subject: Microsoft Patents 'IsNot' In-Reply-To: <16798.19635.797903.635071@montanaro.dyndns.org> Message-ID: <20041119212434.A47021E4009@bag.python.org> Pardon me, what's "QOTW"? [ Quote|Quiz ] of The Week, is the nearest thing Google tells me. :) -e- -----Original Message----- From: Skip Montanaro [mailto:skip at pobox.com] Sent: November 19, 2004 12:43 PM To: Eddie Parker Cc: 'Neal D. Becker'; python-list at python.org Subject: RE: Microsoft Patents 'IsNot' Eddie> Best way to discourage visual basic knock offs, is to try and use Eddie> visual basic, in my opinion. QOTW? S --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 From cm012b5105 at blueyonder.co.uk Fri Nov 26 17:21:45 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Fri, 26 Nov 2004 22:21:45 +0000 Subject: Introduction/box Message-ID: <200411262221.45343.cm012b5105@blueyonder.co.uk> Hello every body this is my first post i would just like to say im new to to python iv tried out several different tutorials.And i think its great anyway i would like to ask a question if i may i want to know how to make a box /square i was hoping some one would tell me. That way i would have something to work off,iv just downloaded pygame and i haqve done all my practice using "idle" thanks nige From rstephens at vectron.com Sat Nov 20 15:09:30 2004 From: rstephens at vectron.com (Ron Stephens) Date: 20 Nov 2004 12:09:30 -0800 Subject: seeking a new host for the "Python Grimoire" References: Message-ID: I notice that the Grimoire is no longer accessible. Please let us know when it comes back online. I do think it fills a niche. Also, I love the idea of the Grimoire coming back as a Wiki, it seems the perfect candidate for folks to post best practices. Ron Stephens From timr at probo.com Tue Nov 9 02:11:14 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 08 Nov 2004 23:11:14 -0800 Subject: cherrypy/cheetah vs twisted/nevow References: Message-ID: Charlotte wrote: > >Carlos Ribeiro wrote: >> Hi! That was the same reason that got me hooked on CherryPy: it's >> simplicity, and the fact that it seemed so 'obvious' to use. > >Yes, I continue to love it. I wonder why it is not much more used. Do you expose the CherryPy server directly to the public, or do you run a proxy through Apache? I also find CherryPy very natural and easy to understand, but I'm concerned about deployment issues. Every site I do has to share the serverspace with other web apps. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From phil at riverbankcomputing.co.uk Tue Nov 9 04:23:21 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 9 Nov 2004 09:23:21 -0000 (GMT) Subject: Help on installing PyQt on MacOSX 10.3 needed In-Reply-To: <5fb00e69.0411081405.35d40c1b@posting.google.com> References: <5fb00e69.0411081405.35d40c1b@posting.google.com> Message-ID: <32029.82.68.80.137.1099992201.squirrel@82.68.80.137> > Hi, > > I wanted to run a program that is written in PyQt on my mac, and went > over to Riverbank to get PyQ 3.13 and SIP 4.1.1 sources. > > I followed the installation guide except for the compiling python as > Macosx already has python. > > I had no problem with compiling SIP and also no problem with compiling > PyQt nor did I have any error message during make install. > > Now the last step in the install documentation says that I have to > edit several files regarding python itself, and then recompile it. > This is where I got stuck. The mac native python cannot find the > package qt with a import qt command on the commandline, and I have no > experience whatsoever with python. > > Maybe somebody has been successful installing PyQt with the native > python in macosx 10.3 and can help me? Where does it say that you need to re-compile Python? You don't need to touch Python - unless you are deploying applications and want to build a version of Python with PyQt as builtin modules. Phil From jgrahn-nntq at algonet.se Sat Nov 13 04:23:09 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 13 Nov 2004 09:23:09 GMT Subject: generic way to access C++ libs? References: <5V0kd.30218$K7.5461@news-server.bigpond.net.au> Message-ID: On Thu, 11 Nov 2004 12:07:57 GMT, Neil Hodgson wrote: > Neil Hodgson: > > # Much of the time C++ code only has to be compatible with the other > # modules it is delivered with. > > > Jorgen Grahn: > >> But most of the time it has to be compatible with the standard library. >> >> Even if these flags exist, I think it's very rare to encounter more than > one >> layout, for one specific compiler/compiler version/architecture. > > The most commonly changed layout option is structure packing. Many C/C++ > projects decide upon a particular packing option often just to be compatible > with files from the initial version or other applications and libraries. > > [...] C system libraries like standard I/O and platform > libraries like Win32 use explicit compiler instructions to ensure they can > deal with client option choice. The Win32 headers use #pragma pack(n) to > ensure that client code will compile assuming particular packing of system > structures no matter how the client code is packing its own structures. ... I see. Then this seems to me to be a Windows culture issue which I've missed because I'm a Unix person. The GNU and Solaris libcs (and all other Unix shared libraries that I'm aware of) do not do this. Same thing with AmigaDOS, as I recall it. Access these from code compiled with non-standard packing and you're toast. (Some Unix include files (things in /usr/include/netinet/, for example) have structs with elaborate padding so that they can match e.g. an IP header perfectly. This places a restriction on compiler writers, of course.) That also explains to me why so many embedded projects I've been in have messed with structure packing - the architects were Windows people. One reason this is rare in the non-Windows world is (I suppose) that there's often a huge run-time penalty for accessing misaligned words on non-x86 processors. The default layout is almost always the best possible, unless you are low on memory. /J?rgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From __peter__ at web.de Fri Nov 19 16:44:09 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Nov 2004 22:44:09 +0100 Subject: Question about thread References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> <1100879122.755150@eng-ser4> Message-ID: Jarek Zgoda wrote: >> You need to cause the main thread to wait on the child threads until >> they've all finished, otherwise - as Peter Hickman just mentioned - your >> script will terminate and all threads will end. Ten seconds on Google >> found this: >> >> http://www.faqts.com/knowledge_base/view.phtml/aid/1364 > > Are you sure? I keep observing that child threads continue its execution > until completion even if I do nothing in main thread. Consider this > example: You are using the real thing - the highlevel threading.Thread class - not the underlying thread.start_new_thread() function. The threading module creates a _MainThread (a Thread subclass) instance that registers itself as an atexit handler and waits for the other (non-demon) Thread instances to terminate. Failure-to-provide-the-source-code-will-ultimately-work-against -companies-sitting-on-a-pile-of-crap-patents-ly yours Peter From aleaxit at yahoo.com Sun Nov 7 03:10:34 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 Nov 2004 09:10:34 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> <418C7DCB.60502@acm.org> <62kv52-npq.ln1@home.rogerbinns.com> <1gmun13.6rynz217b0hm1N%aleaxit@yahoo.com> <4ab062-2rs.ln1@home.rogerbinns.com> Message-ID: <1gmvh6o.jbx87e1ruu14fN%aleaxit@yahoo.com> Roger Binns wrote: ... > I/O is one area where Java is *very* different than other environments. > Java emphasises the ability to select at runtime (typically from Python's dynamism at runtime is definitely one of its fortes. > Note how in Python, files do read/write whereas sockets do > send/recv. Sure, since the semantics are different. Which is why we have the makefile method of socket objects: for those occasions in which you want signature-polymorphism at the expense of the overhead of adaptation. > But you are comparing Apples to Oranges. Java programs are written > in certain ways with various emphases (flexibility, interfaces and > factories). Python programs emphasise other things (generators, > typing). Exceptions are expensive in Java and not used much. They > are "cheap" in Python and used frequently. Generators are a reasonably recent addition to Python, and I have no idea what you mean by stating that Python emphasizes typing more than Java does -- I typically see far more mention of the types of everything in Java code than in Python, where the usual duck-typing generally obviates the need. Python's flexibility is definitely one of its fortes, and while duck typing obviates much of the need for explicit interfaces, nevertheless they're getting popular in large Python frameworks. And factory-based design patterns are everywhere in Python, of course; indeed, it's in Java that you see lots of 'new ThisClass' constructs which build an instance of some hardwired concrete class -- in Python, instantiation is generally by calling, which makes it trivially easy to arrange for a function, rather than a class, to be called, getting factory-effect. Do not underestimate the flexibility you get by classes and functions being first-class objects, passed as arguments as easily as any other, ready to call for instantiation... In other words, I do not consider your observations to be at all well founded; the one about exceptions is rather inapplicable to the example codes posted so far. If, as the OP claimed, Python is slower than Java for disk-intensive programs, this should be easy for him to show, and I have not seen it shown yet. > >> The Python code is reading the entire string into memory and > >> then writing it. > > > > Right, _Python_'s default. > > Arguably Python's default is reading a line at a time, and it Not for the somefile.read method -- read doesn't do lines. You may be thinking of iter(somefile).next instead, and I'm not sure what the Java equivalent of _that_ one is. > is a bad default in some circumstances (large files), just > as the Java code was a bad way of doing anything but small > files. Python's default makes it trivially easy to read most files in a single gulp, so it's appropriate in many cases; Java's makes it hard and slow to read ANY file, so it's never appropriate. > > The claim posted to this newsgroup, without any support nor examples > > being given, was that Python's I/O was far slower than Java's in > > _disk-intensive_ operations. I'm still waiting to see any small, > > verifiable examples of that posted on this thead. > > If the language code is the same, then that claim boils down to > the Java Native Interface vs the Python C API. In the case of > Java, I can see the claim having some relevance in multi-threaded > code since Java doesn't have the GIL. Python does, but drops it during blocking I/O operations so that the relevance should be just about the same in both cases. > > defaults are tuned, making Python much faster. Great, then let those > > who claim Java's I/O is much faster in disk intensive operation post > > suitable examples, and we'll see. > > Your timing included the overhead of starting up and shutting down > both environments, making the rest of the measure less than > interesting. If the OP intended their claim to apply only to long-running programs where the difference in environment startup/shutdown gets fully amortized, they *MIGHT* have deigned to mention the fact. I have seen no such claim yet, nor as yet ANY benchmark posted that purports to prove anything related to the original claim. I did observe (at some point along the substantial chain of small benchmarks I and some other posters exchanged) that the 4:1 ratio in runtime in favour of Python exactly matched the 4:1 ratio in pagefaults, again in favour of Python, btw. I guess the startup/shutdown costs can be amortized by simply looping over the filecopy operation N times. > The idea isn't to emphasise the open source side, but rather so > that anyone can see for themselves how it was all put together. > If I have a business critical app, and claim it is written in > Python but noone can see the insides then they can't really > know too much. The biggest thing is that they can't tell > if they could write code like that (or even how much was written) > to produce an app of similar functionality and complexity. However, firms that choose not to release their business critical applications as open source are likely to require at the very least a non-disclosure agreement before they show you those sources, making it impractical to use those sources to meet your wishes. Note that even GPL would be no use here: if you do not _distribute_ your programs, but keep them for in-house use, you keep the option to not show anybody those programs' sources even when GPL applies. Therefore, the problem applies equally to all languages, even a hypothetically GPL'd one (not that I know of any GPL-covered language in common use for writing business critical apps). As for your latter sentence, I've never met a programmer whose default assumption was that they would NOT be able to write code just as good as most anybody else's. Alex From autismuk at autismuk.muralichucks.freeserve.co.uk Fri Nov 26 03:35:42 2004 From: autismuk at autismuk.muralichucks.freeserve.co.uk (Paul Robson) Date: Fri, 26 Nov 2004 08:35:42 +0000 Subject: Microsoft Patents 'IsNot' References: <30ijkhF31dg9sU1@uni-berlin.de> <3byxq0a1.fsf@telus.net> Message-ID: On Thu, 25 Nov 2004 17:57:44 +0000, Lenard Lindstrom wrote: >> I believe the author of .NET is the bloke that designed Turbo Pascal, so >> it's hardly surprising :) > > Is this Andreas Heiljberg which you mentioned in an earlier posting to > this thread? Yes.... well the name is something like that. The similarities between Delphi and C# are so obvious if anyone should be suing it's Borland. VB.NET is much much closer to Delphi than it is to VB6.0. From deetsNOSPAM at web.de Tue Nov 23 07:35:01 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 23 Nov 2004 13:35:01 +0100 Subject: Help for newbie References: <419f06a8$0$32335$636a15ce@news.free.fr> <41a10093$0$4569$626a14ce@news.free.fr> <39eca62c.0411222340.35d1c80f@posting.google.com> Message-ID: Jean-Louis Nespoulous wrote: > Thank you very much, but I will use ZODB as a server, and from a > distance client I'll get and save objetcts with XML-RPC. Do you think > it will be ok? You can't get objects using xmlrpc. At least not over language-boundaries. Of cours you can access your python server using xmlrpc, and if thats sufficient, ok. But you can not pass a java object and expect it to be stored in zodb. And I personally wouldn't go for xmlrpc, but corba for java/python interoperability, but thats of course a matter of taste. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sat Nov 6 17:26:47 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 Nov 2004 23:26:47 +0100 Subject: Shortcut needed: avoiding temporary variables with regular expressions References: <418d498f$0$12683$39db0f71@news.song.fi> Message-ID: <1gmurhc.qo6t801s8j7j6N%aleaxit@yahoo.com> Pekka Niiranen wrote: > Hi there, > > I am using regular expressions like this: > > matcher = re.compile(r'(.*)\s(.*)', re.UNICODE) > tmp = matcher.search(mystring) > if tmp: > myvariable = tmp.group(1) > > The idea is that group(1) is accessed only if > it was found from 'mystring'. Is there a way > to avoid the usage of 'tmp' -variable? Yeah, quite a few recipes on the cookbook could help, starting with one of mine, many years old now, about how to do assign-and-test together in Python (the only use case being to transcribe faithfully an algorithm coming from languages that focus on assign-and-test, such as Perl or C; once you move the algorithm fully to Python, it's best to use Python idioms, of course). In my old recipe,, you need to have somewhere an auxiliary class and instance thereof, such as: class Data(object): def set(self, value): self.value = value return value d = Data() then, you can do: if d.set(matcher.search(mystring)): myvariable = d.value.group(1) This is very general and generic. For your specific case, you could do: try: myvariable = matcher.search(mystring).group(1) except (AttributeError, TypeError): pass i.e., just try to access .group even if the search results in None, and simply catch the error that happens when you do (I think it will be an AttributeError, but I'm not sure that holds in all versions you care about, so I threw in a TypeError for good measure;-). Alex From tjreedy at udel.edu Mon Nov 8 15:04:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Nov 2004 15:04:48 -0500 Subject: Yet another Python advocacy meant for students References: <1099933487.007129.62640@z14g2000cwz.googlegroups.com> Message-ID: "Sridhar R" wrote in message news:1099933487.007129.62640 at z14g2000cwz.googlegroups.com... > We are the students of Anna University and would like to share our > thoughts on Python. Here it is > http://cs.annauniv.edu/~portal/wiki/index.php/Python Very nice. Most of us here think that adopting Python as a main language will give you a competitive advantage in your future careers. Suggestion: 1)Your departments main page http://cs.annauniv.edu/ should link 'Anna University' to its main page http://www.annauniv.edu/. 2) I looked there for but did not find an explanation of 'Anna'. Does it refers to a woman, your 'pennies', or something else ;-). 3) Most people around the world have no idea of where Chennai, TN is. A link on the www page to a map with an outline of India and Tamil Nadu within it and a dot/star for Chennai would 'put you on the map' for those of us who are ignorant. Terry J. Reedy (American who has been to northern/central India and but not yet to the south.) From no-mail-please at nospam.com Mon Nov 15 10:36:55 2004 From: no-mail-please at nospam.com (Robert Oschler) Date: Mon, 15 Nov 2004 10:36:55 -0500 Subject: Python generators in Java? Message-ID: Preamble: - I know this is the Python forum - I know about (and have used) Jython I already posted this question in comp.lang.java. But after a week I have still not received a single reply. One of my favorite Python features is generators. I have to use Java for one particular project (it happens). I would like to have something at least close to Python's generators for the project. Jython won't do because last I checked it was dormant, and has been for quite some time. In addition, the version that it is "frozen" at (2.1) does not contain generators (if this is wrong on any point, *please* point me to a URL for a current version). I checked the mailing list archive and except for a single recent post from a party external to the Jython project, there hasn't been any mailing list activity since 2002. In fact, I saw my two unanswered posts about Jython and generators from 2002. There was a 2.2a (alpha release) in July of 2003 with lots of warnings about using the code in a production environment, but nothing since. So does anyone here that has Python and Java experience have any ideas on this? Also, has anybody had any experience integrating CPython with Java, if it is at all possible? Thanks. -- Robert Oschler http://www.robotsrule.com/phpBB2/ Robot & Android Discussion Forum From cme at lampcoders.net Wed Nov 10 14:46:47 2004 From: cme at lampcoders.net (Christian Meissner) Date: Wed, 10 Nov 2004 20:46:47 +0100 Subject: Announce: csv_xs.py References: Message-ID: > Can you explain what you liked about Perl's csv_xz package and/or didn't > like about Python's csv module that motivated you to write your own class? > > Thx, > > Skip I'm a native perl speaker, but at my last work i had to learn python, to edit some zope thinks (quite difficult). Now i wanna learn python for me and i often work with csv files with perl but now i wanna develop some python programs for csv file working. In this task i would extend the csv module for my needs but there i get any errors, so it was easier for me to develop a class which is like the perl one. hope it is ok Chris From jerf at jerf.org Sat Nov 13 04:39:19 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 13 Nov 2004 04:39:19 -0500 Subject: a very newbie question about threading References: <9c3edc58.0411121629.45652543@posting.google.com> Message-ID: On Fri, 12 Nov 2004 16:29:53 -0800, Chris Patton wrote: > Hey Everyone. > > I've recenently stumbled upon a concept known as "threading". Can > anyone tell me what this IS and how it is used, or show me where I can > get information about this? Chris S. gave you the bare-bones basic. I'd add that with no insult intended, "threading" and "very newbie" do not go together well. Threading is the most common source of the notorious "heisenbug", that randomly appears and disappears, resisting capture and elimination by even the best of 'em. It's a complicated topic that gives even the most expert programmers pause. I'm not exaggerating in the slightest. Generally, unless you *know* you need them, you don't, and there are ways around using threads. Threads are kind of like the old "goto" statements; it isn't that the idea of "goto" is intrinsically bad, it is just that without discipline they rapidly become more problem than solution. So instead of "goto", we use certain special cases of them, like function calls and loops, that behave much more nicely. Most thread uses can equally well be satisfied with certain other "special cases" that are much less dangerous, like the "async" module for processing multiple incoming files(/sockets/pipes whatever), or firing off seperate processes for long running computations. That said, I have used them when they were the best tool for the job. But raw threads scare me every time. From ed at leafe.com Mon Nov 1 08:58:28 2004 From: ed at leafe.com (Ed Leafe) Date: Mon, 1 Nov 2004 08:58:28 -0500 Subject: OT: Ruby programmers use Python (was Re: ruby on rails ... python on ?) In-Reply-To: <20041101120902.30033.qmail@engcorp.com> References: <20041101120902.30033.qmail@engcorp.com> Message-ID: <1B1CCD41-2C0E-11D9-949E-003065B11E84@leafe.com> On Nov 1, 2004, at 7:09 AM, Peter Hansen wrote: >> Do you mean Zope? > > Most definitely not! Zope is a "content management system". No, Zope is a web application framework. There is a product called 'Plone' that is a content management system built on Zope, but Zope does quite a bit more than just content management. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From pwatson at redlinepy.com Wed Nov 17 10:52:38 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 17 Nov 2004 09:52:38 -0600 Subject: newbie question References: Message-ID: <301aedF2q0m75U1@uni-berlin.de> "Jeremy Jones" wrote in message news:mailman.6431.1100623812.5135.python-list at python.org... > John wrote: > >>Can python do Shell programming or system programming as perl does? >>Thanks. >> >>John >> > Yes. The only problem is that the perpetual migraine you have from doing > Perl and shell will quickly go away. So, if you're into pain, stick with > Perl and shell. If you want relief, come to Python. > > Seriously, though, Python is an excellent language for doing sysadmin type > tasks. (I'm assuming that's kind of what you wanted?) Most sysadmin type > tasks are in modules whereas with Perl, they're cluttering the toplevel > namespace (I don't think Perl has the concept of namespace, but you get > the drift). So, not knowing what you want to do, you may want to checkout > the os module in Python (I've found os.path.* to be specifically helpful). > You may also want to checkout the shutil module. > Jeremy While I usually use Python, I must admit that doing: $s = `ls -al $thefilename` seems easier and clearer than: import os s = os.popen("ls -al %s" % thefilename) From steven.bethard at gmail.com Wed Nov 17 17:47:45 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 17 Nov 2004 22:47:45 GMT Subject: regular expressions and internationalization (WAS: permuting letters...) In-Reply-To: References: <67lld8kr76.fsf@aster.homelinux.net> <34Skd.24295$KJ6.17501@newsread1.news.pas.earthlink.net> <4195217c$1@nntp0.pdx.net> <3B8ld.24947$KJ6.15770@newsread1.news.pas.earthlink.net> Message-ID: <5yQmd.99846$HA.82149@attbi_s01> Dieter Maurer wrote: > Steven Bethard writes on Fri, 12 Nov 2004 20:15:28 +0000 (UTC): > > > > Is there any way to match \w but not \d? > > It is: r'(?!\d)\w' Yeah, I guess you could use negative lookahead assertions too. My proposed solution to the problem discussed in this thread: >>> re.findall(r'[^\W\d_]{4,}', 'asdg1dfs _asfd s adfsa') ['asdg', 'asfd', 'adfsa'] A solution using a negative lookahead assertion: >>> re.findall(r'(?:(?![\d_])\w){4,}', 'asdg1dfs _asfd s adfsa') ['asdg', 'asfd', 'adfsa'] This seems a fair bit more verbose (and IMHO harder to read) than the solution I proposed, but perhaps you had a clearer version in mind? I tend to shy away from lookahead assertions because IMHO there's usually an easier way. They are occasionally useful though... Steve From alban at magproductions.nl Mon Nov 8 08:19:19 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 08 Nov 2004 14:19:19 +0100 Subject: psycopg, transactions and multiple cursors In-Reply-To: References: Message-ID: Alban Hertroys wrote: > Attached is a simplified example (the except's are a bit blunt, I know) > of what I'm trying to do. In reality, the different cursors are > sometimes run in differeent threads, or they're nested, which is why I > can't use the same cursor for all queries. I suppose the actual error message would be useful too (Doh!): > python transaction.py {'id': 1L} Traceback (most recent call last): File "transaction.py", line 40, in ? cursor2.execute("INSERT INTO y (x_id) VALUES (%s)" % row["id"]) psycopg.IntegrityError: ERROR: insert or update on table "y" violates foreign key constraint "$1" DETAIL: Key (x_id)=(1) is not present in table "x". INSERT INTO y (x_id) VALUES (1) From kent3737 at yahoo.com Sat Nov 20 09:14:18 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 20 Nov 2004 09:14:18 -0500 Subject: Reading Formatted Text File In-Reply-To: References: Message-ID: <419f5004$1_3@newspeer2.tds.net> Kevin McBrearty wrote: > Hello All, > > I'm trying to read a formatted text of strings and > floats. I have looked through previous posts and > couldn't deciper a good method. I'm new to python so > any suggestions would be helpful. Here is a solution using pyparsing (http://pyparsing.sourceforge.net). The result is a nested list structure containing the original data in a structured form blocktype list of facets normal vector list of vertices Kent from pyparsing import * import string point = Literal( "." ) e = CaselessLiteral( "E" ) fnumber = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) + Optional( e + Word( "+-"+nums, nums ) ) ) fnumber.setParseAction( lambda s,l,t: [ float(t[0]) ] ) triple = Group(fnumber + fnumber + fnumber) normal = Suppress('normal') + triple vertex = Suppress('vertex') + triple facet = Suppress('facet') + normal + Suppress('outer loop') + Group(OneOrMore(vertex)) + Suppress('endloop') blockType = Word(string.uppercase) solid = Suppress('solid') + blockType + Group(OneOrMore(facet)) data = ''' solid SIMPLEBLOCK facet normal 0.000000e+00 0.000000e+00 -1.000000e+00 outer loop vertex 1.000000e+00 -1.000000e+00 0.000000e+00 vertex -1.000000e+00 -1.000000e+00 0.000000e+00 vertex -1.000000e+00 1.000000e+00 0.000000e+00 endloop endfacet ''' print solid.parseString(data) prints: ['SIMPLEBLOCK', [[0.0, 0.0, -1.0], [[1.0, -1.0, 0.0], [-1.0, -1.0, 0.0], [-1.0, 1.0, 0.0]]]] > > Regards, > Kevin > > solid SIMPLEBLOCK > facet normal 0.000000e+00 0.000000e+00 -1.000000e+00 > outer loop > vertex 1.000000e+00 -1.000000e+00 0.000000e+00 > vertex -1.000000e+00 -1.000000e+00 0.000000e+00 > vertex -1.000000e+00 1.000000e+00 0.000000e+00 > endloop > endfacet > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > From lbates at syscononline.com Wed Nov 17 11:12:39 2004 From: lbates at syscononline.com (Larry Bates) Date: Wed, 17 Nov 2004 10:12:39 -0600 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: References: Message-ID: I think what you want is : def analysis(self, morf): filename, statements = self.analyze_morf(morf) missing = [] for line in statements: if not self.cexecuted[filename].has_key(line): missing.append(line) return (filename, statements, missing, self.format_lines(statements, missing)) There is complete symmetry. You can return as many "things" as you want. All Jeremy is saying is that it the tuple/list of things gets complex, you should probably refactor your code and make the "things" into a class with the return values as attributes. Larry Bates Robert Brewer wrote: > Greg Ewing wrote: > >>Jeremy Bowers wrote: >> >>>Generally, returning a tuple is either a sign that your return value >>>should be wrapped up in a class, or the function is doing too much. >> >>While I suspect you may be largely right, I >>find myself wondering why this should be so. We >>don't seem to have any trouble with multiple inputs >>to a function, so why should multiple outputs be >>a bad thing? What is the reason for this asymmetry? >> >>Perhaps it has something to do with positional vs. >>keyword arguments. > > > Hm. I'd guess it has more to do with arguments at all. That is, a > function has an input argument list which is metadata with respect to > the function body. There's no such "output argument list", at least not > specified in code. That's the fundamental asymmetry. Maybe we should > support: > > def analysis(self, morf): > filename, statements = self.analyze_morf(morf) > missing = [] > for line in statements: > if not self.cexecuted[filename].has_key(line): > missing.append(line) > end analysis(filename, statements, missing, > self.format_lines(statements, missing)) > > > /ducking and running ;) > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org From tim.peters at gmail.com Mon Nov 15 14:54:23 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 15 Nov 2004 14:54:23 -0500 Subject: Zope 3.0, and why I won't use it In-Reply-To: <4198e036$0$289$edfadb0f@dread12.news.tele.dk> References: <41985663$0$272$edfadb0f@dread12.news.tele.dk> <4198cc5f$0$258$edfadb0f@dread12.news.tele.dk> <4198e036$0$289$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae04111511541a26e236@mail.gmail.com> [Max M] > Shure. I wasn't bitching. I just tried the Window installer yesterday > evening, so I haven't really had time to comment. But I crosspost this > to z3dev (via gmane), and vill continue the discussion there. > > I tried to follow the instructions in the Zope3Book at: ... Ya, I sure agree it's not obvious what to do on Windows! There have been detailed Windows instructions since X3 alpha 1, but subsequent release pages didn't point to them. I see Jim updated the 3.0.0-final release page to include them now: Start from that next time, and it should go much easier. From mr_ravi_patil at yahoo.com Wed Nov 17 03:57:23 2004 From: mr_ravi_patil at yahoo.com (SoftwareTester) Date: 17 Nov 2004 00:57:23 -0800 Subject: psSerial: how to write a single byte value to the serial port? Message-ID: <5a050156.0411170057.6c27a6a4@posting.google.com> http://pyserial.sourceforge.net/ example shows how to write string to serial port. #Open port 0 at "9600,8,N,1", no timeout >>> import serial >>> ser = serial.Serial(0) #open first serial >>> ser.write("hello") #write a string >>> ser.close() #close port how do i write a single byte value to the serial port? From jzgoda at gazeta.usun.pl Fri Nov 19 15:56:30 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Nov 2004 21:56:30 +0100 Subject: Question about thread In-Reply-To: References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> <1100879122.755150@eng-ser4> Message-ID: Craig Ringer wrote: >>When I do it line by line in python's console, I have similar result to youl. >>But when I try to run it in a file, say: >> >>python demo.py >> >>It just returns me nothing. I have no idea on this right now... > > You need to cause the main thread to wait on the child threads until > they've all finished, otherwise - as Peter Hickman just mentioned - your > script will terminate and all threads will end. Ten seconds on Google > found this: > > http://www.faqts.com/knowledge_base/view.phtml/aid/1364 Are you sure? I keep observing that child threads continue its execution until completion even if I do nothing in main thread. Consider this example: import random, time from threading import Thread class Worker(Thread): def __init__(self, name): Thread.__init__(self) self.name = name print 'thread %s created' % self.name def run(self): amt = random.randint(1, 4) print 'thread %s waiting %d seconds' % (self.name, amt) time.sleep(amt) print 'thread %s finished' % self.name def __del__(self): print 'thread %s is being destroyed' % self.name if __name__ == '__main__': for i in range(10): t = Worker('%.04d' % (i + 1, )) t.start() print 'finished creating threads' Even after printing "finished creating threads" all spawned threads continue its execution up to final "thread nnnn is being destroyed", so I think there's no need to take any special action (unless it's Python on iSeries, buy this is another story) to wait for completion. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From changli_to at hotmail.com Sat Nov 20 01:40:32 2004 From: changli_to at hotmail.com (Chang LI) Date: 19 Nov 2004 22:40:32 -0800 Subject: Python with Apache 2.0 References: <89cc6e1f.0411190632.2976b3e1@posting.google.com> <306sikF2sueanU1@uni-berlin.de> Message-ID: <89cc6e1f.0411192240.456eb9bb@posting.google.com> Damjan wrote in message news:<306sikF2sueanU1 at uni-berlin.de>... > > Does python support threads safely along with Apache 2.0 in web > > applications. > > Are you talking about mod_python? > If so, then yes. But note that Apache threads entering the python > interpreter (via mod_python) will be serialized on the GIL. Yes, use mod_python. I plan to use Python to replace PHP and other languages. The low efficient CGI will be replaced by embedded Python program. Apache 2.0 is faviority becuase the threads are must have features. From sadiztik07 at yahoo.com Wed Nov 10 05:25:59 2004 From: sadiztik07 at yahoo.com (HellCat) Date: 10 Nov 2004 02:25:59 -0800 Subject: Looking for a mail server with Python backend. Message-ID: <9832c909.0411100225.39ac124f@posting.google.com> Can anyone here point me to a mail server with a Python backend? The Java Apache Mail Enterprise server is for Java, is there a comparable mail server for Python? I could install JAMES but I prefer to use Python rather than Java. I am going to use it in a small (less than 500 users) enterprise setting so my requirements are not that strict. Thanks in advance. From adsheehan at eircom.net Fri Nov 26 10:01:27 2004 From: adsheehan at eircom.net (Alan Sheehan) Date: 26 Nov 2004 07:01:27 -0800 Subject: Protecting Python source Message-ID: Hi pythonistas, I am looking for methods of deploying applications with end users so that the python code is tamper proof. What are my options ? I understand I can supply .pyc or .pyo files but they can easily be reverse engineered I am told. Is it possible to load the scripts from zip files where the zip files are password protected ? Any other ideas ? Many thanks, Alan From bill.mill at gmail.com Sat Nov 13 01:16:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: 12 Nov 2004 22:16:29 -0800 Subject: numarray + cPickle problem Message-ID: <1100326589.669597.252570@f14g2000cwb.googlegroups.com> Hello all, I've pickled a numarray array object using cPickle like so: pickle = cPickle.Pickler(fout, -1) pickle.dump((myarray, list1, list2)) and this seems to work fine, until I try to load the array back into memory: up = cPickle.Unpickler(fin) myarray, list1, list2 = up.load() which causes an odd traceback: Traceback (most recent call last): File "do_lsi.py", line 7, in ? data, artists, users = up.load() ImportError: No module named generic To which I say, huh? There is indeed a numarray.generic module - but numarray is already included into this file. I tried including numarray.generic, or "from numarray import generic" or "from numarray.generic import *", but none of those did anything. Anybody able to guess what is happeneing here? Anybody that can explain the unpickling process in greater detail for me so that I may understand it better? Peace Bill Mill bill.mill at gmail.com From alban at magproductions.nl Mon Nov 8 09:04:21 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Mon, 08 Nov 2004 15:04:21 +0100 Subject: psycopg, transactions and multiple cursors In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > As the error is about integrity violation, its safe to assume that the > problem is postgresql related. Well, actually it merely shows that the queries aren't in the same transaction, or that there was never a transaction to begin with. That's what I hoped to illustrate with this example; Apparently, I could have been more clear... > And changes made in one transaction can't be seen in another until they are > commited _and_ the other transaction is opened after the first one is > commited - that makes sense, as otherwise the second transaction could > create references that then are invalidated by rolling back the first > transaction, creating undefined state. Of course, that's on of the reasons to have transactions; to make sure that 'other' users don't see data that cannot be guaranteed to be valid yet. > Now looking at your code, one sees that BEGIN is called on the cursor1 - so > the transaction boundaries are around cursor1, thus they are not visible to AFAIK, you can't open a transaction w/o using a cursor; You need a query that says "BEGIN;". You can commit a connection object, however. It would be nice to be able to start a transaction on a connection object, but then you still could only have one transaction per connection... :( This would make it impossible to have nested loops of queries inside a transaction (the cursor gets repositioned in the inner fetch of the loop and the outer fetch looses track of which record it was positioned at). Maybe the transaction shouldn't be closed until the cursor is closed, even if other cursors are opened (in the same transaction) before that happens. Aside from that, it turns out that the first query gets committed, even though the transaction should have failed. This probably just indicates that the transaction indeed is closed too soon, however, I didn't tell it to commit. Shouldn't it issue a rollback instead? [This would probably confuse people, but is it correct to do otherwise? Shouldn't it rollback if you don't commit?] I know PostgreSQL can do transactions on nested cursors, I have used that now and then in stored procedures (pl/pgsql). > So the cursor2 seems to be using its own connection, thus its own > transaction. This is also in the README for psycopg. So that's why I couldn't find the documentation... (Though the DBAPI 2.0 document linked from the Python site is rather helpful). It would probably be nice to have those documents on the psycopg site somewhere... (Or if they are, put clear pointers to them from the main site - I've never been able to find them). > As I don't have psycopg running here, I can't experiment myself, but I think > you should use cursor1 for all of your sql statements that belong to one > transaction. I cross my fingers that such may not be necessary. Thanks for helping. From peter at engcorp.com Wed Nov 24 09:00:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Nov 2004 09:00:02 -0500 Subject: is int(round(val)) safe? In-Reply-To: References: Message-ID: Tim Peters wrote: > [Steve Holden] >>Note, however, that I don't believe it's guaranteed that the contents of >>d will turn out the same in different Python versions. > > If you do > > d[k] = v > > when d already has a key equal to k, its associated value is replaced, > but it's really not defined whether the old key is replaced or > retained. All known implementations of Python retain the old key in > this case. > > The other *seeming* ambiguity here isn't one: whether, in {a: b, c: > d}, a or c is added first. Python requires "left to right" > evaluation, so that's actually defined -- although this one may be > more clearly defined in Guido's head than by the docs. Leading to very interesting results like this: >>> d = { 1: 'a', 1.0: 'b' } >>> d {1: 'b'} Perhaps unexpected, but clearly explained by the comments above... -Peter From fumanchu at amor.org Sun Nov 7 10:42:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 7 Nov 2004 07:42:21 -0800 Subject: remove assert statement (Was: Re: PEP new assert idiom) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3245187@exchange.hqamor.amorhq.net> Gerrit wrote: > In my opinion, assert is almost useless. It can sometimes be > useful for > debugging purposes, but beyond that, it isn't. The exception raised by > 'assert' is always AssertionError. That is a major > disadvantage, because > it's not specific. If a method I'm calling would raise an > AssertionError > in some cases, and I want to catch it, I'm catching too much. > Creating a > new exception-class and raising that one is better because of this. > > I don't see the use of a statement like > "assert isinstance(message, basestring)". It's by far the most common > use of assert: some assertions about the types of the > arguments. This is > at best redundant. In the case of warnings.py, it's followed by > re.compile(message, ...). Removing the assertion in this > example would result > in three differences: > - The error raised would be TypeError, not > AssertionError. Therefore > it's more specific and thus easier to catch. > - The error would me raised by the re module, not warnings module > - The error would be "first argument must be string or compiled > pattern" instead of "message must be a string". Therefore, the > assertion makes it impossible to pass a compiled pattern instead > of a string. > > Duck typing eliminates the use of assert. > > In my opinion, assert should be deprecated and then removed in Py3K: > assertions are redundant, unspecific, and conflict with the philosophy > of duck typing and EAFP. > > What do others think of this? Whole-hearted +1. Let's get it into PEP 3000. There are cases where isinstance is useful (as you point out, when you wish to raise a more meaningful error of your own Exception subclass). But you don't need an assert keyword for that either. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From newsgroups at jhrothjr.com Wed Nov 10 12:04:25 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 10 Nov 2004 11:04:25 -0600 Subject: [development doc updates] References: <41923be3$1_2@newspeer2.tds.net> Message-ID: <10p4igs3vu33o60@news.supernews.com> "Kent Johnson" wrote in message news:41923be3$1_2 at newspeer2.tds.net... > Fred L. Drake wrote: >> The development version of the documentation has been updated: >> >> http://www.python.org/dev/doc/devel/ >> >> Please review the tables and report any strange presentations; be sure >> to include the specific browser (including platform and version!) in >> your report. > > Do you wath the reports here or in the bug tracker? Anyway here is one: > > Using Firefox 1.0 and Firefox 1.0PR on Win2K, the tables are missing the > left and right borders. For example in Section 2.3.6, the table of > operations for sequence types, in the 2.3.4 docs I have a black border on > left, right and bottom; in the dev docs it is only on the bottom. Same problem on Win XP SP2 with Firefox 1.0PR. John Roth > > Kent From danperl at rogers.com Thu Nov 11 20:34:58 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 11 Nov 2004 20:34:58 -0500 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: Maurice, As a member of this group, I regret the comments that you got from "Y2KYZFR1", whatever his name is and whatever his real email address is. Please do not let it affect you and please do not let it affect your view of the group in general. Dan "Y2KYZFR1" wrote in message news:c718a6cf.0411101051.3c8935fd at posting.google.com... > Maurice LING wrote in message > news:... >> > >> > dude that "comparision" from twistedmatrix you refrence is ANCIENT!!! >> >> I am wondering the impact when IBM decided that the base memory to not >> exceed 64kb, in the late 1960s... >> >> I suppose more experienced people in this list can agree that certain >> decisions made can be almost an edict. So, there is a re-building >> process every now and then, hopefully to by-pass such edicts. Python >> itself is already such an example. >> >> > >> > it is comparing versions that are YEARS out of date and use! >> >> Are the codebase of Python 1.5.2 and Java 1.1 totally replaced and >> deprecated? > > yes it has, in both cases : proof again that you don't understand > enough to comprehend why your question is irrelevant, and that you > can't understand the answer as such. > > you can't compare something from so many years ago to each other and > then EXTRAPOLATE the results to NOW. > > It would be like comparing a 1965 Mustang to a 1965 Corvette and then > coming to the conclusion that you could EXTRAPLATE those results to > compare the 2005 models. Just completely lacking in any understanding > of scientific theory. > >> Lisp compiler is the 1st compiler to be created (according to the >> Red-Dragon book, I think) and almost all others are created by >> bootstrapping to LISP compiler. What are the implications of design >> decisions made in LISP compiler then affecting our compilers today? I >> don't know. I repeat myself, I DO NOT KNOW. >> >> > >> > you are just trolling or your don't know enough to understand the >> > answer to your question which is way to vague to be answered, as there >> > is no real correct answer. >> >> Certainly I do not have 15 PhDs in computer science or computating >> mathematics...... I suppose there are some syntax error in your >> statement to allow me to parse it completely. "too vague", not "to >> vague". > > an this just proves that YOU are irrelvant also, go troll somewhere > else. PLONK > >> Thanks >> maurice From minho_chae at yahoo.com Sat Nov 13 13:26:29 2004 From: minho_chae at yahoo.com (Minho Chae) Date: 13 Nov 2004 10:26:29 -0800 Subject: Creating combination of sequences Message-ID: <7dc80c2.0411131026.c4cf2e@posting.google.com> Hello, python lovers!! I'm trying to create combinations of sequences. For example, if the sequence is 'acgt' and the length is 8, then I would like to have 4^8 results such as 'aaaaaaaa', 'aaaaaaac', 'aaaaaaag', 'aaaaaaat', ... 'tttttttt' Is there an easy way doing this? Any help will be greatly appreciated. Minho From finite.automaton at gmail.com Tue Nov 9 14:59:32 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 Nov 2004 11:59:32 -0800 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> <4b39d922.0411051555.24f31663@posting.google.com> Message-ID: <4b39d922.0411091159.3b6e2682@posting.google.com> Hehe. I'm really not trying to start a flame war, honest :P I don't even like Java. My point was just that it's sort of misleading to say "wxPython is faster than Swing, therefore Python tends to be faster than Java for all things". Jacek Generowicz wrote in message news:... > finite.automaton at gmail.com (Lonnie Princehouse) writes: > > > Yes, wxPython is typically quicker than swing. It's not fair to use > > this in a generic Python-vs-Java speed shootout, though, since > > wxPython is just a wrapper around wxWidgets' C++ code; you're really > > comparing C++ vs. Java here. > > And Python's list.sort is just a wrapper around C code. So I guess > that it's not fair to use that, or any other Python built-in function, > in a Python-vs-X speed shootout. This would mean you can't use Python > classes in such a shootout either, as type.__new__ and object.__new__ > are both also merely wrappers around C code ... not to mention Python > dictionaries: wrappers around C code which are used in just about > every name lookup in Python. > > So, the conclusion is that it's not fair to use Python in a > Python-vs-X speed shootout. > > I rather like that conclusion :-) From ncoghlan at email.com Tue Nov 30 07:58:16 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Tue, 30 Nov 2004 22:58:16 +1000 Subject: Restricted Execution on the cheap In-Reply-To: <-OOdncnDLL2e1jHcRVn-hw@lmi.net> References: <-OOdncnDLL2e1jHcRVn-hw@lmi.net> Message-ID: <41ac6e67$0$25782$5a62ac22@per-qv1-newsreader-01.iinet.net.au> David Pokorny wrote: > Hi, > > Suppose that one wants to set up a machine to accept python code from, > say, arbitrary email, and run it safely. Would the following > (somewhat draconian) precautions be sufficient? In short, no. Python's introspection capabilities kill you. There are too many ways to spell things to be certain all the loopholes are closed. For instance, take a look at the result of: type(sys.stdout) Sure, you can add 'type' to the banned list, but eventually the banned list is so long, writing a useful program is damn near impossible. 'chr' and '__dict__', for instance, would almost certainly have to be on the banned list, otherwise: key1 = ''.join([chr(x) for x in [95, 95, 98, 117, 105, 108, 116, 105, 110, 95, 95]]) key2 = ''.join([chr(x) for x in [102, 105, 108, 101]]) sys.modules[key1].__dict__[key2] It isn't accidental that Bastion and rexec got deprecated - the developers just can't guarantee that the modules are actually providing adequate protection. A chroot() jail, setuid() to some permission-less sandbox user and your monitoring daemon are likely to get you a lot further. Regards, Nick. P.S. Both examples above are bizarre ways of spelling 'file', for anyone who can't be bothered figuring it out. From guettli at thomas-guettler.de Mon Nov 22 10:07:24 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 22 Nov 2004 16:07:24 +0100 Subject: Help for a newbie in Python and ZODB References: <39eca62c.0411212341.330dabdc@posting.google.com> Message-ID: Am Sun, 21 Nov 2004 23:41:39 -0800 schrieb Jean-Louis Nespoulous: > Hello everybody, > I am in charge to develop a system who will analyse a network, type > Three-Tier Architecture. I would like to use ZODB or (exclusive) > PostgreSQL. But I don't know witch one to use? > Someone could help me > and tell me what are the differencies between ZODB and PostgreSQL? PostgreSQL is a relational database. You store data in tables which have columns and rows. You access it with SQL. PostgreSQL supports inheritance, but you still need some mapping between your objects and the database. You can access postgres with any programming language. > My system will be developped in Java. If I use ZODB how I'll make the > transition with Python? If you use Java, you can't use ZODB. ZODB stores pickled (serialized) objects. Here you don't need a mapping between objects and database. SQL makes no sense with ZODB. The query language is python. HTH, Thomas From timh at zute.net Tue Nov 9 01:09:53 2004 From: timh at zute.net (Tim Hoffman) Date: Tue, 09 Nov 2004 14:09:53 +0800 Subject: Summary: strong/weak typing and pointers In-Reply-To: <2vaj5oF2jl25lU1@uni-berlin.de> References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> <2vaj5oF2jl25lU1@uni-berlin.de> Message-ID: <41905f33@news.highway1.com.au> Greg Ewing wrote: > JCM wrote: > >> I think both liquids and gases are considered fluids. Liquid Typing >> and Gaseous Typing would be sub-categories. > > > Hmmm. So maybe with liquid typing, your data sloshes > around in the bottom of your address space, whereas > with gaseous typing, it expands to fill all available > memory... > Continuing in this theme, does this mean that phase transition (between solids and fluids ) typing, is typing of an indeterminate nature ;-) Oops now that we are on the slippery slope of metaphors ;-) do we class super cooled liquid types as ones that can be co-oerced but just take a very long time ;-) Tim From autismuk at autismuk.muralichucks.freeserve.co.uk Fri Nov 26 03:33:40 2004 From: autismuk at autismuk.muralichucks.freeserve.co.uk (Paul Robson) Date: Fri, 26 Nov 2004 08:33:40 +0000 Subject: The use of : References: <89cc6e1f.0411251858.40b6bbc7@posting.google.com> Message-ID: On Thu, 25 Nov 2004 18:58:16 -0800, Chang LI wrote: > Some statements use : in the tail such as while x > 0: and def func(): > What is the meaning and the usage of : in Python? It, together with the indent, identifies a block of code. Most languages use either a terminating keyword like "WEND" "ENDIF" "NEXT" to identify the end of a group of instructions, or alternatively a bracketing syntax such as {} begin..end or $( $) So these are roughly equivalent. The difference with the Python version (the last one) is without the indentation it won't work - the indentation does the job of WEND, { } and begin .. end WHILE I > 0 PRINT I I = I-1 WEND while (i > 0) { printf("%d\n",i); i = i-1; } while i > 0 do begin writeln i; i := i - 1; end; while i > 0: print i i = i - 1 this code, unlike most other languages is different to the one above. Changing the indentation actually changes what the code does. while i > 0: print i i = i - 1 it is equivalent to C while (i > 0) { printf("%d\n",i); } i = i-1; From ianb at colorstudy.com Tue Nov 16 12:55:34 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 16 Nov 2004 11:55:34 -0600 Subject: Zope 3.0, and why I won't use it In-Reply-To: References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> Message-ID: <419A3F16.6070401@colorstudy.com> Ville Vainio wrote: >>>>>>"Alex" == Alex Martelli writes: > > > Alex> where builtin 'adapt' does protocol adaptation. On the > Alex> other hand, if the semantics of those 'as' clauses were > Alex> something like: > > Alex> def x(y, z): > Alex> if type(y) is not foo: raise TypeError, 'y must be foo' > Alex> if type(z) is not bar: raise TypeError, 'z must be bar' > Alex> > > Alex> then that's the day I move to Ruby, or any other language > Alex> that remained halfway sensible (if any). > > Even if it allowed portions of the code to be statically compiled to > reach "native" performance? Or if it allowed resolving ambiguous > situations in type inference? Type declarations would of course be > optional, and they could be a big win esp. for non-cpython > implementations of the language. Beats reverting to C#/whatever for > situations where you want good JITtability. In CPython "adaptation" > might be the way to go, of course, but that would still enable the > same code to run on different variants of Python. I would think of it differently. I don't see a need for static typing to deal with the outside world. There's always a bridge when communicating with the outside world, and if that bridge is smart enough it should be okay. You can annotate things (I think type annotation for PyObjC was one of the motivations behind the decorator syntax), that's different from static typing, and is just a guide for coercion. And obviously foreign functions cannot take arbitrary arguments. Nothing in Python can, there's always limits; though foreign functions may not accept immitation objects (e.g., list subclasses), and that's just part of the API. That's why people tend to create wrappers around non-Python libraries. I can see some performance advantages to static typing. I don't think it would be worth it for any external interface, but for internal interfaces it might be worth it, where there's less of a concern about flexibility. In that case, decorators might be all that's necessary, e.g.: @constrain_types(a=float, b=str, c=int: def foo(a, b): c = 1 ... Imagining an implementation of constrain_types that knew how to pick apart a function's code, apply the type information and optimizations, and put it back together. It really doesn't need pretty syntax, because it's not a pretty operation (though the decorator syntax is actually reasonably attractive). It would be nice if this applied both to arguments and local variables. Now, I could imagine this turning into a Cargo Cult programming practice, where people mindlessly apply this type information despite there being no reason or performance gain, thus adding weight to their code and reducing flexibility. But then, I'd rather work under the expectation that the programmer will do the right thing. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From steve at holdenweb.com Thu Nov 18 02:29:06 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Nov 2004 02:29:06 -0500 Subject: SQL Server stored prcedures with output parameters In-Reply-To: References: Message-ID: Steve Holden wrote: > Has anyone, with any driver whatsoever, managed to retrieve output > parameters from a SQL Server stored procedure? I've just been rather > embarrassed to find out it's not as easy as it might seem, and people > are saying bad things about Python as a result :-( > > mx.ODBC, which I regard as a highly-capable module, does not support the > callproc() API, and suggests use of the ODBC call format. It has caveats > in (some of) the documentation implying that output parameters cannot be > handled due to their indeterminate memory requirements, however. > > The adodbapi module does have a stored procedure call in its unit tests, > and manages to pass that test, but when I call my own stored procedure > (which retrieves columns into the output parameters rather than using > SET to establish their values) I get back whatever value I supplied as > the output parameter rather than what the stored procedure is returning. > > So, can anyone help me to fulfill what must be a very common database > requirement? > > regards > Steve Hmmm, following up, added another test to adodbapi to retrieve a value from a table into an output parameter it works, so this puts the suspicion on to the stored procedure. Since this was written by the client I'll take a look at it later (when I'm back in the office) and see what the problem might be. happily-talking-away-to-myself-ly y'rs - steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From rajiv at cbmi.pitt.edu Mon Nov 1 13:32:30 2004 From: rajiv at cbmi.pitt.edu (Wadhwa, Rajiv) Date: Mon, 1 Nov 2004 13:32:30 -0500 Subject: Reading data in lists: Error Message-ID: <09D04633DAED5F489FFEB6A0EAF22C16EAFACD@pikachu.health.pitt.edu> Hello, Saw your name and address on internet regarding a python problem. I am a medical doctor in US taking some Python classes. WE have a problem where we are supposed to find a 'term' (substring) in a list. Format is: [ [ as, fe kd]. [dr ft js] ...]] Is there a way that this words or 'parts' of them( e.g. 'dr' ) can be read from this and then the answer is supposed to write the complete list from where that word or parof it I coming from. Any input would be much appreciated. Thanks, rajiv -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Thu Nov 11 15:37:26 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 11 Nov 2004 20:37:26 +0000 (UTC) Subject: I don't quite get this "string".find() References: Message-ID: Caleb Hattingh telkomsa.net> writes: > > I don't know why the function was set up this way. However, an empty > string can be found in an infinite number of places within any other > string. Infinite might be an exaggeration. Since there are only a finite number of indices into a string (len(s) + 1), there are only a finite number of places an empty sting may be found in any given string: >>> s = 'abc' >>> s.find('') 0 >>> s.find('', 1) 1 >>> s.find('', 2) 2 >>> s.find('', 3) 3 >>> s.find('', 4) -1 You can't, say, find the empty string somewhere between indices 1 and 2. > Also, if you want to check whether a string is empty, I do > > >>> "test" == "" > False An empty string evaluates to False in a boolean context, so you probably don't usually want to actually test like this. A couple of options: >>> s = '' >>> bool(s) False >>> s = '' >>> if s: ... print 'not empty' ... else: ... print 'empty' ... empty My suspicion is that any time you actually test against an empty string, you're probably doing this in the context of an if statement or a while loop, so you can simply use the string directly instead of testing anything. Steve From ncoghlan at email.com Fri Nov 26 10:38:00 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sat, 27 Nov 2004 01:38:00 +1000 Subject: Protecting Python source In-Reply-To: References: Message-ID: <41a74dd9$0$25780$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Alan Sheehan wrote: > Hi pythonistas, > > I am looking for methods of deploying applications with end users so > that the python code is tamper proof. What are my options ? > > I understand I can supply .pyc or .pyo files but they can easily be > reverse engineered I am told. If all you want to prevent is casual user tinkering, just shipping compiled bytecode is probably enough. (yes it *can* be decompiled, but a casual user isn't going to bother, any more than they bother disassembling standard binaries). For slightly greater obfuscation, push the key parts you wish to obscure into a C/C++ extension module. There's nothing to be done to stop the determined cracker, though, as anyone who can effectively reverse engineer pure C++ programs is going to be able to figure out how to interpret .pyc files pretty quickly. > Is it possible to load the scripts from zip files where the zip files > are password protected ? Since the interpreter needs to read your zipfile, there are potential problems with that. I believe it could be done, though. You'd need a C extension module which knew the password and installed a custom import hook to handle opening the zip file. And disassembling the extension module would also give an attacker the password, thus allowing them access to the zipfile. So, as Gerhard said, it really depends on what you mean by "tamper proof". Cheers, Nick. From DesertLinux at netscape.net Tue Nov 30 15:55:24 2004 From: DesertLinux at netscape.net (Byron) Date: Tue, 30 Nov 2004 20:55:24 GMT Subject: comment out more than 1 line at once? In-Reply-To: References: Message-ID: <075rd.8066$NU3.5188@newsread1.news.pas.earthlink.net> Marc Boeren wrote: > Well, you could fake it by doing > > """ > block of code here is commented out > """ """ Yes, this is generally how it is done in python. """ Byron --- From bokr at oz.net Mon Nov 15 02:47:02 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 15 Nov 2004 07:47:02 GMT Subject: range and wx co - ords References: <4191dc09.80425295@news.oz.net> Message-ID: <41985e17.97850521@news.oz.net> On 14 Nov 2004 04:45:25 -0800, mj.clift at virgin.net (Malcolm Clift) wrote: >Hi Bengt, > >I thought that I would be able to work out how to do this, but as I'm >new to python it's harder than I thought... > >Could you tell me how I would get the text to flow on to a new page? > Maybe, but I'd have to know what you meant by that. E.g., are you showing multiple pages at once? Waiting for a page-turn click? Do you need to turn back to previous pages? Once you can spell out _exactly_ what you want to happen in English, you will probably be able to do it in Python. (And when you get more fluent in Python, you will likely prefer to spell such things in Python first ;-) Regards, Bengt Richter From finite.automaton at gmail.com Thu Nov 18 13:05:23 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 18 Nov 2004 10:05:23 -0800 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) References: <30001hF2ptnqcU1@uni-berlin.de> Message-ID: <4b39d922.0411181005.62ca5d67@posting.google.com> Not quite the syntax you want, but better imho since it doesn't involve name redundancy: locals().update( {'a': 1, 'b': 2, 'c': 3} ) Greg Ewing wrote in message news:<30001hF2ptnqcU1 at uni-berlin.de>... > > Maybe things would be better if we had "dict unpacking": > > a, c, b = {'a': 1, 'b': 2, 'c': 3} > > would give a == 1, c == 3, b == 2. Then we could > accept outputs by keyword as well as inputs... From craig at postnewspapers.com.au Fri Nov 19 11:20:16 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 20 Nov 2004 00:20:16 +0800 Subject: Question about thread In-Reply-To: <1100879122.755150@eng-ser4> References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> <1100879122.755150@eng-ser4> Message-ID: <1100881216.5029.5.camel@rasputin.localnet> On Fri, 2004-11-19 at 23:45, Valkyrie wrote: > When I do it line by line in python's console, I have similar result to youl. > But when I try to run it in a file, say: > > python demo.py > > It just returns me nothing. I have no idea on this right now... You need to cause the main thread to wait on the child threads until they've all finished, otherwise - as Peter Hickman just mentioned - your script will terminate and all threads will end. Ten seconds on Google found this: http://www.faqts.com/knowledge_base/view.phtml/aid/1364 -- Craig Ringer From sw at wordtech-software.com Mon Nov 8 20:42:26 2004 From: sw at wordtech-software.com (Kevin Walzer) Date: Mon, 08 Nov 2004 20:42:26 -0500 Subject: Help on installing PyQt on MacOSX 10.3 needed In-Reply-To: <5fb00e69.0411081405.35d40c1b@posting.google.com> References: <5fb00e69.0411081405.35d40c1b@posting.google.com> Message-ID: <9gVjd.928$yk5.254@fe37.usenetserver.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I am working on a PyQt package bundle for OS X. I have everything installed correctly on my Mac (10.3.6), and am running Eric3 without a problem. Building everything isn't terribly difficult, but it is very time-consuming (think two or three days of continuous compiling). Putting together a package installer is actually harder than building it because there are so many moving parts (patch Qt, build Qt, build QScintilla, build SIP, build and install PyQt). I've gotten a Sourceforge project approved, and as soon as I get everything worked out, I will announce the release. So, if you can wait a little longer... svenn.are at bjerkem.de wrote: | Hi, | | I wanted to run a program that is written in PyQt on my mac, and went | over to Riverbank to get PyQ 3.13 and SIP 4.1.1 sources. | | I followed the installation guide except for the compiling python as | Macosx already has python. | | I had no problem with compiling SIP and also no problem with compiling | PyQt nor did I have any error message during make install. | | Now the last step in the install documentation says that I have to | edit several files regarding python itself, and then recompile it. | This is where I got stuck. The mac native python cannot find the | package qt with a import qt command on the commandline, and I have no | experience whatsoever with python. | | Maybe somebody has been successful installing PyQt with the native | python in macosx 10.3 and can help me? | - -- Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBkCCBJmdQs+6YVcoRAh8EAJwNFTUpXnCxV2fBbxIgjPTbiQHItwCgiyeN Kf8GFPCPJOTkK3u3RYbd8JA= =Kmx9 -----END PGP SIGNATURE----- From craig at postnewspapers.com.au Thu Nov 18 05:38:39 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 18 Nov 2004 18:38:39 +0800 Subject: Correct way to handle independent interpreters when embedding in a single-threaded C++ app Message-ID: <1100774319.18258.249.camel@bucket.localnet> Hi folks I'm a bit of a newbie here, though I've tried to appropriately research this issue before posting. I've found a lot of questions, a few answers that don't really answer quite what I'm looking for, but nothing that really solves or explains all this. I'll admit to being stumped, hence my question here. I'm also trying to make this post as clear and detailed as possible. Unfortunately, that means it's come out like a book. I hope a few kind souls will be game to read it, on the theory that I'm a user who's putting in the time to actually provide enough information for once. I have a Python interpreter embedded in a C++/Qt application (Scribus - http://www.scribus.net). Scribus, while using multi-threading enabled libraries, runs in a single 'main' thread. The Python interpreter is implemented as a plug-in that's used to run user scripts. Overall it's working very well. I've run into two problems that are proving very difficult to solve, however, and I thought I'd ask here for some words of wisdom. I'm only tackling the first one right now. First I'll provide some background on how I'm doing things, and what I'm trying to achieve. If anything below comes out as a request for Python functionality it's not intended to be - it's just a description of what /I'm/ trying to do. The Scribus Python plugin is pretty standard - it both embeds the Python interpreter and provides an extension module to expose application-specific functionality. It is used to permit users to execute Python scripts to automate tasks within the application. I also hope to make it possible to extend the application using Python, but that's not the issue right now. I need to isolate individual script executions as much as possible, so that to the greatest extent we can manage each script runs in a new interpreter. In other words, I need to minimise the chances of scripts treading on each others toes or leaking too much with each execution. Specifically, as much as possible I need to: - Ensure that memory allocated by Python during a script run is all freed, including any objects created and modules loaded. An exception can be made for C extension modules, so long as they don't leak every time a script is run. - Ensure that no global state (eg loaded modules, globals namespace, etc) persists across script executions. I have no need to be able to run Python scripts in parallel with the application, nor with each other. If a script goes into an endless loop, that's a bug with the script, and not the application's problem. I'd like to reduce the chances of scripts conflicting or messing up the app state, but don't intend to even try to make it possible to safely run untrusted scripts or to completely isolate scripts. If the odd C extension module doesn't like it, I can deal with that too. Also, some of the extension module functions make Qt gui calls (for example, create and display a file chooser dialog) or access internal application state in QObject derived classes. According to the Qt documentation, this should only be done from the main thread. This is another reason why I'm making no attempt to make it possible to run normal Python scripts without blocking the application, or run scripts in parallel. It also means that all my Python sub-interpreters need to share the main (and in fact only) application thread. I've hit two issues with this. The first is that executing a script crashes the application with SIGABRT if a Python debug build is being used. Python crashes the app with the error "Invalid thread state for this thread". I'm working with Python 2.3.4 . The crash is triggered by a check in pystate.c line 276 - in the PyThreadState_Swap() function: The code in question is: /* It should not be possible for more than one thread state to be used for a thread. Check this the best we can in debug builds. */ #if defined(Py_DEBUG) && defined(WITH_THREAD) if (new) { PyThreadState *check = PyGILState_GetThisThreadState(); if (check && check != new) /* Py_FatalError("Invalid thread state for this thread"); */ printf("We would've died here\n"); } #endif A trimmed down and simplified version (eg no error checking, etc) of the code I'm using in the plugin that hits this check is: PyThreadState *stateo = PyEval_SaveThread(); PyThreadState *state = Py_NewInterpreter(); initscribus(Carrier); // init the extension module PySys_SetArgv(1, scriptfilename); PyObject* m = PyImport_AddModule("__main__"); PyObject* globals = PyModule_GetDict(m); char* script_string = ... // build script that calls execfile() PyObject* result = PyRun_String(script_string, Py_file_input,\ globals, globals); ... // handle possible failure and capture exception Py_EndInterpreter(state); PyEval_RestoreThread(stateo); (The full version can be found in scribus/plugins/scriptplugin/scriptplugin.cpp line 225-279 of Scribus CVS, http://www.scribus.net/) The script text isn't really important. It just execfiles()s the user's script within a try/catch block to ignore SystemExit and to catch and capture any other fatal exceptions. The crash occurs at Py_NewInterpreter, when it calls PyThreadState_Swap. It's pretty clear _what_ is happening - Python is aborting on a sanity check because I'm trying to use multiple thread states in one thread - what I'm looking for help with is _why_. When run with a non-debug build, scripts run just fine. It also runs fine when I use a debug build of Python without thread support (as is obvious from the code snippet above). I'm sure there are cases where things can / do go wrong, but for general use it appears to be just peachy. So ... my question is, what are the issues behind this check? Does it indicate that there will be a problem with this condition in all cases? My understanding is that it's to do with the way Python doesn't use the full capabilities of platform threading libraries, and has some shared globals that could cause issues. Correct? If so, is there a way around this? All I'm looking to do is to create a clean sub-interpreter state, run a script in it (in the main thread, with nothing else running) then dispose of the interpreter at script exit. It's desirable to keep the main interpreter usable as well, but there will never be more than one sub-interpreter, and there will never be Python code running in the main and sub interpreters at the same time. Does the existence of this check mean that what I'm trying to do is incorrect or unsafe? If not, might it be possible to provide apps with a way to disable this check (think an "I know what I'm doing" flag)? Is there another, saner way to do what I want? This post describes a similar issue to mine, though their goals are different, and I don't think the solution will work for me: http://groups.google.com.au/groups?hl=en&lr=&client=firefox-a&selm=brlicq%243dh%241%40arachne.labyrinth.net.au&rnum=7 This message describes the issue I'm seeing: http://groups.google.com.au/groups?q=Py_NewInterpreter&hl=en&lr=&group=comp.lang.python.*&client=firefox-a&selm=knbstvgsn3o3qmmtu975g8eb94rhpmae2o%404ax.com&rnum=5 Another related message: http://groups.google.com.au/groups?q=Py_NewInterpreter&hl=en&lr=&group=comp.lang.python.*&client=firefox-a&selm=mailman.3563.1095687831.5135.python-list%40python.org&rnum=1 Someone says it's just broken: http://groups.google.com.au/groups?q=Py_NewInterpreter&start=10&hl=en&lr=&group=comp.lang.python.*&client=firefox-a&selm=m34r8r5jwr.fsf%40mira.informatik.hu-berlin.de&rnum=17 I've tried one other approach that doesn't involve Py_NewInterpreter/Py_EndInterpreter, but didn't have much success. What I tried to do was run each script with a new global dict, so that they at least had separate global namespaces (though they'd still be able to influence the next script's interpreter state / module state). If I recall correctly I ended up with code like this: execfile(filename, {'__builtins__'=__builtins__, '__name__':'__main__', '__file__':filename}) being called from PyRun_String. This appeared to work fine, but turned out to leak memory like a sieve. Objects in the script's global namespace weren't being disposed of when the script terminated. Consequently, if I had a script with one line: x = x = ' '*200000000 then each time I ran the script the app would gobble a large chunk more memory and not release it. If I wrote a script that very carefully deleted everything it put in the top-level namespace before it exited, such as all variables, imports, classes, and functions, I still leaked a little memory and a few references, but nothing much. Unfortunately, doing that is also rather painful at best and seems _really_ clumsy. It looked to me after some testing with a debug build like the global dictionaries that were being created for each execfile() call were not being disposed of after the call terminated, even though no code I was aware of continued to hold references to them. Circular references? Do I have to manually invoke the cyclic reference cleanup code in Python when embedding? I'm sorry for the lack of detail provided in the discussion of this approach. It was a while ago. If folks here think it's viable I can go back and get some more hard data. With the 'new globals dict' approach, it was also possible for people to mangle modules and for the next script to see the changes. If there's a way to re-init modules between runs (at least the built-in ones like sys, __builtins__, etc, plus the app's extension module and any modules written in Python), that'd be fantastic. If there's some way to do achieve what I want to do - get scripts to execute in private or mostly-private environments in the main thread of an application - I'd be overjoyed to hear it. I'm very sorry for the mammoth message, and hope I've made some sense and provided enough information without boring you all to tears. It's clear that there's been quite a bit of interest in this topic from my digging through the list archives, but I just wasn't able to find a clear, definitive answer. Phew. To anybody who got this far, thankyou very much for your time and patience. -- Craig Ringer From exogen at gmail.com Tue Nov 30 11:03:41 2004 From: exogen at gmail.com (Brian Beck) Date: Tue, 30 Nov 2004 11:03:41 -0500 Subject: py.test anyone? In-Reply-To: References: Message-ID: Robert Brewer wrote: > > http://www.google.com/search?q=%22py.test%22 > Just a little OT note, but Google ignores the '.' and, in fact, any punctuation whether it is in a quoted string or not. And while on the subject, many people incorrectly assume that Google supports parentheses to change precedence or to clear search term ambiguity. These are likewise completely ignored. ;) Have a helpful day. -- Brian Beck Adventurer of the First Order From merman at snafu.de Mon Nov 8 14:50:36 2004 From: merman at snafu.de (T. Kaufmann) Date: Mon, 08 Nov 2004 20:50:36 +0100 Subject: MySQLdb installation In-Reply-To: References: <418f99db$0$175$9b622d9e@news.freenet.de> <418fba73$0$161$9b622d9e@news.freenet.de> Message-ID: <418fcca7$0$165$9b622d9e@news.freenet.de> Diez B. Roggisch wrote: > T. Kaufmann wrote: > > >>>... which mentions, among others: >>> >>>* Red Hat Linux packages: >>> - mysql-devel to compile >>> - mysql and/or mysql-devel to run >> >>... and what does it mean? I don't understand it. > > > Install the package mysql-devel. I can't find it!? o-o Thomas From dd55 at cornell.edu Fri Nov 5 18:21:11 2004 From: dd55 at cornell.edu (Darren Dale) Date: Fri, 05 Nov 2004 18:21:11 -0500 Subject: executing python code References: <418c0870$1_4@omega.dimensional.com> Message-ID: Michael Fuhr wrote: > Darren Dale writes: > >> Some time ago I asked about executing a python program or script. For >> windows, I was informed that the .py extension could be added to some >> list of executable extensions, and then I could just type "mycode" >> instead of "python mycode.py". Great advice, worked like a charm. >> >> I recently jumped ship, and have been running Gentoo Linux for about two >> months. Is it possible to get the same behavior on Linux? I thought it >> would have something to do with adding the #!/usr/bin/env python line to >> my code, but I'm not sure what this is supposed to do (it didnt work, >> that much I know.) > > How didn't it work? What did you do and what happened? What errors > were printed? Did you use chmod to make the script executable? Is > the script in a directory that's in your PATH? Is Python installed > on the system? > Yes, I did chmod, the script is in the current directory. $ mycode.py bash: mycode.py: command not found I just tried: $ ./mycode.py and that will execute. From oliver.schoenborn at utoronto.ca Sat Nov 13 16:26:46 2004 From: oliver.schoenborn at utoronto.ca (HumbdyDum) Date: Sat, 13 Nov 2004 16:26:46 -0500 Subject: problem with "setup.py bdist --formats=zip" In-Reply-To: References: Message-ID: Peter Hansen wrote: > HumbdyDum wrote: > >> Peter Hansen wrote: >> >>> you'll find that the installer has an option to install for the >>> current user only, so that you don't have to be an Administrator >>> to do it. >> >> >> Really? I've installed several (like Numeric etc) and looked but never >> seen that option, I must be blind. Actually, I remember clearly that >> they always say, after being started, something like "You don't have >> sufficient priviledge, you must be administrator". I'll take another >> look. Thanks, > > I'm talking about the Python installer itself, not installers > for other things. Perhaps I misunderstood what you meant > when you said you wanted to create a binary distribution. > I assumed you meant "of Python". No I meant "of a Python package I want to distribute". I'd like to create a zip file that contains the same stuff that the bdist_wininst would contain. Is there a way to intercept the bdist_wininst to make it create a zip instead of an exe installer? Oliver From kent3737 at yahoo.com Sat Nov 27 06:52:27 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 27 Nov 2004 06:52:27 -0500 Subject: Subclassing complex with computed arguments In-Reply-To: References: Message-ID: <41A86A7B.3040800@yahoo.com> Peter Olsen wrote: > I want to define a class "point" as a subclass of complex. > > When I create an instance > > sample = point() > > I want "sample" to "be" a complex number, but with its real and > imaginary parts computed in point()'s __init__ function with their > values based on the arglist. I want to compute with point instances > as though they were native complex numbers, but I want to be able to > define some new methods and over-ride some of complex's existing ones. I have come up with two solutions to this. They both have warts. Disclaimer: I have not extensively tested either of these. In particular, I have not tested all the numeric operations to make sure they give correct results! The first attempt was to subclass complex directly, overriding __new__() to process the input parameters, and delegating all the numeric special methods to the base class implementation. The delegation wrapper converts the returned result back to a point. The trick to getting this to work was to realize that, for example, complex.__add__(self, y) requires an actual complex instance for self. If self is a subclass of complex it returns NotImplemented. So my delegation wrapper constructs a new complex object before calling the base class method. The wart in this implementation is that mixed operations with complex don't always return a point. If the complex is the left operand, complex.__op__ is called directly and the result is not wrapped back to a point. Here is the implementation: ############## point.py ################ ''' A subclass of complex that supports the full range of complex numeric operations by subclassing complex. >>> p=point(1,2) >>> p point(1+2j) >>> p+1 point(2+2j) >>> 1+p (2+2j) >>> p-1 point(2j) >>> c=complex(1,2) >>> p+c point(2+4j) A point can be used where a complex is expected - though the result is a complex, not a point: >>> import cmath >>> cmath.sqrt(p) (1.272019649514069+0.78615137775742328j) This doesn't work correctly - it calls complex.__add__() directly and the result doesn't get wrapped: >>> c+p (2+4j) ''' class point(complex): def __new__(cls, *args, **kwds): if len(args) == 2: # return complex.__new__(cls, args[0]*2, args[1]*2) # Special args processing goes here return complex.__new__(cls, args[0], args[1]) return complex.__new__(cls, *args, **kwds) def __str__(self): return self.__repr__() def __repr__(self): s = complex.__repr__(self) if s.startswith('('): return 'point' + s return 'point(%s)' %s def makeWrapper(attr): def wrapper(self, *args): val = getattr(complex, attr)(complex(self), *args) # print attr, args, val return point(val) return wrapper for special in ['__abs__', '__add__', '__div__', '__divmod__', '__floordiv__', '__mod__', '__mul__', '__neg__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__']: setattr(point, special, makeWrapper(special)) def _test(): import doctest, point return doctest.testmod(point) if __name__ == "__main__": _test() ########################################### My second attempt uses delegation rather than subclassing. point instances have a complex attribute and delegate operations to it. The trick to getting this one to work was to realize that I had to call coerce() explicitly in my wrapper function. The wart in this implementation is that points are not instances of complex, so to pass a point to e.g. cmath.sqrt(), you have to explicitly convert to a complex. I think this implementation is probably safer, since it fails noisily and failures are easy to fix, whereas the first implementation could silently give errors (depending on how point and complex actually differ). Here is the implementation: ################# point2.py #################### ''' A class that supports a full range of complex numeric operations by delegating to an instance of complex. >>> p=point(1,2) >>> p point(1+2j) >>> p+1 point(2+2j) >>> 1+p point(2+2j) >>> p-1 point(2j) >>> p-4j point(1-2j) >>> c=complex(1,2) >>> p+c point(2+4j) >>> c+p point(2+4j) Since point does not subclass complex, it must be explicitly coerced to a complex when one is needed: >>> import cmath >>> cmath.sqrt(p) Traceback (most recent call last): File "", line 1, in ? TypeError: a float is required >>> cmath.sqrt(complex(p)) (1.272019649514069+0.78615137775742328j) ''' class point(object): def __init__(self, *args, **kwds): if len(args) == 1 and isinstance(args[0], complex): self.c = args[0] if len(args) == 2: # self.c = complex(args[0]*2, args[1]*2) # Special args processing goes here self.c = complex(args[0], args[1]) else: self.c = complex(*args, **kwds) def __str__(self): return self.__repr__() def __repr__(self): s = repr(self.c) if s.startswith('('): return 'point' + s return 'point(%s)' %s def __complex__(self): return self.c def makeWrapper(attr): def wrapper(self, y): x, y = coerce(self.c, y) val = getattr(x, attr)(y) # print attr, x, y, val return point(val) return wrapper for special in ['__abs__', '__add__', '__div__', '__divmod__', '__floordiv__', '__mod__', '__mul__', '__neg__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__']: setattr(point, special, makeWrapper(special)) def _test(): import doctest, point2 return doctest.testmod(point2) if __name__ == "__main__": _test() #################################### HTH, Kent From justinhsia at yahoo.com Fri Nov 5 08:33:49 2004 From: justinhsia at yahoo.com (Chaser) Date: 5 Nov 2004 05:33:49 -0800 Subject: ?? Modules for GPIB and Ethernet ?? References: <21240387.0411041337.7b17172b@posting.google.com> <0-GdnfBAPrZPXBfcRVn-sw@powergate.ca> Message-ID: <21240387.0411050533.4d145e2a@posting.google.com> Peter Hansen wrote in message news:<0-GdnfBAPrZPXBfcRVn-sw at powergate.ca>... > Chaser wrote: > > Just wondering if anyone knows where I can find modules for NI-488.2 > > GPIB and for a generic ethercard? > > Can't help directly with the GPIB thing, except to note that > using something like ctypes it is generally pretty easy to > wrap the NI libraries for such things. > > As for the other question: do you actually mean you want a > way to talk "raw" Ethernet, or are you just trying to do > some networking? > > -Peter Hi Peter, I have an equipment that's controlled through ethernet. (The control program is currently written in C++.) I guess my really difficulty is, how do I send commmands to that devise through ethernet using Python? Any suggestions are appreciated. Thanks. v/r, Justin From stuart at stuartbishop.net Mon Nov 15 02:36:31 2004 From: stuart at stuartbishop.net (Stuart Bishop) Date: Mon, 15 Nov 2004 18:36:31 +1100 Subject: psycopg, transactions and multiple cursors In-Reply-To: References: Message-ID: <41985C7F.9000807@stuartbishop.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alban Hertroys wrote: | Oh no! It's me and transactions again :) | | I'm not really sure whether this is a limitation of psycopg or | postgresql. When I use multiple cursors in a transaction, the records | inserted at the start of the transaction aren't visible to those later | on in that transaction (using a different cursor). If you didn't get the answers you want in this thread, there is a psycopg specific mailing list available at http://lists.initd.org/mailman/listinfo/psycopg where you can talk directly with the developers and other users. - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFBmFxvAfqZj7rGN0oRAqQAAJ9QMWjVc2B/ZtjAQpxjI24J+AKvEQCdHiqb CXSeHZYRg7TwNnALmyiywDs= =EdkG -----END PGP SIGNATURE----- From ville at spammers.com Tue Nov 2 10:58:06 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Nov 2004 17:58:06 +0200 Subject: Python needs a CPyAN References: Message-ID: >>>>> "Steve" == Stephen Ferg writes: Steve> Python's lack of a CPAN-like facility, and I submit that Steve> without a CPyAN Python will never even get close to Steve> achieving the degree of widespread usage that Perl Steve> currently enjoys. ... Steve> It is no good saying that Python doesn't need a CPyAN Steve> because we've got Google, or we've got SourceForge, or Steve> we've got PyPI or distutils or the Vaults of Parnassus. Steve> Even used together, all of these tools still fall short of Steve> the capabilities of CPAN. Only a full CPyAN will provide Steve> the quality and ease-of-use of external modules that will Steve> enable Python to flourish in the coming decade. I think you are overselling CPAN a little bit here. It is not an absolute requirement, and I think Python can easily surpass Perl in popularity even without CPAN functionality. Perl popularity in general seems to be going down, and I don't think Perl is something to worry about anymore. Hell, people rarely even mention Perl these days anyway. Steve> one: "I wish I could convince my organization to use Steve> Python, because Python really is a better technology, and Steve> my organization really does need it." And the answer to Steve> that wish, too, lies in making Python more popular.) I don't think Python is too unpopular to sell to companies anymore. All you need to do is to demonstrate technical superiority, and that should be trivial if the other contender is Perl. Provided that your company is not already too stuck with Perl, which is rarely the case because with Perl you usually dealing with simple scripts. Steve> Building a CPyAN will be a big job, no question. But I Steve> think that for the Python community and for the Python Steve> Software Foundation, it should be job number one. Perhaps the priority should be to build a generic Open Source catalogued repository retrieval system. I don't see why the Python community should do something like this alone, because there really isn't too many Python specific aspects in the problem anyway. Perhaps Arch might be a good starting point... -- Ville Vainio http://tinyurl.com/2prnb From tzot at sil-tec.gr Thu Nov 18 04:44:44 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 18 Nov 2004 11:44:44 +0200 Subject: .pyc files... References: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> Message-ID: <54rop0dgkqb5ing122i0dtrtvotambtfkv@4ax.com> On 17 Nov 2004 22:25:05 GMT, rumours say that Jorgen Grahn might have written: >> As has already been stated on the list, $() is POSIX. > >Sorry, missed that. >> So sh has it. [...] > >Solaris 8's /bin/sh doesn't. Then Solaris 8 /bin/sh is not POSIX conformant. However, you could try if /bin/ksh has it. >> If you're scripting in csh or tcsh, you're making a >> fundamental mistake. > >I don't. I'm not even talking about writing scripts, just about deleting >.pyc files from your average Unix shell (although I hope not many people use >/bin/sh as their interactive shell, POSIX or not). Any particular reason for prefering t?csh over POSIX sh other than habit? I'm asking out of plain curiosity. Anyway, nobody in this thread has offered the pythonic solution, so I'll pretend I am on-topic :) def remove_pyc_files(root_folder): for dirname, dirnames, filenames in os.walk(root_folder): for filename in filenames: if not filename.endswith('.pyc'): continue pathname = os.path.join(dirname, filename) os.remove(pathname) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From mediocre_person at hotmail.com Mon Nov 15 11:33:44 2004 From: mediocre_person at hotmail.com (N Chackowsky) Date: 15 Nov 2004 08:33:44 -0800 Subject: Combining arbitrary lists References: <41982269$1_1@alt.athenanews.com> <419876e1.104196646@news.oz.net> Message-ID: <367fb727.0411150833.4732246c@posting.google.com> Thanks to all who replied; very helpful. Bengt Richter: that's a lovely generator--I'm new to the whole idea of generators, but that's very clear. I will experiment and test it. Nick. From andrea.valle at unito.it Mon Nov 1 05:33:14 2004 From: andrea.valle at unito.it (andrea valle) Date: Mon, 1 Nov 2004 11:33:14 +0100 Subject: name of an instance In-Reply-To: <864d370904103113373b9698f0@mail.gmail.com> References: <40a939c9.0410291820.fada696@posting.google.com> <40a939c9.0410310827.112f13a1@posting.google.com> <864d370904103113373b9698f0@mail.gmail.com> Message-ID: <6FAE7CBE-2BF1-11D9-841C-0003939C968C@unito.it> Hi to all, another basic question, but... How do I access the name of an instance? I.e., if I have: class MyClass: def __init__(self): print "here we are, kids!" and: >>> a = MyClass() I'd like to have: >>> 'a' Thanks a lot -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From ville at spammers.com Tue Nov 16 13:14:54 2004 From: ville at spammers.com (Ville Vainio) Date: 16 Nov 2004 20:14:54 +0200 Subject: Zope 3.0, and why I won't use it References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> Message-ID: >>>>> "Ian" == Ian Bicking writes: Ian> I would think of it differently. I don't see a need for Ian> static typing to deal with the outside world. There's always Ian> a bridge when communicating with the outside world, and if Ian> that bridge is smart enough it should be okay. You can With things like IronPython, there isn't necessarily any "outside world". The compiler can look at the code, determine that it's "typed enough" and compile it to a more static form of code that can be JIT-compiled to native code. Ian> it would be worth it for any external interface, but for Ian> internal interfaces it might be worth it, where there's less Ian> of a concern about flexibility. In that case, decorators Ian> might be all that's necessary, e.g.: Ian> @constrain_types(a=float, b=str, c=int: Ian> def foo(a, b): Ian> c = 1 Ian> ... Guido has stated that we shouldn't jump all over decorator syntax for function/method signatures, because type declarations will appear in language syntax at some point. We'll see how that pans out - in the meantime, perhaps having some kind of "standard" type declaration (-ish) decorator in the standard library would be conductive to having One Obvious Way of telling IDEs about the types. -- Ville Vainio http://tinyurl.com/2prnb From joshway_without_spam at myway.com Wed Nov 3 19:31:52 2004 From: joshway_without_spam at myway.com (JCM) Date: Thu, 4 Nov 2004 00:31:52 +0000 (UTC) Subject: strong/weak typing and pointers References: <1gmp6qz.1pzqqttpu6acpN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > JCM wrote: >> When people talk about "weak typing" they generally mean either >> implicit conversions (or operations on values of different types), >> or reinterpreting representations of values as a different type. > I've seen people complain about "weak typing" mostly to mean an entirely > different issue: types being attached to objects and NOT to names. Ah yep, there's that one too. But I hope most people call that static typing. At least I think I do. c.l.py is bad for my mental dictionary. From aahz at pythoncraft.com Thu Nov 4 09:21:19 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Nov 2004 09:21:19 -0500 Subject: pep 336: Make None Callable References: Message-ID: Before I respond: A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet? In article , The Eternal Squire wrote: >Why not? > >Aahz wrote: > >> In article , >> The Eternal Squire wrote: >> >>>Title: Make None Callable >> >> >> No, *no*, *NO*, and *HELL NO*. >> >> OTOH, once the BDFL Pronounces, we can return to laughing and pointing >> the next time this comes up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From ods at strana.ru Fri Nov 19 05:55:15 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 19 Nov 2004 13:55:15 +0300 Subject: How to sort a list of tuples In-Reply-To: <1100859769.700610@eng-ser6> References: <1100859769.700610@eng-ser6> Message-ID: <20041119135515.0b07106a.ods@strana.ru> On Fri, 19 Nov 2004 18:22:45 +0800 Valkyrie wrote: > I have a list of tuples, and one of the fields in the tuple is score. So how can > I sort the list by the score? In 2.4 you can use key argument of sort method: >>> l = [('a', 2), ('c', 3), ('b', 1)] >>> l.sort(key=lambda i: i[1]) >>> l [('b', 1), ('a', 2), ('c', 3)] otherwise pass comparison function: >>> l = [('a', 2), ('c', 3), ('b', 1)] >>> l.sort(lambda i1, i2: cmp(i1[1], i2[0])) >>> l [('b', 1), ('c', 3), ('a', 2)] -- Denis S. Otkidach http://www.python.ru/ [ru] From ptmcg at austin.rr._bogus_.com Sun Nov 28 01:55:22 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 28 Nov 2004 06:55:22 GMT Subject: Subclassing complex with computed arguments References: <41a6b8a3$1_2@newspeer2.tds.net> Message-ID: "Kent Johnson" wrote in message news:41a6b8a3$1_2 at newspeer2.tds.net... > Jp Calderone wrote: > > On 25 Nov 2004 14:30:18 -0800, pcolsen at comcast.net (Peter Olsen) wrote: > > > >>I want to define a class "point" as a subclass of complex. > >> > >>When I create an instance > >> > >>sample = point() > >> > >>I want "sample" to "be" a complex number, but with its real and > >>imaginary parts computed in point()'s __init__ function with their > >>values based on the arglist. I want to compute with point instances > >>as though they were native complex numbers, but I want to be able to > >>define some new methods and over-ride some of complex's existing ones. > > > I had more luck with a delegation-based approach: > > class point(object): > def __init__(self, *args, **kwds): > if len(args) == 1 and isinstance(args[0], complex): > self.c = args[0] > if len(args) == 2: > self.c = complex(args[0]*2, args[1]*2) > else: > self.c = complex(*args, **kwds) > > def __add__(self, y): > val = self.c+y > return point(val) > > def __repr__(self): > return 'point' + self.c.__repr__() > > > p=point(1,2) > print p > p1 = p+1 > print p1 > > prints: > point(2+4j) > point(3+4j) I believe this is another case of "is-a" being confused with "is-implemented-using-a". I'm skeptical of the merits of an OO design that creates a graphical type by extending a computational type. A Point can *represent* a complex number, and vice-versa, but saying that a Point *is* a complex number seems unlikely, and smells of premature optimization and/or memory conservation (for that matter, does 1 complex really use less memory than 2 ints?). The delegation-based approaches that have already been posted seem to be much more likely to pan out well. -- Paul From davecook at nowhere.net Tue Nov 9 00:56:06 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 09 Nov 2004 05:56:06 GMT Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> Message-ID: In article <87d5ysbkq9.fsf at pop-server.bigpond.net.au>, Israel Raj T wrote: > On Windows XP, Windows NT and Linux (Gentoo ), I have consistently > found python apps using wxpython to be far faster to load > and to be far more responsive than Java apps. I've casually compared the jython/Swing tree widget with the pygtk tree widget, both with the same large data set, and the Swing tree widget responds quite a bit faster than the gtk tree widget (there have been a lot of complaints about the gtk treeviews slowness). Obviously the Swing tree widget is much better optimized. wxpython runs on top of gtk on Linux, but I don't know if they use the gtk treeview as a "peer" or work around it and implement their own tree widget. Dave Cook From martin at v.loewis.de Sun Nov 21 04:37:37 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 21 Nov 2004 10:37:37 +0100 Subject: unicode question In-Reply-To: <419ff7cd_3@newspeer2.tds.net> References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> Message-ID: <41A061E1.8050203@v.loewis.de> Kent Johnson wrote: > Martin v. L?wis wrote: > >> wolfgang haefelinger wrote: >> >>> I wonder especially about case 2. I can see that "print y" makes a >>> call to >>> Y.__str__() . But Y.__str__() can be printed?? So what is 'print' >>> exactly doing? >> >> >> >> It looks at sys.stdout.encoding. If this is set, and the thing to print >> is a unicode string, it converts it to the stream encoding, and prints >> the result of the conversion. > > > I hate to contradict an expert, but ISTM that it is > sys.getdefaultencoding() ('ascii') that is the problem, not > sys.stdout.encoding ('cp437') It seems we were answering different parts of the question. I answered the part "What is 'print' exactly doing"; you answered the part as to what the problem with str() conversion is (although I'm not sure whether the OP has actually asked that question). Also, the one case that is interesting here was not in your experiment: try print gamma This should work, regardless of sys.getdefaultencoding(), as long as sys.stdout.encoding supports the characters to be printed. Regards, Martin From jgrahn-nntq at algonet.se Tue Nov 16 13:32:08 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 16 Nov 2004 18:32:08 GMT Subject: a very newbie question about threading References: <9c3edc58.0411121629.45652543@posting.google.com> Message-ID: On Fri, 12 Nov 2004 21:59:04 -0600, Mike Meyer wrote: > chrispatton at gmail.com (Chris Patton) writes: > >> I've recenently stumbled upon a concept known as "threading". Can >> anyone tell me what this IS and how it is used, or show me where I can >> get information about this? > > Now that you know what they are - be warned that they tend to be a > source of very hard to track down bugs. If you can avoid writing > threaded code, do so. One common use of threads is to handle multiple > IO streams at one time. Asyncore is a much saner solution to that > problem. For more threading criticism along those lines, see Eric Raymond's TAOUP: http://www.catb.org/~esr/writings/taoup/html/ch07s03.html#id2923889 /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From deetsNOSPAM at web.de Mon Nov 8 07:45:24 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 13:45:24 +0100 Subject: Python OS References: Message-ID: > I didn't read the OP, just Richard. Unless he was the OP, > in which case I'm confused about various comments that have > been made, but not concerned enough to go back and try to > figure the whole thing out. *Your* comments appear right > on the mark, as far as I can see. ;-) Richard was the OP. > Nope. Python has no ability to interface to something that is > defined only at the assembly level (interrupt routines) without > using assembly. (I don't even mention C here, as it requires > special non-standard C extensions to support these things, in > effect doing a quick escape to assembly.) My words.... > I'll add an additional note: there's a qualitative difference > between being fast enough to respond to hardware interrupts > at the 100-CPU cycle sort of level of performance, and at > a speed 100 times slower. It's not a matter of just having > a slower overall system, which might be fine for a prototype > or a simulation. In fact *it simply won't work*. That's > because if hardware interrupts aren't answered fast enough, > in most non-trivial cases _information will be lost_, and > that means the system is broken. That's the definition of > a "hard realtime system", by the way, and an unfortunate > reason that Python in its current form (i.e. assuming its > bytecode interpreted rather than compiled to some kind of > native code) cannot ever be used at the lowest levels of > an OS. Yup. And writing an OS is exactly about these nitty gritty things - otherwise, its only a collection of more or less useful lib routines. So writing a "virtual os" that doesn't have to deal with problems like these is barely useful for teaching anything about writing an os at all... -- Regards, Diez B. Roggisch From ch.pingel at web.de Fri Nov 19 05:25:29 2004 From: ch.pingel at web.de (Christoph Pingel) Date: Fri, 19 Nov 2004 11:25:29 +0100 Subject: orange + bus error - is there a 'usual' reason? Message-ID: Trying to import the 'orange' datamining module, I get a bus error and python crashes (Python 2.3 on Mac OS X). Tried it with an older lib that runs on another mac, with orange inside orange.app, and with a lib I compiled from source myself. I'm wondering if there is anything wrong with my Python installation, for the orange.app (which is mainly a qt-wrapper for the python scripts and orange lib) runs without problems whatsoever. Is there any 'general' reason for bus errors so that I could begin to track down the problem? Any ideas for mac-specific compiler settings that I could play with? Any input is highly appreciated. best regards, Christoph From carribeiro at gmail.com Sun Nov 7 13:00:46 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 7 Nov 2004 16:00:46 -0200 Subject: cherrypy/cheetah vs twisted/nevow In-Reply-To: <69cbbef2.0411070346.6c6c0eaf@posting.google.com> References: <418818ca$0$19452$626a14ce@news.free.fr> <69cbbef2.0411050857.6dfe11bd@posting.google.com> <69cbbef2.0411070346.6c6c0eaf@posting.google.com> Message-ID: <864d3709041107100070fbe689@mail.gmail.com> On 7 Nov 2004 03:46:43 -0800, has wrote: > Carlos Ribeiro wrote in message news:... > Carlos Ribeiro wrote: > > > I'm not sure if I understand your point, and it may be the case that > > I'm really missing something. I think that, by its very definition, > > templating systems (including variables, conditionals, loops, and > > other control structures) *do* mix some aspects from the model into > > the view. > > You're confusing presentation logic with business logic. In MVC, only > *business* logic should go in the Model layer; presentation logic > belongs elsewhere. The Model does *not* dictate how the User Interface > layer(s) should receive input or present data. Think of the Model as a > complete program within another program, containing all the smarts > needed to do its job but providing no way for end-users to interact > with that data. All it supplies is an API into which user-interface > code can connect. Well, there are lots of stuff that deserve commenting here. But I feel that we aren't very far from each other (though my terminology definitely needs improvement :-). I agree that presentation logic (the term that I was missing) is different from business logic. But I still think that the more you can take the presentation logic *out* of the HTML template, the better. That's my point when I talk about the reporting example. I may be wrong, because I never programmed Macs, but I think that in the original Apple MVC implementation, you had "resources" (that stored the form definitions), and there was code to fill the form with data ("presentation logic", right?). I have a lot of experience with Delphi, that is also based on the same concept. In both cases (Apple and Delphi), the resource is clearly separated from the code; they're in separate files, and use different languages. This example shows one of the problems with (many) templating systems; one has to write both the 'resource' (the HTML Template) and the 'presentation logic' in the same file. Now, I'm reallly struggling to catch up with a lot of stuff, and I don't know about HTMLTemplate, so I have to take your word for it; you say it's good, and it separates the presentation logic from the template, and that's what I am looking for. I'll check it now. Thanks for the all the info. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From __peter__ at web.de Tue Nov 16 11:58:52 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Nov 2004 17:58:52 +0100 Subject: determining the number of output arguments References: Message-ID: Jeremy Bowers wrote: > the instances I do have is a tree iterator that on every "next()" returns > a depth and the current node, because the code to track the depth based > on the results of running the iterator is better kept in the iterator than > in the many users of that iterator. But I don't like it; I'd rather make > it a property of the iterator itself or something, but there isn't a > code-smell-free way to do that, either, as the iterator is properly a > method of a certain class, and trying to pull it out into its own class > would entail lots of ugly accessing the inner details of another class. You could yield Indent/Dedent (possibly the same class) instances whenever the level changes - provided that the length of sequences of nodes with the same depth does not approach one. Peter From brion at pobox.com Mon Nov 8 20:40:47 2004 From: brion at pobox.com (Brion Vibber) Date: Mon, 08 Nov 2004 17:40:47 -0800 Subject: unicodedata . normalize (NFD - NFC) inconsistency In-Reply-To: <6rouo0timlrp4ddhoh88a38ftpekms75va@4ax.com> References: <6rouo0timlrp4ddhoh88a38ftpekms75va@4ax.com> Message-ID: <2valh1F2igeo2U1@uni-berlin.de> Christos TZOTZIOY Georgiou wrote: > I found at least one case where decombining and recombining a unicode > character does not result in the same character (see at end). > > I have no extensive knowledge about Unicode, yet I believe that this > must be a problem of the Unicode 3.2 specification and not Python's. I've been spending some time lately writing a normalizer (in PHP of all things -- yeesh!), and yes Unicode is a scary world. :) Although it may seem counterintuitive, it is in fact perfectly legitimate for a character not to be its own canonical composition. >>>>u1=u'\N{greek small letter alpha with oxia}' >>>>report(u1) > > 8049 GREEK SMALL LETTER ALPHA WITH OXIA This character is a "singleton decomposition". It decomposes into GREEK SMALL LETTER ALPHA WITH TONOS, which further decomposes into GREEK SMALL LETTER ALPHA and a COMBINING ACUTE ACCENT. It is by definition not normalized, so when you normalize it to form C it will turn into GREEK SMALL LETTER ALPHA WITH TONOS; there is no way to get "back" to the original character in a normalized string. For some more info see: http://www.unicode.org/unicode/reports/tr15/#Primary_Exclusion_List_Table >>>>u2=ud.normalize('NFD', u1) >>>>report(u2) > > 945 GREEK SMALL LETTER ALPHA > 769 COMBINING ACUTE ACCENT > >>>>u3=ud.normalize('NFC', u2) >>>>report(u3) > > 940 GREEK SMALL LETTER ALPHA WITH TONOS You should get this same result directly for ud.normalize('NFC', u1). Converting directly to NFC should always give the same result as converting to NFD and then NFC. Either will give you back the string you started with if and only if it's already normalized to form C. -- brion vibber (brion @ pobox.com) From exarkun at intarweb.us Sun Nov 14 15:01:32 2004 From: exarkun at intarweb.us (exarkun at intarweb.us) Date: Sun, 14 Nov 2004 20:01:32 GMT Subject: Zope 3.0, and why I won't use it In-Reply-To: Message-ID: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> On 14 Nov 2004 11:09:38 -0800, hwlgw at hotmail.com (Will Stuyvesant) wrote: >Hello all, > > So Zope still lives, yay. Well, I like that they use Python. > > > > What amazed me is they write that they "added types to the variables > and hope that it will be added to the Python project too". Really. > ROFL. Guido has repeatedly stated that a future version of Python will include static type support. The Zope project has driven numerous past changes to Python. What's funny about this? Jp From gandalf at geochemsource.com Fri Nov 26 13:58:02 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 26 Nov 2004 19:58:02 +0100 Subject: Number of colors in an image In-Reply-To: <41a77a69$0$1067$db0fefd9@news.zen.co.uk> References: <41a77a69$0$1067$db0fefd9@news.zen.co.uk> Message-ID: <1085906393.20041126195802@geochemsource.com> Hello Will, Friday, November 26, 2004, 7:48:08 PM, you wrote: > Laszlo Zsolt Nagy wrote: >> Hello, >> >> How can I determine the number of colors used in an image? I tried to >> search on Google but I could figure out. I read the PIL handbook but I >> do not see how to do it. Can anyone help? > You may get a better response on how to do it in Python, but the > following C++ code should be easy to translate if necessary. All it > requires is a get pixel function. > int CImage::CountUsedColours() const .... > Regards, > Will McGugan Yes, this can be efficient in C++. I'm not sure but possible it is not so efficient in Python. Also it would be far better to have direct access to the pixels (and not using a method/function). Now I'm thinking about ImageMagick and something like this: f = os.popen('identify -verbose ' + fullpath + ' | grep -e "Colors:"') s = f.read() index = s.find(':') color_count = long( (s[index+1:]).strip() ) Probably ImageMagick uses direct access to pixels but it still take seconds to run. It is not that portable but I'll stay at this version. :-) Thank you very much. -- Best regards, Laszlo mailto:gandalf at geochemsource.com web:http://designasign.biz From eternalsquire at comcast.net Thu Nov 4 00:22:18 2004 From: eternalsquire at comcast.net (The Eternal Squire) Date: Wed, 03 Nov 2004 22:22:18 -0700 Subject: pep 336: Make None Callable Message-ID: Terry Reedy wrote: > "The Eternal Squire" wrote in message news:dv6dndASE7CxNBTcRVn-pw at comcast.com... > >> PEP: 336 >> Abstract >> >> None should be a callable object that when called with any >> arguments has no side effect and returns None. > > > > Please no. The None object, by definition, is an object with no value, no behavior (except compares), and no specific attributes (other than those common to all descendents of object). I always saw None not as an object without value, but as the universal false or ground symbol, similar to NIL in Lisp. That one can currently compare None > to other objects can be considered a bug, and this might go away in the future. > > Anyone who wants a null function can write it in about 20 keypresses, and include it in a utility module if one has one. But isn't the point of Pythonic style to write something as tersely elegant as possible? I'd rather not see a bunch of null methods sprinkled thru the classes in the libraries that I have to write, and I'd rather not to have to import it either. > > It would be more sensible to promote the addition to builtins of a predefined null function -- one somewhat equivalent to 0, [], and {}. > I'd like to see it standardized, and I'd like to see it intuitively obvious. That's why None appears to me to be such an obvious candidate. If None is seen as the ground symbol that happens to evaluated to false in logical expressions, that it would seem to make sense to say that calling the symbol is another form of evaluation of the symbol, and so if evaluating None as a value results in None, then evaluating None as a call should also result in None. > Terry J. Reedy > > > > From hanzhupeng at kingsoft.net Wed Nov 10 21:49:21 2004 From: hanzhupeng at kingsoft.net (hanzhupeng) Date: Thu, 11 Nov 2004 10:49:21 +0800 Subject: Sorting email addresses by domain Message-ID: <20041111025050.5255C1E4002@bag.python.org> Jp Calderone: It's cool . tkx >On Thu, 11 Nov 2004 01:58:35 -0000, "Peter Murray" wrote: >>Hi! I hope someone can assist me, I have been using Python for a year or >> two, but I am not a programmer and only use it occasionally for small issues >> or just for fun. So I perhaps do not have the right 'mindset' to always see >> the answer to a problem. >> >> Anyway, I have a list of email address and I want to sort them by domain. >> List.sort() wont work as this looks at the start of each address only. So >> the answer I have come up with is to split each email address around the >> "@", swap the position of the name and domain, build a new list with these >> and then sort this. Then switch positions back, and join with an "@". It >> works, but it seems a little inelegant. Is there a better, or easier way to >> do this? > > In Python 2.3, > > def key(addr): > parts = addr.split('@') > parts.reverse() > return parts > addresses.sort(lambda a, b: cmp(key(a), key(b))) > > In Python 2.4, re-using the above definition of key: > > addresses.sort(key=key) > > Jp >-- >http://mail.python.org/mailman/listinfo/python-list = = = = = = = = = = = = = = = = = = = = ????????? ?? ????????hanzhupeng ????????hanzhupeng at kingsoft.net ??????????2004-11-11 From OlafMeding at compuserve.com Thu Nov 18 12:09:40 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 18 Nov 2004 09:09:40 -0800 Subject: PyChecker "self is argument in staticmethod" Message-ID: <9e5ea2c4.0411180909.35db39d5@posting.google.com> What does the below PyChecker warning mean? More importantly, is there a way to suppress it? PyChecker warning: ..\src\phaseid\integration.py:21: self is argument in staticmethod My best guess is that the warning is related to PyChecker not supporting C++ extensions. Thanks much for your help. Olaf From fumanchu at amor.org Mon Nov 15 03:20:23 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 15 Nov 2004 00:20:23 -0800 Subject: os.path.exists discrepancy Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32451F5@exchange.hqamor.amorhq.net> Andreas Kostyrka wrote: > On Sun, Nov 14, 2004 at 11:47:18PM -0800, Robert Brewer wrote: > > > > > > As you can see, the two paths are equal. Prompting my > reaction: bzuh? My > > next thought was to read through the os module source--perhaps the > > import of "path" was dependent on context. It is, but > os.path.__file__ > > is the same in both contexts: 'C:\\Python23\\lib\\ntpath.pyc' > > > > Any ideas or workarounds? > > Permissions? Even Windows know these nowadays ;) -> and it's probable > that the Webserver runs with minimal priviledges ;) Bah. I bet you're right. The webserver runs as LocalSystem, and the folder in question is a mapped drive on another machine. I'll test that tomorrow. Thanks! Robert Brewer MIS Amor Ministries fumanchu at amor.org From deetsNOSPAM at web.de Mon Nov 8 09:30:18 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 15:30:18 +0100 Subject: psycopg, transactions and multiple cursors References: Message-ID: > AFAIK, you can't open a transaction w/o using a cursor; You need a query > that says "BEGIN;". > You can commit a connection object, however. It would be nice to be able > to start a transaction on a connection object, but then you still could > only have one transaction per connection... :( thats actually the case for all DBs I know including e.g. oracle with jdbc - so the abstraction layers usually use connection pooling to speed up opening a connection thus the app doesn't suffer so much. > Aside from that, it turns out that the first query gets committed, even > though the transaction should have failed. This probably just indicates > that the transaction indeed is closed too soon, however, I didn't tell > it to commit. Shouldn't it issue a rollback instead? [This would > probably confuse people, but is it correct to do otherwise? Shouldn't it > rollback if you don't commit?] No idea why thats happening - on jdbc, one can set an "autocommit" connection property that will do exactly that: enforce a commit if a statement was successful. Maybe psycopg has that too? > I know PostgreSQL can do transactions on nested cursors, I have used > that now and then in stored procedures (pl/pgsql). I didn't find much on nested cursors on google, so I don't know how they work - but I assume if they are part of psycopg, they somehow have to be created using an existing cursor, as otherwise how should psycopg know that what you want is a nested and not a new cursor. So is there something on cursor objecst to get a new cursor, or at least the connection so you can get a cursor on the very same connection? -- Regards, Diez B. Roggisch From zach at cs.uni-bonn.de Fri Nov 5 12:33:33 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 5 Nov 2004 17:33:33 GMT Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: I had already compiled a little file of clips plus the two definitions I had seen so far. But your summary is better, so it goes into my summary file, too. ;-) Cheers, gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From carribeiro at gmail.com Thu Nov 18 09:28:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 18 Nov 2004 12:28:47 -0200 Subject: Named tuples In-Reply-To: References: <10pntj5m0spvl3f@corp.supernews.com> <419c20da.344317031@news.oz.net> Message-ID: <864d37090411180628e5fe6ca@mail.gmail.com> On Thu, 18 Nov 2004 14:21:58 GMT, Bryan wrote: > Carlos Ribeiro wrote: > > I think that a better way to solve the problem is to create a names > > method on the tuple itself: > > > > return ('1', '2').names('ONE', 'TWO') > > > > It's shorter and clean, and avoids a potential argument against named > > parameters for the tuple constructor -- none of the standard > > contructors take named parameters to set extended behavior as far as I > > know. > > > > but doesn't this feel more pythonic and more consistant? > > return ('ONE':'1', 'TWO':'2') The problem is that it involves changing the language, and at this point, the idea is to devise a solution that *doesn't* need to change the language. But it's a possibility for the future, after a simpler version of the same basic feature is approved and implemented. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From pinard at iro.umontreal.ca Tue Nov 30 17:52:33 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 30 Nov 2004 17:52:33 -0500 Subject: pre-PEP generic objects In-Reply-To: <41acd7fb$1@nntp0.pdx.net> References: <41acd7fb$1@nntp0.pdx.net> Message-ID: <20041130225233.GA16829@alcyon.progiciels-bpi.ca> [Scott David Daniels] > You can simplify this: > class Hash(object): > def __init__(self, **kwargs): > for key,value in kwargs.items(): > setattr(self, key, value) Might it be: def __init__(self, **kwargs): self.__dict__.update(kwargs) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From Michael.J.Fromberger at Clothing.Dartmouth.EDU Thu Nov 11 15:05:27 2004 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Thu, 11 Nov 2004 15:05:27 -0500 Subject: html parsing? Or just simple regex'ing? References: Message-ID: In article , Dan Stromberg wrote: > I'm working on writing a program that will synchronize one database with > another. For the source database, we can just use the python sybase API; > that's nice and normal. > > [...] > > 1) Would I be better off just regex'ing the html I'm getting back? (I > suppose this depends on the complexity of the html received, eh?) > > 2) Would I be better off feeding the HTML into an HTML parser, and then > traversing that datastructure (is that really how it works?)? I recommend you look at BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ It is very forgiving of the typical affronts HTML writers put into their code. -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From Florian.Wilhelm at web.de Tue Nov 9 19:05:36 2004 From: Florian.Wilhelm at web.de (Florian Wilhelm) Date: Wed, 10 Nov 2004 01:05:36 +0100 Subject: Problems with user input References: Message-ID: Thank you very much! That solved both problems! From niels_bohr at uol.com.br Tue Nov 9 17:52:53 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Tue, 09 Nov 2004 20:52:53 -0200 Subject: Concise idiom to initialize dictionaries In-Reply-To: <20041109183738.GF3567@unpythonic.net> References: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> <20041109183738.GF3567@unpythonic.net> Message-ID: <1100040773.14227.1.camel@localhost.localdomain> > Perhaps you want a dict of dicts. > d = dict([(s, {}) for s in 'abc...z']) > now refer to d['a'][key] instead of a[key] Or even: >>> a,b,c,d = [ {} for i in range(4) ] Fabio From hancock at anansispaceworks.com Fri Nov 5 17:33:08 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 5 Nov 2004 16:33:08 -0600 Subject: Wrapping or converting Perl module? In-Reply-To: <418C503E.9020800@ceid.upatras.gr> References: <200411030759.15909.hancock@anansispaceworks.com> <418C503E.9020800@ceid.upatras.gr> Message-ID: <200411051633.08338.hancock@anansispaceworks.com> On Friday 05 November 2004 10:17 pm, Stelios Xanthakis wrote: > Terry Hancock wrote: > > 1) Wrap a perl module the way you would a C module > > (does this ever make sense to do?) > I don't know if it helps but do you know the "pyperl" module. > It's rather interesting. No I didn't. I'm surprised I didn't find it when googling for a solution, but voila, typing "pyperl" gets some interesting links. I still have some trepidation about introducing a Perl dependency into my code, but this is indeed what I was looking for. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From Dennis.Benzinger at gmx.net Tue Nov 30 08:22:58 2004 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 30 Nov 2004 14:22:58 +0100 Subject: recombination variations In-Reply-To: References: Message-ID: <41ac7430$1@news.uni-ulm.de> David Siedband wrote: > [...] > Is there a better way to do this? > [...] Take a look at Biopython: http://biopython.org/ Your problem may be solved there already. From deetsNOSPAM at web.de Mon Nov 8 07:19:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 13:19:12 +0100 Subject: Python OS References: Message-ID: > If you followed the link in my last post, you saw a paper on one of > the early LISPMs, which put a virtual LISP machine in silicon. The >From that page: """ n the software of the Lisp Machine system, code is written in only two languages (or "levels"): Lisp, and CONS machine microcode There is never any reason to hand-code macrocode, since it corresponds so closely with Lisp; anything one could write in macrocode could be more easily end clearly written in the corresponding Lisp. The READ, EVAL, and PRINT functions are completely written in Lisp, including their subfunctions (except that APPLY of compiled functions is in micro-code). This illustrates the ability to write system functions in Lisp. """ So they do have a underlying assembler. As I said before: I never doubted the possibilty to tightly integrate a higher level language that even is interpreted and a piece of hardware together so that the OS is based on that hl language. But you simply don't _want_ your virtual memory paging code written in python or (uncompiled) lisp, lest you like to drink lots of coffe sitting idly in front of your machine :) > same could be done for JVM. However, the success of LISPMs and Forth > in silicon would contraindicate doing that. Then we're not talking about "V"Ms ;) AFAIK there have been attempts to make java bytecode interpreters in hardware - but I'm not aware that these have been a large success in the market or even reached a level where they entered the market at all. -- Regards, Diez B. Roggisch From ialbert at mailblocks.com Mon Nov 1 09:29:59 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 01 Nov 2004 09:29:59 -0500 Subject: ruby on rails ... python on ? In-Reply-To: References: Message-ID: flab ba wrote: > /also/ familiar with Rails - and if they could recommend something in the > Python world that is comparable. yeah, zope. It is so good it does not even look like python on the surface ... one of the biggest mistakes in developing web-frameworks is over-emphasizing the underlying programming language. A good web-framework should not look like Ruby or Python, that is not what these languages were designed for. Of course the framework should allow easy access to any class or module written in these languages, but in the end the most important things are the services that promote collaboration, allow a finely grained access control by various means, create a self contained solutions that can be easily deployed replicated or backed up. Web frameworks must do the hardest thing of all, support radically changing requirements. These overly "programmatic" frameworks revolve around a single person's ability to understand all aspects of the website, and crash and burn when that person is not around anymore. Istvan. From daniel.dittmar at sap.corp Mon Nov 15 11:46:39 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 15 Nov 2004 17:46:39 +0100 Subject: Python generators in Java? In-Reply-To: References: Message-ID: Robert Oschler wrote: > One of my favorite Python features is generators. I have to use Java for > one particular project (it happens). I would like to have something at > least close to Python's generators for the project. Sketch: - create a Queue class - the 'generator' would run in a thread and put objects into the queue (equivalent to yield) - the 'main' program would run in the main thread and consume objects from the queue (equivalent to calling generator.next ()) - the consumer must block if the queue is empty - the producer must block if the number of objects in the queue exceeds a certain amount (queue size = 1 is perfectly acceptable unless the producer is I/O bound) - if you use generators to walk recursive structures, then you probably need only one queue instead of one generator for each level. - perhaps you can get away with one superclass that creates both queue and thread, the 'generator' could then be implemented as an anonymous class. Daniel From foo at bar.com Wed Nov 10 19:53:41 2004 From: foo at bar.com (Steve Menard) Date: Wed, 10 Nov 2004 19:53:41 -0500 Subject: JPype download? In-Reply-To: References: Message-ID: Tim Couper wrote: > David Morgenthaler wrote: > > > >>The example I wrote is too long to include here, but > > you can get it at > > http://home.comcast.net/~david.g.morgenthaler/Jpypejms.zip. > It > > The .zip file doesn't appear to be there? > > Tim > > > > > > ___________________________________________________________ > ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com Works fine for me. If you still have problem, contact me through sourceforge (I am the maintainer for JPype) and I will send it to you via email. Steve From jstroud at mbi.ucla.edu Sun Nov 7 18:30:30 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 7 Nov 2004 15:30:30 -0800 Subject: How come wxPython isn't in the standard library? In-Reply-To: <1099858260.250679.61490@f14g2000cwb.googlegroups.com> References: <1099858070.544710.146320@z14g2000cwz.googlegroups.com> <1099858260.250679.61490@f14g2000cwb.googlegroups.com> Message-ID: <200411071530.30175.jstroud@mbi.ucla.edu> On Sunday 07 November 2004 06:43 am, BJ?rn Lindqvist wrote: > IMHO, this is a no issue. It doesn't matter that much if the source is > 8 or 26 mb. In fact, 8 mb is extremely small download for a > programming language. What am I missing here? Lets look at it from an END USER's perspective. I come from a situation where I was sys-admin to where I am the 0 privelige user. I wanted to install a python module. So I called in the sys-admin. He tried to add it with RPM. This rpm depended on that rpm and that rpm depended on a chicken which depended on an egg which, expectedly, depended on a chicken--you can guess where this is going. So I decided I would make my own little universe in my user folder building everything from scratch. To get Tkinter to work, I had to install Tcl/Tk and python, and probably some other stuff I already forgot about (blt or something?). That was easy-ish, but painful from an END USER's perspective. I then tried wxPython to take advantage or something or the other module that I guess I won't be able to use because I had to install (to make sure every library was compatible) a bunch of other libraries (zlib, jpeg, pango, etc.). Pango needed gtk+ and didn't like the one my machine already had. (I work at an INSTITUTION, not my home office with my customized linux box.) That would make two gtk distributions on my machine, causing too many problems for my short term attention span to figure out. So I did the only reasonable thing an END USER might do in this situation--I said screw it on wxPython and whatever module that was that I wanted to use. Lets try to see things with naieve eyes: how do we think an END USER with few administrative priveleges but operating system choices might respond to a situation like this? Right! He'll use M$ windows--guaranteed. Now I think we understand why graphics libraries might have a tough time making it into a standard distro. Personally, as an end user who only wants to use a program and not re-compile his kernel and such, I vote for tweaking out tkinter and making Tcl/Tk/blt/etc. part of the standard distro with that 18 mb otherwise required for wxPython (as cool as wx might be). One installer, wham-bam-program. James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From larry at portcommodore.com Sat Nov 13 13:14:26 2004 From: larry at portcommodore.com (Larry Anderson) Date: Sat, 13 Nov 2004 10:14:26 -0800 Subject: Advice needed References: <1100361297.413616.17890@f14g2000cwb.googlegroups.com> Message-ID: <1100369583.B0xHtDLWff5lyRJbOybqQw@teranews> Alberto wrote: > I was trying to understand the reasons why I should learn Python. More > like a pros/cons about this language. Currently, I use C, C/C++, Java, > Perl, Visual VB and was looking to see the usefulness of Python. Any > suggestions? Well if you can do more things with python or if python enables you to do things on other platforms that you can't do now, then those would be good reasons. It's all really up to you and whether it will meet YOUR needs. Are you hitting walls in the languages you are using? Can you find oportunities in using Python? That's where you need to convice yourself. My reasons for python: Cross platform (very important for me) Inexpensive (very important for me and where I work) Has loads of hooks & libraries to do just about anything from web apps, games, printing, creadint PDFs, music, etc. Easily approachable, readable syntax (should be easier for others to take up my coding projects) Interfaces with MySQL (or other database) Integrated into apps like GIMP. Larry -- 01000011 01001100 01000001 01010011 01010011 01001001 01000011 Larry Anderson - Sysop of Silicon Realms BBS (209) 754-1363 300-14.4k Set your 8-bit rigs to sail for http://www.portcommodore.com/ 01010001 01010101 01000001 01001100 01001001 01010100 01011001 From deetsNOSPAM at web.de Mon Nov 1 09:52:04 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 01 Nov 2004 15:52:04 +0100 Subject: global variable not assigned, newbie question References: Message-ID: <2un1h8F2cgjhtU2@uni-berlin.de> You need myNum to be declared global: def setNum(): global myNum myNum = 10 print myNum Apart from that, its usually considered bad style using global variables - better use this: def calcNum(): myNum = 10 return myNum myNum = calcNum() -- Regards, Diez B. Roggisch From bokr at oz.net Wed Nov 10 03:06:21 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 10 Nov 2004 08:06:21 GMT Subject: Concise idiom to initialize dictionaries References: Message-ID: <4191c6b8.74968689@news.oz.net> On Tue, 9 Nov 2004 16:40:48 -0000, "Frohnhofer, James" wrote: >My initial problem was to initialize a bunch of dictionaries at the start of a >function. > >I did not want to do >def fn(): > a = {} > b = {} > c = {} > . . . > z = {} >simply because it was ugly and wasted screen space. > >First I tried: > > for x in (a,b,c,d,e,f,g): x = {} > >which didn't work (but frankly I didn't really expect it to.) >Then I tried: > > for x in ('a','b','c','d','e','f','g'): locals()[x]={} > >which did what I wanted, in the interpreter. When I put it inside a function, >it doesn't seem to work. If I print locals() from inside the function, I can >see them, and they appear to be fine, but the first time I try to access one >of them I get a "NameError: global name 'a' is not defined" > >Now obviously I could easily avoid this problem by just initializing each >dictionary, but is there something wrong about my understanding of locals, >that my function isn't behaving the way I expect? > Others explained why locals()[x] worked interactively, and not in a function, but if you just want a one-liner, you could just unpack a listcomp: >>> a,b,c = [{} for i in xrange(3)] >>> a,b,c ({}, {}, {}) If you have single-letter names, you can avoid the count by stepping through the letters: >>> x,y,z = [{} for dont_care in 'xyz'] >>> x,y,z ({}, {}, {}) Or if you have a long target list and you can just type it and copy/paste it like: >>> fee,fie,fo,fum,bim,bah = [{} for ignore in 'fee,fie,fo,fum,bim,bah'.split(',')] >>> fee,fie,fo,fum,bim,bah ({}, {}, {}, {}, {}, {}) >>> map(id, (fee,fie,fo,fum,bim,bah)) [9440400, 9440976, 9438816, 9441120, 9440256, 9440544] The dicts are separate, as you can see: >>> id(a),id(b),id(c) (9153392, 9153248, 9439248) >>> a,b,c = [{i:chr(i+ord('0'))} for i in xrange(3)] >>> a,b,c ({0: '0'}, {1: '1'}, {2: '2'}) Regards, Bengt Richter From foo at bar.com Fri Nov 5 07:54:22 2004 From: foo at bar.com (Steve Menard) Date: Fri, 05 Nov 2004 07:54:22 -0500 Subject: JMS for CPython via JPype? In-Reply-To: References: <1b2k1czwwox4i$.ae466jlsmeu2$.dlg@40tude.net> Message-ID: <7KKid.39488$ab.575312@weber.videotron.net> Wolfgang Keller wrote: > Hello, > > and thanks for your reply. > > >>>would JPype make it possible >>>for a CPython program to use JMS? > > > >>I am not very well versed in JMS, but unless it absolutely REQUIRE >>subclassing, JPype will allow you to make full use for it without problem. >> >>How to actually interpret the contents of the JMS message is left as an >>exercise to the reader ;) > > > Err, does JPype not provide something for interfacing with Java like CTypes > provides it for interfacing with C? I.e. working with Java/C types in > Python as if they were Python variables? > > TIA, > > Regards > > Wolfgang Keller Indeed it does. For the most part, Java classes can be used just like regular Python classes. What I meant is that JMS messages can contain just about ANYTHING. Serialized Java classes, XML, plain text, etc ... Of course, if a regular Java program cna generate/interptet the contents, A python+Jpype program will be able to do it too. Again, with the same caveat that JPype does not (yet) support subclassing Java classes in python. Steve Menard From mefjr75 at hotmail.com Fri Nov 12 19:55:15 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 12 Nov 2004 16:55:15 -0800 Subject: Regarding color conversion (RGB->CMYK) References: <4194bd54$0$75308$edfadb0f@dread15.news.tele.dk> Message-ID: <18282ecb.0411121655.6dfb471e@posting.google.com> Johan Holst Nielsen wrote in message news:<4194bd54$0$75308$edfadb0f at dread15.news.tele.dk>... > Hi all, > > I hope someone can help me. > > I have do do a color conversion from RGB to CMYK. It's harder than I > thought :D Anyway, here is my problem. >[snip] > After that my thoughts was on PIL (Python Imaging Library). The colors > was better - but to bright - cause it didn't include K (so it was > basicly a RGB=>CMY conversion - Black is 100% Cyan, Magenta and Yellow). > I tried some googling - and again - some people said that PIL shouldn't > be used for images that should be printed "professional". This link might be a start. 'http://mail.python.org/pipermail/image-sig/2001-March/001386.html' Basically you are right the conversion is not straightforward and is somewhat error prone. Most of the time you have to tweak the colors, especially the deep blues. It is somewhat unavoidable when you map a additive colorsystem to a subtractive colorsystem. Maybe others might have a commandline hack for you. HTH, M.E.Farmer From peter at engcorp.com Tue Nov 30 14:47:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Nov 2004 14:47:51 -0500 Subject: Python 2.4c1 vs. 2.4 In-Reply-To: References: Message-ID: Russ wrote: > My sysadmin recently installed 2.4c1 on our network. Should we now > install 2.4, or is it the same as 2.4c1? Thanks. See http://www.python.org/2.4/NEWS.html -Peter From export at hope.cz Mon Nov 15 13:48:06 2004 From: export at hope.cz (Lad) Date: 15 Nov 2004 10:48:06 -0800 Subject: How to pass a parameter Message-ID: <81a41dd.0411151048.78af4fd3@posting.google.com> I have a sript that downloads a webpage. According to the picture on this webpage I need to pass a parameter to this , running script a few lines later. How can I do that? Thanks for help Lad From terti at mighty.co.za Mon Nov 29 13:52:34 2004 From: terti at mighty.co.za (tertius) Date: Mon, 29 Nov 2004 20:52:34 +0200 Subject: date diff calc In-Reply-To: References: Message-ID: <9fOdnRhSYreJ7TbcRVn-rw@is.co.za> Diez B. Roggisch wrote: > > I can't imagine what could possibly be easier than subtracting two dates - > in fact, most times one has to jump through much more hoops to achieve > these results, e.g. in java. > I'll try that. Thanks, T From domma at procoders.net Sat Nov 6 15:19:50 2004 From: domma at procoders.net (Achim Domma (Procoders)) Date: Sat, 06 Nov 2004 21:19:50 +0100 Subject: Pythonbindings for Subversion Message-ID: Hi, I'm looking for precompiled binaries of the SWIG Python 2.3 bindings for Subversion. I need them for http://www.edgewall.com/trac/ which does not work with PySvn. Can anybody help? regards, Achim From someone at microsoft.com Sat Nov 27 18:53:10 2004 From: someone at microsoft.com (Jive) Date: Sat, 27 Nov 2004 23:53:10 GMT Subject: A lock that times out but doesn't poll References: Message-ID: "David Bolen" wrote in message news:uis7sxu95.fsf at fitlinxx.com... > "Jive" writes: > > > I did find the MS-Windows timed lock extension though. > > That's pretty much what I use when I need them (at least under > Windows). For example, in a recent application I had a serious need > for low latency events and minimizing CPU while blocked. Switching > from the threading.Event to a Win32 event object was a big win on both > fronts, and are pretty drop-in in terms of functionality. I imagine > there is something similar in pthreads, but have not had the need > there yet. > > Probably the best way to support this sort of thing in Python itself > is with OS-specific blocks for cases which are easy to do and fall > back to the current implementation in others. But as has been posted > here before, that needs someone to make, test and then propose the > changes. > > -- David Ah ha! You understand. I live and breath this stuff. You too? Here is a common example from my line of work: You set a piece of machinery into motion. If everything is operating normally, it will reach a certain point and interrupt a light beam. You must react to that event instantly. However, if it has not interrupted the beam after some longer time, you must wake up because something is wrong. > Probably the best way to support this sort of thing in Python itself > is with OS-specific blocks for cases which are easy to do and fall > back to the current implementation in others. But as has been posted > here before, that needs someone to make, test and then propose the > changes. I would ammend that to read, "fall back on an improvement of the current implementation," but otherwise I agree. A year ago I volunteered (on this group) to do the general work, and the specific module for Windoze. I was told, "Just post your cute little code to some free software repository somewhere." At least that's the way I felt at the time. Of course, no one here knows "Jive" from Adam. There is a tendency on the net to assume anyone you don't recognise is a clueless newbie, and everything they post is naive blather. I've been cruising and using the newsgroups under one name or another since the mid 80's. So where was I before I went off into old fart mode? Oh yeah. It really should go into the main Python distribution. From opengeometry at yahoo.ca Mon Nov 22 14:51:23 2004 From: opengeometry at yahoo.ca (William Park) Date: 22 Nov 2004 19:51:23 GMT Subject: split large file by string/regex References: <7m9972-0c6.ln1@pc.dieringer.dyndns.org> Message-ID: <30eu9qF2vfdciU1@uni-berlin.de> Martin Dieringer wrote: > Jason Rennie writes: > > > On Mon, Nov 22, 2004 at 09:38:55AM +0100, Martin Dieringer wrote: > >> I am trying to split a file by a fixed string. > >> The file is too large to just read it into a string and split this. > >> I could probably use a lexer but there maybe anything more simple? > > > > If the pattern is contained within a single line, do something like this: > > Hmm it's binary data, I can't tell how long lines would be. OTOH a > line would certainly contain the pattern as it has no \n in it... and > the lines probably wouldn't be too large for memory... man strings (-o option) -- William Park Linux solution for data management and processing. From jack at performancedrivers.com Thu Nov 4 23:07:30 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 4 Nov 2004 23:07:30 -0500 Subject: Has anyone released a Python "mock filesystem" for automated testing? In-Reply-To: References: Message-ID: <20041105040729.GU16033@performancedrivers.com> On Thu, Nov 04, 2004 at 09:31:04PM -0500, Peter Hansen wrote: > The term "mock filesystem" refers to code allowing unit > or acceptance tests to create, read and write, and manipulate > in other ways "virtual" files, without any actual disk > access. Everything is held in memory and therefore fast, > without risk of damaging real files, and with none of the > messiness of leftover files after testing. > > Googling the archives and the web suggests that only I and > Remy Blank have done much along these lines. I don't see > any sign that anyone has actually released such a beast > yet, however. If linux only support is OK you should check out FUSE http://fuse.sourceforge.net/ It allows userspace implementations of file systems in python. The gmailfs (mount your gmail account) uses it. You could use it to write a 'real' file system that just has no disk backend store. It would be easy to implement special files to do things for testing, echo '1' > /op/nuke # clean everything echo '1' > /op/push # push the state of the filesystem echo '1' > /op/pop # restore the state of the filesystem to last 'push' And any other handy thing you can think of. It has the advantage that you can use regular python files in your program. Bugs in the implementation would hurt testing but that is the case any way you do it. Unrelated: I'm strongly tempted to [re]write a simple webapp like a blog as a filesystem. Just put apache on top to handle GETs and cat POSTs/PUTs directly to the filesystem. Can't get more unix-y than that! -Jack From NutJob at gmx.net Wed Nov 17 12:15:17 2004 From: NutJob at gmx.net (Markus Kemp) Date: 17 Nov 2004 09:15:17 -0800 Subject: Need function to test if EFFECTIVE UID has read-access to a file. Message-ID: <9b96ed1.0411170915.2b88da0e@posting.google.com> Hi all, Well, basically the title says it all. I can't use os.access() because it tests whether the REAL UID can read/write/exec the file. Surely there has to be a function that does what I need, but I can't seem to find it. Any input welcome. Regards, Markus From benn at cenix-bioscience.com Wed Nov 24 11:21:10 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 24 Nov 2004 17:21:10 +0100 Subject: teaching OO In-Reply-To: References: Message-ID: <41A4B4F6.2090602@cenix-bioscience.com> >As for the interesting C++ issues, those same students were able to pick >those concepts up quickly in their later classes. "Overloading", for >example, was a pretty simple concept to grasp for people who had previously >spent a whole semester heads down learning OO. > >Rob > > Hello, Just out of interest, did the students get confused between polymorphism acheived through duck-typing and polymorphism acheived through inheritence. Obviously not all OO languages have duck typing and they are subtly different concepts which may confuse a learner. Just a question, I'm not in education so I wouldn't know the best way to perform structured education (my teacher friends remind me of this all the time!!). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From bokr at oz.net Tue Nov 2 14:40:53 2004 From: bokr at oz.net (Bengt Richter) Date: Tue, 02 Nov 2004 19:40:53 GMT Subject: List problem References: <1gmiyon.jvyq1w1ob9r59N%aleaxit@yahoo.com> <41853d5f.1278687054@news.oz.net> <1gmjqh9.oialil1r1xwffN%aleaxit@yahoo.com> <41858eaa.1299498379@news.oz.net> <1gmkg86.1nzf8g91e7yby5N%aleaxit@yahoo.com> <418603c1.1325873395@news.oz.net> <1gmkjv7.fmssxmzmspbhN%aleaxit@yahoo.com> Message-ID: <4187e1bf.1448239858@news.oz.net> On Mon, 1 Nov 2004 11:01:15 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Bengt Richter wrote: > ... >> >I ran these on an 800 MHz laptop, the one I invariably use for netting >> >-- best ergonomics. OK, I'll try with faster machines when I get a >> >chance -- I'm surprised you measure almost a 1:2 ratio with _br faster. >> > >> Maybe the listcomp optimizations were introduced in 2.3.4? Or even 2.4.x? > >2.4, I think. > >> I have Python 2.3.2 on an old 300 MHz P2 with 320 MB RAM and NT4 as OS, >> so the mystery deepens ;-) > >The real mistery is why you don't download and install 2.4b1, which can >perfectly live side by side with your (outdated) 2.3 install...!-) > >Python's quality depends on people downloading and trying out the betas, >after all. If knowledgeable enthusiasts like you don't do it, who?-) > Ok, I made an effort ;-) The newfangled M$ installer is not compatible with my NT4 service pack level, so I will have to build from tgz. Ok, but my disk is too full for that at the moment ;-( So it will have to wait. Sorry. Regards, Bengt Richter From michele.simionato at gmail.com Fri Nov 19 13:42:25 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Nov 2004 10:42:25 -0800 Subject: using the bsddb from Python (missing docs!) References: <4edc17eb.0411180549.33719f1e@posting.google.com> Message-ID: <4edc17eb.0411191042.64ee3c7@posting.google.com> vincent wehren wrote in message news:... > The bsddb3 package has become part of the standard library as of 2.3, I > believe. The docs for this "full blown" bsddb package are not (yet) part > of Python docs, but off-site on http://pybsddb.sourceforge.net/bsddb3.html. I am a bit confused about pybsddb; is pybsddb exactly the same as the module bsddb in Python 2.3+ ? Originally I thought that pybsddb had more stuff in it, but now I tend to believe that they are the same. It is confusing since the docs are not in the standard distribution, so it is not clear if they are the same package (as optik and optparse, for instance) or not. Also, the docs of pybsddb are kind of terse: there is the API but there are no examples, so they are not very suitable for people without previous experience with the sleepycat database. This is the reason why I asked is somebody is aware of some journal article, or tutorial, or other useful stuff. Michele Simionato From news at weatherley.net Wed Nov 10 10:16:04 2004 From: news at weatherley.net (James Weatherley) Date: Wed, 10 Nov 2004 15:16:04 -0000 Subject: How to find MAC address and uids? References: Message-ID: In article , postmaster at earthlink.net says... > I'm writing a script for work and to finnish it, I need two bits of > information which I'm having trouble finding. > > 1) How can I programatically find the MAC address of the machine? Is it > stored in a file I can look into? (MacOS X) $ ifconfig | grep ether | awk {'print $2'} Note that there may be 0, 1 or many MAC addresses. > 2) If I have a user name in a string how do I get his UID? This gets the uid for 'james': $ nireport . /users name uid | grep james | awk '{print $2}' From mark.doberenz at righthemisphere.com Mon Nov 29 18:42:30 2004 From: mark.doberenz at righthemisphere.com (Mark Doberenz) Date: Tue, 30 Nov 2004 12:42:30 +1300 Subject: python API wrapper for C++ API Message-ID: <7A977E70F2DA7446B6F631A8A66CF18F01754C41@deep.cadtech> I'm fairly new at Python, but I've got a project I really want to do. I'm working with a real-time 3D program called Deep Creator, and it has a C++ API written for it. I'm wondering what it would take to create a Python wrapper that would allow me to write Python programs that would call the C++ API. The main issue I'm running into is that I need to create a DLL that I load as a plugin into Deep Creator. I then will specify a python program inside Deep Creator that I want to run, and the DLL plugin will be the link between the python program and Deep Creator. I'd really appreciate any ideas or issues that people see with this set up. Thanks, Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Fri Nov 12 05:57:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 12 Nov 2004 11:57:01 +0100 Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> <10p1ud2juqlkb7c@corp.supernews.com> <60dfb6f6.0411101037.5cd6a17d@posting.google.com> <10p52ccen1ql956@corp.supernews.com> <60dfb6f6.0411102119.2091c0d@posting.google.com> Message-ID: <1gn4za8.1sdorbl11cqco5N%aleaxit@yahoo.com> Carl Banks wrote: > My criteria is not whether the meaning is literal or figurative, but > whether it's specific. Solid is; rigid isn't. Hmmmm... I like to bank with a solid bank --> they won't go bankrupt tomorrow. Hopefully they're not rigid --> can accomodate to changing circumstances. And the bank's officers have years of solid experience at their jobs, and deserve my solid trust... Alex From caroundw5h at yahoo.com Mon Nov 8 23:48:01 2004 From: caroundw5h at yahoo.com (caroundw5h) Date: 8 Nov 2004 20:48:01 -0800 Subject: Problem flushing stderr in embedded python References: Message-ID: "Farshid Lashkari" wrote in message news:... > Hi, > > My application has python embedded into it. I noticed that when I run any > python code the output is buffered and doesn't get flushed until my > application exits. To fix this I simply flush sys.stdout and sys.stderr > every once in while by using the following code: > > //Get handle to python stdout file and flush it > PyObject *pyStdout = PySys_GetObject("stdout"); > if(pyStdout && PyFile_Check(pyStdout)) { > PyObject *result = PyObject_CallMethod(pyStdout,"flush",NULL); > Py_XDECREF(result); > } > > //Get handle to python stderr file and flush it > PyObject *pyStderr = PySys_GetObject("stderr"); > if(pyStderr && PyFile_Check(pyStderr)) { > PyObject *result = PyObject_CallMethod(pyStderr,"flush",NULL); > Py_XDECREF(result); > } > > This works for stdout but not for stderr. In order to flush stderr I have to > do: > > PyRun_SimpleString("sys.stderr.flush()"); > > Does anybody know why my first method doesn't work with stderr? I checked > and PyObject_CallMethod is being called for both objects and no errors are > occuring. The solution I have is acceptable, but I would still like to know > why my first method didn't work. > > BTW, I'm running python 2.3 on Windows XP > > Thanks, > > Farshid I'm sorry to notice that you haven't received any responses back to your questions even though you have found a workaround. I've noticed this trend quite a lot in the python community and having learned python first and now C(in order to understand python better) I'm frankly disspapointed. I believe python and C are a wonderful marriage but I suppose because many ppl come to python as their intro language they info on extending and embedding is limited. I myself haven't started using the python api but will soon, I hope I for one will be someone who will be able to provide an answer next time. Good luck. BTW: from a C perspective. I don't understand your problem though. stdout and stderr are the normal output device for your system - usally your screen. I don't see why you should have to call one via python sys module. Perhaps because one doesn't normally flush(stderr) explicity but flush(stdout). interested to know as well. From nehalmistry at gmx.net Tue Nov 23 17:58:05 2004 From: nehalmistry at gmx.net (Nehal) Date: Tue, 23 Nov 2004 14:58:05 -0800 Subject: problems uploading zipfile with cgi In-Reply-To: References: Message-ID: <20041123145805.00007313@nehal> On Tue, 23 Nov 2004 17:21:49 -0500 "Matthew Perpick" wrote: > > Hello All, > > trying to upload a zip file to a python cgi-script and I am > having some trouble. the form has enctype="multipart/form-data". > > i can access the file as a string like this: > > zip = form.keys['zip_file'].value > > but I cannot seem how to create a ZipFile object from this data. > It only wants a filename or a "file-like object" in the > constructor. > > can anyone help? I am a little bit lost. > > Matt > StringIO.StringIO(form.keys['zip_file'].value) will create a file-like object that you can use to construct the ZipFile -- Nehal From oliver.schoenborn at utoronto.ca Fri Nov 12 10:57:36 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Fri, 12 Nov 2004 10:57:36 -0500 Subject: problem with "setup.py bdist --formats=zip" Message-ID: I would like to create a "binary" distribution for Windows, but in zip format, since the installer requires root access. I don't want to use sdist because that includes all the C source and the source for generating documentation etc. When I try bdist_dumb, or "bdist --formats=zip", the zip has the files with *absolute* paths, as found on *my* system. This doesn't seem to make sense, since anyone with Python not installed in the same place as mine won't be able to unzip the distribution. Section 6.1 of python 2.3 docs has only one line of text saying something about "absolute" vs "relative" and "not implemented yet", somewhat surprising. So how do people do this? I guess I could create a MANIFEST_bin.in where I remove all the source stuff I don't want and replace sys.argv[1] with "sdist" if I find "bdist" there, but that doesn't seem very robust. Plus I then don't get the benefit of "bdist"-related stuff like putting "win32" in the zip file name, etc. Surely I'm not the only one who needs this? Thanks, Oliver From kent3737 at yahoo.com Sun Nov 28 10:54:23 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 28 Nov 2004 10:54:23 -0500 Subject: deleting os files In-Reply-To: References: Message-ID: <41a9f352$1_3@newspeer2.tds.net> John Aherne wrote: > Unfortunately, when it comes to delete, I get a permission error. And > yes, when I run the program and try to delete the file from the > command prompt, I get a permission error. > > As far as I can tell, I assume the file is being kept open in the > DictReader call. But I can't work out how I can close the file - > .close comand also returns an error. I was assuming that on the return > from the call the file would be closed - mistakenly I now think. > locallist = [(x) for x in os.listdir(localdir) if > os.path.getsize(os.path.join(localdir, x)) > 0] # upload all local > files > localfiles = fnmatch.filter(locallist, '*.OUT') > for localname in localfiles: > localpath = os.path.join(localdir, localname) > if localname[-3:] == 'OUT': > csv_file = file(localpath) > reader = csv.DictReader(csv_file,['phone', 'msg', 'PZ', 'MP']) > for row in reader: > phone = row['phone'] > msg = row['msg'] > > print time.ctime(time.time()),' uploading', msg, 'to', > phone csv_file.close() # after you finish reading the rows Kent From aleaxit at yahoo.com Wed Nov 3 16:53:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 3 Nov 2004 22:53:36 +0100 Subject: Python needs a CPyAN References: Message-ID: <1gmp685.b540351c59oy4N%aleaxit@yahoo.com> Ville Vainio wrote: > Python is no longer the obscure up-and-coming > scripting language. Yep, that's what Ruby is for. Alex From steven.bethard at gmail.com Tue Nov 2 15:15:41 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 20:15:41 +0000 (UTC) Subject: strong/weak typing and pointers References: <4187aafe$1@nntp0.pdx.net> Message-ID: Gabriel Zachmann writes: > > I understand strong/weak typing is more like a continuum -- > is there kind of a programming langauges hierarchy sorting various > langauges accoring to "type-strongness" that is generally agreed upon? Well, as you can probably see from the discussion, the definition of strong/weak typing isn't even agreed upon, so I'd be wary of giving a hierarchy. ;) The two main interpretations that I've seen in this thread: (1) Weakly-typed languages allow you to take a block of memory that was originally defined as one type and reinterpret the bits of this block as another type[1]. (This is the definition usually used in Programming Languages literature.) (2) Weakly-typed languages have more implicit coercions than strongly-typed languages. (This seems to be the favored definition on this newsgroup.) The answer to your question depends on which one of these definitions you're interested in. Definition (1) will have a much flatter hierarchy than definition (2). Which definition are you interested in? Steve [1] see my example at http://mail.python.org/pipermail/python-list/2004-November/248983.html From dripton at ripton.net Wed Nov 17 09:39:44 2004 From: dripton at ripton.net (David Ripton) Date: 17 Nov 2004 06:39:44 -0800 Subject: Python 2.2 on Red Hat References: Message-ID: <9b6f95cb.0411170639.6e5c45fc@posting.google.com> Andy Jacobs wrote in message news:... > I'm trying to install some anti spam software called ASK. This relies on > Python2.2 whereas my Cobalt RAQ4 is running 1.5.2 so I need to upgrade from > RPM. > > I've done a search and everything for Python2.2 says that it's for Red Hat > 7, 8 or 9. I'm running 6. I don't want to just go at this like a bull in a > china shop so wondered what the advice here might be. RedHat uses Python 1.5.2 for key OS tools like the Anaconda installer. Upgrading /usr/bin/python to something newer than 1.5.2 will break them. So you need to put a newer Python somewhere else. My advice is to install modern Python (like 2.3.4), from source (it's easy: standard ./configure; make; su; make install), under /usr/local. Then make sure that ASK usess /usr/local/bin/python instead of /usr/bin/python, by manipulating the PATH or a shebang line or whatever. RedHat's tools are hardcoded to /usr/bin/python so putting a second Python under /usr/local is safe. From ptmcg at austin.rr._bogus_.com Wed Nov 10 16:18:20 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 10 Nov 2004 21:18:20 GMT Subject: ConfigParser References: <35t4p0lou2lmcigaj2ic1fv9b253d5nq6k@4ax.com> Message-ID: "Ivo Woltring" wrote in message news:35t4p0lou2lmcigaj2ic1fv9b253d5nq6k at 4ax.com... > > ...the whole question is mute ;-)) > > Ivo. The word you are looking for is "moot", not "mute" - this is actually a common word misuse (known as a "malapropism") even for native English speakers. :) Pedantical-ly yours, -- Paul From thorsten at thorstenkampe.de Mon Nov 8 20:56:13 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 9 Nov 2004 02:56:13 +0100 Subject: Mixing Python And Bash References: Message-ID: <1swlxj7821qzo$.dlg@thorstenkampe.de> * Tom Purl (2004-11-08 21:17 +0100) > I just wrote a Python script that is going to be called from bash script. > If the Python script fails, I want the bash script to also stop running. > Unfortunately, I can't seem to get that to work. Here's the script so > far: > > # custom python script > /usr/bin/python /home/username/Dev/Python/packZODB.py \ > -s"gsgmc.sigma.zettai.net" -b 7 > > # next program > /usr/bin/someOtherProgram > > I don't want the second program to run if the first program fails. Isn't > that the default in bash? If someone could please point me in the right > direction regarding this problem, I would really appreciate it. Hm, not Python but bash related: if ~/Dev/Python/packZODB.py -s"gsgmc.sigma.zettai.net" -b 7; then someOtherProgram; fi From bingham at cenix-bioscience.com Tue Nov 30 04:36:28 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 30 Nov 2004 10:36:28 +0100 Subject: comment out more than 1 line at once? In-Reply-To: References: Message-ID: <41AC3F1C.5050404@cenix-bioscience.com> Riko Wichmann wrote: > Dear all, > > is there a way in Python to comment out blocks of code without putting > a # in front of each line? Somethings like C's > > /* > block of code here is commented out > */ No. Why do you want this? Any good programmer's editor will have a comment/uncomment feature to make it easy to comment out whole blocks of code at a time using the hash character ('#'). Aaron From peter at engcorp.com Fri Nov 5 09:26:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Nov 2004 09:26:56 -0500 Subject: Has anyone released a Python "mock filesystem" for automated testing? In-Reply-To: References: Message-ID: Mike Meyer wrote: > Peter Hansen writes: > >>The term "mock filesystem" refers to code allowing unit >>or acceptance tests to create, read and write, and manipulate >>in other ways "virtual" files, without any actual disk >>access. Everything is held in memory and therefore fast, >>without risk of damaging real files, and with none of the >>messiness of leftover files after testing. > > Just out of curiosity, does your os implement some form of disk in > memory disk? Go to and > search for either mfs or md for examples. I need to be cross-platform, so Windows and Linux must both be supported. I suspect there isn't good support on Windows for the sort of thing you describe. In any case, though I thank you and Jack for the ideas, the pure-Python in-memory approach seems to be quite viable and probably quite a bit simpler. In addition it allows testing with paths and operations that could not be safely supported if real file access was permitted at all, so I think I'll stick with it. > Second, consider using os.sep for path seperation, so that testing can > be done correctly for the OS the project is running on. Or possibly a > flag to indicate whether or not you want to use os.sep. I've never had to resort to using os.sep myself. I use os.path.split() and os.path.join() and it seems they do the job for me. ;-) -Peter From ggg at zzz.it Fri Nov 5 03:25:54 2004 From: ggg at zzz.it (deelan) Date: Fri, 05 Nov 2004 09:25:54 +0100 Subject: MySQL blobs confusion In-Reply-To: <3mclo05un9qh2ojufh02ic8me6o7c2mh11@4ax.com> References: <3mclo05un9qh2ojufh02ic8me6o7c2mh11@4ax.com> Message-ID: <3gdfmc.aq9.ln@news1.interplanet.it> Kirby Urner wrote: > I've been testing the Cookbook example 8.6 (2002 edition) re using cPickle to > insert and retrieve BLOBs from mySQL, using Python's MySQLdb module. > > When I try to cPickle.loads(blob), I get an error telling me that loads wants a > string, not type array.array. So I go cPickle.loads(blob.tostring()) instead > and it works. see bug: ''Cursor returns array instead of string for blob column type The standard cursor class ('Cursor') used to return MySQL blob row types as Python string values. In version 1.0 it returns arrays containing a single item with the string 'c' as key and the blob string as the value.'' BTW i'm using this code: pickle.loads(row['meta']) to unpickle a blob field (in the 'meta' column) from a mysql4's MyISAM table and it works as-is. i'm using both mysqldb 1.0.0 (dev box) and 1.1.6 (on the server). but i'm using DictionaryCursor instead of classic return-as-tuples Cursor. cheers, deelan. -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From mfuhr at fuhr.org Fri Nov 5 18:35:50 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 5 Nov 2004 16:35:50 -0700 Subject: executing python code References: <418c0870$1_4@omega.dimensional.com> Message-ID: <418c0e56_1@omega.dimensional.com> Darren Dale writes: > Yes, I did chmod, the script is in the current directory. > > $ mycode.py > bash: mycode.py: command not found > > I just tried: > > $ ./mycode.py > > and that will execute. That means the directory isn't in your PATH environment variable, neither as a full path (/path/to/the/directory) nor as ".", which means the current directory. For security reasons it's usually wise to leave "." out of your PATH, so if you don't want to type ./mycode.py each time then put your scripts in a directory that PATH knows about. As others have mentioned, a common place for a user's private scripts is in ~/bin, that is, the "bin" directory under your home directory. If it doesn't exist then you can use mkdir to create it, and if it's not in your PATH then you'll need to add it. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From tim.peters at gmail.com Tue Nov 16 22:58:15 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 16 Nov 2004 22:58:15 -0500 Subject: Will python ever have signalhandlers in threads? In-Reply-To: References: <4195419b.303035081@news.oz.net> Message-ID: <1f7befae04111619586865dca9@mail.gmail.com> [Uncle Timmy, explains why Python requires so little of platform threads] [Antoon Pardon] > I don't fault the current Queue implementation. I think your arguments > are very strong I don't <0.5 wink>. Threading support in Python is forever frustrated by the seeming need not to make trouble for the oddball thread implementations we have but aren't even sure anyone uses anymore. For example, the Python core could benefit from exploiting platform-supplied thread-local-storage gimmicks. But we never move in that direction, because the prospects of implementing it for all the existing thread_PLATFORM.h wrappers appear too dim. Instead we rolled our own implementation of thread-local storage, again building on no more than "the Python lock". It's not particularly efficient, and especially not after I fixed a critical thread race in it just a few weeks ago, effectively serializing all lookups. If Python *could* assume, e.g., that only pthreads boxes and Windows are still interesting (it's clearly impossible that we could get away with supporting a set that doesn't include those two; it's not clearly impossible that we could get away with supporting only those two), then we could assume a much richer set of platform-supplied threading primitives to build on. > and I'm not arguing that the current Queue implementation > should be replaced by a dozen none portable system dependent > implementation. That's OK -- the only *effective* away to make that argument would have been to supply a patch doing all the work yourself anyway . > But by limiting the signal module as it is now you make > it that much harder for people on posix systems to come up for a > different implementation on those systems. Who's "you"? It can't be me. Since I normally run on Windows, I pay no attention to the signal module, let alone stay up nights plotting to make it harder to live with. Guido is another matter; search Google for, e.g, quotes like Threads and signals don't mix. Period. (Only half a smiley. :-) and I admit that I hate signals so badly that whenever I needed to wait for a child to finish I would always structure the program around this need (even when coding in C). and Why? I don't think hating signals disqualifies me from understanding their problems. and I've always been reluctant about the fact that we had a signal module at all -- it's not portable (no non-Unix system supports it well), doesn't interact well with threads, etc., etc.; however, C programmers have demanded some sort of signal support and I caved in long ago when someone contributed a reasonable approach. I don't regret it like lambda, but I think it should only be used by people who really know about the caveats. and I wish we could invent a Python signal API that only lets you do one of these simple things. I confess I had a similar hatred of signals in my Unixish days (they weren't portable, weren't reliable, & usually created debugging nightmares much worse than the problems uses of signals were introduced "to solve"), but Guido is the one who'll stab you in the back today. I'll just cheer him on . > The problem I have with the current implementation is not so much one > of burden on the system but one of possible "starvation" of a thread. > > Suppose we have a number of consumers on a Queue, some simply > block and others use timeouts. The current implementation disfavors > those threads with a timeout too much IMO, because the block > threads ask for the lock continuosly while the timeout threads only > ask for the lock periodically. That's certainly true. OTOH, I've never written, or worked with, an app where, for a given Queue, some threads used timeouts but others didn't. It seems strained to me. Then again, I'm not sure I've ever worked on a real app where any thread used a timeout gimmick with a Queue. most-things-that-are-possible-shouldn't-be-done-ly y'rs - tim From irmen at -nospam-remove-this-xs4all.nl Mon Nov 22 15:40:03 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 22 Nov 2004 21:40:03 +0100 Subject: if need small python executable In-Reply-To: <77969915.0411221152.6f293b6f@posting.google.com> References: <77969915.0411221152.6f293b6f@posting.google.com> Message-ID: <41a24ea1$0$78753$e4fe514c@news.xs4all.nl> Nickolay wrote: > it's easy to create small executable from python code, when using > assembler compilers. I ask you if need it? What's an assembler compiler? I also don't understand your actual question. --Irmen From tjreedy at udel.edu Wed Nov 3 23:23:15 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 3 Nov 2004 23:23:15 -0500 Subject: pep 336: Make None Callable References: Message-ID: "The Eternal Squire" wrote in message news:dv6dndASE7CxNBTcRVn-pw at comcast.com... > PEP: 336 > Abstract > > None should be a callable object that when called with any > arguments has no side effect and returns None. Please no. The None object, by definition, is an object with no value, no behavior (except compares), and no specific attributes (other than those common to all descendents of object). That one can currently compare None to other objects can be considered a bug, and this might go away in the future. Anyone who wants a null function can write it in about 20 keypresses, and include it in a utility module if one has one. It would be more sensible to promote the addition to builtins of a predefined null function -- one somewhat equivalent to 0, [], and {}. Terry J. Reedy From theller at python.net Wed Nov 3 12:50:05 2004 From: theller at python.net (Thomas Heller) Date: Wed, 03 Nov 2004 18:50:05 +0100 Subject: threads and exception in wxPython References: <6_qdnQZOZ_YYZRXcRVn-sw@powergate.ca> Message-ID: <4qk6zusy.fsf@python.net> Peter Hansen writes: > Peter Hansen wrote: >> So the exception managed to get to the new thread, even though >> I called SetAsyncExc *before* the thread was even created. >> Now _that's_ what I call "asynchronous". ;-) > > Actually, it's what you call pilot error. I was retrieving > threading._get_ident() in the thread initializer *before* > the thread was even started... stupid pilot. > > Here's the final working version: > > >>> class T(threading.Thread): > ... def __init__(self): > ... threading.Thread.__init__(self) > ... self.stopped = False > ... self.start() > ... def run(self): > ... self.id = threading._get_ident() > ... try: > ... while not self.stopped: > ... time.sleep(0.1) > ... except: > ... print 'thread terminated!' > ... > >>> t = T() > >>> t > > >>> asyncexc = ctypes.pythonapi.PyThreadState_SetAsyncExc > >>> exc = ctypes.py_object(ValueError) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > >>> asyncexc(t.id, exc) I'm not sure this is the way to do it (but py_object is completely undocumented, so far, and I don't rememeber the details myself). But, it is fine to pass the id() of a python object, which is an integer specifying it's address, when the function expects a PyObject*: asyncexc(t.id, id(ValueError(42))) > 1 > >>> thread terminated! > > >>> t > > > > -Peter Thomas From kayschluehr at gmx.de Sat Nov 20 20:19:34 2004 From: kayschluehr at gmx.de (Kay Schluehr) Date: Sun, 21 Nov 2004 02:19:34 +0100 Subject: Python and generic programming Message-ID: <419FED26.4030606@gmx.de> Jive Dadson wrote: > How about specialization? I'm relatively new to Python. I ask for > information, not to be argumentative. There is no such thing as template specialisation or method overloading in Python due to the lack of static typing. > If you have, for example, several data-types for matrices, how do you > write code that will automatically find the right routine for quickly > multiplying a vector by a diagonal matrix represented as a vector, and > automatically call the right code for multiplying by a sparse matrix > represented by some sparse coding, etc? Here is some code that enables automatical dispatches according to a chain of function decorators. The chain is terminated by a decorator that does not force any type ( here symbolized by None ) and triggers a default function. The mul() function in the example defines inner functions that represent different algorithms on different types. The mul() function itself does not return the result of a multiplication, but the list of "specialized" inner functions ( which are in fact as generic as all other Python functions, but they can be regarded as specialized in this context ). Keep attention that the decorator chain will not work if the decorator @when(None,"default") is not the last one in the chain. # decorator function def when(types, name): def push(f): def eval(*t): funcs = [] args = t[3] conds = [t[:2]] while 1: s = t[2](*t[3]) if s[-1]=='stop': conds.insert(0,s[:2]) else: funcs = s break t = s for (_types, funcname) in conds: bTypesOk = True if _types: for (a, t) in zip(args, _types): if not isinstance(a,t): bTypesOk = False break if bTypesOk: for f in funcs: if f.func_name == funcname: return f(*args) else: bTypesOk = True raise NameError,"No available function found that matches default" def pop(*args): if types is None: return eval(types,name,f,args,"stop") return types,name,f,args,"stop" return pop return push # example code from decimal import Decimal @when(None,"default") @when((int,float),'mul_float') @when((float,float),'mul_float') @when((Decimal,Decimal),'mul_dec') def mul(m1,m2): def default(m1,m2): return "default",m1*m2 def mul_float(m1,m2): return "mul_float",Decimal(str(m1))*Decimal(str(m2)) def mul_dec(m1,m2): return "mul_dec",m1*m2 return (default,mul_dec,mul_float) Ciao Kay From abra9823 at mail.usyd.edu.au Thu Nov 4 09:06:07 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Fri, 5 Nov 2004 01:06:07 +1100 Subject: seg fault Message-ID: <1099577167.418a374fbc1fc@www-mail.usyd.edu.au> hi! i have some code with a gui that does some processing in another thread, say t2. when t2 needs to display something on the gui, it generates an event (which i have binded earlier). the code runs fine on windows but segfaults on linux. the point where it segfaults is when it generates the event. any ideas why? the code is #app.py import sys sys.path.append('\\Program Files\\Python\\Lib\\python23.zip\\lib-tk') sys.path.append('/n/filer1/u1/hons2004/rwhitake/elvin/local/usr/lib/python2.3/site-packages/') import os from Tkinter import * import tkMessageBox import tkFileDialog import tkSimpleDialog from Queue import Queue from time import localtime import threading import elvin class Phone: def __init__(self, master): self.frame = Frame(master) self.frame.pack() Label(self.frame, text="Enter message", justify=LEFT).grid(row=0) self.entryMessage = Entry(self.frame, width=25) self.entryMessage.grid(row=1, column=0) Button(self.frame, text="Send", command=self.sendMessage).grid(row=4, column=0) v_scrollbar = Scrollbar(self.frame, orient=VERTICAL) v_scrollbar.grid(row=5, column=1, sticky=N+S) h_scrollbar = Scrollbar(self.frame, orient=HORIZONTAL) h_scrollbar.grid(row=6, column=0, sticky=E+W) self.answerText = Text(self.frame, width=25, height=15, xscrollcommand=h_scrollbar.set, yscrollcommand=v_scrollbar.set) self.answerText.grid(row=5, column=0, sticky=N+S+E+W) self.answerText.config(state=DISABLED) self.q = Queue() self.reply="" self.frame.bind("<>", self.displayReply) self.phnumber = tkSimpleDialog.askstring("Phone number", "Enter phonenumber", parent=self.frame) if self.phnumber is None: sys.exit(0) self.th = threading.Thread(target=self.setElvin) self.th.start() def setElvin(self): elvin_con = elvin.connect("elvin://praxis.it.usyd.edu.au") sub = elvin_con.subscribe("equals(type, 'FREEVO_SMS_REPLY')") sub.add_listener(self.answerMessage) sub.register() elvin_con.run() def sendMessage(self): message = self.entryMessage.get() if message == "": tkMessageBox.showerror("Error", "Enter message", parent=self.frame) return offset = "+1000" t=localtime() date=str(t.tm_mday) + "/" + str(t.tm_mon) + "/" + str(t.tm_year) time=str(t.tm_hour) + ":" + str(t.tm_min) + ":" + str(t.tm_sec) con = elvin.connect("elvin://praxis.it.usyd.edu.au") con.notify(type="FREEVO_SMS", SMSSource=self.phnumber, SMSDestination="foo", SMSDate=date, SMSTime=time, SMSGMTOffset=offset, SMSText=message) def answerMessage(self, sub, msg, insec, rock): print msg self.reply = msg.get("SMSMessage") dest = msg.get("SMSDestination") if dest == self.phnumber: self.frame.event_generate('<>', when='tail') def displayReply(self, event=None): self.answerText.config(state=NORMAL) self.answerText.insert(INSERT, self.reply+"\n\n") self.answerText.config(state=DISABLED) root = Tk() phone = Phone(root) root.mainloop() ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From elbertlev at hotmail.com Tue Nov 2 11:43:26 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 2 Nov 2004 08:43:26 -0800 Subject: Twisted problem Message-ID: <9418be08.0411020843.7061abc8@posting.google.com> Hi! I'm having a problem with twisted on windows. Installed it and started finger tutorial. All was working fine untill stem 11 - running twistw (twistd in documentation). It dies with now error indication. Tried debugin it, but also with no succes: process terminates before getting to the run() method def run(): app.run(runApp, ServerOptions) Please help. From carribeiro at gmail.com Thu Nov 18 07:18:48 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 18 Nov 2004 10:18:48 -0200 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) In-Reply-To: <1gnf7n6.1spfeu41yhjcdaN%aleaxit@yahoo.com> References: <1gnbg4k.13z20mj1w1o0ysN%aleaxit@yahoo.com> <30001hF2ptnqcU1@uni-berlin.de> <419bbf2a.319309032@news.oz.net> <1gnf7n6.1spfeu41yhjcdaN%aleaxit@yahoo.com> Message-ID: <864d370904111804185f293932@mail.gmail.com> On Thu, 18 Nov 2004 08:56:30 +0100, Alex Martelli wrote: > Bengt Richter wrote: > > Still, as Carlos pointed out, formal parameter names > > are private to a function, > > ? No they're not -- a caller knows them, in order to be able to call > with named argument syntax. On my original post I pointed out that named arguments are an exception to this rule. For the most of the times, the caller does not *need* to know the internal argument names. Named arguments are entirely optional, and in fact, if you provide the arguments in the correct order, you can avoid using them in almost every situation (**kw being the exception). The point was: fixing names on the return code introduces coupling. But after thinking a little bit more, the issue does not seem as clear to me as before. After all, *some* coupling is always needed, and positional return values also are "coupled" to some extent. I think that the named tuples idea is nice because it works entirely symmetrical with the named arguments; it allows to use a shortcut positional notation, or to use a named access, at the will of the programmer, for the same function call. > > I.e., if the dict has additional content, it is not an error > > Agreed, by analogy with '%(foo)s %(bar)s' % somedict. > > > Hm, do you want to go for a dict.get-like default value in that? > > No, enriching dicts to support an optional default value (or default > value factory) looks like a separate fight to me. As does syntax sugar, > IMHO. If we can get the semantics in 2.5 with a PEP, then maybe sugar > can follow once the usefulness is established to GvR's contents. I'm also trying to focus on tuples, so I'm leaving dicts out of this for now. But clearly named tuples & immutable dicts are closely related; but of the two, named tuples have an advantage because they are naturally ordered. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Wed Nov 3 17:06:39 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 3 Nov 2004 23:06:39 +0100 Subject: general class functions References: Message-ID: <1gmp6em.1ln10wve2zid5N%aleaxit@yahoo.com> syd wrote: ... > But more importantly, why is subclassing object a good practice in "Subclassing object" gives you newstyle classes, instead of the default classic classes we're stuck with, for backwards compatibility, until a Python 3.0 comes out that can break such compatibility. Other ways to make a class newstyle include inheriting from any other newstyle type (including builtin types) and setting __metaclass__=type . The newstyle object model fixes many tiny but irritating warts that the classic object model is stuck with, such as instance dicts always taking precedence over classes (and thus the inability to use descriptors, e.g. properties, to full advantage), the classic model's oversimplified concept of method resolution order in multiple-inheritance situations, and the intrinsic asymmetry of class->metaclass vs instance->class semantics in the classic object model. Alex From peter at engcorp.com Fri Nov 12 22:55:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Nov 2004 22:55:32 -0500 Subject: Python 2.4: Why only assignments to None are forbiden? In-Reply-To: <4195190f@pfaff2.ethz.ch> References: <4195190f@pfaff2.ethz.ch> Message-ID: Josef Meile wrote: > I think in general assignments to built-in types, functions, and > variables should be also forbiden. Very little in Python should be *forbidden*. Certainly not something like this! Maybe make it hard to do inadvertently. Maybe require it be an explicit call to a special function or something. But forbid it? Please no! One perfectly good reason to assign to builtins (and there are others, I'm sure) is to provide a "mock" function to replace a standard one, for use during automated testing. See, for example, the reference to a "mock filesystem" that I posted a few days ago, where you can insert your own "open" function in the builtin namespace, providing a fake filesystem that intercepts all file creation and reading and simulates the behaviour. You can do this easily on a single module, or several, just by inserting a global into the module(s) in question, but if you want to do it through an application it becomes a real burden (and a way to let bugs leak through) to have to do it that way. A single assignment override to the standard open is much more effective and safe. Every time this issue comes up I feel compelled to point out this perfectly useful and valid use of assigning to builtins... I really hope the message gets through. -Peter From crgre.znnf at hgvybt.qr Fri Nov 12 16:07:14 2004 From: crgre.znnf at hgvybt.qr (Peter Maas) Date: Fri, 12 Nov 2004 22:07:14 +0100 Subject: web hosting with Python In-Reply-To: <3cccb1d8.0411101416.690960c3@posting.google.com> References: <3cccb1d8.0411101416.690960c3@posting.google.com> Message-ID: <2vkn2sF2nli34U1@uni-berlin.de> MJR schrieb: > anybody could recommend web hosting company which offer professional > reseller package with Python, preferable located in Europe? www.domainfactory.de. They installed Python 2.3.4 to get rid of my support requests :). They are offering some reseller packages, too. Python support is confined to plain CGI, nothing fancy like mod_python, Webware, ... -- Peter Maas, Aachen, Germany, Tel +49-241-38200 e-mail crgre.znnf at hgvybt.qr From nhodgson at bigpond.net.au Thu Nov 11 07:07:57 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 11 Nov 2004 12:07:57 GMT Subject: generic way to access C++ libs? References: <5V0kd.30218$K7.5461@news-server.bigpond.net.au> Message-ID: Neil Hodgson: # Much of the time C++ code only has to be compatible with the other # modules it is delivered with. Jorgen Grahn: > But most of the time it has to be compatible with the standard library. > > Even if these flags exist, I think it's very rare to encounter more than one > layout, for one specific compiler/compiler version/architecture. The most commonly changed layout option is structure packing. Many C/C++ projects decide upon a particular packing option often just to be compatible with files from the initial version or other applications and libraries. The C++ standard library data types (vector, basic_string, etc.) are mostly defined in header files which are compiled with the client code and so use the same options. C system libraries like standard I/O and platform libraries like Win32 use explicit compiler instructions to ensure they can deal with client option choice. The Win32 headers use #pragma pack(n) to ensure that client code will compile assuming particular packing of system structures no matter how the client code is packing its own structures. A C++ specific example is the use of the __declspec(novtable) compiler directive (indirectly through the AFX_NOVTABLE macro) on many of the interfaces in Microsoft's widely used ATL to remove code that references the vtable and hence (normally) remove the vtable. A generic C++ library accessor that opens a library based on ATL may have to know that some classes that would be expected to have vtables will not actually have them. Neil From jgrahn-nntq at algonet.se Sun Nov 14 02:27:27 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 14 Nov 2004 07:27:27 GMT Subject: Advice needed References: Message-ID: On Sat, 13 Nov 2004 20:00:23 +0000, Paul Robson wrote: > On Sat, 13 Nov 2004 16:57:41 +0000, Premshree Pillai wrote: > >> Lots of reasons why you should learn Python. I'll >> leave that to others in the mailing-list. :) >> >> I'm not sure where I heard the following, but I've >> heard it: >> "If God did OOP, he'd do it in Python." > > If God did it he might have figured out len() should be a method... Another reason to stay away from monotheism I guess ... -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From steve at holdenweb.com Sat Nov 13 11:10:43 2004 From: steve at holdenweb.com (Steve Holden) Date: Sat, 13 Nov 2004 11:10:43 -0500 Subject: Advice needed In-Reply-To: <1100361297.413616.17890@f14g2000cwb.googlegroups.com> References: <1100361297.413616.17890@f14g2000cwb.googlegroups.com> Message-ID: <1sqld.731$nj.183@lakeread01> Alberto wrote: > I was trying to understand the reasons why I should learn Python. More > like a pros/cons about this language. Currently, I use C, C/C++, Java, > Perl, Visual VB and was looking to see the usefulness of Python. Any > suggestions? > Do some Googling, look at what Python can do, make your mind up. There's no point adding yet another language to the armory just for the sake of it, good though the new language might be. Think of problems that have been difficult to solve using your present toolset and see if you can find Python soltuions that seem to be more elegant. With your programming background you can learn enough Python in a long day's Googling to let you make your mind up. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From fumanchu at amor.org Tue Nov 30 17:54:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 30 Nov 2004 14:54:57 -0800 Subject: A way to wait Python event Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32452E5@exchange.hqamor.amorhq.net> Diez B. Roggisch wrote: > > I tried to launch "python.exe test.py" in another program. After the > > launch the console was showed and exited on Windows. I want the > > console stay there. Is there a Python statement to wait an > event loop > > like Tcl's "after forever"? > ... > Apart from that, there might be some hidden "keep this damn > window open > after the executed progam terminated"-checkbox. Happy hunting. http://www.google.com/search?q=windows+console+remain+open Use the /k switch to cmd.exe Robert Brewer MIS Amor Ministries fumanchu at amor.org From bokr at oz.net Mon Nov 29 18:56:11 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 29 Nov 2004 23:56:11 GMT Subject: Random number generation from functions References: Message-ID: <41abb4bd.1365216397@news.oz.net> On Mon, 29 Nov 2004 20:51:50 GMT, "drs" wrote: >Is there any way to generate random numbers based on arbitrary real valued >functions? I am looking for something like random.gauss() but with natural >log and exponential functions. > >thanks, Don't know what you mean. This kind of thing? (the 1-random... is to make the random numbers in (0,1] instead of [0,1)) >>> import random >>> import math >>> math.log(1.0-random.uniform(0,1)) -0.90030288455841156 >>> math.log(1.0-random.uniform(0,1)) -0.261249141864835 >>> math.log(1.0-random.uniform(0,1)) -0.99694366818547997 Regards, Bengt Richter From mortenjo at ifi.uio.no Tue Nov 30 15:17:20 2004 From: mortenjo at ifi.uio.no (Morten Lied Johansen) Date: Tue, 30 Nov 2004 20:17:20 +0000 (UTC) Subject: RELEASED Python 2.4 (final) References: Message-ID: On Tue, 30 Nov 2004 23:31:34 +1100, Anthony Baxter wrote: > > On behalf of the Python development team and the Python community, I'm > happy to announce the release of Python 2.4. Question from a noob: I have several third party python-modules installed on my current Windowssystem, and I was wondering if there is a way to upgrade to Python 2.4 without having to download and install all of those again? Thanks in advance for any suggestions. :) -- Morten Trees hit cars only in self-defence. From bokr at oz.net Mon Nov 15 15:25:12 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 15 Nov 2004 20:25:12 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: <4199072c.141135391@news.oz.net> On 15 Nov 2004 11:44:31 GMT, Antoon Pardon wrote: >Op 2004-11-15, Peter Hansen schreef : >> Antoon Pardon wrote: >>> AFAIU the Queue module doesn't block on a full/empty queue when >>> a timeout is specified but goes in a loop sleeping and periodically >>> checking whether place/items are available. With signals that >>> can be sent to a thread the queue could just set an alarm and >>> then block as if no timeout value was set and either unblock >>> when place/items are available or get signalled when the timeout >>> period is over. >> >> I'm fairly sure that the Queue uses an internal Event >> (or REvent?) to signal when space or a new item is >> available, so I believe your description (and possibly >> conclusion) above is wrong. There should be no >> "periodical check", as that would imply polling. Check >> the source if you're interested. > >I did check the source, I just didn't study it carefully >and got my understanding mostly from the comments. >But anyway here is the relevant part and IMO we have >a polling loop here. It looks like you are right, at least on NT, where it is a shame, since thread_nt.h only uses WaitForSingleObject with INFINITE timeout specified, and it would seem the ideal timeout support API could be provided. Maybe the lock acquire method could have an optional keyword arg timeout=floatingseconds, and for NT that could be converted to milliseconds and used to wait for the mutex with a non-inifinite wait. But it's platform dependent what low level OS support there is for locks with timeouts. However, a win32 solution should benefit a fair proportion of users, if many windows users do threading. > > >class Queue: > > ... > > def get(self, block=True, timeout=None): > """Remove and return an item from the queue. > > If optional args 'block' is true and 'timeout' is None (the default), > block if necessary until an item is available. If 'timeout' is > a positive number, it blocks at most 'timeout' seconds and raises > the Empty exception if no item was available within that time. > Otherwise ('block' is false), return an item if one is immediately > available, else raise the Empty exception ('timeout' is ignored > in that case). > """ > if block: > if timeout is None: > # blocking, w/o timeout, i.e. forever > self.esema.acquire() > elif timeout >= 0: > # waiting max. 'timeout' seconds. > # this code snipped is from threading.py: _Event.wait(): > # Balancing act: We can't afford a pure busy loop, so > # we > # have to sleep; but if we sleep the whole timeout time, > # we'll be unresponsive. The scheme here sleeps very > # little at first, longer as time goes on, but never > # longer > # than 20 times per second (or the timeout time > # remaining). > delay = 0.0005 # 500 us -> initial delay of 1 ms > endtime = _time() + timeout > while 1: > if self.esema.acquire(0): > break > remaining = endtime - _time() > if remaining <= 0: #time is over and no element arrived > raise Empty > delay = min(delay * 2, remaining, .05) > _sleep(delay) #reduce CPU usage by using a sleep > So, it would seem this kind of thing could be hidden in platform-specific files where it was really necessary. Probably the people who can do it are too busy ;-) Regards, Bengt Richter From aleaxit at yahoo.com Fri Nov 12 05:27:01 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 12 Nov 2004 11:27:01 +0100 Subject: ZIP files References: <808f000f.0411100805.7bff7e5d@posting.google.com> <6f402501.0411120120.3f5147d6@posting.google.com> Message-ID: <1gn4y9w.3frb611oy9y8pN%aleaxit@yahoo.com> Michael Foord wrote: > Hmmm... does this mean that > > open(filename, 'w').write(filedata) > > is unsafe ? It's so much more convenient when the object is only going > to be used for the single action. It's not exactly unsafe -- but you do risk, depending on what implementation of Python you're dealing with, that the file object will just stay open until some unknown time in the future (no later than the end of your program's run;-). This may potentially lead to problems if your program is long-running or open lots of files, etc. def write_data(filename, data, flags='w'): fileobject = open(filename, flags) try: fileobject.write(data) finally: fileobject.close() needs to be coded once, and then makes the operation just as convenient as doing it inline... Alex From davecook at nowhere.net Tue Nov 30 06:11:37 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 30 Nov 2004 11:11:37 GMT Subject: comment out more than 1 line at once? References: Message-ID: On 2004-11-30, Uwe Grauer wrote: > if you are using emacs, try C-c # to comment out a block of code. > Unfortunally Uncomment is not bound to a key by default. Uncomment is C-u C-c #, at least in xemacs. Rectangle delete sometimes works in a pinch (C-x r k, once you've marked the rectangle.) Dave Cook From sxanth at ceid.upatras.gr Tue Nov 16 01:26:13 2004 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Mon, 15 Nov 2004 22:26:13 -0800 Subject: save a dictionary in a file In-Reply-To: <2vsa8hF2oa58tU1@uni-berlin.de> References: <2vsa8hF2oa58tU1@uni-berlin.de> Message-ID: <41999D85.2010409@ceid.upatras.gr> Luis P. Mendes wrote: > > Is there a more commonly used form to do it, yet in a simple way? > Yes. If the dictionary contains only strings, numbers, lists and tuples of strings, numbers, and lists and tuples, of (infinite resursion. program halted) You can FILE.write ('D=' + str (D)) and then execfile the file. Stelios From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Nov 15 23:14:44 2004 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 15 Nov 2004 23:14:44 -0500 Subject: Identifying bundles in MacOS X References: <2vt7veF2nues7U1@uni-berlin.de> Message-ID: In article <2vt7veF2nues7U1 at uni-berlin.de>, Greg Ewing wrote: > Michael J. Fromberger wrote: > > Given the pathname of a directory in my filesystem, I would like a > > graceful way to determine whether or not that directory represents > > a "bundle", in the sense that, when you double-click on the > > directory's icon in the Finder, it is launched rather than "opened" > > for viewing. Applications behave this way by default, but so do > > various other file types (e.g., the "rtfd" files created by > > TextEdit, and the data files for certain applications such as > > Quicken). > > I think that a MacOSX-style application can be recognised simply by > the fact that it's a directory whose name ends in ".app". (You don't > usually see that extension in the Finder, but all MacOSX application > bundles seem to have it.) Actually, Apple's developer documentation seems to imply that there is a "bundle bit" in the Finder info (or possibly the extended Finder info) for directories, and that if this bit is set, the Finder will treat the folder as a bundle. At any rate, there are many bundle-like directories other than just ".app" files and old-style 'APPL' type files. The trouble is, the Carbon.File module does not seem to expose the appropriate fields of the FSCatalogInfo structure from the Carbon API, so I can't get at that bit from within Python. I found and adapted a patch to Mac/Modules/file/_Filemodule.c, that makes the finderInfo and finderXInfo fields visible, but either I did it wrongly, or there is some other issue I've missed, for I get nothing but an empty FInfo structure back when I try to access either of them. I guess my next step should be to write a C program against the Carbon API, and see if I can get the information that way -- if so, I guess I will just have to patch the Carbon.File module myself. If not, I might have to admit defeat for now. Meanwhile, I'm using a workaround, a.k.a. a gross hack: If the directory's name has one of a set of "known" extensions, or if it contains a directory named "Contents", and if it doesn't have more than a few files at its top level apart from the "Contents" directory, I'm considering it a bundle. That works well enough for my purposes, but I'd really rather have it work "correctly." Thanks for taking the time to write back! Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From strombrg at dcs.nac.uci.edu Wed Nov 10 17:41:09 2004 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Wed, 10 Nov 2004 22:41:09 GMT Subject: html parsing? Or just simple regex'ing? References: Message-ID: On Wed, 10 Nov 2004 12:26:04 +0100, Diez B. Roggisch wrote: > >> So, I've got Basic AUTH going with http, but now I'm faced with the >> following questions, due to the fact that I need to pull some lists out of >> HTML, and then make some changes via POST or so, again over HTTP: >> >> 1) Would I be better off just regex'ing the html I'm getting back? (I >> suppose this depends on the complexity of the html received, eh?) >> >> 2) Would I be better off feeding the HTML into an HTML parser, and then >> traversing that datastructure (is that really how it works?)? > > I personally would certainly go that way - the best thing IMHO would be to > make a dom-tree out of the html you then can work on with xpath. 4suite > might be good for that. While this seems a bit overengineered at first, > using xpath allows for pretty strong queries against your dom-tree so even > larger changes in the "interface" can be coped with. And writing htmlparser > based class isn't hard, either. This sounds interesting. But if I use an XML parser to parse HTML instead of a dedicated HTML parser, will I still get smart handling of unpaired tags? I'm not sure we can count on getting 100% properly formed HTML... From steve at holdenweb.com Tue Nov 9 19:30:13 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Nov 2004 19:30:13 -0500 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <878y9eya0r.fsf@pop-server.bigpond.net.au> Message-ID: <41916115.1080002@holdenweb.com> Jeremy Bowers wrote: > On Sat, 06 Nov 2004 20:53:26 +0000, Israel Raj T wrote: > >>As for non desktop apps, the entire portage system of Gentoo is written in >>Python. 'emerge sync' causes a python app to synchronise a local >>application database with database at a non-local mirror. It is i/o >>intensive and appears to work very well and very fast. > > > "emerge sync" mostly runs an rsync command (at least on standard > installs). The python contribution to that process is minimal. > > The primary slowdown with "emerge" appears to be the way the database is > stored as many thousands of little files in /usr/portage. Again, not > really python; you want to accelerate emerge, speed up your hard drive. > > (They have more cached metadata now at least in the cutting-edge release, > but as that is the one I use I don't know if that is now considered > stable. It has really sped things up. A couple more iterations and Python > might actually become the bottleneck.) Jeremy: I just noticed your date is set a month ahead. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From exarkun at divmod.com Fri Nov 19 10:10:53 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 19 Nov 2004 15:10:53 GMT Subject: Question about thread In-Reply-To: <1100875819.430462@eng-ser6> Message-ID: <20041119151053.27631.1215974317.divmod.quotient.2773@ohm> On Fri, 19 Nov 2004 22:50:17 +0800, Valkyrie wrote: >To be more precise, what I want to do is to have a threaded program to handle > some jobs concurrently (while those jobs are fetching information from the > Internet, so threading could speed up the process if the network is slow) > > start > | (blahblahblah...) > v > +-----+-----+-----+-----+ > | | | | | > --+-- --+-- --+-- --+-- --+-- > | | | | | | | | | | > | A | | B | | C | | D | | E | > | | | | | | | | | | > --+-- --+-- --+-- --+-- --+-- > | | | | | > +-----+-----+-----+-----+ > | (blahblahblah...) > v > finish! If your goal is efficient network concurrency, threads are a second-rate solution. Asynchronous IO is the winner: http://www.twistedmatrix.com/ Here's an example (untested as usual): from twisted.web.client import downloadPage from twisted.internet import defer, reactor # Map URLs to files to which to save them URLs = {'www.google.com', 'google', # ... 'wigu.com', 'wigu', } # Initiate the download and save of each page downloads = [] for url in URLs: downloads.append(downloadPage(url, open(URLs[url], 'w'))) # Wait for all of the downloads to finish, then stop defer.DeferredList(downloads).addCallback(lambda r: reactor.stop()) # Start the reactor reactor.run() Jp From deetsNOSPAM at web.de Thu Nov 4 07:29:37 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 04 Nov 2004 13:29:37 +0100 Subject: Extending Python questions References: Message-ID: > > Thanks for the reply. I'll try those. > The reason I'm trying it this way is that a user can add python code > inside the scripts. Sorry to say that, but then you'll have to either write a real parser that understands both syntaxes - and I bet thats more effort as converting your existing scripts. You can't have your cake and eat it - if you want python, you should use its syntax. -- Regards, Diez B. Roggisch From OlafMeding at compuserve.com Wed Nov 24 14:05:27 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 24 Nov 2004 11:05:27 -0800 Subject: Deleting keys from shelve Message-ID: <9e5ea2c4.0411241105.3554551d@posting.google.com> Why does a shelve file never get smaller? I noticed that the shelve file (db.txt, see below) does not change (get smaller) when deleting a key. The key is deleted but the file size does not change. I expected the db.txt file to get smaller. def delete(): s = shelve.open('db.txt') del s['test3'] s.close() I am using Python 2.2.1 on MS Windows. Thanks so much for your help. Olaf From przemas_r at o2.pl Wed Nov 17 12:43:42 2004 From: przemas_r at o2.pl (przemas_r at o2.pl) Date: Wed, 17 Nov 2004 18:43:42 +0100 Subject: os.system vs os.system inside thread -> why is there any difference? Message-ID: Hello everybody. I've found python's behaviour I can't understand. Namely the way os.system () works depending if it's being run in Thread's run function or run in 'normal' way. >>> os.system ('arping -w 1 -c 1 -I eth1 192.168.0.2') ARPING 192.168.0.2 from 62.233.239.115 eth1 Sent 1 probes (1 broadcast(s)) Received 0 response(s) 256 >>> Here as you can see, arping command quits sending packets after 1 second and outputs failure (Received 0 response(s)) information. Now the same thing, but running from thread: >>> class A (threading.Thread): ... def __init__ (self): ... threading.Thread.__init__ (self) ... def run (self): ... os.system ('arping -w 1 -c 1 -I eth1 192.168.0.2') ... >>> A ().start () >>> ARPING 192.168.0.2 from 62.233.239.115 eth1 Now, although the only difference is that command arping is being run in thread, command never quits, informing about it's failure (-w 1 switch means that it should quit in 1 second). Mistery. Please help me if you know what's going on. -- Przemys?aw R??ycki From syd.diamond at gmail.com Tue Nov 2 13:09:50 2004 From: syd.diamond at gmail.com (syd) Date: 2 Nov 2004 10:09:50 -0800 Subject: general class functions References: Message-ID: Many many thanks, Andrea and Kent! To keep changes to calls in my current code to a minimum, I'm hoping I can encode Andrea's "on-the-fly" get function. I added Andrea's __getattr__ to my Library() class, populated the class with a few nations, and tried: >>> library.get_continent('Europe') Traceback (most recent call last): File "", line 1, in ? File "foo.py", line 16, in __getattr__ return self.__dict__[name] KeyError: '__repr__' I then commented out lines 15 and 16... #else: #return self.__dict__[name] ... and re-ran. >>> library.get_continent('Europe') Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable I tweaked a bit, but I could not get to the bottom of this problem. I see the logic here (and it's brilliant I should add, Andrea), but I'm not sure what is wrong. Ideas? From michele.simionato at gmail.com Thu Nov 25 07:10:29 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 25 Nov 2004 04:10:29 -0800 Subject: redirecting stderr Message-ID: <4edc17eb.0411250410.6b460253@posting.google.com> Maybe it is something obvious, but what is going on with this code? import sys myerr = file("myerr.txt", "w") sys.stderr = myerr try: raise Exception, "some error" finally: myerr.close() sys.stderr = sys.__stderr__ I would expect the error message to be written into "myerr.txt", instead it is displayed on the console, on regular stderr (?) and "myerr.txt" is empty. I guess I misunderstood something ... Michele Simionato From tdelaney at avaya.com Mon Nov 1 01:19:00 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 1 Nov 2004 17:19:00 +1100 Subject: How to change the combo box lists as my wish Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A905F@au3010avexu1.global.avaya.com> Austin wrote: > ................. > self.diskList = ['3','4','5'] > self.cB = > wxComboBox(self,-1,wxDefaultPosition,wxDefaultSize,self.diskList) > ................. > > The code is executed initially. > If i want to update only the diskList, what could i do? Follow the advice at this URL: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From martin at v.loewis.de Mon Nov 8 17:03:01 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Nov 2004 23:03:01 +0100 Subject: unicode string literals and "u" prefix In-Reply-To: References: Message-ID: <418fed14$0$156$9b622d9e@news.freenet.de> nico wrote: > But if I understand well, prefixing a unicode string literal with 'u' > will eventually become obsolete ( in python 3.0 ? ), as all strings > will be unicode in a more or less distant future. I think you misunderstand. It might become deprecated (in the sense of becoming redundant yet still possible); in any case, this future is certainly distant (maybe five or ten years). > So, to write "clean" script code, is it a good idea to write a script > like this ? No. Do use Unicode literals whenever you can. > ( I know the -U option can disappear in a next python version, but is > not better to delete the "-U" option at the top of the scripts than > all "u" unicode prefixes, when python will consider all strings as > unicode ?... ) As you say: *when*. Current Python doesn't, and explicit is better than implicit. There is no plan yet as to when (or even if) to release Python 3. > It seems that "print" encodes by default with the shell current > encoding. Yes, it should. > Do you think that a script written like this will still work with > python 3.0 ? Most certainly. Even when string literals become Unicode by default, u""-prefixes will still be accepted - most likely so for ten or twenty years. Regards, Martin From jcarlson at uci.edu Mon Nov 8 14:14:23 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 08 Nov 2004 11:14:23 -0800 Subject: write-time call tree? In-Reply-To: <418F8975.2080406@bellsouth.net> References: <418F8975.2080406@bellsouth.net> Message-ID: <20041108110335.F87C.JCARLSON@uci.edu> Jeremy Jones wrote: > Does anyone know of a tool that will look at a Python source file > (without executing the file - just analyzing it) and generate a report of > > * functions, classes, methods defined > * objects created > * method/function calls (I'm really looking for a map of which calls > were made from within which functions/methods), preferably with > the option of filtering which calls to trace > * trace imports if possible, show blank stub if an ImportError is > encountered, again, preferably with the option to filter which > imports to trace > > I found some tools that worked at runtime (trace.py, maybe PyChecker), > but I'm not sure they have the functionality I need even if collecting > the data at runtime were what I am looking for. I would obviously > prefer an open souce/free solution, but if anyone knows of a > commercially developed tool, I might be able to convince the company to > spring for it. Some scripts have differing behavior depending on what other things (that you cannot control) are doing at that same time. An example of this would be CGI applications, web servers, etc. So requiring analysis without running can't happen in the general case. One can even make the claim that such analysis requires a solution to the halting problem, which is as of yet unsolved, and believed to be unsolvable. Here are two simple scripts that would not be truely analyzable without running, and even then, it wouldn't do a whole lot of good to attempt to analyze. random.seed(int(time.time())) for i in xrange(random.randrange(1, 65536)): #do something that creates objects h = '217ea9ff0e4add3a51cab9b1f6b56cc5' for possible_string in universe_of_strings(): if md5.new(possible_string).hexdigest(): print possible_string break - Josiah P.S. (h is the hex digest of 'kaukhg98 y243phasd g924h') From milesd at chocksaway.com Fri Nov 26 06:51:21 2004 From: milesd at chocksaway.com (milesd at chocksaway.com) Date: 26 Nov 2004 03:51:21 -0800 Subject: Importing Python 2.3 datetime lib into Python 2.2 - Windows Message-ID: <1101469881.437081.269440@z14g2000cwz.googlegroups.com> Hi, Need some advice on adding datetime functionality into Python 2.2 Windows. Is it worth me trying to get the 2.3 datetime(pyd) file working. I don't think it is. Can someone recommend "Datetime" src which I can use. thanks Miles. From kentsin at yahoo.com Wed Nov 10 02:34:41 2004 From: kentsin at yahoo.com (kent sin) Date: Tue, 9 Nov 2004 23:34:41 -0800 (PST) Subject: HELP : pystemmer win32 binary Message-ID: <20041110073441.70719.qmail@web41523.mail.yahoo.com> I urgently need a binary version of pystemmer. I am using python 2.3 and windows 2000. I have try to download the free MSVC toolkit. But don't known how to do it myself. I just found a guide for building python 2.4 beta. Others were for bcc and gcc which I think is not suitable for my propose. Thank you for any help. Rgs, Kent Sin From deetsNOSPAM at web.de Fri Nov 5 07:37:28 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 05 Nov 2004 13:37:28 +0100 Subject: Simple thread pools References: <418A4900.7020304@debpro.webcom.dk> <20041104102722.F815.JCARLSON@uci.edu> Message-ID: > > Is there no way via Python to download say 1000 files simultaneously? Things as maximum number of file descriptors and generally speaking IO operations and their limits are matters of the underlying OS, not of the programming language itself. So show us a way in another language, and then we can tell you how to do that in python. And while using threads to wait for file IO is tempting, its a waste of resources. -- Regards, Diez B. Roggisch From no at spam.none Tue Nov 30 08:22:50 2004 From: no at spam.none (shark) Date: Tue, 30 Nov 2004 08:22:50 -0500 Subject: Syntax for extracting multiple items from a dictionary Message-ID: row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" : "Alaska"} cols = ("city", "state") Is there a best-practices way to ask for an object containing only the keys named in cols out of row? In other words, to get this: {"city" : "Hoboken", "state" : "Alaska"} Thanks, shark From bradtilley at gmail.com Tue Nov 9 13:34:02 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Tue, 09 Nov 2004 13:34:02 -0500 Subject: should i start looking for a new list? In-Reply-To: References: <20041109101248.F1B661C001B2@mwinf0101.wanadoo.fr> Message-ID: <41910D9A.4070406@gmail.com> James Stroud wrote: > Being a fellow programmer who also has poor style and limited training, I > think your code may be a little to cryptic for people to decipher and thus > come up with answers to your questions. I say this because it has been said > to me on more than one occasion--and I'm sure it will be said to me yet again > in the future as well. Perhaps someone might point you to a python style > manual: I think good programmers like Python because it looks "designed, not accumulated". I heard someone else say that, so I don't take credit for it, but I think that mindset (designed, not accumulated) permeates Python development and its usage. The bad thing about this is that many experienced programmers who see this benefit in Python have learned the hard way why these things are important where as most newbies have not. So at times, assumptions are made that go right over the heads of newbies... I say this from my own experience while learning the language. Perhaps there is some info on the Net that newbie/intermediate users could be directed to to help bridge the gap between those that know the reasons and importance behind 'good design' and those that do not. I think something like this would go a long way to remedying this situation. P.S. I would consider myself 'upper-class newbie' to 'lower-class' intermediate with Python and 'good design' ;) From ianb at colorstudy.com Wed Nov 17 16:48:14 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 17 Nov 2004 15:48:14 -0600 Subject: thread, threading; how to kill a thread? In-Reply-To: References: Message-ID: <419BC71E.4090403@colorstudy.com> Peter Hansen wrote: > Ian Bicking wrote: > >> I might reiterate this request, but knowing the standard answer (you >> can't) -- what if I *really* want to? > > > It looks to me sort of as if you are actually reiterating the > request above... but then going ahead and answering your own > question. Is that what happened here? Because if it isn't, > I'm not sure what other answer one could give.... It's more, "yes, I know the answer, but I remain unsatisfied". I'm 100% okay with a platform-specific way to accomplish this (especially if the platform is Linux and BSD). I'm okay with horrid hacks, or memory leaks, or other possible compromises. But I'm not really okay with the standard answer. And so I'm hoping someone else felt the same way and figured something out...? -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From caleb1 at telkomsa.net Thu Nov 25 21:35:00 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 25 Nov 2004 21:35:00 -0500 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: <41A5EFA9.5030907@arcor.de> Message-ID: Oh well, I might as well give it a shot. I hope nobody has tried map yet? This is is short and quick, although: I sure would appreciate some help changing the list "lkw" into a generator (or something like that) instead...those fancy things are still beyond me :) '>>> keywords = ['my','is'] '>>> sentence = 'hi there my name is caleb' '>>> lsen = sentence.split() '>>> lkw = [] # Yuck! isn't there a better way to generate copies of the same list in the "map" below?? '>>> for i in range(len(lsen)): lkw.append(keywords) '>>> lkw # Like I said, yuck! For 'map' below, can't we use a generator or something like that instead?? [['my', 'is'], ['my', 'is'], ['my', 'is'], ['my', 'is'], ['my', 'is'], ['my', 'is']] '>>> def myfunc(kw,word): if word in kw: return '*'+word+'*' else: return word '>>> ans = map(myfunc,lkw,lsen) '>>> ans ['hi', 'there', '*my*', 'name', '*is*', 'caleb'] '>>> newSentence = ' '.join(ans) '>>> newSentence 'hi there *my* name *is* caleb' '>>> From johng2001 at rediffmail.com Tue Nov 30 15:16:47 2004 From: johng2001 at rediffmail.com (John) Date: 30 Nov 2004 12:16:47 -0800 Subject: Delphi underrated, IDE clues for Python References: <5c882bb5.0411270517.77ccc654@posting.google.com> Message-ID: "Caleb Hattingh" wrote in message news:... > thx, I already have and use PythonForDelphi (and am on the mailing list). > > It works very well indeed, my impression is that Python-Delphi connection > is even easier than Python-C integration (e.g. via SWIG, etc), due once > again to the Delphi IDE. Drag-n-drop in the IDE gets you python code in > your delphi code, or delphi units/objects accessible in python. > > However, Delphi is not platform indpendent (which is important for me as I > use a different OS at work and at home), and I don't know if > PythonForDelphi supports Kylix. I am fairly sure it doesn't support > Lazarus, which IS platform independent, but not as feature-rich as Delphi. > > Btw, on the SHOOTOUT page, you'll see that the Delphi rank for LOC is 28. > This number is pretty meaningless in practice because the IDE does a lot > of code generation for you. More interesting would have been to see the > rank for LOC you have to type yourself... > > On 27 Nov 2004 05:17:38 -0800, bearophile wrote: > > > Delphi is a very good language, and quite fast too: > > http://dada.perl.it/shootout/delphi.html > > > > > > Caleb Hattingh>STILL...Having a Delphi-like IDE for Python would make me > > giddy. > > > > Maybe here you can find a way to use both at the same time: > > http://www.atug.com/andypatterns/pythonDelphiTalk.htm > > http://membres.lycos.fr/marat/delphi/python.htm > > > > Bearophile Python + Delphi is pretty much the Zen of programming for me, for now. Both excel in what they try to accomplish, stand at opposite ends of the spectrum, yet compliment each other beautifully. PythonForDelphi is the only language embedding I have done without any stress recently. When I make GUI software, I only do it for MS Windows. So portability is not an issue. I have not moved to Delphi.NET because Python gives everything missing from Delphi and I can have best of both the worlds while still having a fast, very rich (thanks to all those VCL freeware) and responsive GUI and under 2-3 MB distribution. For same reasons, I never really made a full blown GUI app with any Python bindings. It's just too easy to design a GUI with Delphi and write Windows specific code. I wish Borland focussed more in this direction. Bruce Eckel has been saying for quite a while that Borland should bring their IDE expertise to make a Python IDE. I think Python For Delphi module is grossly under rated like Delphi. From onurb at xiludom.gro Tue Nov 2 17:27:25 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 02 Nov 2004 23:27:25 +0100 Subject: Should I learn Python? In-Reply-To: <624a388a.0411021328.5ac41f4c@posting.google.com> References: <624a388a.0411021328.5ac41f4c@posting.google.com> Message-ID: <418807d0$0$19691$626a14ce@news.free.fr> Sam a ?crit : > Hi, > I have been developing sites and cms's for the past few years using > PHP and mysql. I've been interested in learning a new language and was > considering Python. I have a pretty decent grasp of OOP concepts (i > know, you're skeptical since I mentioned PHP). I don't have a formal > programming background, just learning as I go. > > So, with that being said, here are some dumb questions. > > 1. What can I do with Python that I can't do with php? 1/ Write clean, well structured, readable code, 2/ Have Fun 3/ Use Zope 4/ Use Twisted 5/ etc... > 2. Do you use both PHP and Python in conjunction with each other? No. I use PHP for legacy apps and really dumb scripting. > 3. In what way could I utilize Python to compliment existing sites or > apps built with PHP? a cgi is a cgi, whatever the language (php, perl, python, bash, C, COBOL, assembly....). > Thanks for any help. HTH From vze4rx4y at verizon.net Sat Nov 6 22:50:43 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 07 Nov 2004 03:50:43 GMT Subject: PEP new assert idiom References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> Message-ID: [F?bio Mendes] > This is very similar to what I'm proposing, with the only inconvinience > that is uglier to type: > > assert \ > exp1 and \ > exp2 and \ > ... > expn, > 'ErrorMsg' > > Instead of: > > assert \ > exp1, > exp2, > ... > expn, > 'Errormsg' > > Well, I realize I didn't expressed my thoughts very clearly and that > it's indeed a very minor change in python's syntax. It won't let anyone > does anything new, IFAIK, but it makes a common pattern of code a little > more beautiful, (and why not? more expressive). If one consider the fact > that it won't break old code (only in one very unlikely case) I don't > see it as a completely unreasonable suggestion. Other people may think > differently though. The odds of Guido accepting this proposal are about zero. As you say, it doesn't do anything new, but it does require altering the grammar. Besides, TOOWTDI. Also, Guido tends to not be persuaded by arguments about "too much typing". This is doubly true is you're talking about replacing an "and" with a comma (big whoop). Also, one of the existing alternatives is quite readable: err = 'Errormsg' assert exp1, err assert exp2, err assert exp3, err The alternative has the advantage that a failure will point to the exact expression that failed. The disadvantage is the repetition of the error message; however, I disagree that your use case is common. Instead, it is likely more advantageous to have different error messages for each expression. For example, the following comes from the post condition checks in QR matrix decomposition: assert Q.tr().mmul(Q)==eye(min(m,n)), "Q is not orthonormal" assert isinstance(R,UpperTri), "R is not upper triangular" assert R.size==(m,n), "R is does not match the original dimensions" assert Q.mmul(R)==self, "Q*R does not reproduce the original matrix" One could link all of these by an "and" or the proposed comma, but then you end-up with a single, less informative error message, "The QR decomposition bombed, but I won't tell you why ;-) ". Raymond Hettinger From steve at holdenweb.com Mon Nov 8 07:52:30 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 08 Nov 2004 07:52:30 -0500 Subject: Simple thread pools In-Reply-To: References: <418A4900.7020304@debpro.webcom.dk> Message-ID: Josiah Carlson wrote: > Jacob Friis wrote: > >>I have built a script inspired by a post on Speno's Pythonic Avocado: >>http://www.pycs.net/users/0000231/weblog/2004/01/04.html#P10 >> >>I'm setting NUM_FEEDERS to 1000. >>Is that crazy? > > > Not crazy, but foolish. Thread scheduling in Python reduces performance > beyond a few dozen threads. If you are doing system calls (socket.recv, > file.read, etc.), your performance will be poor. > Is this speculative, or do you have some hard evidence to support it? I recently rewrote a billing program that delivers statements by email. The number of threads it uses is a parameter to the program, and we are currently running at 200 with every evidence of satisfaction - this month's live run sent something over 10,000 emails an hour. > >>Are there a better solution? > > > Fewer threads. Try running at 10-30. If you are finding that you > aren't able to handle the load with those threads, then your > processor/disk/etc isn't fast enough to handle the load. > I'm tempted to say "rubbish", but that would be rude, so instead I'll just ask for some evidence :-). Don't forget that in network-based tasks the time spent waiting for connection turnarounds can dominate the elapsed time for execution - did you perhaps overlook that? regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From fiedzia at fiedzia.prv.pl Wed Nov 10 22:12:39 2004 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Thu, 11 Nov 2004 04:12:39 +0100 Subject: Sorting email addresses by domain References: Message-ID: <20041111031239.E28.0.NOFFLE@fiedzia.homeip.net> Peter Murray wrote: > Anyway, I have a list of email address and I want to sort them by domain. def cmpdomain(email1,email2): [usr1,dmn1],[usr2,dmn2] = email1.split('@'),email2.split('@') if email1 == email2: return 0 if dmn1 == dmn2: return cmp(usr1,usr2) return cmp(dmn1,dmn2) emails.sort(cmpdomain) -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl Captain Kirk, meet my father. He's Dad, Jim. From benevilent at optusnet.com.au Wed Nov 10 03:13:13 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Wed, 10 Nov 2004 19:13:13 +1100 Subject: embedded python: efficency query Message-ID: <1100074394.743.12.camel@wibble> Hey, I am embedding Python in an application, and have an efficency concern about this. There is a Python method which is called from the main application (written in C) many times per second (I am using the PyObject_Call function). Unfortunately this seems to be a bottleneck, as when the performance is compared to another language frontend of this application, when there involves many transitions from the core application to the language frontend, the other frontend outperforms Python. When there are few transitions from the core application to the language frontend (there still may be many transitions from the language frontend to the core application) Python outperforms the other language frontend by a healthy margin. I will try to profile the application with both frontends to find out more details, but I would be intereseted to know if there are any efficency improvements that can be used to speedup the Python frontend in the case described above. Thanks, Laurie From hancock at anansispaceworks.com Sat Nov 6 21:21:18 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 6 Nov 2004 20:21:18 -0600 Subject: PEP new assert idiom In-Reply-To: <1099776960.32393.82.camel@localhost.localdomain> References: <1099776960.32393.82.camel@localhost.localdomain> Message-ID: <200411062021.19253.hancock@anansispaceworks.com> On Saturday 06 November 2004 03:36 pm, F?bio Mendes wrote: > My proposal is to add the following syntax to the language: > > >>> assert (statement 1), (statement 2), ... (statement n), 'Errormsg' > > Or, if the user prefers, the traditional comma rules also applies: > > >>> assert \ > >>> statement1, > >>> statement2, > >>> (...) > >>> statement n, > >>> 'Errormsg' > > This simple syntax change introduces a very useful idiom for unittesting > and may equally be useful in other kinds of code. The most problematic > issue, I see, is the potential ambiguity a assert usage: I don't think it gains much over what is already possible: try: statement1 statement2 (...) statementn except: raise AssertionError("Errormsg") Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From exarkun at divmod.com Wed Nov 24 14:33:27 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 24 Nov 2004 19:33:27 GMT Subject: GCJ equivalent for Python? In-Reply-To: Message-ID: <20041124193327.17481.1285277086.divmod.quotient.3902@ohm> On Wed, 24 Nov 2004 11:16:56 -0800, Ed Suominen wrote: >I have been programming Python for a year or so and like everything about it > except for the difficulty of distributing programs to someone who doesn't > have the 10MB+ interpreter package downloaded installed. > > I'm a frequent user of pdftk, a Java-based PDF-manipulation program that > runs natively (no JVM required) because it is compiled with gcj. It's > plenty fast and you really never know that it was written in Java unless > you try to build it. > > So, the question naturally arises, why isn't there something like the gcj > compiler for Python? Short answer: No real technical reason. Motive, means, and opportunity simply haven't conspired on this front yet. The longer answer includes a list of projects that are similar to gcj, but for Python. py2c is one old example (no longer maintained, I believe). PyPy is headed towards native compilation (and can even do some simple things already). And let's not forget Jython! Just compile your Python to Java and your Java to assembly and your assembly to native code! Jp From __peter__ at web.de Tue Nov 30 04:37:19 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Nov 2004 10:37:19 +0100 Subject: pre-PEP generic objects References: Message-ID: Steven Bethard wrote: > def?__eq__(self,?other): > """x.__eq__(y)?<==>?x?==?y""" > return?(isinstance(other,?self.__class__) > and?self.__dict__?==?other.__dict__) This results in an asymmetry: >>> from bunch import Bunch >>> class B(Bunch): pass ... >>> B().__eq__(Bunch()) False >>> Bunch().__eq__(B()) True With indirect use of __eq__() this puzzling behaviour disappears: >>> B() == Bunch() False >>> Bunch() == B() False Whether this is intended, I don't know. If someone can enlighten me... In any case I would prefer self.__class__ == other.__class__ over isinstance(). Peter From grante at visi.com Thu Nov 4 10:36:43 2004 From: grante at visi.com (Grant Edwards) Date: 04 Nov 2004 15:36:43 GMT Subject: pep 336: Make None Callable References: <2-GdneEPltMGJBTcRVn-3g@comcast.com> Message-ID: <418a4c8b$0$5019$a1866201@visi.com> On 2004-11-04, The Eternal Squire wrote: > But isn't the point of Pythonic style to write something as > tersely elegant as possible? Nope. You seem to have completely missed the Zen of Python. The "point" of Python is to write something in the manner most easily read, understood, and maintained. If that takes more lines of souce code than a "terse and elelgent" one-liner that's impossible to read the next day, so be it. > I'd rather not see a bunch of null methods sprinkled thru the > classes in the libraries that I have to write, and I'd rather > not to have to import it either. Then create a single, global Noop object. -- Grant Edwards grante Yow! I was making donuts at and now I'm on a bus! visi.com From peter at engcorp.com Sat Nov 27 12:54:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 27 Nov 2004 12:54:02 -0500 Subject: Replacing words from strings except 'and' / 'or' / 'and not' In-Reply-To: References: Message-ID: Peter Maas wrote: > Diez B. Roggisch schrieb: >> import sets >> KEYWORDS = sets.Set(['and', 'or', 'not']) >>... >> def decorate(w): >> if w in KEYWORDS: >> return w >> return "*%s*" % w >> > Is there a reason to use sets here? I think lists will do as well. Sets are implemented using dictionaries, so the "if w in KEYWORDS" part would be O(1) instead of O(n) as with lists... (I.e. searching a list is a brute-force operation, whereas sets are not.) -Peter From dradul at shangri-la.invalid Tue Nov 30 16:49:58 2004 From: dradul at shangri-la.invalid (Alejandro López-Valencia) Date: Tue, 30 Nov 2004 16:49:58 -0500 Subject: Random number generation from functions References: Message-ID: <314888F33lqodU1@individual.net> On Mon, 29 Nov 2004 20:51:50 GMT, "drs" wrote: >Is there any way to generate random numbers based on arbitrary real valued >functions? I am looking for something like random.gauss() but with natural >log and exponential functions. Try with CRNG, it may have what you need, or be able to adapt it to what you want. http://www.sbc.su.se/~per/crng/ From evenprimes at gmail.com Fri Nov 5 17:04:15 2004 From: evenprimes at gmail.com (Chris Cioffi) Date: Fri, 5 Nov 2004 17:04:15 -0500 Subject: pep 336: Make None Callable In-Reply-To: <418BC38F.5040705@benjiyork.com> References: <418AE21B.6040905@benjiyork.com> <418BC38F.5040705@benjiyork.com> Message-ID: It was actually very educational. I use many, well, several, of those exceptions often and although I don't import them, it never occured to me that they were builtins! Chris On Fri, 05 Nov 2004 12:16:47 -0600, Benji York wrote: > Chris Cioffi wrote: > > At least _most_ of those are classes as > > opposed to primitives... > > No face-saving needed. :) The most used ones are None, True, and False > which are indeed "primitives". I was just being a bit pedantic. > -- > > > Benji York > benji at benjiyork.com > > -- Get Firefox! From jeff at ccvcorp.com Mon Nov 15 16:41:39 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 15 Nov 2004 13:41:39 -0800 Subject: save a dictionary in a file In-Reply-To: <2vsa8hF2oa58tU1@uni-berlin.de> References: <2vsa8hF2oa58tU1@uni-berlin.de> Message-ID: <10pi8f8ivf320a1@corp.supernews.com> Luis P. Mendes wrote: > > my program builds a dictionary that I would like to save in a file. As others have said, there should be no reason to convert to a list before pickling -- AFAIK, there's no ban against pickling dictionaries. You might also look into the Shelve module, which implements a filesystem-persisting object with dictionary access syntax. (And which, IIRC, uses pickled dictionaries under the covers.) Jeff Shannon Technician/Programmer Credit International From steve at holdenweb.com Fri Nov 19 21:09:45 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Nov 2004 21:09:45 -0500 Subject: SQL Server stored prcedures with output parameters In-Reply-To: <3c91a864.0411190733.1f8de68@posting.google.com> References: <419CAB0E.1040002@holdenweb.com> <3c91a864.0411190733.1f8de68@posting.google.com> Message-ID: logistix at cathoderaymission.net wrote: >>Well, in ADO you'd normally create a command object and then do >>something like >> >>objCmnd.Parameters.Append.CreateParameter("@link_id", & >> adInteger, adParamOutput, , 0) >> >>Unfortunately as far as I can see the DB API docs are silent on how to >>distinguish the output parameters to a callproc(), contenting itself >>with saying """The result of the call is returned as modified copy of >>the input sequence. Input parameters are left untouched, output and >>input/output parameters replaced with possibly new values.""" >> > > > You need to create the parameter seperately so you get a reference to > it. My ADO is a little rusty, but it's something like: > > outparam = win32com.client.Dispatch("ADODB.Paramter") > # set param here instead of function > objCmd.Parameters.Append(outparam) > > Then you can access outparam after executing the stored proc. Erm, I was trying to be DB API compatible in Python, so the ADO stuff was just a response to Tim Golden's comments. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From bearophileHUGS at lycos.com Wed Nov 17 05:39:05 2004 From: bearophileHUGS at lycos.com (bearophile) Date: 17 Nov 2004 02:39:05 -0800 Subject: Parallel processing Message-ID: <5c882bb5.0411170239.2e5f61e2@posting.google.com> Hello, this is a small tutorial page about NESL, an easy parallel programming language: http://www-2.cs.cmu.edu/~scandal/nesl/tutorial2.html Its syntax shares some similarities with python one, for example: function factorial(n) = if (n <= 1) then 1 else n*factorial(n-1); {factorial(i) : i in [3, 1, 7]}; This computes "in parallel, for each i in the sequence [3, 1, 7], factorial i" {sum(a) : a in [[2,3], [8,3,9], [7]]}; sum of sequences is already a parallel operation, so this is a nested parallelism example. So it seems to me that Python can be already fit to be interpreted in parallel, for multicore CPUs, Playstation Cell-like processors, etc. (few things have to be changed/added in the syntax to make it fit for parallelism). Hugs, bearophile From mpatton2152 at yahoo.com Sun Nov 28 23:23:47 2004 From: mpatton2152 at yahoo.com (mpatton2152 at yahoo.com) Date: Mon, 29 Nov 04 04:23:47 GMT Subject: website hosting Message-ID: <04112904234716704@newshost.allthenewsgroups.com> Here is the link to the web hosting company that I use for my 3 sites. http://frontpage-web-hosting.org/ From ofnap at nus.edu.sg Fri Nov 12 09:48:09 2004 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 12 Nov 2004 06:48:09 -0800 Subject: PyTables:Installing hdf5 Message-ID: <37ee60c8.0411120648.3a2ad4c6@posting.google.com> I am trying to install the WinXP version of PyTables which requires hdf5 (from http://hdf.ncsa.uiuc.edu/HDF5/) as a pre-requisite. However, I am at a loss as to how to install hdf5 - I have downloaded the zipped version of hdf5 and unzipped it using WinZip but get a mass of .exe and other files and have no clue as to how to proceed further. Thanks in advance for any help. From aleaxit at yahoo.com Sat Nov 27 02:14:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 27 Nov 2004 08:14:22 +0100 Subject: Protecting Python source References: Message-ID: <1gnwgsz.8wha9c1gk4r2rN%aleaxit@yahoo.com> Alan Sheehan wrote: > Hi pythonistas, > > I am looking for methods of deploying applications with end users so > that the python code is tamper proof. What are my options ? Like for any other language, the code you distribute _can_ be decompiled, analyzed, studied, and modified, by any attacker determined enough to bypass the technical and legal barriers. If your code is worth protecting, then it's worth attacking. Like for any other language, a solid solution is to put crucial parts of your application on a server that is entirely under your control, accessed by the rest of the application (the part that you distribute) via any distributed processing technology -- Corba, XML-RPC, pyro, whatever. The pluses and minuses are obvious: your application will run only with network access (which is more and more widely available but not yet universal); OTOH, you can exert fine control on who and when can access the crucial parts (by subscription, pay per use, whatever business model you fancy). It's the only approach that can be made as solid as the server you use, which is _very_ solid. Even burning some algorithms into a dedicated chip is less robust, since chips _do_ get reverse engineered / decompiled too. If all you want is to make the barriers as high as reasonably feasible, crypted archives with a dedicated pyrex-coded module to decrypt and make them accessible to the main program is one way. Legal barriers however tend to work better than technical ones, which may be perceived as interesting challenges and stimulate attacks. Note that just about any piece of software that's widespread, whatever language and protection scheme it may have used, is available in cracked form in the `warez' circuits. Go server-side as much as you can, and rely on the awesome coercive powers of the state for the rest -- "go legal, young man". Alex From justinhsia at yahoo.com Mon Nov 8 11:16:59 2004 From: justinhsia at yahoo.com (Chaser) Date: 8 Nov 2004 08:16:59 -0800 Subject: ?? Modules for GPIB and Ethernet ?? References: <21240387.0411041337.7b17172b@posting.google.com> <0-GdnfBAPrZPXBfcRVn-sw@powergate.ca> <21240387.0411050533.4d145e2a@posting.google.com> Message-ID: <21240387.0411080816.4ec27411@posting.google.com> Jorgen Grahn wrote in message news:... > On 5 Nov 2004 05:33:49 -0800, Chaser wrote: > > Peter Hansen wrote in message news:<0-GdnfBAPrZPXBfcRVn-sw at powergate.ca>... > >> Chaser wrote: > >> > Just wondering if anyone knows where I can find modules for NI-488.2 > >> > GPIB and for a generic ethercard? > ... > >> As for the other question: do you actually mean you want a > >> way to talk "raw" Ethernet, or are you just trying to do > >> some networking? > ... > > I have an equipment that's controlled through ethernet. (The control > > program is currently written in C++.) I guess my really difficulty > > is, how do I send commmands to that devise through ethernet using > > Python? > > If this really is raw ethernet, I think your best multi-platform shot would > be a bleeding edge version of libpcap (http://www.tcpdump.org), and a Python > wrapper on top of it. Then make your OS accept the presence of the > interface, but not send or listen to it, and use libpcap to listen and to > inject (new feature in libpcap) ethernet frames. > > It /might/ work. High data rates may be a problem; libpcap with a > relatively slow client might drop packets. > > /Jorgen Wow! Thanks for the overwhelming support. I am a computer illiterate. Please be patient with me. I found the following posting that deals with GPIB interface using Python. http://groups.google.com/groups?q=python+gpib&hl=en&lr=&ie=UTF-8&selm=8aok7p%24j0%241%40nnrp1.deja.com&rnum=4 But I got stuck on the first step of installing the dynwin package. The dynwin package relies on two auxiliary dlls, calldll.pyd and npstruct.pyd. I literally downloaded the .zip, unzip them and "drag and drop" the two .pyd into my Python24/DLLs folders. Then I created a dynwin folder in the Python24\Lib directory. 1. Is this the right way? 2. At the Python prompt, I typed "import windll" and got the error message that the module doesn't exist! 3. I then tried "import dynwin.windll" and Python says module calldll doesn't exist! HELP HELP HELP From rtilley at vt.edu Sun Nov 7 11:40:45 2004 From: rtilley at vt.edu (Brad Tilley) Date: Sun, 07 Nov 2004 11:40:45 -0500 Subject: Python for Reverse Engineering In-Reply-To: References: <418c50ad$1_3@omega.dimensional.com> <418C54E9.2000409@vt.edu> Message-ID: Duncan Smith wrote: >>If your friend was worth his salt as an algorithm writer, he'd be more... >>But--he is probably making impossible claims here, anyway... >> > > > [snip] > > Doesn't that depend on exactly what is meant by "figure out exactly how the > algorithm works"? If it means identify (with absolute certainty) the > algorithm used to generate the strings, then it surely can't be possible. > > Duncan That's my thought as well. I don't want to know exactly how the algorithm generates strings. But, I think that if I analyze enough strings I should know, on some level, what an acceptable string looks like. Samba coders never see Microsoft's file and print sharing source code, yet they are able to emulate an NT server quite well just by observing packets. From sjmachin at lexicon.net Wed Nov 10 15:15:54 2004 From: sjmachin at lexicon.net (John Machin) Date: 10 Nov 2004 12:15:54 -0800 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> Message-ID: Hans Nowak wrote in message news:<418C0DB6.1040007 at zephyrfalcon.org>... > John Machin wrote: > > > Or is this a joke/troll?? I can't believe the "unimelb.edu.au"; surely > > a forgery. > > Is it just me, or is the climate in c.l.py getting less friendly to > newbies? In any case, > http://www.zoology.unimelb.edu.au/staff/nicholas.htm mentions Maurice > Ling as an honor student. No it doesn't. It says "honours student", which indicates solely the enrolment status, with none of the connotations of merit that might be attached to the American phrase "honor student". To the main point: I apologise profusely to the whole world for starting the thread of the month by not putting "Please turn your irony detectors on" at the top of my post. From agriff at tin.it Sat Nov 13 13:43:20 2004 From: agriff at tin.it (Andrea Griffini) Date: Sat, 13 Nov 2004 18:43:20 GMT Subject: numarray + cPickle problem References: <1100326589.669597.252570@f14g2000cwb.googlegroups.com> <1100366822.119444.157780@z14g2000cwz.googlegroups.com> <1100367031.042556.162860@z14g2000cwz.googlegroups.com> Message-ID: On 13 Nov 2004 09:30:31 -0800, "Bill Mill" wrote: >Perhaps this should be mentioned in the cPickle documentation? It *IS* documented... Pickler(...) Pickler(file, proto=0) -- Create a pickler. This takes a file-like object for writing a pickle data stream. The optional proto argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and --> read back successfully. When using a protocol --> higher than 0, make sure the file is opened in --> binary mode, both when pickling and unpickling.) ... Andrea From someone at microsoft.com Thu Nov 25 12:32:00 2004 From: someone at microsoft.com (Jive) Date: Thu, 25 Nov 2004 17:32:00 GMT Subject: A lock that times out but doesn't poll References: Message-ID: Okay, I've got a comment: How about some comments? Maybe it's just me, but I find the code a little hard to comprehend. What's up with this? Exception in thread Thread-456: Traceback (most recent call last): File "C:\Python23\lib\threading.py", line 436, in __bootstrap self.run() File "C:\Python23\lib\threading.py", line 544, in run self.function(*self.args, **self.kwargs) File "C:\Python23\Scripts\foo.py", line 29, in break_lock sc.pl.release() error: release unlocked lock That crops up occasionally. It's been a while, but as I recall, the tricky bit in implementing timed locks with an alarm clock thread is seeing to it that threads that don't time out waiting on a timed lock do not leave zombie alarm clock threads running. If you are not careful, they could proliferate and eat up system resources. "Antoon Pardon" wrote in message news:slrncq5vvl.61m.apardon at rcpc42.vub.ac.be... > The queue and condition class allow threads to wait only a limited > time. However this currently is implemented by a polling loop. > > Now for those who like to avoid polling I have here a Tlock > class that allows for a timeout but doesn't use polling. > > All comments are welcome. > > > ----------------------- Tlock.py ------------------------------- > > import threading > > class TimeOut(Exception): > pass > > class Tlock: > > def __init__(self): > > self.mutex = threading.Lock() > self.lktab = [threading.Lock()] > > > def acquire(self, timeout=None): > > class SC: > pass > > > def break_lock(sc, mutex, tab): > > mutex.acquire() > try: > try: > i = tab.index(sc.pl, 1) > del tab[i] > sc.broken = True > sc.pl.release() > sc.pl.release() > except ValueError: > pass > finally: > mutex.release() > > > self.mutex.acquire() > sc=SC() > sc.ll = threading.Lock() > sc.ll.acquire() > self.lktab.append(sc.ll) > sc.pl = self.lktab[-2] > sc.broken = False > if len(self.lktab) > 2 and timeout is not None: > tm = threading.Timer(timeout, break_lock, > args=[sc, self.mutex, self.lktab]) > tm.start() > else: > tm = None > self.mutex.release() > sc.pl.acquire() > if sc.broken: > raise TimeOut, "lock timed out" > else: > if tm is not None: > tm.cancel() > > > def release(self): > > self.mutex.acquire() > self.lktab[0].release() > del self.lktab[0] > self.lktab[0].release() > self.mutex.release() > > > if __name__ == "__main__": > > from time import sleep > from random import randint > > T = Tlock() > > def thrd(Id): > > for _ in xrange(100): > try: > print "Trying %d" % Id > T.acquire(randint(0,6)) > print "Entering %d" % Id > sleep(randint(0,6)) > print "Leaving %d" % Id > T.release() > except TimeOut, ErrId: > print "Failed %d" % Id > sleep(randint(0,6)) > > > for i in xrange(5): > th = threading.Thread(target=thrd, args=(i,)) > th.start() From peter at engcorp.com Thu Nov 4 09:44:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Nov 2004 09:44:17 -0500 Subject: threads and exception in wxPython In-Reply-To: References: <6_qdnQZOZ_YYZRXcRVn-sw@powergate.ca> Message-ID: (Sorry if duplicate: NTTP server screwed up.) Peter Hansen wrote: > Thomas Heller wrote: >> # raise exception in thread >> print pythonapi.PyThreadState_SetAsyncExc(t, id(exc)) > > I should note for the record that neither Thomas' > example above nor even my more complex one > ... implements the required API fully. A further addendum, or a caution/concern: The docs also say that you should own the GIL when you call this routine. I suspect that in fact you are supposed to have a lock on the GIL during the _entire time_ that you are working with this routine, specifically around all the following (pseudo)code: n = PyThreadState_SetAsyncExc(id, Py_Object *) if n > 1: PyThreadState_SetAsyncExc(id, NULL) I suspect that the only reason the second call works (supposedly it "reverts the effects" of the first call) is because the interpreter has not had time to execute any more bytecodes in the affected threads. But since the precise definition of this "reversion" is undocumented, going to the source or an expert (which I'm clearly not) would be the only way to sort out such "minor" issues... -Peter From gregory.lielens at fft.be Sat Nov 27 18:50:28 2004 From: gregory.lielens at fft.be (gregory lielens) Date: Sun, 28 Nov 2004 00:50:28 +0100 Subject: subclassing extension type and assignment to __class__ In-Reply-To: References: <41a87eb5$0$13482$ba620e4c@news.skynet.be> Message-ID: <41a912a8$0$25051$ba620e4c@news.skynet.be> Thanks for your answer, it means I am not the only one having this kind of problem... > I have just run into the same thing with the builtin list type. The trick > was not to declare my subclass directly from list, but rather a subclass > of list. So try this: > > class PClassBase(_PClass): > pass > > class PClass(PClassBase): > ... > > class PClass2(PClassBase): > ... > I think here you mean PClass2(PClassBase2), with a PClassBase2(_PClass2): In my example the 2 class do not inherit fro the same base class... > Why? I cannot say other than I have noted that Python new-style classes > and extension types are not quite the same thing. That is, a new-style > class is a particular kind of extension type. I see how it can help me making PClassBase a PClass (or any type derived from PClassBase), but what I fail to see is how this will allow me to change a _PClass into one of it's derived types: this is necessary for updating methods of _PClass2 that return object of type _PClass (and on this I do not have much control, both _PClass and _PClass2 and all of their methods are implemented in C++). To updates theses methods for the pure python derived class PClass2, I have to make them return the python class PClass instead of the original _PClass, which means I still have to transform a _PClass object into its derived type PClassBase or PClass, and at this time things go pear-shaped :-(....or is there something I miss? Greg. From drew at gremlinhosting.com Sun Nov 28 04:03:02 2004 From: drew at gremlinhosting.com (Andrew James) Date: Sun, 28 Nov 2004 09:03:02 +0000 Subject: Python GTK import error In-Reply-To: References: Message-ID: <1101632582.9345.2.camel@odin> Try checking the permissions on the link and the library - if you installed the module manually the permissions may not allow anyone but the root user to import the module. Andrew On Sat, 2004-11-27 at 20:21 -0800, Qianqian Fang wrote: > no, the file is there, it actually links to another file: > > /usr/lib/libgtk-x11-2.0.so.0.400.13 > > but both files are in the right locations. > anything else that is suspecious to the problem? > > thanks > > > Douglas Soares de Andrade wrote in message news:... > > Hi ! > > > > The error is that the system ins't finding this lib: > > > > /usr/lib/libgtk-x11-2.0.so.0 > > > > Try to see if your system has it. > > > > See ya ! -- Andrew James From jeff at ccvcorp.com Tue Nov 16 13:42:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 16 Nov 2004 10:42:11 -0800 Subject: Will python ever have signalhandlers in threads? In-Reply-To: References: Message-ID: <10pkiaqch4edo08@corp.supernews.com> Antoon Pardon wrote: >Op 2004-11-15, Jp Calderone schreef : > > >>You are correct, but why does it matter? The Queue class works. >> >> > >Does it? > >I'm not so sure. If two consumers ask simultaneously for an element >from the same empty queue. One consumer simply blocking and the >other using a timeout, I think that if an element is produced within >the timeout period the chance for the element going to either consumer >should be equal. I doubr very much we have that in the current >situation. > > This is just my opinion, of course, but it seems to me that if you have two completely different threads (as in, threads running different functions, not merely separate instances of the same threaded function) which are accessing the same queue in different ways, and presumably doing different things with the queue's products (because why would you access the queue differently if you weren't doing different things?), then you've *already* got enough nondeterministic behavior that this timeout issue isn't going to be a burden in practice. To be honest, I find the thought of having different consumers which do different things with a single queue's products to just scream out as a source of hard-to-track problems -- how could one possibly get predictable behavior from that? So yes, if you do that, you might get an odd distribution of products -- but why would you want to do it? I *do* understand about wanting to receive signals in (worker) threads, but I don't understand how this particular behavior of queues could ever be a practical problem in a real program. Of course, maybe I'm just missing something, or maybe you're looking at this from a theoretical-purity aspect... Jeff Shannon Technician/Programmer Credit International From mdraghi at prosud.com Sun Nov 14 23:35:27 2004 From: mdraghi at prosud.com (Mariano Draghi) Date: Mon, 15 Nov 2004 01:35:27 -0300 Subject: Combining arbitrary lists In-Reply-To: <41982e45$1_4@alt.athenanews.com> References: <41982269$1_1@alt.athenanews.com> <41982e45$1_4@alt.athenanews.com> Message-ID: Nick wrote: ... >> I think this is what you're looking for: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 ... > Okay... a) THANK-YOU, and b) HOW did you find that? The ASPN Python Cookbook has plenty of these kind of things. I looked for "combination" there... I think (don't remember exactly). You can also do a search in the comp.lang.python group using Google. Try this: http://groups.google.com/groups?q=combination&meta=group%3Dcomp.lang.python.* Regards, -- Mariano From zanesdad at bellsouth.net Wed Nov 17 11:26:17 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 17 Nov 2004 11:26:17 -0500 Subject: newbie question In-Reply-To: <301aedF2q0m75U1@uni-berlin.de> References: <301aedF2q0m75U1@uni-berlin.de> Message-ID: <419B7BA9.8000905@bellsouth.net> Paul Watson wrote: >"Jeremy Jones" wrote in message >news:mailman.6431.1100623812.5135.python-list at python.org... > > >>John wrote: >> >> >> >>>Can python do Shell programming or system programming as perl does? >>>Thanks. >>> >>>John >>> >>> >>> >>Yes. The only problem is that the perpetual migraine you have from doing >>Perl and shell will quickly go away. So, if you're into pain, stick with >>Perl and shell. If you want relief, come to Python. >> >>Seriously, though, Python is an excellent language for doing sysadmin type >>tasks. (I'm assuming that's kind of what you wanted?) Most sysadmin type >>tasks are in modules whereas with Perl, they're cluttering the toplevel >>namespace (I don't think Perl has the concept of namespace, but you get >>the drift). So, not knowing what you want to do, you may want to checkout >>the os module in Python (I've found os.path.* to be specifically helpful). >>You may also want to checkout the shutil module. >>Jeremy >> >> > >While I usually use Python, I must admit that doing: > $s = `ls -al $thefilename` >seems easier and clearer than: > import os > s = os.popen("ls -al %s" % thefilename) > > > > I find that : import glob s = glob.glob(thefilename) works pretty well. If you need to iterate over a bunch of files in a directory, you can do this in shell: for f in `ls *` do #do stuff done or for f in * do #do stuff done and in Python: import os for f in os.listdir('.'): pass # do stuff here or import glob for i in glob.glob('ipythonrc-*'): pass #do stuff here Some things, mostly very simple tasks, shell is fine for. When you start increasing in complexity, I think you're better off using Python. The samples above are *quite* simple and you'd probably be just as well of doing them in shell as in Python. Actually better from a shell prompt rather than a script. Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at email.com Tue Nov 30 07:30:21 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Tue, 30 Nov 2004 22:30:21 +1000 Subject: pre-PEP generic objects In-Reply-To: References: Message-ID: <41ac67dd$0$25770$5a62ac22@per-qv1-newsreader-01.iinet.net.au> The proposed use cases sound more appropriate for a "named tuple" than any sort of dictionary. (This may have been mentioned in previous discussions. I wasn't keeping track of those, though) Notice that I've used 'fromPairs' rather than 'fromMapping', since consistent order matters for a tuple. Comparison semantics are inherited directly from tuple, and don't care about names (they're only interested in values). Also, it seems like there has to be a better way to do the "opposite of zip()" in fromPairs(), but I sure as hell can't think of it. Cheers, Nick. >>> a = named_tuple(['x', 'y'], (3, 8)) >>> a named_tuple(['x', 'y'], (3, 8)) >>> a.x 3 >>> a.y 8 >>> str(a) '(3, 8)' >>> b = named_tuple.fromPairs(sorted({'x':3, 'y':8}.items())) >>> b named_tuple(['x', 'y'], (3, 8)) >>> b.x 3 >>> b.y 8 >>> str(b) '(3, 8)' >>> a == b True >>> And the code for the above: class named_tuple(tuple): def __new__(cls, names, *args): self = tuple.__new__(cls, *args) self._names = dict(zip(names, range(len(names)))) return self @staticmethod def fromPairs(items): names = [x[0] for x in items] values = [x[1] for x in items] return named_tuple(names, values) def __getattr__(self, attr): if attr in self._names: return self[self._names[attr]] else: return tuple.__getattr__(attr) def __repr__(self): return "named_tuple(%s, %s)" % (str(self.names()), str(tuple.__repr__(self))) def __str__(self): return tuple.__repr__(self) def names(self): return sorted(self._names.keys(), key=self._names.__getitem__) From steve at holdenweb.com Tue Nov 9 08:36:16 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Nov 2004 08:36:16 -0500 Subject: mod_python, multiple calls to PythonAuthenHandler In-Reply-To: References: Message-ID: <4P3kd.13460$931.131@lakeread01> Rune Hansen wrote: > On Mon, 08 Nov 2004 08:18:45 -0500, Steve Holden wrote: > > >>Rune Hansen wrote: >> >> >>>I've posted this question on the mod_python mailing list but didn't get >>>much response, so I thought I'd post it here. >>> [...] > > Now, I've "solved it" with a single PythonHandler (dropping > PythonAuthenHandler and publisher): > > def handler(req): > if not req.headers_in.get("Authorization",0): > req.err_headers_out["WWW-Authenticate"] = 'Basic realm="Restricted\ > area"' > raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED > meth,auth = req.headers_in.get("Authorization").split(" ") > user,pw = decodestring(auth).split(":") > args = dict([(a[0],a[1]) for a in util.parse_qsl(req.args or '')]) > if dbmdbValidate(user,pw,req.server): > return myMethod(req,**args) > else: > return apache.HTTP_UNAUTHORIZED > > This seems to do exactly what I want. Guess I should have tried a litle > harder before posting. > How ever, I'm still curious to why the PythonAuthenHandler is called for > each path element. > I'm afraid that's a little beyond me too, but I think you were quite within your rights to post the question. Glad you've got past the problem. Since you're using the publisher handler you might want to consider using the methods described in http://www.modpython.org/live/current/doc-html/hand-pub-alg-auth.html if you haven't already looked at them. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From fumanchu at amor.org Mon Nov 15 02:47:18 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 14 Nov 2004 23:47:18 -0800 Subject: os.path.exists discrepancy Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32451F4@exchange.hqamor.amorhq.net> I've got a webapp which is behaving oddly. I want to include an image on the webpage, but only if the physical file exists; if it doesn't, I don't want an img element to generate an ugly blank box. I know the physical location of the image(s) in question, and figured I'd use os.path.exists to see if each file exists. A quick test in the interpreter yields: >>> os.path.exists(u'S:/Scans/Projects/2004/TJ/04TJ0267.jpg') True However, when I run the following code in the webapp (served by Apache2 + mod_python on the same Win2k machine): if not os.path.exists(path): scan = u"" % repr(path) ...I get the output: As you can see, the two paths are equal. Prompting my reaction: bzuh? My next thought was to read through the os module source--perhaps the import of "path" was dependent on context. It is, but os.path.__file__ is the same in both contexts: 'C:\\Python23\\lib\\ntpath.pyc' Any ideas or workarounds? Robert Brewer MIS Amor Ministries fumanchu at amor.org From roy at panix.com Thu Nov 25 12:22:52 2004 From: roy at panix.com (Roy Smith) Date: Thu, 25 Nov 2004 12:22:52 -0500 Subject: network programming without goto (refactoring) References: Message-ID: In article , kent sin wrote: > Please help: > > I was really blocked here. without goto I really do > not known how to do it. > > The problem is to use PyZ3950 to consult a lists of > hosts and for each of them to search for a list of > targets. Since the network is undetermined, there were > always some exceptions: I would like to allow it to > retry for 3 times. Moreover, during the query process, > the conn will timeout (set by the remote server). > Reconnect is preferred before fail the current search, > but the reconnect may fail even if the first try is > succeed. [spaghetti code deleted for brevity] The real problem you've got is that you're trying to smash too much stuff into one function. You've got several things going on here at once. First, you're iterating over several hosts to try. Next, you're making several attempts to connect to each host. Lastly, you've got some buildquery()/search() stuff going on (whatever that may be). I'm not at all sure what you're trying to do with "for t in targets", but I'm going to assume it's somehow related to iterating over the various hosts. What you want to do is refactor this into a number of smaller functions, each one encapsulating one piece of the puzzle. To start, I'd build a function which handled the multiple connection attempts to a given host. Maybe something like this: # # Untested code -- this is just to give you some ideas # and get you thinking in the right direction # def connectWithRetries (host, port, retryLimit): attempts = 0 while attempts < retryLimit: try: connection = zoom.Connection (host, port) return connection except ConnectionError: attempts += 1 throw ConnectionError Then, I'd handle the iteration over multiple hosts: def connectToSomeHost (hostlist, port): for host in hostlist: try: connection = connectWithRetries (host, port) return connection except ConnectionError: # ignore throw ConnectionError Finally, It's time to implement your query logic, which I'll leave as an exercise for the reader (mostly because I don't really understand what you're trying to do with that). None of this is network-specfic or even Python-specific. The idea of breaking up a complex operation into smaller steps and implementing each one in its own function is pretty much a universal idea. Each function can be easily designed and tested on its own (and, later, understood by a future reader). The question then becomes, how to decide what stuff to put in what function? There's no hard and fast rules, but the general idea is that each function should do one thing, or a small set of very closely related things. For example, I could imagine possibly combining connectWithRetries() and connectToSomeHost into a single larger function that did both tasks, because they're both part of the basic "get a connection to a host" concept. But, getting the connection and using it to perform a query definitely don't belong together. Here's some rules of thumb: Several smaller functions are usually better than one larger one. If you can't see the entire function code without scrolling in your editor, it's too big. With todays windowing systems, that probably means about 40 lines. If it's got more than a couple of loops, or more than a couple of try blocks, you're probably doing too much in a single function. If you can't explain to somebody in a single sentence what your function is doing, it's doing too much. The take-home assignment is to DAGS for "refactoring". There's been a lot written on the subject in the last 5-10 years. A lot of what's been written assumes an object oriented environment (in a C++ or Java like language), but the basic concepts hold for all languages, and for procedural as well as OO styles. From pierre.barbier at cirad.fr Thu Nov 25 05:44:18 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 25 Nov 2004 11:44:18 +0100 Subject: Operator Overloading In-Reply-To: References: Message-ID: <41a5b716$0$17605$636a15ce@news.free.fr> Peter Maas a ?crit : > Sebastien Boisgerault schrieb: > >> I wonder if the following quotation from the Python Reference Manual >> (release 2.3.3) about operator overloading is true : >> >> "For example, if a class defines a method named __getitem__(), and x >> is >> an instance of this class, then x[i] is equivalent to >> x.__getitem__(i)" > > [...] > >>>>> from Numeric import * >>>>> a = array([0.5]) >>>>> a[0] >> >> >> 0.5 >> >> but >> >> >>>>> a.__getitem__(0) >> >> >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: __getitem__ > > > The quotation above is true. Short form: > > IF __getitem__ in dict THEN [] works. That's not true !!! I's true only for classes defined in Python. If you try to define a class in C, defining the __getitem__ method does not lead to the existence of "[]". But when you define "[]" it creates the "__getitem__" method. This is part of the reason why you cannot dervie from two types if they derives from different classes written in another language and imported in Python (just try to create a class deriving from list and dict ...). Pierre From mep_ at 163.com Tue Nov 30 07:53:21 2004 From: mep_ at 163.com (mep) Date: Tue, 30 Nov 2004 20:53:21 +0800 Subject: UML and OO design tool with Python support References: Message-ID: <3138r6F352en5U1@uni-berlin.de> Any free UML modelling tools that generate python code? -- Best Regards, Wang Kebo http://www.huihoo.org/~mep "Paul McGuire" wrote in message news:f8fqd.47331$KQ2.46722 at fe2.texas.rr.com... > I just found out that my favorite UML modeling tool, Enterprise Architect, > has just released a new version, *with* Python code support. You can > download EA at http://www.sparxsystems.com.au. It is not free, but I think > it is very reasonably priced for the features it provides (under $200 gives > you good UML graphical modeling, including sequence and class diagrams, with > code reverse engineering and round-tripping, vs. $000's for comparable > Rational environment). > > Well, as it turns out, the Python support is still a bit buggy but I have > already gotten good mileage from this tool in other applications, most > notably reverse engineering C++ and C# code, so the Python additions are > icing on the cake. But it is certainly another reassuring note, to see the > inclusion of Python support into this commercial software development tool. > > I've already started to forward bug reports for some of the Python import > errors. Perhaps if they get more feedback from other Python users, it will > help reinforce their opinion of Pythonistas as a valuable target market > segment. > > -- Paul > > > Note: I am *not* an employee or in any way connected with the supplier of > this code, other than as a satistifed customer. > > Note2: the Python support is not an obvious product feature. It requires > installation of a separate (free) add-in, downloaded from the Sparxsystems > web site. The add-in must be separately "add-in"ed to each project, too, > instead of just being a globally installed plug-in. My first couple of > attempts failed at completely reverse engineering my pyparsing module, > although I did get a nice first-pass class inheritance diagram for PIL. We > take what we can get... > > From joshway_without_spam at myway.com Wed Nov 3 14:52:24 2004 From: joshway_without_spam at myway.com (JCM) Date: Wed, 3 Nov 2004 19:52:24 +0000 (UTC) Subject: strong/weak typing and pointers References: Message-ID: JCM wrote: > Gabriel Zachmann wrote: >>> You didn't mention C++. Try this ... >>> >>> std::string s = "Wow"; >>> s += 3.141592654; // Perfectly valid >>> s = 3.141592654; // Also valid >> ah, good example. >> So, would it be valid to say: >> the more coercion (or automatic conversion) rules a language has, the >> weaker the typing? > If that's what your definition of weak typing is. The OP seemed to be > asking about re-interpreting the representation of a value of one type > as a different type. Oops--I guess you are the OP. When people talk about "weak typing" they generally mean either implicit conversions (or operations on values of different types), or reinterpreting representations of values as a different type. The former, in my opinion, is not about weak typing. From corey.coughlin at attbi.com Wed Nov 17 20:29:40 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 17 Nov 2004 17:29:40 -0800 Subject: Parallel processing References: <5c882bb5.0411170239.2e5f61e2@posting.google.com> Message-ID: Josiah Carlson wrote in message news:... > > There are various other reasons why Python is not as parallelizable as > you would think. Among them is the semantics of scoping, and whether > there is shared or unshared scope among the processors/nodes. If shared, > then any operation that could change scopes would need to be distributed > (ick), or if unshared, then you are basically looking at an > automatically distributed tuplespace (LINDA). It gets even uglier with > certain kinds of generators. > > Regardless of which one is the case, heavy modifications to Python would > necessarily need to be done in order to make them happen. > > > - Josiah Well, I'm not sure it's necessarily that grim. Generally, taking an inference engine something like that proposed for Starkiller, tracking variable types as closely as possible, adding some data flow capability to follow the execution path, you could probably do something useful. With Python's for..in loop syntax, the prohibition against chaning loop variables there, and list comprehensions, parallelized loop unrolling, done intelligently, could help out a lot on parallel architectures. Sure, it'd be hard to do effectively in a strictly interpreted environment, but if Starkiller ever comes out, it seems almost inevitable. Then again, that project seems to be getting later all the time. :( From mwm at mired.org Sun Nov 7 15:22:08 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 07 Nov 2004 14:22:08 -0600 Subject: Python OS References: Message-ID: "Diez B. Roggisch" writes: > For example you can't write a OS for the JAVA VM, as there is no such things > like interrupts defined for it - instead IO happends "magically" and is > dealt with on the low level with the underlying OS. The VM only consumes > the results. OS's have been written for VMs (LISP and Forth) that didn't have the notion of interrupt before they were built. For LISPMs, interrupt handlers are LISP objects (*). Java may not be as powerful as LISP, but I'm pretty sure you could turn interrupts into method invocations without having to extend the VM. , under the section on Stack Groups. -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jstroud at mbi.ucla.edu Wed Nov 10 15:51:14 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Nov 2004 12:51:14 -0800 Subject: Beginner's scoping question In-Reply-To: <4ef0f3a4.0411101240.21132006@posting.google.com> References: <4ef0f3a4.0411101240.21132006@posting.google.com> Message-ID: <200411101251.14700.jstroud@mbi.ucla.edu> If you make an assignment in a method, the name assumes a local scope in python. "b" was not assigned so did not assume local scope. James On Wednesday 10 November 2004 12:40 pm, Alan Little wrote: > a=1 > b=[] > class C(): > def __init__(self): > a=2 > b.append(3) > > c = C() > > print b > # [3] > > # but ... > print a > # 1 > > ??? -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From tzot at sil-tec.gr Tue Nov 23 04:26:32 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 23 Nov 2004 11:26:32 +0200 Subject: Python Tutorials, about 100 and sorted by Topic or Category References: Message-ID: <4g06q0t7dim3c8r37202jasut5ufafmgof@4ax.com> On 20 Nov 2004 12:16:23 -0800, rumours say that rstephens at vectron.com (Ron Stephens) might have written: >http://www.awaretek.com/tutorials.html Great job, Ron :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From steven.bethard at gmail.com Thu Nov 4 16:31:33 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 21:31:33 +0000 (UTC) Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> <1gmqqa3.r7hg5g17qatxkN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > > I apologize if I have given the impression of being upset. No problem -- my mistake for misinterpreting you. I'm just sensitive to these kind of things because I know I've previously miscommunicated, and unintentionally got people upset before (you being one of them). ;) > I am, in a > way, I guess -- astonished and nonplusses, as if somebody asked me to > justify the existence of bread -- not of some exotic food, mind you, but > of the most obvious, elementary, fundamental substance of earthly > sustenance (in my culture, and many others around it). Yeah, this goes to the heart of the misunderstanding. I'm not asking anyone to justify the _existence_ of weak-typing. Weak-typing is a direct result of a language's support for untyped (bit/byte) data. I agree 100% that this sort of data is not only useful, but often essential in any low-level (e.g. OS, hardware driver, etc.) code. > So, we have an area > of 8 bytes in memory which we need to be able to treat as: > 8 bytes, for I/O purposes, say; > a float, to feed it to some specialized register, say; > a bit indicating sign plus 15 for mantissa plus 48 for significand, > or the like, to perform masking and shifting thereof in SW -- a > structure of three odd-bit-sized integers juxtaposed; As a quick refresher, I quote myself in what I was looking for: "taking advantage of weak-typing would be a case where you treat the bits as three different things: the sequence of bits, and two (mutually exclusive) intended structures." My response to this example is that your two intended structures are not mutually exclusive. Yes, you have to do some bit-twiddling, but only because your float struct doesn't have get_sign, get_mantissa and get_significand methods. ;) You're still dealing with the same representation, not converting to a different type. You're just addressing a lower level part of the representation. I can see the point though: at least in most of the languages I'm familiar with, float is declared as a type while there's no subtype of float that specifies the sign, mantissa and significand. (Oh, and by the way, in case you really were wondering, they still do teach float representations, even in computer science (as opposed to computer engineering), or at least they did through 1999.) > Another example: we're going to send a controlblock of 64 bytes to some > HW peripheral, and get it back perhaps with some mods -- a typical > control/status arrangement. Depending on the top 2 (or in some case 4) > bytes' value, the structure may need to be interpreted in several > possible ways, in terms of juxtaposition of characters, halfwords and > longwords. Again, the driver responsible for talking with this > peripheral needs to be able to superimpose on the 64 bytes any of > several possible C-level struct's -- the cleanest way to do this would > appear to be pointer-casting, though unions would (as usual, of course) > be essentially equivalent. Is the interpretation of the controlblock uniquely defined by the top 2 or 4 bytes, or are there some values for the top 2 or 4 bytes for which I have to apply two different interpretations (C-level structs) to the same sequence of bits? If the top 2 or 4 bytes uniquely define the structs, then I would just say you're just going back and forth between a typed structure and its untyped representation. If the top 2 or 4 bytes can specify multiple interpretations for the same sequence of bits, then this is the example I was looking for. =) Steve From kent3737 at yahoo.com Mon Nov 15 16:46:04 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Mon, 15 Nov 2004 16:46:04 -0500 Subject: round() to nearest .05 ? In-Reply-To: References: Message-ID: <41992281$1_1@newspeer2.tds.net> tertius wrote: > Hi, > > I'm trying to round my float total to the nearest .05 cents. If you want the *nearest* .05, this works: >>> def fivecents(f): ... return round(f*2.0, 1) / 2.0 ... >>> for f in [ 12.01, 0.14, 2.28, 703.81]: ... print f, fivecents(f) ... 12.01 12.0 0.14 0.15 2.28 2.3 703.81 703.8 > 12.01 should produce 12.00 > 0.14 should produce 0.10 > 2.28 " 2.25 > 703.81 " 703.80 Your example seems to be rounding down always, not what I would call nearest. Here is one that always rounds toward zero: >>> def lowerfivecents(f): ... return int(f*20) / 20.0 ... >>> for f in [ 12.01, 0.14, 2.28, 703.81]: ... print f, lowerfivecents(f) ... 12.01 12.0 0.14 0.1 2.28 2.25 703.81 703.8 If you want to always round toward more negative, use math.floor() instead of int(). Kent > > "%.02f"%100.0099 produces 100.01 (which I know is right) > No combination of round and/or "%.02f" works for me. > > What's the best way to get there? Should I write a function to manage my > rounding or is there a simpler/better way? > > TIA > T From davecook at nowhere.net Tue Nov 30 04:51:00 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 30 Nov 2004 09:51:00 GMT Subject: Python Design Patterns References: Message-ID: On 2004-11-29, Tony Ha wrote: > I wonder, can any Python guru out there translate the Java examples in the Should be a good exercise, and not just for gurus ;}. > book into Python examples, or write a similar book in Python, perhaps I've also wished for a design patterns book aimed at Python, or at least dynamic languages with first class functions and modules. There's a paper Python book with "Patterns" in the title, but it has precious little content in it related to design patterns, at least not the GOF variety. This web book has the word "Patterns" in it, too: http://www.brpreiss.com/books/opus7/ But looks like it's mainly data structures. If you do a google search, and also search the Python Cookbook http://aspn.activestate.com/ASPN/Python/Cookbook/ you can find examples of: Singleton Borg Null Factory Observer (including a Publish/Subscribe recipe) Memento State Decorator Masquerading and Adaptation patterns (Alex Martelli paper) Template (another Alex Martelli paper) Chain of Responsibility Proxy Prototype There must be good examples in actual source code out there, too. > called "Head First Design Patterns in Python". I think, this will be a > great addition to Python books, and a great benefit to Python community. I just bought this book as well. I must have adult ADD, because I do enjoy the Head First format, though I disdained it at first. > P.S. I am not sure is this the right news group to post this request. Yup, this is the place. Dave Cook From duncan.booth at invalid.invalid Thu Nov 18 07:58:49 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Nov 2004 12:58:49 GMT Subject: Named tuples References: <30001hF2ptnqcU1@uni-berlin.de> <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> <10pntj5m0spvl3f@corp.supernews.com> <419c20da.344317031@news.oz.net> Message-ID: Carlos Ribeiro wrote: > There are a few requirements that can be imposed to avoid problems. > First, __names__ is clearly a property, acessed via get & set (which > allows to trap some errors). It should accept only tuples as an > argument (not lists) to avoid potential problems with external > references and mutability of the names. As for the validation, I'm not > sure if it's a good idea to check for strings. maybe just check if the > 'names' stored in the tuple are immutable (or perhaps 'hashable') is > enough. > Your idea of a __names__ attribute suffers from a problem that the common use case would be to return a tuple with appropriate names. Right now you can do that easily in one statement but if you have to assign to an attribute it becomes messy. An alternative would be so add a named argument to the tuple constructor so we can do: return tuple(('1', '2'), names=('ONE', 'TWO')) and that would set the __names__ property. If you allow this then you can make the __names__ property readonly and the problem of introducing a cycle in the __names__ attributes goes away. From jcarlson at uci.edu Tue Nov 16 13:45:02 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 10:45:02 -0800 Subject: determining the number of output arguments In-Reply-To: <1gnc34a.1h31tyf1qbqr06N%aleaxit@yahoo.com> References: <1gnc34a.1h31tyf1qbqr06N%aleaxit@yahoo.com> Message-ID: <20041115234445.F964.JCARLSON@uci.edu> aleaxit at yahoo.com (Alex Martelli) wrote: > > Josiah Carlson wrote: > > > > a, b, c, d = lotsa[:4] > > > > > > _should_ properly give the impression of a code smell, if your "once and > > > only once" sense is finely tuned. What's the business of that ':4' on > > > the RHS? Showing the compiler that you can count correctly?! You're > ... > > The slicing on the right is not so much to show the compiler that you > > know how to count, it is to show the runtime that you are looking for > > a specified slice of lotsa. How would you like the following two cases > > to be handled by your desired Python, and how would that make more sense > > than what is done now? > > > > a,b,c = [1,2,3,4] > > a,b,c = [1,2] > > I would like to get exceptions in these cases, which, being exactly what > IS done now, makes exactly as much sense as itself. Note that there is > no indicator in either of these forms that non-rigid unpacking is > desired. Assuming the indicator for 'and all the rest' were a prefix > star, then: > > a, b, *c = [1, 2, 3, 4] > a, b, *c = [1, 2] > > should both set a to 1, b to 2, and c respectively to [3, 4] and []. Of > course there would still be failing cases: > > a, b, *c = [1] > > this should still raise -- 'a, b, *c' needs at least 2 items to unpack. The only limitation right now is Guido. That is, you need to convince Guido, and likely get the syntax implemented. See James Knight's post on 11/12/2004 in python-dev (or my recent quoting here) with a quote from Guido in regards to this syntax. > > > I think it would be better to have a way to say 'and all the rest'. > > > Lacking that, some automated way to count how many items are being > > > unpacked on the LHS is probably second-best. I have another response to this...what would be shorter, using some automated 'how many items are on the left' discovery mechanism, or just putting in the ':4'? Certainly some symbol could be reused for something like... a,b,c = L[:%] #first part a,b,c = L[%:] #last part, automatically negating the value But is something like the follwing even desireable? a,b,c = L[i:%:j] #automatically calculate the ending index a,b,c = L[%:i:j] #automatically calculate the start index Regardless, I'm not sure I particularly like any symbol that could be placed in either set of slices. If it is not some single-character symbol, then it is actually shorter to just count them. > > Is it worth a keyword, or would a sys.getframe()/bytecode hack be > > sufficient? In the latter case, I'm sure you could come up with such a > > mechanism, and when done, maybe you want to offer it up as a recipe in > > the cookbook *wink*. > > Two recipes in the 2nd ed of the CB can be combined to that effect > (well, nearly; c becomes an _iterator_ over 'all the rest'), one by > Brett Cannon and one by Sami Hangaslammi. Not nearly as neat and clean > as if the language did it, of course. What is to stop the recipes from wrapping that final iterator with a list() call? > > > Another case where a specific number of items is requested, which is not > > > (syntactically speaking) a multiple assignment, is assignment to an > > > _extended_ slice of, e.g., a list (only; assignment to a slice with a > > > stride of 1 is happy with getting whatever number of items are coming). > > > I don't particularly LIKE writing: > > > L[x:y:z] = len(L[x:y:z]) * [foo] > > > > I much prefer... > > > > for i in xrange(x, y, z): > > L[i] = foo > > Not the same semantics, in the general case. For example: > > L[1:-1:2] = ... And I would just use... for i in xrange(1, len(L)-1, 2): L[i] = ... As in anything, if there is more than one way to do something, at least a bit of translation is required. > rebinds (len(L)/2)-1 items; your version rebinds no items, since > xrange(1, -1, 2) is empty. To simulate the effect that assigning to an > extended slice has, you have to take a very different tack: > > for i in slice(x, y, z).indices(len(L)): > L[i] = foo > > and that's still quite a bit less terse and elegant, as is usually the > case for fussy index-based looping whenever it's decently avoidable. You know, terse != elegant. While extended slice assignments are terse, I would not consider them elegant. Elegant is quicksort, the Floyd-Warshall algorithm for APSP, Baruvka's MST algorithm, etc. Being able to say "from here to here with this stride", that's a language convenience, and its use is on par with using fcn(*args, **kwargs). Have I used it? Sure, a few times. My most memorable experience is using a similar functionality in C with MPI. Unbelievably useful for chopping up data for distribution and reintegration. Was it elegant, I wouldn't ever make such a claim, it was a library feature, and extended slice assignments in Python are a language feature. A useful language feature for a reasonably sized subset of the Python community certainly, but elegant, not so much. Using an imperative programming style with Python (using indices to index a sequence), I thought, was to be encouraged; why else would xrange and range be offered? Oh, I know, because people use 'fussy index-based looping' in C/C++, Java, pascal...and don't want to change the way they develop. Or maybe because not every RHS is a sequence, and sequence indexing is the more general case which works for basically everything (with minimal translation). > > But then again, I don't much like extended list slicing (I generally > > only use the L[:y], L[x:] and L[x:y] versions). > > It may be that in your specific line of work there is no opportunity or > usefulness for the stride argument. Statistically, however, it's > somewhat more likely that you're not taking advantage of the > opportunities because, given your dislike, you don't even notice them -- > as opposed to the opportunities not existing at all, or you noticing > them, evaluating them against the lower-level index-based-looping > alternatives, and selecting the latter. If you think that extended > slices are sort of equivalent to xrange, as above shown, for example, > it's not surprising that you're missing their actual use cases. It is the case that I have rarely needed to replace non-contiguous sections of lists. It has been a few years since I used MPI and the associated libraries. Recently in those cases that I have found such a need, I find using xrange to be far more readable. It's an opinion thing, and we seem to differ in the case of slice assignments (and certainly a few other things I am aware of). How about we agree to disagree? I have also found little use of them in the portions of the standard library that I peruse on occasion, which in my opinion, defines what it means to be Pythonic (though obviously many extended slice usages are application-specific). - Josiah From charlotte at donotspam.invalid Mon Nov 8 07:00:11 2004 From: charlotte at donotspam.invalid (Charlotte) Date: 08 Nov 2004 12:00:11 GMT Subject: cherrypy/cheetah vs twisted/nevow References: <418818ca$0$19452$626a14ce@news.free.fr> <69cbbef2.0411050857.6dfe11bd@posting.google.com> <69cbbef2.0411070346.6c6c0eaf@posting.google.com> Message-ID: has wrote: > With HTMLTemplate I finally got it right. Whereas most templating > systems provide direct support for both presentation logic and markup, > HTMLTemplate implements support for the markup side only and leaves > the host language to take care of all logic. This gives a system that > is both extremely simple (turning markup into a simple object model is > trivial) and incredibly powerful (as powerful as the host language, in > fact, since that's what the presentation logic is written in). Thanks for your explanation. I took a look at your website, and HTMLTemplate seems to be very nice indeed. I wonder why I had not discovered this before. > <...> I find this sort of > thing terribly depressing, because it conditions people into thinking > complex solutions to complex problems are actually something to aspire > to, rather than avoid as much as possible. I completely agree. > Nevow implements six or seven extremely interesting ideas. I think its > biggest problem is it does this as one huge package rather than six or > seven independent modules, which makes it a bit of a bear to get on > top of and also cuts down on reusability which is a shame. And I agree again. > I'd suggest looking at HTMLTemplate. It's simpler than Nevow.Renderer > and faster than PyMeld, mature, has no significant dependencies and is > small enough to pull apart and grok (and hack) quite easily: > http://freespace.virgin.net/hamish.sanderson/htmltemplate.html Well, you know how to sell your product :) Thanks. Charlotte. From bdesth.quelquechose at free.quelquepart.fr Fri Nov 12 07:53:56 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Nov 2004 13:53:56 +0100 Subject: Plone and mod_python In-Reply-To: <7l1ld.13845$3_.7287@ns2.gip.net> References: <7l1ld.13845$3_.7287@ns2.gip.net> Message-ID: <4194b228$0$27717$626a14ce@news.free.fr> Tony Ha wrote: > Hello > > Can some one explain what are the differences between "plone" and "Apache + > mod_python"? > From plone.org. It says "Plone is powerful and flexible. It is ideal as an > intranet > and extranet server" does this mean if I use "plone" I do not need to > install > "Apache + mod_python"? Thanks in advance! Plone is a 'portal' type content management system build over Zope and the CMF. Which means that you need at least Zope to run Plone. Now you can either choose to run Zope as a standalone web server, or 'hide' it behind a running Apache server. In both cases, you won't need mod_python. HTH Bruno From zanesdad at bellsouth.net Sat Nov 6 23:54:52 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Sat, 06 Nov 2004 23:54:52 -0500 Subject: Python OS In-Reply-To: References: Message-ID: <418DAA9C.1030702@bellsouth.net> Peter Hansen wrote: > Richard Blackwood wrote: > >> >>>> P.S. If one can program interrupt routines in C, they can do the same >>>> in Python. >>> >>> >>> Show me how you set the interrupt jumptables to your routines in >>> python and >>> how you write time-critical code which has to be executed in a few >>> hundred >>> cpu-cycles. And how good that works together with the GIL. >>> >> Here is my logic: If one can do X in C and Python is C-aware (in >> other words Python can be exposed to C) then Python can do X via such >> exposure. > > > Unfortunately the logic is flawed, even in the case that you > quoted above! Yes and no. See below. > > You _cannot_ use Python for a time-critical interrupt, even > when you allow for pure C or assembly code as the bridge > (since Python _cannot_ be used natively for interrupts, of > course), because -- as noted above! -- the interrupt must > execute in a few hundred CPU cycles. I'm really not trying to contradict nor stir things up. But the OP wanted to know if it were possible to prototype an OS and in a follow-up, referred to a virtual OS. Maybe I mis-read the OP, but it seems that he is not concerned with creating a _real_ OS (one that talks directly to the machine), it seems that he is concerned with building all the components that make up an OS for the purpose of....well.....he didn't really state that.....or maybe I missed it. So, asking in total ignorance, and deferring to someone with obviously more experience that I have (like you, Peter), would it be possible to create an OS-like application that runs in a Python interpreter that does OS-like things (i.e. scheduler, interrupt handling, etc.) and talks to a hardware-like interface? If we're talking about a virtual OS, (again, I'm asking in ignorance) would anything really be totally time critical? Especially if the point were learning how an OS works? > > Given that the cost of invoking the Python interpreter on > a bytecode-interrupt routine would be several orders of > magnitude higher, I don't understand why you think it > is possible for it to be as fast. I totally agree with you...sort of. I totally agree with your technical assessment. However, I'm reading the OP a different way. If he did mean a virtual OS and if time isn't critical, and he was thinking, "well, I'm getting shot down for proposing to do this in Python, so maybe it isn't possible in Python, but it is possible in C and since I can call C from Python, then I should be able to do it", then maybe he has a point. Or, maybe I'm just totally misreading the OP. So, if he's saying that he can just call the C code from python and it'd be just as fast doing interrupt handling that way, then I agree with you. But if he's talking about just the functionality and not the time, is that possible? > > Of course, if you will allow both assembly/C code here and > there as a bridge, *and* you are willing to accept an operating > system that is arbitrarily slower at certain time-critical > operations (such as responding to mouse activities) than we > are used to now, then certainly Python can be used for such things... > OK - so here's my answer. It should be possible, but it will be slower, which seems to be acceptable for what he meant when mentioning prototyping and a virtual OS. But here's another question. Would it be possible, if I've interpreted him correctly, to write the whole thing in Python without directly calling C code or assembly? Even if it were unbearably slow and unfit for use for anything other than, say, a learning experience? Kind of like a combustion engine that has part of it replaced with transparent plastic - you dare not try to run it, but you can manually move the pistons, etc. It's only good for education. > -Peter Jeremy From onurb at xiludom.gro Tue Nov 2 18:39:59 2004 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 03 Nov 2004 00:39:59 +0100 Subject: cherrypy/cheetah vs twisted/nevow In-Reply-To: References: Message-ID: <418818ca$0$19452$626a14ce@news.free.fr> Carlos Ribeiro a ?crit : (snip) > I'm yet to study nevow, but I'm getting more and more interested. I > have my own approach to separation; I use to think about a third > entity, "structure", as being independent from code & ui. The > structure is the common part; it's the "glue" between ui and code; and > it's the first part to be designed. Err... I may have missed something obvious, but doesn't this smells like a good old MVC ?-) From chris.cavalaria at free.fr Thu Nov 11 16:04:55 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Thu, 11 Nov 2004 22:04:55 +0100 Subject: Tkinter and WCK (was Re: How come wxPython isn't in the standard library?) References: <2vgfe5F2m8raqU1@uni-berlin.de> Message-ID: <4193d3f9$0$16439$636a15ce@news.free.fr> Jon Perez wrote: >> Guess, that answers my question, but isn't "Tkinter was there first" a >> very bad answer? :) It is kinda ugly too, so I wonder why it can't be >> replaced? > > Tkinter is a lot less ugly today than it used to be because > Tk has adopted a more native look (i'm talking about windows > here, dunno about other platforms). Motif on Unix ! Ugliest of all ( well, maybe there is worse ) From fumanchu at amor.org Fri Nov 19 11:42:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Nov 2004 08:42:21 -0800 Subject: Python with Apache 2.0 Message-ID: <3A81C87DC164034AA4E2DDFE11D258E324524C@exchange.hqamor.amorhq.net> Chang LI wrote: > Does python support threads safely along with Apache 2.0 in > web applications. The only problem I found using Apache2 (on Windows 2k) was that Apache uses a thread pool, so if you add attributes to a thread, they won't be freed when the request ends. For example, "threading.currentThread().data = 5"; you might encounter that same thread again later, and it will already have .data == 5 at the beginning of your request handler. As long as you're not adding attributes to thread objects, or using a mapping of thread id's, you should be OK. Robert Brewer MIS Amor Ministries fumanchu at amor.org From gandalf at geochemsource.com Fri Nov 26 13:41:21 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 26 Nov 2004 19:41:21 +0100 Subject: Number of colors in an image In-Reply-To: <1075192482.20041126193704@geochemsource.com> References: <1075192482.20041126193704@geochemsource.com> Message-ID: <568241297.20041126194121@geochemsource.com> > Hello, > How can I determine the number of colors used in an image? I tried to > search on Google but I could figure out. I read the PIL handbook but I read: could NOT figure out > do not see how to do it. Can anyone help? From theller at python.net Fri Nov 19 15:57:04 2004 From: theller at python.net (Thomas Heller) Date: Fri, 19 Nov 2004 21:57:04 +0100 Subject: Events References: Message-ID: <7joh7e1r.fsf@python.net> factory writes: > Anyone want to comment on what they think of this following bit of a > simple event framework? You should definitely look into the dispatcher module: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87056 The comments indicate that an enhanced version is maintained on SF. Thomas From tim.peters at gmail.com Wed Nov 17 13:14:34 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 17 Nov 2004 13:14:34 -0500 Subject: don't NaN & infinities hide FP errors In-Reply-To: <419B5965.1010801@geochemsource.com> References: <940ee3e8.0411170130.31d247@posting.google.com> <1f7befae041117054954a8e966@mail.gmail.com> <419B5965.1010801@geochemsource.com> Message-ID: <1f7befae0411171014339b4171@mail.gmail.com> [Gandalf] > I still feel that it would be possible to use some assembly code and > achieve the same behaviour on all platforms. > It is really not difficult to calculate log on a 387. It can be more > difficult on a RISC but not impossible. > Why the implementation stuck on the C standards? Okay, maybe it is > not possible or too difficult to use asm code on some platforms. But at > least Python should try to do the same thing when it is possible. It > could be an 'option' to compile low level code for the most popular > operating systems. What do you think? I think you're not burdened by actual experience writing production-quality math libraries <0.3 wink>. I've done that for a living at times, and writing a production-quality math library, even at the shallow level C89 provides, and even for a single platform, is a whale of a lot of work. OTOH, writing low-quality math libraries is easy. Python defers to C here because platform C vendors are generally in a much better position to provide production-quality platform-specific math libraries than the Python project will ever be. BTW, "same behavior on all platforms" is a non-goal for me when it comes to floating point. There's an enormous range of speed-vs-accuracy tradeoffs that can be made here, and legitimately so. By not trying to force a specific choice here on Python's users, a Python user that *really* cares about this can get the tradeoff they like by obtaining (probably buying) and installing a libm replacement for their platform C libm. Python will automatically use that too then. From simoninusa2001 at yahoo.co.uk Sun Nov 14 03:17:10 2004 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 14 Nov 2004 00:17:10 -0800 Subject: .pyc files... In-Reply-To: References: Message-ID: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> Stephen Waterbury wrote: > > OK, stupid question, but it's been bothering me for ages.. J > > > > I love Python to bits, but .pyc files always litter my source tree, and > > they've always bothered me. ... > One solution (on unices, at least): > > alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" or with backticks: rm -rf `find . -name '*.pyc'` From jcarlson at uci.edu Tue Nov 16 12:25:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 09:25:59 -0800 Subject: determining the number of output arguments In-Reply-To: References: Message-ID: <20041116085933.F96D.JCARLSON@uci.edu> Jeremy Bowers wrote: > > On Mon, 15 Nov 2004 23:43:55 -0800, Josiah Carlson wrote: > > Guido hasn't updated his stance, so don't hold your breath. > > I'm not in favor of it either. I just think that *if* it were going in, it > shouldn't be a "keyword". > > I think variable size tuple returns are a code smell. Now that I think of > it, *tuple* returns are a code smell. (Remember, "code smells" are strong > hints of badness, not proof.) Of the easily thousands of functions in > Python I've written, less than 10 have returned a tuple that was expected > to be unpacked. I agree with you on the one hand (I also think that variable lengthed tuple returns are smelly), and have generally returned tuples of the same length whenever possible. However, I can't agree with you on general tuple returns. Why? For starters, dict.[iter]items(), struct.unpack() and various client socket libraries in the standard library that return both status codes and status messages/data on command completion (smtplib, nntplib, imaplib). > Generally, returning a tuple is either a sign that your return value > should be wrapped up in a class, or the function is doing too much. One of > the instances I do have is a tree iterator that on every "next()" returns > a depth *and* the current node, because the code to track the depth based > on the results of running the iterator is better kept in the iterator than > in the many users of that iterator. But I don't like it; I'd rather make > it a property of the iterator itself or something, but there isn't a > code-smell-free way to do that, either, as the iterator is properly a > method of a certain class, and trying to pull it out into its own class > would entail lots of ugly accessing the inner details of another class. The real question is whether /every/ return of more than one item deserves to have its own non-tuple instance, and whether one really wants the called function to define names for attributes on that returned instance. Me, I'm leaning towards no. Two, three or even four-tuple returns, to me, seem reasonable, and in the case of struct, whatever suits the program/programmer. Anything beyond that should probably be a class, but I don't think that the Python language should artificially restrict itself when common sense would keep most people from: a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z = range(26) ...or at least I would hope. - Josiah From aleaxit at yahoo.com Thu Nov 4 15:21:57 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 Nov 2004 21:21:57 +0100 Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> Message-ID: <1gmqqa3.r7hg5g17qatxkN%aleaxit@yahoo.com> Steven Bethard wrote: > Does this make my concern any clearer? What I'm asking for is an example > like yours above that not only shows that you can treat, say, the bits of > a float as an integer, but also shows why this would be useful. Given a float, extract the (so-called) "mantissa" (what a misnomer!) and exponent. Can you see the usefulness of _that_? Can you see that treating the bits that compose the float as an int and using masking and shifting is the obvious way to perform this task? Say I need to compute some unary float function, such as 'sin', with high speed and precision. One reasonable approach: normalize the float input to a standard range (say 0 to pi/4, remembering what kind of sign inversions &c you need to perform at result time); get "mantissa" (pah!) and exponent and use the latter, partly to select the right lookup table and partly to shift the mantissa appropriately to make it an index into said result table, while keeping track of the bits that shifted out; read out the result base and the multiplier for interpolation, multiply the latter by the bits that shifted out and add the result to the result base; perform sign or other symmetry inversions as previously recorded. There -- you have the function computer to whatever precision is requested, typically an ULP. Depending on your CPU, you may have HW that obviates the need for some or all of these manipulations - but you won't have it for all transcendentals, and what you don't have in HW you'll need to do in SW -- and being able to get at the bits of the floating point representation is often the best approach for that task. Although the details were more antiquated, that was elementary stuff taught in electronic engineers' first-year computing courses back in the '70s, just in case we ever needed to code our own transcendentals (in Fortran, of course -- you weren't expected to master machine code unless you took computing electives in 3rd and later years, much less exoterica such as Pascal, Lisp or APL). Is it considered advanced or specialized these days?! Alex From Scott.Daniels at Acm.Org Tue Nov 30 15:15:11 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Nov 2004 12:15:11 -0800 Subject: weird behaviour of "0 in [] is False" In-Reply-To: References: Message-ID: <41ace762@nntp0.pdx.net> Sylvain Thenault wrote: > Hi there ! > > Can someone explain me the following behaviour ? > > >>>>l = [] >>>>0 in (l is False) > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required > >>>>(0 in l) is False > > True > >>>>0 in l is False > > False > > > This is really obscur to me... > A suggestion: When discussing things on the newsgroup (and in your code), avoid symbols like "l" and "O" -- they look too much like numbers. Picking an actual name is best (but depends on your application context). Second best are names like: "lst", "obj", ...: often, however, such names are necessary when discussing abstract code properties. -Scott From jerry at jerrysievers.com Mon Nov 29 15:49:30 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 29 Nov 2004 15:49:30 -0500 Subject: slicing, mapping types, ellipsis etc. Message-ID: Fellow Pythonists; I am totally puzzled on the use of slicing on mapping types and especially unsure on use of the Ellipsis... and slicing syntax that has two or more groups seperated by comma. I am referring to (from the manual); Slice objects Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function. A quick example on how this is used and/or pointer to more reading is greatly appreciated. Thanks -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From tolot at jupiter.solar-empire.de Mon Nov 8 20:12:53 2004 From: tolot at jupiter.solar-empire.de (Marc Christiansen) Date: Tue, 9 Nov 2004 02:12:53 +0100 Subject: HTML to Text renderer References: <3A81C87DC164034AA4E2DDFE11D258E324510E@exchange.hqamor.amorhq.net> Message-ID: Ian Bicking wrote: > Robert Brewer wrote: >> To clarify: you don't want the HTML tags merely stripped; you want to >> replace e.g. br with a line break and p with, say, two line breaks? > > Right. And word wrapping too. Some other tags would also be > interesting:

,
, 
,
,  , and something > to control alignment (e.g.,

). Have a look at htmllib.HTMLParser and formatter in the standard Python lib (but also look at the source of htmllib). Maybe they provide what you need. HTH Marc From rolandREMOVE_THIS at numeca.be Mon Nov 29 07:56:08 2004 From: rolandREMOVE_THIS at numeca.be (Roland Van Praag) Date: Mon, 29 Nov 2004 13:56:08 +0100 Subject: Load module on IRIX 6 Message-ID: <0rCdnXWobOIcgTbcRVnyjw@scarlet.biz> Dear All, I try to prepare a new module named using python 1.5 on IRIX6. The shared library created is named igg.so and contains the initializarion routine initigg. I call in this routine Py_InitModule giving as first argument "igg". Whe I try to import this module, I always have the message : SystemError: _PyImport_FixupExtension: module igg not loaded. The same example is running well on windows and DEC alpha but I never succeed on Silicon workstation. I try with python 1.5 and 2.3. Thanks for your help Roland From arkham at gmail.com Wed Nov 24 09:29:10 2004 From: arkham at gmail.com (Rob Snyder) Date: Wed, 24 Nov 2004 14:29:10 GMT Subject: teaching OO References: Message-ID: Gabriel Zachmann wrote: > This post is not strictly Python-specific, still > I would like to learn other university teachers' opinion. > > Currently, I'm teaching "introduction to OO programming" at the undergrad > level. My syllabus this semester consists of a bit of Python (as an > example of a scripting language) and C++ (as an example of a compiled > language). With C++, I go all the way up to meta-programming. > > My question now is: do you think I should switch over to Python completely > (next time), and dump all the interesting issues involved in C++'s virtual > classes, overloading, and templates? (In Python, all of that would just > disappear ... ;-) ) > > (The opinion of the people on this NG might well be a little bit biased > towards Python, but that's ok ;-).) > > Interested in all kinds of thoughts. > > Best regards, > Gabriel. > Gabriel - I was in a similar position, and decided to make the change over to Python completely. Key for me was that I knew these same students, at some point in time, would *also* being taking several courses that involved C++. In other words, they didn't need this course to cover C++, they only needed it to get introduced to OO programming, and by switching to Python, I gave them an environment to learn that they could really get their heads around. If the students wouldn't be getting immersed in C++ otherwise, I don't think I would have made the switch, and may have continued not using any Python at all. Python, IMHO, is an excellent teaching language. In my observations, by switching to Python for the OO concepts class, I'd say we easily covered 50% more material in the same amount of time. As for the interesting C++ issues, those same students were able to pick those concepts up quickly in their later classes. "Overloading", for example, was a pretty simple concept to grasp for people who had previously spent a whole semester heads down learning OO. Rob From Norbert.Klamann at klamann-software.de Tue Nov 16 04:10:33 2004 From: Norbert.Klamann at klamann-software.de (Norbert) Date: 16 Nov 2004 01:10:33 -0800 Subject: How to pass a parameter References: <81a41dd.0411151048.78af4fd3@posting.google.com> Message-ID: <1100596233.345798.61700@z14g2000cwz.googlegroups.com> Lad wrote: > I have a sript that downloads a webpage. According to the picture on > this webpage I need to pass a parameter to this , running script a few > lines later. > How can I do that? > Thanks for help > Lad Depends on the environment you use and the script itself. Assuming windows it could go like this: [path_to_python]\python yourscript.py param1 param2 maybe the script takes named parameters, then it looks like this : [path_to_python]\python yourscript.py param1=value1 param2=value2 the path_to_python is not required if python is on your path. 'python' is not required in the statemenst if your system is configured to execute .py files with python anyway. Hope that helps, if it doesn't you should supply details about your system. Norbert From zanesdad at bellsouth.net Tue Nov 9 08:39:26 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 09 Nov 2004 08:39:26 -0500 Subject: should i start looking for a new list? In-Reply-To: <20041109101248.F1B661C001B2@mwinf0101.wanadoo.fr> References: <20041109101248.F1B661C001B2@mwinf0101.wanadoo.fr> Message-ID: <4190C88E.1070803@bellsouth.net> Jelle Feringa // EZCT / Paris wrote: > I've been posting some of my most burning (newbie) questions to this > list, and most of them have been unanswered. > > Should I be posting these questions at a different list, since their > technical level is quite low? Am I looking for answers in the right place? > > > I tried to backtrack and see your emails for the past few days and have only come up with 2 (for the month of November). I'm not questioning that you posted, I just wanted to see the content and let you know if I thought they were appropriate for this group. I'll give you my opinion on the appropriateness of your postings, but I definitely don't claim to speak for the majority of the group. The one dated 11/1/2004 with subject "newbie troubles: os.popen confusion" should have been fine to post here. (BTW - I would use os.path.join() rather than the "+" operator for combining directory paths.) The one dated 11/8/2004 with subject "newbie question | shell scripting" again should be fine. Looks like you got some help there. If you have any still unanswered questions, you could re-post them, with notes of what you've tried since the original posting and failed at and what specific problems you're (still) having. And, not that you're guilty of violating it, but I've got to insert the ubiquitous link to http://www.catb.org/~esr/faqs/smart-questions.html, else I may take some crap for leaving that out. HTH, Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From ianb at colorstudy.com Sun Nov 28 16:06:44 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 28 Nov 2004 15:06:44 -0600 Subject: Python's annoyance. In-Reply-To: References: Message-ID: <41AA3DE4.1070809@colorstudy.com> Giovanni Bajo wrote: > caroundw5h wrote: > > >>Serioulsy, one of python's main selling points is its elegant syntax, >>non perl like, non C like. If it can't live up to it. I guess i might >>as well use perl or ruby or server side javascript. >>how annoying. > > > In fact, I find the decorator syntax awful. But I know this was already > discussed to a large extent, so there must be a very good reason to use @. > Which I totally miss, but hey. I was just recently talking to someone about PHP, and he said that everyone agreed that PHP 5 needed namespaces, but no one could agree on the syntax. So they left it out. Which is bad, because PHP *really* needed this feature, but they simply lacked the decision process which could make it happen. So it's good that we have a decision process (benevolent dictator) which can actually move on in the face of wide disagreement on smaller points. (Other people think we don't need the decorator syntax at all, but that's another discussion; even there, we are again relying on Guido's intuition on the matter) -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From maluke at gmail.com Wed Nov 17 08:37:07 2004 From: maluke at gmail.com (Sergey Schetinin) Date: 17 Nov 2004 05:37:07 -0800 Subject: bsddb built for concurrent access (rh9) Message-ID: <1100698627.853881.29550@f14g2000cwb.googlegroups.com> Hello people, I've spent many hours trying to fix it by myself, but w/ no success. I have a program, that uses bsddb. It needs to access the DB from multiple processes, so it uses it in a concurrent mode. That works fine on windows. Yet, when I've tried it on my server running RedHat9 it gives me this: BaseIndex.env.open(path, envflags | db.DB_CREATE) bsddb._db.DBInvalidArgError: (22, 'Invalid argument -- Berkeley DB library configured to support only DB_PRIVATE environments') I figured it's because of bsddb/db4 is built w/o concurrent access capabilities to avoid some bugs, cause many old systems don't have working crossprocess mutexes. So basically I need a different build - i haven't found one, also I've tried to make one myself, but compilation chokes right away. Giving a ton of syntax errors (this happens w/ python src distrib as well as w/ pybsddb). Please, tell me what am I missing or better yet give me a lead as to where to find a properly built bsddb. Thank you! From jzgoda at gazeta.usun.pl Fri Nov 19 16:33:47 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Nov 2004 22:33:47 +0100 Subject: Question about thread In-Reply-To: References: <1100875373.911763@eng-ser6> <306ic5F2svtsdU1@uni-berlin.de> <1100879122.755150@eng-ser4> Message-ID: Diez B. Roggisch wrote: >>Even after printing "finished creating threads" all spawned threads >>continue its execution up to final "thread nnnn is being destroyed", so >>I think there's no need to take any special action (unless it's Python >>on iSeries, buy this is another story) to wait for completion. > > The OP used the module "thread", while you used "threading" and didn't set > setDaemon(False). Then python waits until all threads are finished. Well... I was bit too fast in replying. ;) > From the thread module docs: > > When the main thread exits, it is system defined whether the other threads > survive. On SGI IRIX using the native thread implementation, they survive. > On most other systems, they are killed without executing try ... finally > clauses or executing object destructors. So it looks that using threading should be preferred over using thread, as presented example works identically on Windows and on linux (it doesn't work on AS/400, though...). -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From mauriceling at acm.org Tue Nov 9 05:58:38 2004 From: mauriceling at acm.org (Maurice Ling) Date: Tue, 09 Nov 2004 21:58:38 +1100 Subject: possible to pass python objects into java without jython? Message-ID: <4190A2DE.6040505@acm.org> Hi, I have read that this had been asked before but there's no satisfactory replies then. I have a module (pA) written in python, which originally is called by another python module (pB), and passes a python object (pO) to pB. Now I require pA to be called in a java class (jC) and pass pO into jC. As pA uses non-python modules, I am not able to use Jython on this. Are there any way out in this? Thanks in advance. Maurice -------------- next part -------------- A non-text attachment was scrubbed... Name: mauriceling.vcf Type: text/x-vcard Size: 347 bytes Desc: not available URL: From jzheng at jpl.nasa.gov Fri Nov 12 15:19:08 2004 From: jzheng at jpl.nasa.gov (Jason Zheng) Date: Fri, 12 Nov 2004 12:19:08 -0800 Subject: popen help In-Reply-To: References: Message-ID: exarkun at intarweb.us wrote: > On Fri, 12 Nov 2004 11:29:46 -0800, Jason Zheng wrote: > >>I'm trying to open a subshell to run some csh commands, and I want to >>connect the stdout of the subshell to the main stdout: >> >>sub = Popen4('csh -f') >>sub.tochild.write('source source.me\n') >>sub.tochild.write('runthis\n') >>sub.tochild.close() >> >>for x in sub.fromchild.readlines(): >> print x >> > > >>>>import os, time >>>>for x in iter(os.popen('for x in `seq 3`; do echo $x; sleep 1; done').readline, ''): > > ... print time.time(), x, > ... > 1100290304.55 1 > 1100290305.56 2 > 1100290306.56 3 > > The difference is that readline() returns one line whereas readlines() returns all of the lines. Since you cannot know what all the lines are until you have read all of the data, it cannot return until the child process exits. > > Jp Jp, I doubt that's gonna resolve the problem I have tho. Suppose I send one command which doesn't not have the 'sleep' but prints some output line periodically, wouldn't I have to wait till the end of the execution to see any output? Can I just connect sys.stdout to the stdout of the subshell? jz From bokr at oz.net Mon Nov 1 02:20:51 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 01 Nov 2004 07:20:51 GMT Subject: "number-in-base" ``oneliner'' References: Message-ID: <4185e098.1316872382@news.oz.net> On Mon, 01 Nov 2004 03:11:42 GMT, exarkun at divmod.com wrote: >On Sun, 31 Oct 2004 19:00:07 GMT, bokr at oz.net (Bengt Richter) wrote: >> [snip] >> >> BTW, will anything that works in a list comprehension work in a generator expression >> (assuming one does not depend on the generator expression having leftover outside >> side effect bindings like the LC version)? >> > > Nope. For example, I don't think the code in this thread will work if converted to a generator expression. A simplified example: > > >>> x = 0 > >>> list(x for x in iter(lambda: x + 1, 4)) > ( runs forever, so C-c ) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > KeyboardInterrupt > >>> [x for x in iter(lambda: x + 1, 4)] > [1, 2, 3] > >>> > > `x' in the lambda in the list comprehension resolves to a different name than `x' in the generator comprehension. > I had a sneaky suspicion that it _could_ be so, hoping not. But your example doesn't play fair because you don't give x an initial condition inside the scope of the expression. E.g., >>> [x for x in [0] for x in iter(lambda:x+1, 4)] [1, 2, 3] >>> list(x for x in [0] for x in iter(lambda:x+1, 4)) File "", line 1 list(x for x in [0] for x in iter(lambda:x+1, 4)) ^ SyntaxError: invalid syntax Well, I don't have 2.4 yet, but what does it do? If the generator expression scope causes a closure access from lambda it should be ok, IWT. Regards, Bengt Richter From Scott.Daniels at Acm.Org Mon Nov 1 18:28:08 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Nov 2004 15:28:08 -0800 Subject: Why is heapify linear? Message-ID: <4186cb77$1@nntp0.pdx.net> I am sorry, but in the Python 2.4 description of "heapify", I find the description of "Transform list x into a heap, in-place, in linear time," unbelievable. I understand the hand-wave that makes dictionary building linear (though I have a hard time with even that). Could somebody tell me what twist of logic makes "heapify" linear, except in the sense that linear is coming to mean "very fast?" Skeptically, -Scott David Daniels Scott.Daniels at Acm.Org From foo at bar.com Sat Nov 6 00:12:04 2004 From: foo at bar.com (Steve Menard) Date: Sat, 06 Nov 2004 00:12:04 -0500 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> <4b39d922.0411051555.24f31663@posting.google.com> Message-ID: Mike Meyer wrote: > finite.automaton at gmail.com (Lonnie Princehouse) writes: > > >>Yes, wxPython is typically quicker than swing. It's not fair to use >>this in a generic Python-vs-Java speed shootout, though, since >>wxPython is just a wrapper around wxWidgets' C++ code; you're really >>comparing C++ vs. Java here. > > > Is it unfair to compare Python dictionaries to Java HashTables because > Python is using hand-tuned C where Java is using Java? I'd say that's > a perfectly fair comparison. If that's fair, what's unfair about > comparing graphics toolkits that happen to be written in C rather than > Python (is there a graphics toolkit written in Python?). > > That's *how* interpreted languages manage to compete with compiled > languages - they perform the common operations in hand-tuned compiled > code. That people tend to write Java libraries in Java rather than C > just means they're going to get slower libraries. > > >>AFAIK the major two reasons for Python's relative slowness are that >>it's interpreted and dynamically typed. > > > Java is interpreted just like Python is. The only difference is that > Java splits the compiler and VM implementation into two different > binaries. > > Message-ID: In article , Aahz wrote: > >Keep in mind that it's been several years since I used Python with SQL >Server and about all I remember is that we used stored procedures >heavily with no problems. I have no clue whether we tried using stored >procedures with output parameters, but I wonder why you can't just use a >SELECT to call the stored procedure and return the values. Or at least >right another stored proc that does something roughly similar. s/right/write/, but you knew that. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From ialbert at mailblocks.com Tue Nov 2 15:19:12 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 02 Nov 2004 15:19:12 -0500 Subject: Python needs a CPyAN In-Reply-To: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > The real trick is going to be getting the existing module authors to The real trick is that the need for CPyAN is not an acute one. A whole lot of tasks can be done just with the standard library. This makes CPAN like functionality useful but not essential. I can't think of a single instance where I would have had to hunt down package dependencies whereas when I was using perl that was a very significant problem where automated installations really saved a lot of time. Programming environments evolve like real biological systems. They develop useful features in response to much needed functionality and not vice versa. Istvan. From caleb1 at telkomsa.net Thu Nov 25 21:12:18 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 25 Nov 2004 21:12:18 -0500 Subject: dictionary initialization References: Message-ID: Hmm :) "b[1]" looks like a List (but you created a Dict) "b['1'] looks more like a Dict (but this is not what you used). If lists are your thing: >>> a = [] >>> a.append(1) >>> a [1] >>> a[0] += 1 >>> a [2] If dicts are your thing: >>> b = {} >>> b['1'] = 1 >>> b {'1': 1} >>> b['1'] += 1 >>> b {'1': 2} Lists are ordered, Dicts are not. Dict entries accessed with 'string' keys, List entries accessed with a position integer. Which feature specifically do you want justification for? thx Caleb > With Python, I got > >>> b={} > >>> b[1] = b[1] +1 > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 1 > > That is, I have to initialize b[1] explicitly in the first place. > > Personally, I think > > a[i]++ > > in awk is much more elegant than > > if i in a: a[i] += 1 > else: a[i] = 1 > > I wonder how the latter is justified in Python. > > Thanks, > Weiguang From michael.bierenfeld at web.de Fri Nov 26 05:14:20 2004 From: michael.bierenfeld at web.de (michael) Date: 26 Nov 2004 02:14:20 -0800 Subject: How do you execute external programs from Python? References: <251120041136391879%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: > > Here is my crontab entry: > > > > 30 * * * * python -c "import os; os.chdir('/home/alpha/mymusic/P2/Jazz/'); > > import KKJZ" Hi, if cron is running as root say 30 * * * * "su - user; script.sh" su - user means that .profile, .bash-profile etc is read. I think its an "Environmental" Problem From max at alcyone.com Tue Nov 16 02:04:58 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 15 Nov 2004 23:04:58 -0800 Subject: int literals and __class__ (WAS: Is a list an instance of a class?) In-Reply-To: References: <4197c013$1_1@newspeer2.tds.net> Message-ID: Steven Bethard wrote: > Why does this work? Or, perhaps my real question is why *doesn't* it work > without the space? Pointers to the appropriate point in the docs would be > fine... I assume it's something about making parsing easier...? It's because otherwise it's confusing it for a floating point literal. All you need to do is put a break so that the parser can't get confused. 1 ._class__ or (1).__class__ will work just fine. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Love is the triumph of imagination over intelligence. -- H.L. Mencken From garbagecollector86 at hotmail.com Tue Nov 30 01:17:36 2004 From: garbagecollector86 at hotmail.com (Tom Hanks) Date: 29 Nov 2004 22:17:36 -0800 Subject: PIL 1.1.4 paste PNG's with transparency problem References: Message-ID: <3b6f03cd.0411292217.23ca37cb@posting.google.com> "Caleb Hattingh" wrote in message news:... > >>> iconBallImage.paste(iconShieldImage, (10,10)) >>> iconBallImage.paste(iconShieldImage, (10,10), iconShieldImage) ^^^^^^^^^^^^^^^ transparency as 3rd parameter TTFN Tom. From dmerrillq at usaq.netq Mon Nov 29 12:23:03 2004 From: dmerrillq at usaq.netq (Dave Merrill) Date: Mon, 29 Nov 2004 12:23:03 -0500 Subject: Newbie MySQLdb / MySQL version problem, I think References: <23ae7099.0411290103.51bd5fb0@posting.google.com> Message-ID: Thanks Allastair, Leon, Tim, anyone else I missed. Bingo, that was it. I didn't even try looking at mysql.com, duh. In my defense (;-), I'd already spent a bunch of time in incompatible version hell with other things, so I was (too) ready to think it either wouldn't work period, or I'd borked it up somehow. Bless the problems you can fix, easily, even... Dave Merrill > I'm using MySQLdb with mysql 4.1 and I've seen this too - to get > around it go to the following link: > > http://dev.mysql.com/doc/mysql/en/Old_client.html From danperl at rogers.com Wed Nov 3 13:59:21 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 3 Nov 2004 13:59:21 -0500 Subject: general class functions References: Message-ID: <3q6dnTBD--UTtxTcRVn-1w@rogers.com> I probably cannot do justice to the topic, although I have personally encountered cases where by following the advice of people more experienced in python than me I was able to improve my code. But I can point you to a couple of links: http://www.python.org/2.2.1/descrintro.html http://www.python.org/doc/2.2.1/whatsnew/ In a nutshell, subclassing from object is part of the new-style classes introduced in python 2.2. Quoting from "Learning Python" 2nd ed., "perhaps the most visible change in new style classes is their slightly different treatment of inheritance for the so-called diamond pattern of multiple inheritance trees-where more than one superclass leads to the same higher superclass further above". Look also at cooperative methods in the links I mentioned above (if I remember correctly, cooperative methods have been the main reason for me to change classes to the new style). I'm sure other people in this newsgroup can make a better case for new-style classes than I can. HTH, Dan "syd" wrote in message news:a76ba315.0411030818.9457fe3 at posting.google.com... > "Dan Perl" wrote in message >> >>>> library.get_continent('Europe') >> This line creates and returns an instance of Library. I assume that you >> imported foo in a python session and then you executed that line. That >> results in a call to Library.__repr__( ), which is not defined. First of >> all, I recommend you change class Library to subclass from object. >> That's >> just good practice in general and in this case it will give you a default >> __repr__( ) method. But that's probably not what you want. What you >> probably want is to still use a line like: >> print library.getContinent('Europe').getNameList() >> Otherwise, library.get_continent('Europe') is going to print something >> like: >> <__main__.Library object at 0x00A9F430> > > You're 100% right, Dan -- I meant to have the "getNameList()" tacked > on. > > But more importantly, why is subclassing object a good practice in > general? I see under dir(object) that you get some good default > methods. I looked under the documentation, but could not find a good > specific examples as to why this was a good practice. Can you > elaborate, please? From aslakr+news at idi.ntnu.no Fri Nov 5 10:59:50 2004 From: aslakr+news at idi.ntnu.no (Aslak Raanes) Date: Fri, 5 Nov 2004 16:59:50 +0100 Subject: How do you execute an OS X application (bundle) from Python? References: <70bb9f8d.0411040250.1f4ac1a@posting.google.com> <69cbbef2.0411041513.120fc039@posting.google.com> <1gmrrsj.7ljqd6f3sgkfN%aleaxit@yahoo.com> <1gms4py.c7p5cjeee3clN%aleaxit@yahoo.com> <1gmsdj3.12zknwuzpl15lN%aleaxit@yahoo.com> Message-ID: <1gmseyg.1vucxrh8e5hf6N%aslakr+news@idi.ntnu.no> Alex Martelli wrote: > Nice!!! OK, so what we need are similar commandline tools for other > useful apps, since MacOSX's own 'open' does not provide such a -w switch > (maybe it's too generic a tool for such a switch to be conceivable...?) One might use the external editor protocol for this: http://www.barebones.com/support/develop/odbsuite.shtml http://www.merzwaren.com/external_editor.html Several text editors support this protocol. -- Vennlig hilsen Aslak Raanes From carribeiro at gmail.com Wed Nov 17 19:14:28 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 17 Nov 2004 22:14:28 -0200 Subject: Named tuples In-Reply-To: <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> References: <1gnbg4k.13z20mj1w1o0ysN%aleaxit@yahoo.com> <30001hF2ptnqcU1@uni-berlin.de> <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> Message-ID: <864d3709041117161462eb1bcd@mail.gmail.com> On Wed, 17 Nov 2004 23:56:31 +0100, Alex Martelli wrote: > Carlos Ribeiro wrote: > > > But perhaps we could have something like "named tuples"; immutable > > objects, like tuples, with the property that a unique name can be > > associated to every item. > > Of course we should -- I've lost count of how many recipes in the > cookbook I've merged that were implementing that idea in umpteen ways, > not counting several other ideas that only flew by in this NG. Since > standard modules time, os (for stat), resource (dunno if any others), > started returning this kind of supertuples, their convenience has been > obvious to all. I do believe they SHOULD _be_ tuples (that matters when > they're the only RHS argument of a % formatting operator) and it should > also be easy to get from them a name->value mapping (for % formatting > with named-items format style, and the like). Definitely PEP time... > who's gonna carry the torch? *After* I posted that message, I *did* some research (wrong order, I know). And you're right, the situation now is pretty much like Tanenbaum's famous quote: "the nice thing about standards is that there are so many of them to choose from". I am tempted to start writing this PEP. I think that I have a pretty good idea about what do I want (which by itself isn't worth very much). Anyway, it's a starting point: 1. Do not change the syntax. This leaves out some of the fancy proposals, but greatly improves the acceptance chances. 2. Named tuples should, for all practical purposes, be an extension of standard tuples. 3. Conventional access returns a tuple. __getitem__ works as in a tuple, and the object itself is represented (by repr() and str()) as a tuple. 4. Named attribute access is supported by __getattr__. Names are looked up on the magic __names__ attribute of the tuple. 5. On slicing, a named tuple should return another named tuple. This means that the __names__ tuple has to be sliced also. 6. Although useful, a new named tuple *cannot* be built directly from a dict, as in this example: tuple({'a':1, 'b':2}) ...because the dict isn't ordered, and there is no way to guarantee that the tuple would be constructed in the correct order. This will only be possible if the dict stores the ordering information (btw, the 'correct' order is the definition order; it's the only one that can't be inferred later at runtime, and alphabetical ordering can be always obtained by a simple sort). (However, *if* ordered dicts ever make it into the language, then a conversion between 'named tuples' and 'ordered dicts' would become natural -- think about it as an 'adaptation' :-) 7. Now for the controversial stuff. NamedTuples can be implemented as a regular class -- there are many recipes to look at and choose from. However, I think that is possible to implement named attribute access as an "improvement" of regular sequence types, with no syntax changes. The idea is that any tuple could be turned into a named tuple by assigning a sequence of names to its __names__ magic attribute. If the attribute isn't assigned (as it's the case with plain tuples), then the named attribute is disabled. BTW, adding names to an unnamed tuple *does not* violates the immutability of the tuple. The usage would be as follows: time = now() time.__names__ = ('hour', 'minute', 'second') print time.hour The reasoning behind this proposal is as follows: 7.1. It's fully backwards-compatible. 7.2. It allow for easy annotation of existing tuples. 7.3. It allows for internal optimization. By using an internal mapping directly wired into the sequence, it is possible to hide the mapping mechanism, and also to make it work faster. This also adds a safety layer, and helps to avoid direct 'peeking' at the internal mapping structure that will be exposed by a native Python implementation. The *biggest* problem of this proposal is that it's MUCH more complex -- orders of magnitude, perhaps -- and also, that it may present problems for others implementations besides CPython. Anyway, it's something that I think deserves discussion. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From paul at boddie.org.uk Tue Nov 2 11:00:19 2004 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Nov 2004 08:00:19 -0800 Subject: Python AST as XML References: <1e015c2a.0410272209.3e831f94@posting.google.com> <3sg1o0djs6u5o055pvu88610n5k5498i1q@4ax.com> Message-ID: <5339b60d.0411020800.41c07c17@posting.google.com> Andy Dingley wrote in message news:<3sg1o0djs6u5o055pvu88610n5k5498i1q at 4ax.com>... > On 27 Oct 2004 23:09:02 -0700, olepar at gmail.com (Oleg Paraschenko) > wrote: > > >maybe of some interest: > > Maybe 5 years ago, before we realised what a bad idea it was. Actually, it's something I've considered before myself, and there are apparently various extensions to GCC (the compiler suite, not just the C compiler) which support similar concepts, so I suppose it's the royal "we" you're using. > >http://pysch.sourceforge.net/ast.html > > > >[quote] > >XML can be considered as an external representation of in-memory > >tree-like structures, > > Yes. But why would I want to ? XML is a clumsy _internal_ > representation and it's only useful as an external representation if > you need some lowest-common-denominator more than you need a good and > appropriate representation. The best external representation of > Python is some Python source, not some over-abstracted XML version. Unless you're writing tools in other languages. I personally find the various Python modules for source code inspection to be adequate, but you can't just import the compiler package in Java, for example. > > and XML-related standards as methods of processing such data. > > XML-related protocols don't process data, they process an XML > representation of that data. Their ability to do so is based on the > XML aspect of it, not the underlying data model. This makes them > somewhere between clumsy to develop wiith, or simply incapable of > addressing the problem. > > "Lets make all our data standards interwork by using XSLT" was the > theme of late '99. It didn't work. It may not have worked in the royal court, but XSLT has lots of interesting and productive uses provided you choose your problems carefully. I can imagine that transforming various sections of Python code (for simple macro implementations, for example) *is* one of those problem areas in which XSLT can usefully be used. Moreover, by choosing XML, the developer(s) have at least opened an area up to various effective tools (including XSLT) which could not have been readily used in that area before; that in itself suggests that the project was worth undertaking, if only for the benefits subsequent projects can derive from it. Paul From peter at engcorp.com Tue Nov 30 16:02:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Nov 2004 16:02:19 -0500 Subject: RELEASED Python 2.4 (final) In-Reply-To: References: Message-ID: Morten Lied Johansen wrote: > On Tue, 30 Nov 2004 23:31:34 +1100, Anthony Baxter wrote: > >>On behalf of the Python development team and the Python community, I'm >>happy to announce the release of Python 2.4. > > > Question from a noob: > > I have several third party python-modules installed on my current > Windowssystem, and I was wondering if there is a way to upgrade to > Python 2.4 without having to download and install all of those again? > > Thanks in advance for any suggestions. :) If they're pure Python, done as standard packages with no special dependencies etc, you could just copy their folders from the lib/site-packages folder of your old Python to the equivalent place in the new one. If they're not, it may still be possible, but downloading and installing may be easier. My approach is to maintain a folder with the original .exe files for each package I install, separate from everything else. When I upgrade, I just run them again and select Python 2.4 as the destination, and I don't have to worry about extracting them from the old version. If, by the way, these packages include C extensions, you definitely have to download new ones and install from scratch... -Peter From helten0007 at yahoo.com Tue Nov 23 15:34:51 2004 From: helten0007 at yahoo.com (Pete.....) Date: Tue, 23 Nov 2004 21:34:51 +0100 Subject: Transfer data from webpage form to database References: <41a36ab7$0$23056$ba624c82@nntp05.dk.telia.net> <41a38f13$0$23068$ba624c82@nntp05.dk.telia.net> Message-ID: <41a39c29$0$29447$ba624c82@nntp06.dk.telia.net> Hi again and thanks. I think I understand the meaning of string formatting operators, I also understand the meaning with % (form['name'].value, form['surname'].value, form['username'].value)) And that it is a dictionary that I use. The thing I find really hard to understand is how I can send the data from the webform to my postgresql database. I cant find the right commands, i been searching the web for days now without luck. PgSQL.query(''' INSERT into form Select persons.idpersons, person.username, persons.surname, phone.phone (And so on ) ( its what the specific tables is called in my db) >From persons, phone( And so on ) Where persons.name = 'Name'%s AND persons.surname ='Surname'%s AND persons.username = 'Username'%s ''' (And so on with the rest) I dont really know if I have to write Pgsql.query("INSERT into form ........................ or if I have to write something else. I know that I have to take the input from my webform, and store each input ( with each input I mean what the user types in each field, could be the name, the username etc) in a "variable" so that I can put it into the right place in the db. I can see that I do this by using % (form['name'].value, form['surname'].value, form['username'].value)) But I dont know how I put the data form['name].value in to my database in the table persons.name. Sorry for all this questions, just getting really confused with this little project of mine, thinks its fun, but I just cant figure it out anymore, and I cant find any info I can use on the web.... Thanks for taking your time to read this.... "Jerry Sievers" wrote in message news:m3u0rg49kx.fsf at prod01.jerrysievers.com... > "Pete....." writes: > >> Hi, yeah It's try I want to change it to a python.cgi.script. And thanks >> for >> your input..... >> >> I use the api pgsql >> So the first thing I do is to import the following and connect to the >> server: >> >> #!/pack/python-2.3.2/bin/python2.3 >> from pyPgSQL import PgSQL >> import cgi >> import cgitb >> cgitb.enable() >> >> form = cgi.FieldStorage() ( I added this ) >> connect = PgSQL.connect(user="vvvvv", password="zzzzz", >> host="xxx.xxx.xx", >> database="yyyyy") >> >> Do I then have to write: >> >> PgSQL.query(''' INSERT into form >> Select persons.idpersons, person.username, >> persons.surname, phone.phone (And so on ) ( its what the specific tables >> are called in my database) >> From persons, phone >> ( >> And so on ) >> Where persons.name = 'Name'%s >> AND persons.surname ='Surname'%s >> AND persons.username = 'Username'%s ''' >> (And so on with the rest) >> % (form['name'].value, form['surname'].value, >> form['username'].value)) >> >> I dont think I get it quite right, any help would be highly appreciated. >> Thanks for all help... > > It looks to me like the part here that you don't understand is how to > interpolate your form data into the string for the database query. > > You should study up on the % string formatting operator in the Python > docs. > > I'll throw you a bone here; > > """ > %s %s %s > """ % (form[key1].value, form[key2].value, form[keyN].value) > > Each of those %s tokens is going to be replaced with one of the values > in the tuple right of the % operator. > > If you want to pile the form values into a dict and then use symbolic > names in the string... > > dict = {} > for key in form: > dict[key] = form[key].value > > """ > %(key1)s %(key2)s... > """ % dict > > Maybe there is a function in the cgi module that will make the dict > for you? I am not sure. > > Have fun! > > > -- > ------------------------------------------------------------------------------- > Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant > 305 321-1144 (mobile http://www.JerrySievers.com/ From peter at engcorp.com Thu Nov 25 16:44:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 25 Nov 2004 16:44:03 -0500 Subject: copytree if directory exists In-Reply-To: References: Message-ID: Thomas Guettler wrote: > I need to copy a directory into an existing directory. > shutil.copytree does complain that the directory already > exists. > > I need something like "cp -rp": Copy recursively, overwrite > if file already exist. Preserve mtime and modes if possible. > > A keyword argument "may_exist=1" for shutil.copytree would be nice. Thomas, shutil.copytree is written in pure Python. Grab the source and stick in the appropriate exception handling around the call to os.mkdir() and you should have about what you need... -Peter From steve at holdenweb.com Tue Nov 23 09:20:29 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Nov 2004 09:20:29 -0500 Subject: is int(round(val)) safe? In-Reply-To: References: Message-ID: Tim Peters wrote: > [Peter Hansen] > .... > >>I wonder if it would be appropriate to say something along >>the lines of '''round() returns an integer, but not an "int".''' > > > Well, round() is a 2-argument function, whose second argument defaults > to 0. It's quite defensible to say that round returns an integer > value when the second argument is 0. > > >>Obviously the mathematicians will have something to say about >>this. In computers, 1.0 may not be an integer data type, but >>I think in math it's still considered an integer. > > > Depends on which mathematician you're talking to. The integer 1 is > most often defined as the set containing the empty set, or, in a > suitably restricted set theory, with the set of all sets containing 1 > element (which is a proper class in most set theories). A real, OTOH, > is a godawful construction that Americans typically don't learn until > after they've completed "calculus" and gone on to "analysis". > And most of them don't understand even then. What I want to know is why doesn't Python 2.4 have a speedy implementation of infinite-dimensional Banach spaces? > So, instead of talking to mathematicians, I advise talking to me > . Yes, 1.0 is an integer! In fact, so is 1.9998e143: all > sufficient large floats are exact integers. That's why, e.g., > math.ceil() and math.floor() return arguments like 1.9998e143 > unchanged -- such inputs are already integers. > > >>I am most definitely not going to claim authority in this area, however, >>since as an engineer I consider 1.0 and 1 merely "equal to a >>first approximation". > > > If they differ at all, then e = 1.0 - 1 must be nonzero. Since it > isn't, they're identical . You can tell this by examining the behavior of something as simple (;-) as a Python dict: >>> d = {1.0: "Something", ... 1: "Something else"} >>> d {1.0: 'Something else'} >>> Python has known for a long time that 1.0 and 1 are the same thing. Note, however, that I don't believe it's guaranteed that the contents of d will turn out the same in different Python versions. I suppose Tim would be able to quote chapter and verse, given his familiarity with every little implementation detail of the dict. guaranteed-to-confuse-the-confusable-ly y'rs - steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From zach at cs.uni-bonn.de Wed Nov 3 12:38:52 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 3 Nov 2004 17:38:52 GMT Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: Just a little question: would sort of a summary of this thread be of any help? Regards, gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From dsa at unilestemg.br Wed Nov 10 10:48:31 2004 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 10 Nov 2004 15:48:31 +0000 Subject: About a python module (iptables) In-Reply-To: References: <200411100957.29615.dsa@unilestemg.br> Message-ID: <200411101548.31571.dsa@unilestemg.br> Hi ! Thank you for the amazing aswer. I will check you program now. Really thanks. See you ! Em Qua 10 Nov 2004 16:00, voc? escreveu: > >>>>> "Douglas" == Douglas Soares de Andrade writes: > > Douglas> Hi ! Is there a module to do the interaction between > Douglas> python and iptables ? I want to make a app to interect > Douglas> with iptables (new chain, erase chain, list chain, > Douglas> generate rules and so on). > > I've written one that I've used privately for years on standalone > machines as well as routers using NAT/etc. It doesn't support all of > iptables, but it does the common stuff. In debug mode, it only prints > out the rules to the logfile, but doesn't execute them. > > Whether it is sophisticated enough for your app, I don't know. It was > designed simply to setup the iptables config and then run, so there is > no support for erasing chains, etc.... > > I've uploaded a tarfile to > http://jdh.uchicago.edu/share/py_iptables.tar.gz which contains the > module code and some example scripts. > > Here is a simple script to configure the firewall for a typical > standalone machine. > > #!/usr/bin/env python > from IptablesRules import IptablesRules > > # debug=False executes the commands - you must be superuser > ipt = IptablesRules(debug=True, verbose='moderate') > > nameservers = ipt.get_nameservers() > > # udpAccept and tcpAccept are dictionaries from ports to > # machines which have access to those ports > udpAccept = {"domain" : nameservers,} > > # we've parsed /etc/services so you can specify ports by name or > # number. > tcpAccept = { > ('smtp', 'ntp', 'ssh', 'ftp', 'http', 'https') : 'all', > ('postgres', ) : "128.135.0.0/16", # limit to U of C > ('all', ) : "128.135.90.217/32", # my printer > } > > ipt.broadcast_policy(eth_iface="eth0", chain='DROP') > ipt.drop_nolog_ports(ports = ('auth', 'netbios-ns', 'microsoft-ds'), > eth_iface="eth0") ipt.implement_rules( udp_accept = udpAccept, > icmp_accept = ( 0, 3, 5, 8, 11 ), > tcp_accept = tcpAccept, > eth_iface = "eth0" > ) > ipt.execute( logfile = '/var/tmp/iptables_rules' ) From R.Brodie at rl.ac.uk Tue Nov 30 09:19:25 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 30 Nov 2004 14:19:25 -0000 Subject: weird behaviour of "0 in [] is False" References: Message-ID: "Laszlo Zsolt Nagy" wrote in message news:mailman.6923.1101824130.5135.python-list at python.org... > Did you really try these examples? >>> l is 1 False From rroberts at adobe.com Wed Nov 17 00:36:38 2004 From: rroberts at adobe.com (Read Roberts) Date: Tue, 16 Nov 2004 21:36:38 -0800 Subject: Problem with Tkinter and some Kanji unicode values. Message-ID: Has any one else seen the following? Mac OSX 10.3.6, standard Python from 10.3.4 installation + tkAqua Tkinter.tkinter.TK_VERSION is '8.4' I set a unicode string into a tKinter widget. Some kanji display correctly, some do not. The ones that don't show up as a white square followed by a black square. The font used by the widgets does contain glyphs for all the Unicode values in the test string. I can copy and text from the Entry widget, and paste it elsewhere, and see that i still get the correct Unicode values, so the problem is one of display rather than encoding conversion. from Tkinter import * from tkFont import Font as TKFont root = Tk() root.font = TKFont(root, font = (u'\u30d2\u30e9\u30ae\u30ce\u89d2\u30b4 Pro W3', 12)) print root.font.actual() myFrame = Frame(root) root.resizable(1, 1) root.rowconfigure(0,weight=1) root.columnconfigure(0,weight=1) myFrame.grid() myFrame.rowconfigure(0,weight=1) myFrame.columnconfigure(0,weight=1) myEntry = Entry(myFrame, borderwidth = 10, font=root.font) testString = u"\u8146, \u500e, \u440c" myEntry.insert(0, testString) myEntry.grid() print repr(myEntry.get()) myFrame.mainloop() The font is used in this example is Hiragino Kaku Gothic-W3. FontBook shows that it has glyphs for all three Unicode values in the test string. u8146 shows up correctly, the others do not. Works fine on Windows. From richardblackwood at cloudthunder.com Sat Nov 6 18:26:22 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sat, 06 Nov 2004 18:26:22 -0500 Subject: Python OS In-Reply-To: <20041106160313.14104.810245925.divmod.quotient.643@ohm> References: <20041106160313.14104.810245925.divmod.quotient.643@ohm> Message-ID: <418D5D9E.6020609@cloudthunder.com> exarkun at divmod.com wrote: > > > > For an actively developed Python OS project, see unununium. > > > > This is the project I was referring to when I said, _has_ been done. From claird at lairds.us Fri Nov 5 13:08:04 2004 From: claird at lairds.us (Cameron Laird) Date: Fri, 05 Nov 2004 18:08:04 GMT Subject: How do you execute an OS X application (bundle) from Python? References: <70bb9f8d.0411040250.1f4ac1a@posting.google.com> <69cbbef2.0411041513.120fc039@posting.google.com> Message-ID: In article <69cbbef2.0411041513.120fc039 at posting.google.com>, has wrote: >dfh at forestfield.co.uk (David Hughes) wrote in message >news:<70bb9f8d.0411040250.1f4ac1a at posting.google.com>... >> For example, in Python in a Nutshell, Alex Martelli shows how you can >> run a Windows (notepad.exe) or Unix-like (/bin/vim) text editor using >> os.spawnv(os.P_WAIT, editor, [textfile]) >> But how would you call the OS X text editor /Applications/TextEdit.app >> - which appears to be a whole directory inside /Applications? > >Using os.system to execute open is pretty simple, as other folks have >pointed out. The other way is to use Apple events, the standard >high-level IPC system used by Mac GUI apps. The AE support currently >in the standard library leaves something to be desired and is due for >replacement. Much improved, though unfinished, AE support is available >from my site: > >http://freespace.virgin.net/hamish.sanderson/appscript.html > >Fastest way to open a document is via the lower-level aem package >(lower overheads, though you have to use raw AE codes): > >from aem.send import Application >from Carbon.File import FSSpec >Application('/Applications/TextEdit.app').event('aevt', 'odoc', >{'----':FSSpec(pathToFile)}).send() > > >Alternatively, the high-level appscript package wraps all this stuff >in OO-like syntactic sugar and human-readable terminology (takes >longer to initialise as it has to retrieve and parse the application >terminology): > >from appscript import * >app('TextEdit.app').open(FSSpec(pathToFile)) . . . This thread's focus on editing casuistry and Mr. Sanderson's own modesty might lead many to overlook what interesting riches he's offering here. While his work is "unfinished", I think it'll intrigue anyone who works with MacOS. Try it. From paul.drummond at dsl.pipex.com Tue Nov 23 12:08:29 2004 From: paul.drummond at dsl.pipex.com (Paul Drummond) Date: 23 Nov 2004 09:08:29 -0800 Subject: pyQt data aware objects for Windows Message-ID: <1101229709.560806.122070@z14g2000cwz.googlegroups.com> Hi Guys, Sorry if this is the wrong place to post - is there a pyQt newsgroup? I know there is a mailing list but I hate them! I am using pyQt and BlackAdder which comes with Qt 3.3.3 - it costs about ?30 but its worth it for Qt. However, it doesn't come with any Qt Database Drivers. So the question is, is there any way to use QDataTable (and other QT Database widgets) using my setup? Or do I have to resort to using python database modules which don't have any data aware widget support. All I want to do is easily display resultsets in a QTable! From jcarlson at uci.edu Thu Nov 18 11:59:36 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 18 Nov 2004 08:59:36 -0800 Subject: Rationals? In-Reply-To: <419c3185.348584998@news.oz.net> References: <419c3185.348584998@news.oz.net> Message-ID: <20041118084736.F9C1.JCARLSON@uci.edu> bokr at oz.net (Bengt Richter) wrote: > > On Wed, 17 Nov 2004 19:47:27 -0800, Josiah Carlson wrote: > > > > >Mike Meyer wrote: > >> > >> With the decimals and the unification of int and long coming, it's natural > >> (for me, anyway) to wonder how much interest there is in a rational type. > >> There are two PEPs (239 and 240), and the Guido rejects them as no one > >> seems interested in doing the work, but points out that the python > >> distribution comes with examples/Demo/classes/Rat.py. > >> > >> I propose - in the spirit of "batteries included" - that Rat.py be > >> cleaned up some (mostly to take advantage of the union of ints and > >> longs) and moved into the standard library. > >> > >> Any good reasons not to do this? > > > >Update the PEP, do the work, and offer a good rational number object (if > >you are interested in doing such). I have personally written at least > >two different rational classes, and I am aware of at least 3 others > >(though I can't remember their names). > > > >If it is implemented in Python; stay away from the binary GCD algorithm, > >Euclid's is faster. > > > I just looked at Rat.py in the demos, and I am wondering why floating point > is at all included. IMO rationals should be exact, and unless you define > what exact value you would like to have a floating point value represent (e.g., > all available bits, or some rounding specification) you don't have a way > to make an exact rational. With longs there is no legal floating point double > number whose value can't be represented exactly as a rational, so there's no > problem except deciding. Likewise any floating point string literal can be > converted exactly, e.g., '123.4e-5' => Rat(1234, 1000000) etc., which I think > can be handy. BTW, IIRC complex is implemented strictly with floating point pairs, > so that doesn't seem satisfactory, unless a new complex class is implemented using > rational pairs. Otherwise I'd say leave complex out. > > Obviously fractional powers can produce non-rational results, so that poses > a design problem if you want to handle them at all. > > Anyway, am I the only one who thinks that rational should be exact? I'm a big fan of being exact whenever possible (hence the symbolic maximum and minimum values PEP...which strangely enough, a friend that I introduced to Python commented out of the blue that a symbolic infinity /should/ be in Python, but I digress). Every rational class I've written used longs, and I am of the opinion that any reasonable rational class /would/ use longs. The moment one cannot help but return a float, return a float (like sqrt(1/2)). It does look like gmpy does the right thing in most cases, though I am uncertain as to its suitability for Python stdlib inclusion. - Josiah From steven.bethard at gmail.com Thu Nov 18 14:56:55 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 18 Nov 2004 19:56:55 GMT Subject: Building a word list from multiple files In-Reply-To: <3oqdnVtPVOyFMgHcRVn-rA@comcast.com> References: <3oqdnVtPVOyFMgHcRVn-rA@comcast.com> Message-ID: Larry Bates wrote: > 2) Are the words in the file separated with some consistent > character (e.g. space, tab, csv, etc). > > If not, you will probably need to use regular expressions > to handle all different punctuations that might separate > the words. Things like quotes, commas, periods, colons, > semi-colons, etc. Simple string split won't handle these > properly. If you go this way, you probably ought to read this thread: http://mail.python.org/pipermail/python-list/2004-November/250520.html which suggests finding words with a regexp something like r'[^\W\d_]+'. (If you're not concerned about internationalization, it could be simpler.) STeve From square690410 at yahoo.com.tw Wed Nov 3 22:12:35 2004 From: square690410 at yahoo.com.tw (Leon) Date: Thu, 4 Nov 2004 11:12:35 +0800 Subject: how to handle command line output(not terminal handle) Message-ID: such as : c:\>python test.py ##Interval 1 seconds the "name" change next friend : name don't have to run clear,the "name" dynamic change content and "friend" is stable From greg at invalid.invalid Thu Nov 18 08:48:10 2004 From: greg at invalid.invalid (Greg Krohn) Date: Thu, 18 Nov 2004 13:48:10 GMT Subject: TPG error when using 't' as the first letter of a token In-Reply-To: References: Message-ID: Andrew James wrote: > Gentlemen, > > I'm running into a problem whilst testing the parsing of a language I've > created with TPG . It seems that for some reason, TPG balks when I try > to parse an expression whose first letter is 't' (or, in fact, at any > time when 't' is at the beginning of a token). This doesn't happen with > any other letter (as far as I know), nor if the 'T' is capitalised. I have no idea what TPG is, but if it's only having trouble with a lower case t, could it be that the t is somehow getting escaped and TPG thinks it's a tab character? Just a thought. greg From greg at cosc.canterbury.ac.nz Mon Nov 15 21:46:01 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 16 Nov 2004 15:46:01 +1300 Subject: Identifying bundles in MacOS X In-Reply-To: References: Message-ID: <2vt7veF2nues7U1@uni-berlin.de> Michael J. Fromberger wrote: > Given the pathname of a directory in my filesystem, I would like a > graceful way to determine whether or not that directory represents a > "bundle", in the sense that, when you double-click on the directory's > icon in the Finder, it is launched rather than "opened" for viewing. > Applications behave this way by default, but so do various other file > types (e.g., the "rtfd" files created by TextEdit, and the data files > for certain applications such as Quicken). I think that a MacOSX-style application can be recognised simply by the fact that it's a directory whose name ends in ".app". (You don't usually see that extension in the Finder, but all MacOSX application bundles seem to have it.) A Classic-style application is a file with a type code of "APPL". As for other files, they can be associated with applications using either the old type/creator code system, or the new filename-extension-based system (which is disappointingly Windows-like, but sadly seems to be the dictated Way of the Future :-(.) The type and creator of a file can be found using FSpGetInfo. You're right that this doesn't work for directories, but directories don't have type/creator codes anyway. MacOSX bundles seem to be recognised purely by filename suffix (and possibly also by having the right internal structure). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jbperez808 at wahoo.com Thu Nov 11 00:36:18 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 11 Nov 2004 13:36:18 +0800 Subject: why python is slower than java? In-Reply-To: <418b166f$1@news.unimelb.edu.au> References: <418b166f$1@news.unimelb.edu.au> Message-ID: <2vgbgjF2lj7hsU1@uni-berlin.de> First of all, I really really really love Python but unlike the other people posting on this thread I am not allergic to criticisms of python and I feel the attitude of some on this list is way too defensive and actually works against the outside perception of the language. (OTOH, what I saw on this thread is still considered mild, you should see those LISPers defend their language! :-D ) Anyway, on to the topic at hand. I actually don't believe python is slower than java. But truth to tell, the answer can never be a simple 'one is faster than the other'. In the cases where Python is slower than Java, it is because Java is JIT-compiled whereas Python by default is bytecode-interpreted (unless you use Psyco). In the cases where Python is faster than Java, it is because much of Python's core and library functionality is actually coded very efficiently in C, and said code path is using much of this functionality. When it comes to the language proper, Java is just way more primitive than Python, and considering that the speed of both will be *** of roughly the same order ***, I'll take Python any day. The fact that you can much more easily use and write Python C extensions (still not exactly a picnic though) than JNI ones is yet another speed-related thing in favor of Python over Java. Maurice LING wrote: > This may be a dumb thing to ask, but besides the penalty for dynamic > typing, is there any other real reasons that Python is slower than Java? > > maurice From lbates at syscononline.com Wed Nov 3 11:40:46 2004 From: lbates at syscononline.com (Larry Bates) Date: Wed, 03 Nov 2004 10:40:46 -0600 Subject: Send HTML e-mail in Python? In-Reply-To: References: Message-ID: Google is your friend: python send htlm email turns up a recipe at ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083 Larry Bates Max wrote: > I am looking for some simple example code on generating SMTP e-mail > messages in Python. I have a script that sends system reports to me at > a central e-mail address, and it works fine using smtplib with plain > text messages. I would like to enhance this script to send HTML > formatted messages instead. > > Simply sending a text message with HTML tags does not work. The e-mail > client displays the message as plain text with visible . From peter at engcorp.com Thu Nov 4 10:05:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Nov 2004 10:05:03 -0500 Subject: recover data from html form In-Reply-To: References: Message-ID: Armand Federico - INFO wrote: > How can i recover data from an html module? > I have a form that send 3 or 4 text field > > I wanna to recover this data, to analyse, and process, and insert in MySQL > > (mod_python, Mysql4, Apache1.3) The question is unclear. Are you looking for suggestions on the process called "web scraping"? (search the web before responding, if that term is unfamiliar to you, please) -Peter From tim.tadh at gmail.com Sun Nov 21 23:05:20 2004 From: tim.tadh at gmail.com (Tim Henderson) Date: 21 Nov 2004 20:05:20 -0800 Subject: Class Encapsulation Errors in Python 2.3.3 References: <47f7cc78.0411182007.1b77c2b1@posting.google.com> <47f7cc78.0411191409.3b3607fc@posting.google.com> Message-ID: <47f7cc78.0411212005.46c3894@posting.google.com> actually i bunch of the code that was posted above has been changed including this. code: -------------------------------------------------------------- class Artist: def __init__(self, name): self.songs = [] self.albums = [] self.unknownAlbum = Album('unknown') self.albums.append(self.unknownAlbum) self.name = name self.unknownAlbum.setArtist(self.name) -------------------------------------------------------------- cheers tim From NutJob at gmx.net Thu Nov 18 12:37:24 2004 From: NutJob at gmx.net (Markus Kemp) Date: 18 Nov 2004 09:37:24 -0800 Subject: Need function to test if EFFECTIVE UID has read-access to a file. References: <9b96ed1.0411170915.2b88da0e@posting.google.com> Message-ID: <9b96ed1.0411180937.2383c517@posting.google.com> Me again, haha Okay, I've solved my problem. Rearranged my program logic and eliminated the check that was to verify if the dir are accessable or not, because if yes I would have called os.listdir() a few lines down in the code anyway. So I sort of did what Skip suggested and just listdir'd catching any OSError exceptions that get thrown if the dir is not accessible for some reason. =) Regards, Markus From mfuhr at fuhr.org Mon Nov 8 02:41:30 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 8 Nov 2004 00:41:30 -0700 Subject: checking a thread has started References: <418d3323$1_2@omega.dimensional.com> <418da3e0$1_4@omega.dimensional.com> <418f0f8e$1_4@omega.dimensional.com> Message-ID: <418f232a$1_2@omega.dimensional.com> Deepak Sarda writes: > max user processes (-u) 7168 That refutes the hypothesis that you've hit a process limit; it must be something else. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From rff_rff at remove-yahoo.it Sun Nov 28 14:17:52 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Sun, 28 Nov 2004 19:17:52 GMT Subject: The use of : In-Reply-To: <30ukhmF357ptdU1@uni-berlin.de> References: <89cc6e1f.0411251858.40b6bbc7@posting.google.com> <89cc6e1f.0411260953.4b6b98e7@posting.google.com> <41aa1abb$0$25542$636a15ce@news.free.fr> <30ukhmF357ptdU1@uni-berlin.de> Message-ID: Reinhold Birkenfeld ha scritto: > Without the ':', single-line suites are impossible. If you allow only > multi-line suites, you're right. > are they really? if and the likes would invho parse just fine From carribeiro at gmail.com Mon Nov 1 09:39:24 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 1 Nov 2004 12:39:24 -0200 Subject: cherrypy/cheetah vs twisted/nevow In-Reply-To: References: Message-ID: <864d37090411010639114872b3@mail.gmail.com> On 01 Nov 2004 09:36:59 GMT, Charlotte wrote: > I am developing a web application and am looking for the best framework > to do this in. I know this is an old question, and I have read the list > archives and a couple of comparison pages on the web. I played around > with some, and I have reduced my choices to two very different > frameworks: cherrypy+cheetah and twisted+nevow. > > I am writing the prototype in cherrypy with cheetah, and I like it > very much. I am very impressed with the speed of development, and > cherrypy seems to fit the way I think. Before this I used webware, but > cherrypy is simpler and easier and does the things I want very well. > Cherrypy is being completely redesigned at the moment. The 'old' > version is no longer developed, the new version just had the first > alpha release. While the new version looks promising, I am uncertain > that it will be ready for production use very shortly. I can of course > just use the old version, which is stable. Hi! That was the same reason that got me hooked on CherryPy: it's simplicity, and the fact that it seemed so 'obvious' to use. As for the redesign, I'm already using the CP2 alpha project for a few projects of mine. None of them is 'life critical', and I'm not using all features, but it seems very stable to me right now. The main difference is that CP2 is now 'pure python', with no intermediate compilation step, which makes it even more natural to use than before. > Because of my doubt, I went looking for alternatives, and stumbled > upon nevow. I now absolutely think this is the way a web application > should be developed. I like the way ui and code is seperated, I love > formless, and livepage looks very promising. However, it is still > beta, and reportedly rather difficult to use. I'm yet to study nevow, but I'm getting more and more interested. I have my own approach to separation; I use to think about a third entity, "structure", as being independent from code & ui. The structure is the common part; it's the "glue" between ui and code; and it's the first part to be designed. I'm still experimenting with this concept. For what I have read so far, nevow seems to follow a similar approach, although I haven't seen any reference to "structure" as a third element in the design anywhere. > The application should have a first version finished in about six > months. Security is very important. The users of the application are > fully trusted, so the most important in this regard is authentication > (and encryption, of course), I think. I could, if needed, just code this > myself. It is a relatively small application, at most a few thousand > users, who will not be using the application, much less sending > requests, at the same time. At the moment I do not expect to use much > of twisted's great possibilities. For what I know, twisted is a huge beast, and forces you to a totally different programming paradigm. There is a wsgi gateway for twisted in the works, and that may make things simpler for pure web development, as it will hide some of the inherent complexity of twisted async design. For my own needs, I still prefer to stay with CherryPy. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From nhodgson at bigpond.net.au Mon Nov 8 06:15:58 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 08 Nov 2004 11:15:58 GMT Subject: Color schemes References: <41838c6e$0$7153$d5255a0c@news.wanadoo.nl> <18282ecb.0410301418.1ee469f5@posting.google.com> <418c2006$0$34293$cd19a363@news.wanadoo.nl> <18282ecb.0411061242.7deceef3@posting.google.com> <18282ecb.0411070931.34508476@posting.google.com> Message-ID: M.E.Farmer: > Isn't PythonWin now based on Scintilla too? Circular refrences ;) Yes, but PythonWin first used RichEdit for syntax colouring which was hard to make work well and so was turned off by default. Neil From bokr at oz.net Wed Nov 10 03:40:26 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 10 Nov 2004 08:40:26 GMT Subject: Getting Windows computer system info References: <93c5215b.0411090947.a955001@posting.google.com> Message-ID: <4191cf1d.77117799@news.oz.net> On 9 Nov 2004 09:47:31 -0800, gao_bolin at voila.fr (Bolin) wrote: >I was wondering how to get some system info from a PC running Windows >in python. I am especially interested in knowing how much RAM the >computer has, how much diskspace is still left, and what jobs are >already running and how much memory they take. If this is off-topic, I >would appreciate if you redirect me. > >Thank! I use this to get a quick summary of disk free space from the console command line: ----< df.py >---------------------- import os def df(drives='C', showna=1): for drive in drives: drive = drive.upper() d = os.popen('dir/w '+drive+':\\').readlines() if not d: if showna: print '%s: (n/a)' % drive continue print '%s: (%-12s %12s bytes free ' %( drive, d[0].strip().split(' is ', 1)[-1]+')', d[-1].strip().split(' bytes ')[0] ) if __name__ == '__main__': import sys if len(sys.argv)<2: df() else: df(sys.argv[1]) ---------------------------------- actually, i start it with df.cmd, which has: @python c:\util\df.py CDEVW since those are my useful drive letters. As for dynamic stuff, if it's just for you, see if you have pstat.exe on your path (likely if you have MS dev tools). If so, try it from the command line to see what it gives you. Then you can write a quick python function to run it via popen and extract what you want from the read result, e.g., >>> import os >>> for line in os.popen('pstat.exe'): ... if 'mem' in line.lower(): print line.rstrip() ... Pstat version 0.3: memory: 327080 kb uptime: 0 21:40:12.957 Memory: 327080K Avail: 274140K TotalWs: 40132K InRam Kernel: 3264K P:12572K c 18 22 8011f9ba 0:00:00.000 0:00:00.160 Wait:VirtualMemory 2a 17 1 801223a4 0:00:00.000 0:00:00.000 Wait:VirtualMemory Or eliminate the first-guess garbage >>> import os >>> for line in os.popen('pstat.exe'): ... if 'emory:' in line: print line.strip() ... Pstat version 0.3: memory: 327080 kb uptime: 0 21:43:48.997 Memory: 327080K Avail: 274668K TotalWs: 39520K InRam Kernel: 3260K P:12484K HTH Regards, Bengt Richter From eurleif at ecritters.biz Mon Nov 8 18:22:05 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 Nov 2004 18:22:05 -0500 Subject: Mixing Python And Bash In-Reply-To: References: Message-ID: <2vadd9F2infd2U1@uni-berlin.de> Tom Purl wrote: > I just wrote a Python script that is going to be called from bash script. > If the Python script fails, I want the bash script to also stop running. > Unfortunately, I can't seem to get that to work. Here's the script so > far: > > # custom python script > /usr/bin/python /home/username/Dev/Python/packZODB.py \ > -s"gsgmc.sigma.zettai.net" -b 7 > > # next program > /usr/bin/someOtherProgram Have your Python script return a non-zero return code (e.g. sys.exit(1)) when it fails and then have your shell script check for that: # custom python script /usr/bin/python /home/username/Dev/Python/packZODB.py \ -s"gsgmc.sigma.zettai.net" -b 7 if [ $? -ne 0 ]; then exit 1 fi # next program /usr/bin/someOtherProgram From chris.cavalaria at free.fr Tue Nov 2 16:52:08 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Tue, 02 Nov 2004 22:52:08 +0100 Subject: strong/weak typing and pointers References: <4187aafe$1@nntp0.pdx.net> Message-ID: <41880188$0$14993$626a14ce@news.free.fr> Gabriel Zachmann wrote: >> wall of abstraction". A Smalltalk programmer would say that >> Python is more weakly typed than Smalltalk for user-defined types. > > which brings me to another related question. > > I understand strong/weak typing is more like a continuum -- > is there kind of a programming langauges hierarchy sorting various > langauges accoring to "type-strongness" that is generally agreed upon? > > I'd be interested in a hierarchy containing some of the following > languages: ANSI-C++, C, Perl, Python, Pascal, ML. > (because these happen to be some of the languages i know a bit ;-) ) > > Would the following be justifiable? > > Perl < C < C++ < Pascal < Python < ML ? > > Or does anyone have a pointer? If by ML you thing of OCaml you should try again. OCaml isn't type safe because of a few modules of the standard library. The marshaling module comes to mind. Using it you can "typecast" a pointer to an integer as a pointer to a string and segfault in the process because the unmarshal function trusts the caller to cast the result in the good type. In fact, it seems impossible to write a correct typesafe marshaling module in OCaml since there is no rtti info in the language for an anonymous piece of data. From deetsNOSPAM at web.de Wed Nov 3 12:17:26 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 03 Nov 2004 18:17:26 +0100 Subject: Problems using numarray References: Message-ID: > Now, how can I use a numaray to store the body objects? I read the docu, > but didn't figure out how to solve my problem. In C++ I just created a > multidimensilnal array like data = new body[objects*timeframes] and I'm > looking for something synonymous with numarray. import Numeric print Numeric.zeros((10, 20), Numeric.Float) -- Regards, Diez B. Roggisch From steve at ferg.org Tue Nov 9 15:04:29 2004 From: steve at ferg.org (Stephen Ferg) Date: 9 Nov 2004 12:04:29 -0800 Subject: Tkinter for system administration? References: Message-ID: the ability to > crank out simple GUIs quickly and without a lot of hassles or trips to > the reference manual is more important. Look at Easygui http://www.ferg.org/easygui/index.html From peter at monicol.co.uk Fri Nov 19 06:10:25 2004 From: peter at monicol.co.uk (Peter Mott) Date: Fri, 19 Nov 2004 11:10:25 -0000 Subject: CGI and logging module References: <419d0a70$0$221$bed64819@news.gradwell.net> Message-ID: <419dd4a5$0$218$bed64819@news.gradwell.net> This was a Columbus Egg. The version of Python Apache used had reverted to 2.2.2 after a recent system failure. The version used for console logins was 2.3.4. I'll contact my ISP :-). Thanks for all the help. Peter "Peter Mott" wrote in message news:419d0a70$0$221$bed64819 at news.gradwell.net... >I am using: > > Python 2.3.4 (#2, Nov 14 2004, 18:06:48) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > > with Apache/1.3.26. The following script causes an Internal Server Error > (with nothing in the Apache error logs AFAIK): > > #!/usr/local/bin/python > > import logging > > print "Content-type: text/html\n\n" > print "

OK

""" > print "" > > The same script with the import statement commented out works as expected. > Has anyone encountered this? I have googled without success. > > Thanks > > Peter > From eddie at kickingdragon.com Sat Nov 13 19:06:35 2004 From: eddie at kickingdragon.com (Eddie Parker) Date: Sat, 13 Nov 2004 17:06:35 -0700 Subject: Advice needed In-Reply-To: Message-ID: I think you hit a good point, Matt. Python is a WICKED language for prototyping. I'm not saying that's ALL it's good for, however it's a great way to start out. Tuples, Dictionary's, easy to manipulate String functions, and code that just makes sense (the tab-as-a-way-to-define-scope bit used to annoy me, but in all honest, it's a "Good Thing" (TM)). As for what Python can offer that the other languages can't, that's a case-by-case comparison, and also has a dash of personal preference for flavour. Personally: I agree with Matt. But to add to it: vs. Perl and VB, I like Python as it has a nicer syntax, cleaner looking code, and more "space" in the code - i.e., you don't need to write so much to get a lot of functionality out of it. I find myself using Python as a way to figure out something, when I don't know what the problem scope is. Sometimes, my work STAYS in Python, when I'm done, but if it's performance critical, you can always use the concept to write it in C/C++, or you can even use something like Python's ability to embed in C/C++ to farm out the performance bottlenecks, or Jython, if you're a Java person (never used Jython, just saying it's an option. :)). Anyhow - you can't go wrong with Python, in my opinion. But I'm rather heavily biased. I'm also always right, however. :) (Jus' kidding). :) -e- -----Original Message----- From: python-list-bounces+eddie=kickingdragon.com at python.org [mailto:python-list-bounces+eddie=kickingdragon.com at python.org] On Behalf Of Matt Garman Sent: Saturday, November 13, 2004 4:59 PM To: python-list at python.org Subject: Re: Advice needed On 13 Nov 2004 07:54:57 -0800, Alberto wrote: > I was trying to understand the reasons why I should learn Python. > More like a pros/cons about this language. Currently, I use C, > C/C++, Java, Perl, Visual VB and was looking to see the usefulness > of Python. Any suggestions? As others have suggested, the best thing you can really do is spend several hours with Google and some sample Python code and see how you like it. The reason I started getting into it is the following: I do most of my programming in C/C++. For me, the problem with those languages is that it takes relatively more code to do many tasks compared to Python. So if I'm working on something that I haven't thought all the way through, I find myself back-tracking from time to time. This can be *very* time-consuming in C/C++ (the trial-and-error method of programming). However, things can be developed so quickly in Python, that if you have to back-track, little time is lost. In a nutshell, I like and use Python for creating quick proof-of-concepts and as a development concepting tool. Although, most very high level languages (such as Perl and VB) are good for this too---so we're back to personal preference :) But also, for me, I enjoy learning new languages just for the sake of learning them. I think it's fun, and as another said, new languages usually teach you how to think about problems in a different way. I've benefitted from this language "cross pollination" many times---using another language's techniques and paradigms has helped me come up with elegant solutions on more than one occasion. At the end of the day, it's personal preference... but if you can spare the time, and enjoy learning and playing with new languages, why not learn Python? Matt -- Matt Garman email at: http://raw-sewage.net/index.php?file=email -- http://mail.python.org/mailman/listinfo/python-list --- Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 11/1/2004 --- Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 11/1/2004 From donn at drizzle.com Wed Nov 24 00:26:37 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 24 Nov 2004 05:26:37 -0000 Subject: protocols, inheritance and polymorphism References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> <786dnYZkrq-ieT7cRVn-tw@rogers.com> Message-ID: <1101273995.954137@yasure> Quoth "Dan Perl" : | "Donn Cave" wrote in message | news:donn-D778C1.17100223112004 at gnus01.u.washington.edu... | > I'm very sympathetic to the advantages of static typing | > (NB, I read here that Python is strongly, though dynamically, | > typed. It is not statically typed.) Rather than embrace | > subtype polymorphism through inheritance, however, I see it | > as evidence that no one has figured out how to make static | > typing really work with OOP. There has to be a better way | > to do it. | | You're right, I should have said statically typed instead of strongly typed. | | But did you really mean "no one has figured out how to make *static* typing | really work with OOP" or did you mean *dynamic* typing? Static. I figure dynamic & OOP get along fine -- as Smalltalk showed, along with I believe Objective C and of course Python. Static typing and Functional Programming seem to go hand in glove, cf. Haskell type classes. Static OOP seems to invite inelegant and unsound compromises. Donn Cave, donn at u.washington.edu From NOmanlio_perilloSPAM at libero.it Wed Nov 10 12:03:30 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 10 Nov 2004 17:03:30 GMT Subject: ConfigParser References: <8g84p0597pvl6ag102ejc1v4rvaockp0an@4ax.com> Message-ID: <9ei4p0pnmos0c8avto0b9i0if517i8uclj@4ax.com> On Wed, 10 Nov 2004 15:39:42 +0100, Ivo Woltring wrote: >On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo > wrote: > >>Regards. >> >>Since sections in CongiParser files are delimited by [ and ], why >>there is not an escape (and unescape) function for escaping >>&, [, and ] characters to &, [ and ] ? >> >> >> >> >>Thanks Manlio Perillo > >just subclass from ConfigParser and add the functionality youself > Actually I have written two functions: def escape(data): """Escape &, [ and ] a string of data. """ data = data.replace("&", "&") data = data.replace("[", "[") data = data.replace("]", "]") return data def unescape(data): """Unescape &, <, and > in a string of data. """ data = data.replace("[", "[") data = data.replace("]", "]") # must do ampersand last return data.replace("&", "&") Maybe also '\n' to &nl; translation should be performed. Thanks and regards Manlio Perillo From bj_666 at gmx.net Sat Nov 20 13:22:13 2004 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 20 Nov 2004 19:22:13 +0100 Subject: stopping the sound server in PySol code -- how? References: Message-ID: In , Lynn wrote: > I have a SuSe 9.1 linux box (although this isn't a new issue) with > reasonably up to date everything. When I run PySol, it grabs the sound > system in a rude and complete way. > > I don't listen to sound and I NEED my sound system available even if PySol > is running. Do you have KDE and its sound server running? Then you can try to start PySol with the ``artsdsp`` wrapper. The program intercepts access to the low level sound devices in /dev/* and passes the data to the sound server. See ``artsdsp --help`` for options. Ciao, Marc 'BlackJack' Rintsch From peter at monicol.co.uk Fri Nov 19 04:00:00 2004 From: peter at monicol.co.uk (Peter Mott) Date: Fri, 19 Nov 2004 09:00:00 -0000 Subject: CGI and logging module References: <419d0a70$0$221$bed64819@news.gradwell.net> Message-ID: <419db612$0$220$bed64819@news.gradwell.net> Thanks for these responses all useful. I had completed a fairly large script which threw these unrecorded errors at me. Took ages to locate the soiurce of the problem. I should have used the try: except: round the import statement (I was using the 'import cgitb;cgitb.enable()' mantra but _after_ the impoprt statement :-( ). As I said I am using Python on FreeBSD: Python 2.3.4 (#2, Nov 14 2004, 18:06:48) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> and I imported loggng successfully. When I modify my script to the following: =============== #!/usr/local/bin/python try: import logging except Exception, e: print "Content-type: text/html\n" print "

" + str(e) +"

""" else: print "Content-type: text/html\n" print "

OK

""" ============== It reports the error which is " No module named logging " . Something is wrong here. Does anyone have any ideas? Peter "Peter Mott" wrote in message news:419d0a70$0$221$bed64819 at news.gradwell.net... >I am using: > > Python 2.3.4 (#2, Nov 14 2004, 18:06:48) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > > with Apache/1.3.26. The following script causes an Internal Server Error > (with nothing in the Apache error logs AFAIK): > > #!/usr/local/bin/python > > import logging > > print "Content-type: text/html\n\n" > print "

OK

""" > print "" > > The same script with the import statement commented out works as expected. > Has anyone encountered this? I have googled without success. > > Thanks > > Peter > From kent3737 at yahoo.com Tue Nov 30 09:26:34 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 30 Nov 2004 09:26:34 -0500 Subject: slicing, mapping types, ellipsis etc. In-Reply-To: <41ac7b0f$0$25780$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41ac5701$0$25761$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41ac6c55$1_2@newspeer2.tds.net> <41ac7b0f$0$25780$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41ac81d0$1_2@newspeer2.tds.net> Nick Coghlan wrote: > Kent Johnson wrote: > >> Maybe instead of referring to mappings it should say "The primary must >> implement __getitem__(), which is called with a value that is >> constructed from the slice list, as follows." > > > In the section you mention, 'mapping' is equivalent to 'has __getitem__ > defined', and I'd be surprised if it's an isolated usage. Python > actually has trouble distinguishing between sequences and mappings, as > anyone who as tried to use the 'isMapping' API would know (the isMapping > API uses much the same definition as the reference manual does - so all > sequences show up as mappings, as they map indices and slices to objects). > > Section 3 of the reference manual is actually more use for anyone > developing custom types that override special methods. E.g. proper > handling of slice objects is described here under container emulation: > http://www.python.org/dev/doc/devel/ref/sequence-types.html I understand that the distinction between sequences and mappings is fuzzy, as both use __getitem__() for access. But the usage of 'mapping' in 5.3.3 is inconsistent with the section you refer to. That page says "It is also recommended that mappings provide the methods keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update() behaving similar to those for Python's standard dictionary objects." and under __getitem__(): "For *sequence* types, the accepted keys should be integers and slice objects." I just think 5.3.3 is unnecessarily opaque. Particularly since the only built-in mapping (dict) doesn't even accept simple slices as indices. Kent > > Regards, > Nick. > From steven.bethard at gmail.com Thu Nov 11 12:38:14 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 11 Nov 2004 17:38:14 +0000 (UTC) Subject: typed variables (WAS re.compile.match() results ...) References: <2vh2mlF2lbkrdU1@uni-berlin.de> <41938e20$1@nntp0.pdx.net> Message-ID: Stefan Seefeld sympatico.ca> writes: > > Scott David Daniels wrote: > > Axel Bock wrote: > > > > This shows a misunderstanding. Python does not have typed variables. > > huh ? It is perfectly valid to ask what type a variable has, i.e. python > is 'strongly typed'. I think perhaps Axel Bock was getting a little pedantic here. Technically Python does not have typed variables; any "variable" in Python can hold an object of any type. Hence examples like: >>> a = 'a' >>> a = 4.5 Probably a better way of saying this is to say that *names* in Python can be *bound* to objects of any type. Of course, Python is strongly typed, so the objects 'a' or 4.5 will not change type on you, though you are free to bind any name you like to these objects: >>> a = b = c = 'a' >>> a is b True >>> b is c True >>> a, b, c ('a', 'a', 'a') I think Axel Bock would have been happier if the sentence: "now a,b,c,d are all string variables, and they all come out as unicode strings" had been expressed as something like: "now the names a,b,c,d are all bound to unicode objects" Steve From foo at bar.com Sat Nov 6 00:15:14 2004 From: foo at bar.com (Steve Menard) Date: Sat, 06 Nov 2004 00:15:14 -0500 Subject: How come wxPython isn't in the standard library? In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: > See: http://www.wxpython.org/quotes.php. especially: > > "wxPython is the best and most mature cross-platform GUI toolkit, > given a number of constraints. The only reason wxPython isn't the > standard Python GUI toolkit is that Tkinter was there first." - Guido > van Rossum > > Guess, that answers my question, but isn't "Tkinter was there first" a > very bad answer? :) It is kinda ugly too, so I wonder why it can't be > replaced? Or maybe another GUI library could complement it. IMHO, > having a good GUI library in the stdlib would make distributing GUI > apps much easier. Windows users (and many Linux users) doesn't like > searching the net to find and download lots of dependancies. > I haven't used WxPython for a little while, but not long ago (less than a year) it was dreadfully easy to crash a program if even a little mistake happened. Add to that that WxPython prigram will silently eat any unexpected exceptions, and you get a very hard to debug situation. For me, this would sisqualify wxPython as a standard Library component. Steve From zanesdad at bellsouth.net Wed Nov 10 08:39:51 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 10 Nov 2004 08:39:51 -0500 Subject: jython and curses In-Reply-To: References: Message-ID: <41921A27.3050209@bellsouth.net> Sateesh wrote: >Hi, >Is there any version of jython that has support for curses library? >Or is there anyway I can use curses library for my jython programs? > >Thanks >Sateesh > > > > You could try using a Java curses library: http://sourceforge.net/projects/javacurses/ Jeremy Jones From peter.jakubik at stonline.sk Tue Nov 30 04:37:42 2004 From: peter.jakubik at stonline.sk (Peter Jakubik) Date: 30 Nov 2004 01:37:42 -0800 Subject: Python Embedding and pep-0263 Message-ID: Hi I am embedding Python 2.3.3 in C++ under Win2k. I am using in my App only Python DLL and empty site.py (so that User doesn't have to install Python). The Python Scripts contains Non-ASCII characters and i get DeprecationWarning pep-0263. How can i set Python File encoding from C-Code before Script starts ? Any help would be appreciated. peter From exogen at gmail.com Sun Nov 7 09:34:12 2004 From: exogen at gmail.com (Brian Beck) Date: Sun, 07 Nov 2004 09:34:12 -0500 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: Pythogoras wrote: > OK. I will rewrite it in Java. > > /// > long t = currentTimeMillis(); > tryCopyFile("in.txt","out.txt"); > out.println( (currentTimeMillis() - t) / 1000); > /// > > You lost. The Java-version is shorter! > I didn't count import- and import static-statements > because Eclipse cares about imports automatically. I don't know what version of Java they're using in this troll's fantasy land, but tryCopyFile does not, and has never existed in any Java implementation. The real code for copying a file would look something like the contents of this function (which is not a part of the standard library): public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } From drew at gremlinhosting.com Thu Nov 18 13:23:59 2004 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 18 Nov 2004 18:23:59 +0000 Subject: FIXED TPG error when using 't' as the first letter of a token In-Reply-To: <1100792193.27722.35.camel@odin> References: <1100792193.27722.35.camel@odin> Message-ID: <1100802240.27722.59.camel@odin> Gentlemen, Fixed what turned out to be my appalling knowledge of regexps. It turns out that inline tokens are parsed as regular expressions by TPG and I hadn't properly escaped the '[' characters. This means the START rule has been changed to this: START -> CatExpr ('\[' MetaExpr '\]')? Now things work as expected, but I'm still unsure as to why this symptom was only occurring with the uncapitalised character 't'.... can anyone enlighten me? Regards, Andrew On Thu, 2004-11-18 at 15:36 +0000, Andrew James wrote: > Greg, > Thanks for your response. Thought about this and tried with a lowercase > 'n' and a few other letters to check it out. It ran fine, so I'm back to > square one ;-/ > > TPG is a parser generator for Python (which is really quite cool) and > can be found at: http://christophe.delord.free.fr/en/tpg/ > > Can anyone else offer any insight? > > Regards, > Andrew > > On Thu, 2004-11-18 at 13:48 +0000, Greg Krohn wrote: > > Andrew James wrote: > > > Gentlemen, > > > > > > I'm running into a problem whilst testing the parsing of a language I've > > > created with TPG . It seems that for some reason, TPG balks when I try > > > to parse an expression whose first letter is 't' (or, in fact, at any > > > time when 't' is at the beginning of a token). This doesn't happen with > > > any other letter (as far as I know), nor if the 'T' is capitalised. > > > > I have no idea what TPG is, but if it's only having trouble with a lower > > case t, could it be that the t is somehow getting escaped and TPG thinks > > it's a tab character? > > > > Just a thought. > > > > greg > -- > Andrew James > -- Andrew James From tim.peters at gmail.com Mon Nov 22 22:14:57 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 22 Nov 2004 22:14:57 -0500 Subject: is int(round(val)) safe? In-Reply-To: References: Message-ID: <1f7befae0411221914249357d1@mail.gmail.com> [Peter Hansen] ... > I wonder if it would be appropriate to say something along > the lines of '''round() returns an integer, but not an "int".''' Well, round() is a 2-argument function, whose second argument defaults to 0. It's quite defensible to say that round returns an integer value when the second argument is 0. > Obviously the mathematicians will have something to say about > this. In computers, 1.0 may not be an integer data type, but > I think in math it's still considered an integer. Depends on which mathematician you're talking to. The integer 1 is most often defined as the set containing the empty set, or, in a suitably restricted set theory, with the set of all sets containing 1 element (which is a proper class in most set theories). A real, OTOH, is a godawful construction that Americans typically don't learn until after they've completed "calculus" and gone on to "analysis". So, instead of talking to mathematicians, I advise talking to me . Yes, 1.0 is an integer! In fact, so is 1.9998e143: all sufficient large floats are exact integers. That's why, e.g., math.ceil() and math.floor() return arguments like 1.9998e143 unchanged -- such inputs are already integers. > I am most definitely not going to claim authority in this area, however, > since as an engineer I consider 1.0 and 1 merely "equal to a > first approximation". If they differ at all, then e = 1.0 - 1 must be nonzero. Since it isn't, they're identical . From tdelaney at avaya.com Tue Nov 23 16:34:06 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 24 Nov 2004 08:34:06 +1100 Subject: Python and generic programming Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A90F0@au3010avexu1.global.avaya.com> Ronald Oussoren wrote: > On 23-nov-04, at 5:56, Delaney, Timothy C (Timothy) wrote: > >> And now a version that works with multiple arguments ... > > PEAK (http://peak.telecommunity.com/) has an implementation of generic > functions in its repository. It seems to be more complete than your > version ;) I should hope so. My version was 30 minutes building on Carl's work ;) Tim Delaney From db3l at fitlinxx.com Mon Nov 15 19:37:09 2004 From: db3l at fitlinxx.com (David Bolen) Date: 15 Nov 2004 19:37:09 -0500 Subject: os.path.exists discrepancy References: Message-ID: "Robert Brewer" writes: > Bah. I bet you're right. The webserver runs as LocalSystem, and the > folder in question is a mapped drive on another machine. I'll test that > tomorrow. That'll do it. Under Windows, LocalSystem has nearly unlimited local privileges, but it has no network privileges. -- David From lisawill4u at yahoo.com Sun Nov 21 06:33:51 2004 From: lisawill4u at yahoo.com (I found this great little site.) Date: Sun, 21 Nov 2004 11:33:51 GMT Subject: I found this great little site. Message-ID: <04112106335153693@news-server.cfl.rr.com> An HTML attachment was scrubbed... URL: From carribeiro at gmail.com Wed Nov 17 21:01:22 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 18 Nov 2004 00:01:22 -0200 Subject: ANN Python IRCD In-Reply-To: References: Message-ID: <864d3709041117180124b4d68c@mail.gmail.com> On Wed, 17 Nov 2004 23:32:47 GMT, Joseph T. Bore wrote: > > I would like to let everyone know about, and release onto the world, > my python IRCD. > > The goals of it were to be small and light, not a full IRC protocol > implementation. To that end, it's under 500 lines of code and just > one file. > > It's stable, and seems ready for others to use, I'll probably spend > the next few releases working on more comments and adding a few more > basic functions. > > I Hope others find it useful.. > > http://pyircd.sf.net I was thinking about making a IRC-to-Web gateway... something like a web-based IRC client, using some Javascript & RPC tricks to make it work in real time, without page reloads. But this is not really a priority, and I am already way too busy, so I don't think that I'll be able to do it anytime soon. But having something related already written in Python is nice. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From trentm at ActiveState.com Fri Nov 19 18:34:10 2004 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 19 Nov 2004 15:34:10 -0800 Subject: ANN: ActivePython 2.4c1 is available Message-ID: <419E82F2.4020203@activestate.com> ActivePython 2.4c1 is now available from: http://www.ActiveState.com/Products/ActivePython This is a release candidate matching the recently tagged core Python 2.4c1. Builds for Windows, Linux and Solaris are available. We would welcome any and all feedback to: ActivePython-feedback at ActiveState.com Please file bugs against ActivePython at: http://bugs.ActiveState.com/ActivePython What is ActivePython? --------------------- ActivePython is ActiveState's quality-assured binary build of Python. Builds for Windows, Linux and Solaris and made freely available. ActivePython includes the Python core and core extensions (zlib 1.2.1, bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.4, and Tix 8.1.4). On Windows, ActivePython includes the PyWin32 suite of Windows tools developed by Mark Hammond, including the Pythonwin IDE, bindings to the Win32 API and Windows COM; and more. ActivePython also includes a wealth of Python documentation, including: - the core Python docs; - Andrew Kuchling's "What's New in Python" series; - the Non-Programmer's Tutorial for Python; - Mark Pilgrim's excellent "Dive into Python"; and - a snapshot of the Python FAQs, HOWTOs and PEPs. An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html Thanks, and enjoy! Trent -- Trent Mick trentm at activestate.com From zanesdad at bellsouth.net Fri Nov 5 17:11:04 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 05 Nov 2004 17:11:04 -0500 Subject: xml.dom.minidom appendChild/toxml formatting problem In-Reply-To: <6471d296.0411051330.1477041@posting.google.com> References: <6471d296.0411051330.1477041@posting.google.com> Message-ID: <418BFA78.3050108@bellsouth.net> Ray wrote: >I have put together some pretty simple code for adding and removing >elements from an XML file, but am having a problem with toxml writing >out the correct format after I have called appendChild on a node. > >Here is a snippet: > >if (action == 'add'): > newCluster = domi.createElement(elementType) > newCluster.setAttribute("Name", elementName) > elem.appendChild(newCluster) >else: > elem.removeChild(childElem) > >domi.normalize() > > > > >Or, if I append "RAYTEST3" to "RAYTEST", it comes out as: > > > > >Instead of: > > > > > > >The rest of the XML file retains its original whitespace and >linebreaks. How can I get this to format the new changes correctly? >Calling toprettyxml instead of toxml seems to double the whitespace >and linebreaks in the rest of the file. > > I'd like to offer you a more automated method, but I can't. Perhaps someone else can. The only way I can think of to do it is to see what kind of text nodes exist around where you are inserting your elements and get that for formatting and insert similar text nodes before you insert your elements. Just out of curiosity, why are you interested in preserving the whitespace? Is this going to be something that is human read rather than machine read (or human read in addition to machine read)? Jeremy Jones From FRANKABEL at tesla.cujae.edu.cu Sun Nov 7 12:31:28 2004 From: FRANKABEL at tesla.cujae.edu.cu (Frank Abel Cancio Bello) Date: Sun, 07 Nov 2004 13:31:28 -0400 Subject: About mhtml Message-ID: Hi all! I need to make a cgi in python that send mhtml instead of html to client web browser. With Internet Explorer I save a .mhtm file and then build the following python script. But this not work. Some suggestion?. All I need is an example. print """Content-Type: multipart/related; boundary="----=_NextPart_000_0000_01C4C4CB.1CCA6D50"; type="text/html" ------=_NextPart_000_0000_01C4C4CB.1CCA6D50 Content-Type: text/html; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable Content-Location: file://C:\Documents%20and%20Settings\temp\Desktop\test.html ------=_NextPart_000_0000_01C4C4CB.1CCA6D50 Content-Type: image/png Content-Transfer-Encoding: base64 Content-Location: file:///C:/Documents%20and%20Settings/temp/Desktop/test.png iVBORw0KGgoAAAANSUhEUgAAACIAAAAjCAIAAAB+eU8wAAAAAXNSR0IArs4c6QAAAARnQU1BAACx jwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAKJJREFU SEvtVtEOgCAItP//aLM53Q1QkRkPBeuhDDvuDrUrpZxcosA4XB4Yj2AOVALGJnJ4Y9CNiZbPBayW v8AUyvoQk1WiecD0Qioh8khG+FsyS9g6u1CdDdKq9/MR/EKrYNxpCIMbOVbKa0I797yZmCQytrMh VR8WjevGKxU13GgB/aIZZaq8+QTMOz8hcXqeOD3Dm3UfrTMMTvApAbMt4w1iaNSBMh1elwAAAABJ RU5ErkJggg== ------=_NextPart_000_0000_01C4C4CB.1CCA6D50-- """ __________________________________________ Aniversario 40 de la CUJAE Visite: XII Convencion de Ingenieria y Arquitectura http://www.cujae.edu.cu/eventos/convencion/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pfalcone at localhost.localdomain Sat Nov 27 19:43:19 2004 From: pfalcone at localhost.localdomain (Paolo Alexis Falcone) Date: Sun, 28 Nov 2004 08:43:19 +0800 Subject: I Need a Python Mentor References: Message-ID: On Thu, 25 Nov 2004 13:07:30 +0000, abhay wrote: > Hi, > I have just ended learning to program in Python using the book "Programming > in Python" by Mark Lutz. > But to my dismay there are no excercises or programming projects in the > book. I'm seeking for a good programming project to be implemented in > python. Do you have any projects to share, I'm ready to spend my free time > over it to learn the best. > There are other books on Python that have quite served me well, such as "Dive into Python" by Mark Pilgrim, "Think in Python" by Bruce Eckel, and "How to Think Like a Computer Scientist: Learning with Python" by Allen B. Downey, Jeffrey Elkner and Chris Meyers. Would you care to have a shot for an open source statistical package using Python? Currently I have CVS access to the salstat project (salstat.sourceforge.net). Of course, there are other projects that are very interesting to do in Python (I'm building an open source ERP using Zope + CMF + ERP5, and all of them ultimately boil down to Python). -- Paolo Alexis Falcone pfalcone at free.net.ph From aleaxit at yahoo.com Thu Nov 4 16:00:33 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 Nov 2004 22:00:33 +0100 Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> <10oim483n2b7r7f@corp.supernews.com> Message-ID: <1gmqy8k.b4isct1okot00N%aleaxit@yahoo.com> Steven Bethard wrote: ... > I wonder what people think about Ruby, which, I understand, does allow you to > modify builtins. Can anyone tell me if you could make Ruby strings do the > horrible coercion that PHP strings do? Yes, you could. Reliable Ruby friends tell me that's not DONE in the real world of Ruby, any more than pythonistas call their methods' first argument 'foo' rather than 'self' or pepper their code with 'exec' statements or code 200-chars nested-lambda oneliners. But though culturally frowned on, it _is_ technically possible. The one real example I saw, which was enough to turn me off my quest to explore Ruby for production purposes, was making (builtin) string comparisons case-insensitive -- apparently that _IS_ the kind of thing _SOME_ perhaps-inexperienced Rubystas _DO_ perpetrate (breaking library modules left, right, and center, of course). Maybe it's similar to rather inexperienced Pythonistas dead keen on "exec myname+'='+value"; I _have_ seen that horror perpetrated in real Python code (doesn't break any library, but slows function execution down by 10 times w/o any real advantage wrt dicts or bunch usage, and is a bug-prone piece too...). Alex From alexs at advfn.com Thu Nov 25 04:35:24 2004 From: alexs at advfn.com (Alex Stapleton) Date: Thu, 25 Nov 2004 09:35:24 +0000 Subject: XUL Parser? In-Reply-To: <1101324939.28137.0.camel@odin> References: <41A4B77C.3010703@advfn.com> <1101324939.28137.0.camel@odin> Message-ID: <41A5A75C.4040603@advfn.com> A.M. Kuchling wrote: > I'm not aware of any. Considering that there's no real XUL > specification, > implementing a XUL renderer would be difficult. Note that Luxor > implements its own format, also called XUL, that has nothing to do > with the XUL > implemented by Mozilla. > > --amk I'm not sure a spec is really required as long as it remains mostly compatible with Mozilla, and primarily the XUL Tutorial examples. We can always help work towards a standard spec, which XUL 1.0 is supposed to be, but thats current non-existent. Andrew James wrote: > Alex, > This is a very cool idea. I've been working with XUL for a little while > now and I'd like to be able to work with it in Python.... all steam > ahead! > > Andrew Andrew, is that an offer of help? Either in consultancy or in programming :) I have a lot of ideas for what i've started calling PyXUL I think it could make Pythons already fairly awesome GUI making facilities even more so. I've created a SourceForge project (called PyXUL) and will try and get an initial design up this weekend in one format or another. From steve at ferg.org Thu Nov 4 09:25:08 2004 From: steve at ferg.org (Stephen Ferg) Date: 4 Nov 2004 06:25:08 -0800 Subject: Python needs a CPyAN References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: > I suggest you present your proposal to the PSF; I suppose > the Board would be the group that would consider it. I agree. I attempted to post it to the grants-discuss list, but was turned down. "Interesting discussion, but I don't think the grants-discuss list is the right place for it." From peter at engcorp.com Tue Nov 30 14:03:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Nov 2004 14:03:56 -0500 Subject: date diff calc In-Reply-To: References: <16811.29264.547058.669652@montanaro.dyndns.org> Message-ID: Tim Peters wrote: > [Peter Hansen] >>I think Skip was intending that the format string be mandatory, >>to avoid such ambiguity. > > It's still a bottomless pit -- ask Brett, who implemented the Python > strptime . True, I did overlook timezones at the time. On the other hand, that's because *my* use cases for "simple" fromstring() behaviour are all involving local time. When I'm interested in non-local time, I would be happy having to specify that behaviour in a more complex manner. > OTOH, is that what people really want? For all I know, > rfc822.getdate() or rfc822.getdate_tz() are what's really wanted, or > maybe some DWIM thing like Zope's date guessers. To each his own, although I think there's a hope here that for those who might need/want a really simple solution, 95% of people have this in mind (pseudo-code): class datetime.date: def fromstring(format, string): ts = time.mktime(time.strptime(string, format)) return datetime.date.fromtimestamp(ts) The .fromtimestamp() methods already work only for local time, and I haven't heard anyone complaining about that either. (Hmm... haven't been listening either though. :-) -Peter From drew at gremlinhosting.com Wed Nov 24 14:35:39 2004 From: drew at gremlinhosting.com (Andrew James) Date: Wed, 24 Nov 2004 19:35:39 +0000 Subject: XUL Parser? In-Reply-To: <41A4B77C.3010703@advfn.com> References: <41A4B77C.3010703@advfn.com> Message-ID: <1101324939.28137.0.camel@odin> Alex, This is a very cool idea. I've been working with XUL for a little while now and I'd like to be able to work with it in Python.... all steam ahead! Andrew On Wed, 2004-11-24 at 16:31 +0000, Alex Stapleton wrote: > Is there a Python XUL parser which will create GUIs in a Mozilla like > fashion for me? I've had a poke around but the closest I could find was > Luxor, and thats Jython bound (which isn't feasible.) > > If not is anyone interested in helping design and implment one? I'm > rather keen on seeing a python XUL module which supports multiple widget > systems (wxPython, Qt , GTK+ etc) -- Andrew James From jepler at unpythonic.net Tue Nov 9 11:53:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 9 Nov 2004 10:53:06 -0600 Subject: Umlauts, encodings, sitecustomize.py In-Reply-To: References: Message-ID: <20041109165304.GE3567@unpythonic.net> No matter what you do, you won't change this behavior: >>> chr(0x84) '\x84' str.__repr__ always escapes characters in the range 0..31 and 127..255, no matter what the locale is. >>> print chr(0x84) will behave differently (it will write that byte to standard output, followed by a newline) You should note that chr(0x84) is *not* a-umlaut in iso-8859-1. That's chr(0xe4). You may be using one of these Windows-specific encodings: cp437.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp775.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp850.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp852.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp857.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp861.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS cp865.py: 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From manu.1982 at gmail.com Thu Nov 18 02:44:32 2004 From: manu.1982 at gmail.com (Manu) Date: 17 Nov 2004 23:44:32 -0800 Subject: Building a word list from multiple files Message-ID: Hi, Here's what i want to accomplish. I want to make a list of frequenctly occuring words in a group of files along with the no of occurances of each The brute force method will be to read the file as a string,split,load the words into a dict with words as key and no of occurances as key. Load the next file ,iterate through the new words increment the value if there is a match or add a new key,value pair if there is none. repeat for all files. is there a better way ?? Thanks in advance. Manu From dthierbach at gmx.de Thu Nov 11 16:35:01 2004 From: dthierbach at gmx.de (Dirk Thierbach) Date: Thu, 11 Nov 2004 22:35:01 +0100 Subject: distutils and Debian References: <4192AD69.5040707@sympatico.ca> <1UKkd.32427$km5.1574845@news20.bellglobal.com> Message-ID: <20041111213501.F5E.2.NOFFLE@ID-7776.user.dfncis.de> Colin J. Williams wrote: > Robert Kern wrote: >> Why are you trying to install distutils over the one provided by >> python-dev? It's probably not a good idea. > I am doing this because there is no distutils in the Debian packages for > Python2.3.4 or Python 2.3.4-dev. $ dpkg -l python2.3-dev ... ii python2.3-dev 2.3.4-5 Header files and a static library for Python $ dpkg -L python2.3-dev ... /usr/lib/python2.3/distutils/README /usr/lib/python2.3/distutils/__init__.py ... So either there's something strange with your version of the package (download a new one), or you didn't look carefully enough. - Dirk From rtilley at vt.edu Sun Nov 7 20:02:24 2004 From: rtilley at vt.edu (Brad Tilley) Date: Sun, 07 Nov 2004 20:02:24 -0500 Subject: Stop spaces from appearing when printing to file Message-ID: I'm printing some info into a txt file that will be uploaded into a MySQL DB. I use ';' as field separaters. How can I stop spaces from appearing on both sides of the ';' When I do this: print >> x,';',object,";",AN_string,";",ascii,";",sum My file looks like this: ;12345 ; 23456 ; [1,2,3,4,5] ; 15 I need it to look like this to make the DB happy: ;12345;23456;[1,2,3,4,5];15 From someone at microsoft.com Tue Nov 23 18:19:33 2004 From: someone at microsoft.com (Jive) Date: Tue, 23 Nov 2004 23:19:33 GMT Subject: Python 2.4 and Visual C++ Express References: Message-ID: <9APod.4998157$ic1.468025@news.easynews.com> Are you saying that Python 2.4 will not compile under MS VC++ 6.0? That's horrifying. Say it isn't so!!! I have just ported Python to an embedded system using VC++ 6.0. It will always be compiled using 6.0, for two reasons: 1) I cannot afford the manhours for changing compilers, and 2) Bill Gates has enough money already, alright? I would hate to think that I am now stuck at Python 2.3 for eternity. "Steve Menard" wrote in message news:XQfod.15475$3u6.726077 at wagner.videotron.net... > I will soon have to write start providing Python extensions, in binary > form, for python 2.4, and I have a few questions. > > I have Visual C++ 6 installed, which works great for python 2.3. > > I do not have access to Visual C++ 2003, which seems to be the compiler > to be used with Python 2.4. Unless I am mistaken, the free command-line > compiler is not a solution, as it cannot produce binaries that > dynamically link the C runtime. > > I have downloaded the Visual C++ 2004 "express" from the Microsoft.site. > > Now my question is, will I be able to compile Python 2.4 extension if I > use the Visual C++ 2004? And since I will be distributing the extension > for both Python 2.3 and 2.4, will distutil choose the right compiler ? > > Before some people mention MingW and Cygnus, I know and use them. > However, for redistributing I feel it safer to use the Microsoft compilers. > > Thanks for any help, > > Steve From dave.benjamin at gmail.com Thu Nov 4 23:39:32 2004 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Thu, 04 Nov 2004 21:39:32 -0700 Subject: dijkstra algorithm by object oriented In-Reply-To: References: Message-ID: <0pDid.79281$bk1.18493@fed1read05> Ricardo Batista wrote: > I need that someone help me. No, you need to do your own work like everybody else. > I need to program the dijkstra algorithm by object oriented. No, you don't, and you should tell your professor to unsubscribe from silver-bullet OO hype and realize that OO has little to add to mathematical problems like this. Dijkstra must be rolling in his grave. Dave From steve at holdenweb.com Sun Nov 21 16:11:25 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Nov 2004 16:11:25 -0500 Subject: ftplib callbacks In-Reply-To: References: Message-ID: Matija Papec wrote: > I would like to reimplement ftplib "nlst" using ftplib.dir (ftp server > doesn't support nlst) so I'm trying to guess how to use ftp callbacks. > Any help is appreciated. > tia! > > ============ > #!/usr/bin/python > > # nlst vs list > > import pprint > pp = pprint.PrettyPrinter(indent=4) > > import ftplib > > def myfilter(line): > return line > > ftp = ftplib.FTP("localhost") > ftp.login("mpapec", "island88") > #print ftp.retrlines("LIST") > dir = ftp.dir("", myfilter) > print dir > > The callback is called each time the FTP client softwrae has something to deal with. Try (untested): lines = [] def myfilter(line): global lines lines.append(line) with the remainder of your code unchanged. The lines list will then contain a list of all lines. The problem with your current callback is that its return value is ignored by the FTP module that calls it. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From kent3737 at yahoo.com Sat Nov 6 16:19:50 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 06 Nov 2004 16:19:50 -0500 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> <418C7DCB.60502@acm.org> Message-ID: <418d3f0b$1_3@newspeer2.tds.net> I rarely find myself acting as an apologist for Java, and I understand that the point Alex is making is that Python's performance for this operation is quite good, and that the OP should post some code, but this is really too unfair a comparison for me not to say something. There are two major differences between these two programs: - The Java version is doing a character by character copy; the Python program reads the entire file into a buffer in one operation. - The Java program is converting the entire file to and from Unicode; the Python program is copying the literal bytes. Here is a much more comparable Java program (that will fail if the file size is over 2^31-1): import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("/usr/share/dict/web2"); int bufferSize = (int)inputFile.length(); File outputFile = new File("/tmp/acopy"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte buffer[] = new byte[bufferSize]; int len=bufferSize; while (true) { len=in.read(buffer,0,bufferSize); if (len<0 ) break; out.write(buffer,0,len); } in.close(); out.close(); } } Here are the results I get with this program and Alex's Python program on my G4-400 Mac: kent% time java Copy 0.440u 0.320s 0:00.96 79.1% 0+0k 9+3io 0pf+0w kent% time python Copy.py 0.100u 0.120s 0:00.31 70.9% 0+0k 2+4io 0pf+0w The Python program is still substantially faster (3x), but with nowhere near the margin Alex saw. Kent Alex Martelli wrote: > OK, could you provide a simple toy example that meets these conditions > -- does lot of identical disk-intensive I/O "in batch" -- and the > execution speed measured (and on what platform) for what Python and Java > implementations, please? > > For example, taking a trivial Copy.java from somewhere on the net: > > import java.io.*; > > public class Copy { > public static void main(String[] args) throws IOException { > File inputFile = new File("/usr/share/dict/web2"); > File outputFile = new File("/tmp/acopy"); > > FileReader in = new FileReader(inputFile); > FileWriter out = new FileWriter(outputFile); > int c; > > while ((c = in.read()) != -1) > out.write(c); > > in.close(); > out.close(); > } > } > > and I observe (on an iBook 800, MacOSX 10.3.5): > > kallisti:~ alex$ java -version > java version "1.4.2_05" > Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_05-141.3) > Java HotSpot(TM) Client VM (build 1.4.2-38, mixed mode) > > -r--r--r-- 1 root wheel 2486825 12 Sep 2003 /usr/share/dict/web2 > > kallisti:~ alex$ time java Copy > > real 0m7.058s > user 0m5.820s > sys 0m0.390s > > versus: > > kallisti:~ alex$ time python2.4 Copy.py > > real 0m0.296s > user 0m0.080s > sys 0m0.170s > > with Python 2.4 beta 1 for the roughly equivalent: > > inputFile = file("/usr/share/dict/web2", 'r') > outputFile = file("/tmp/acopy", 'w') > > outputFile.write(inputFile.read()) > > inputFile.close() > outputFile.close() > > which isn't all that far from highly optimized system commands: > > kallisti:~ alex$ time cp /usr/share/dict/web2 /tmp/acopy > > real 0m0.167s > user 0m0.000s > sys 0m0.040s > > kallisti:~ alex$ time cat /usr/share/dict/web2 >/tmp/acopy > > real 0m0.149s > user 0m0.000s > sys 0m0.090s > > > I'm sure the Java version can be optimized easily, too -- I just grabbed > the first thing I saw off the net. But surely this example doesn't > point to any big performance issue with Python disk I/O wrt Java. So, > unless you post concrete examples yourself, the smallest the better, > it's going to be pretty difficult to understand where your doubts are > coming from! > > > Alex > From tim.peters at gmail.com Thu Nov 18 19:00:59 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 18 Nov 2004 19:00:59 -0500 Subject: Rationals? In-Reply-To: References: Message-ID: <1f7befae041118160013cb18cc@mail.gmail.com> [Tim Peters] >> ... >> There's a better implementation in the Python sandbox: >> >> [Mike Meyer] > Cool. I knew there had to be some out there, but couldn't find one in > either PyPI or the cookbook. I picked on Rat.py because it was what I > found. ... > Actually, I don't like the two PEPs. Both include changes to the > language that would surprise programmers and non-programmers as > well as having a negative impact on performance. You should only > get a rational if you specifically ask for a rational. Not true of PEP 239. The only specific thing it proposes is adding a rational() constructor to the builtins, of course backed by a new rational type. Some *possible* interactions with the rest of the language are briefly discussed in its "open issues" section. ... >> PS: If you simply want to *use* a high-powered rational type, >> download gmpy and be happy tonight. > No - it's that rationals are available in a number of other > programming languages I use, and it seems strange that they would be > missing from a language that comes with "batteries included". > > And yes, I am willing to do this work. But don't want to bother if > there's no chance of it getting into the standard library. Creating > yet another rational package outisde the standard library is pretty > pointless. If you want to use rationals in Python, gmpy is a fine way to do it today. There's always been some interest in adding rationals to the core, but I wouldn't say "a lot". There was a lot more interest in adding a decimal type to the core, and the first version of that is being released in Python 2.4 this year. Since the decimal type supports user-settable precision, it can handle exact decimal-fraction + - * operations within the bounds of the precision set, and "gracefully" lose precision when that bound is crossed. Many arguments in favor of rationals have been made over the last decade, but it's unclear how many will still be made after the decimal type becomes familiar. For example, the historically common argument that rationals would support exact addition of dollars-and-cents values will lose all force. The less common argument that it's somehow obscene not to have a type for which 1/x*x == 1 will still hold. In any case, if you don't like the existing rational PEPs (which isn't hard to understand ...), the best hope to get rationals into the core is to ask Guido to reject the current dead-in-the-water PEPs, and start a new alternative PEP. I suspect you assume that adding a library module would be exempt from the PEP process, but that's not so. The most relevant example is that 2.4's decimal module is a pure Python module, and absolutely nothing in the rest of the language changed to accommodate it -- it didn't even get a builtin constructor. That may change over time, but its PEP was only "selling" the Python module we now have. From FBatista at uniFON.com.ar Tue Nov 16 11:23:53 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 16 Nov 2004 13:23:53 -0300 Subject: using python with -c (as a inline execution in shell) Message-ID: [les_ander at yahoo.com] #- but suppose I want to read from the stdin (piped) i don't #- know how to do this since #- python -c "from sys import stdin; for x in stdin: print x" #- #- gives a syntax error. #- #- Anyone one know how to do this? What are you trying to achieve? Are you sure this is the best way? . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From square690410 at yahoo.com.tw Wed Nov 3 05:20:14 2004 From: square690410 at yahoo.com.tw (Leon) Date: Wed, 3 Nov 2004 18:20:14 +0800 Subject: how to count server response time from client ?? References: Message-ID: .....in not use NTP(network time protocol) Protocols,do it "Leon" ???g???l???s?D:cma9fb$kru$1 at netnews.hinet.net... >I want to write a web test tool(HTTP Protocols) > I use header 'Date' do obtin server response time > but client and server time clock is different > how to count server and client time clock interval or discrepancy > Can obtin server receive time ???? > > thank everybody... > From sean_mcilroy at yahoo.com Tue Nov 23 13:51:56 2004 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 23 Nov 2004 10:51:56 -0800 Subject: drag and drop graphics in tkinter? References: <41a2fb94$0$8155$8fcfb975@news.wanadoo.fr> Message-ID: Eric Brunel wrote in message news:<41a2fb94$0$8155$8fcfb975 at news.wanadoo.fr>... > I'm not quite sure I understand your question: drag and drop between what and > what? I'm looking for a way to use drag-and-dropping to pick up a graphic and move it from one place to another. For example, I thought I could get my feet wet by writing a script to represent small graphs (in the nodes-and-vertices sense) as collections of dots and lines onscreen. Moving the the dots around (while maintaining line-indicated connections between dots) could furnish a graphical way of investigating questions like planarity and isomorphism. From deetsNOSPAM at web.de Fri Nov 5 09:25:11 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 05 Nov 2004 15:25:11 +0100 Subject: Simple thread pools References: <418A4900.7020304@debpro.webcom.dk> <20041104102722.F815.JCARLSON@uci.edu> Message-ID: > I need to download 150000 files several times every day. > How would you solve that? How do you download them? http, ftp? What sizes, filetypes? Can they be packed beforehand? Do you even have enough bandwitdth? From how many servers do you query them? As you can see, there are more than a few questions - so how about elaborating a bit on the task you have to accomplish? -- Regards, Diez B. Roggisch From sjmachin at lexicon.net Sat Nov 20 18:27:59 2004 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2004 15:27:59 -0800 Subject: instant messenging References: Message-ID: Peter Hansen wrote in message news:... > Lucas Raab wrote: > > Are there any instant messenging programs out there for use in a Python > > app?? I've heard of Jabber, but never looke into it. > > Maybe try Googling for "python instant messenging"? I note that > in the first page of results there are at least two Python > modules for the Jabber protocol... > > -Peter And for even more results, try Googling for "python instant messaging". [OT] Aarrgghh!! What's happening to the language? From steve at holdenweb.com Sun Nov 14 21:33:31 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 14 Nov 2004 21:33:31 -0500 Subject: Zope 3.0, and why I won't use it In-Reply-To: References: Message-ID: <%FUld.2118$nj.1676@lakeread01> Istvan Albert wrote: > Steve Holden wrote: > >> You managed to get it to run? I found the whole load opaque beyond >> belief, and removed it after an hour's examination. > > > I had no problems whatsoever ... on the other hand I > been using Zope 2.7 for a more than a year so > that might have helped me. > > In Zope X3 they make a big deal out of interfaces, > everything seems to revolve around that. > > http://dev.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/Zope3Book/interfaces.html > > > then I looked at this, > > http://dev.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/FrontPage/Zope3Book > > > totally overwhelming. But I have confidence in > the Zope developers. I have had good experience with Zope > in general, did not let me down yet ... in the way > a few years back for example Tomcat would crash > if one set a cookie value that had a newline character > in it. > > Well indeed, the developers are a bunch of smart cookies (no pun intended). But I still await a comprehensible description of how the whole system works for 2.7, let alone X3 - how to put sites together, and the best way to achieve various results, and so on. Searching for information about Zope is a nightmare of broken links and outdated content that makes it difficult to find one's way through to the really useful stuff. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From usenet04q3 at hczim.de Tue Nov 30 08:25:54 2004 From: usenet04q3 at hczim.de (Heike C. Zimmerer) Date: Tue, 30 Nov 2004 14:25:54 +0100 Subject: pdb with emacs References: <10qms9e7rgrhn42@corp.supernews.com> Message-ID: <313aojF37djsrU1@uni-berlin.de> "Yuri Shtil" writes: > I am trying to learn python and use the gud/pdb from emacs. The > functionality that I am used to under gud/gdb and gud/perldb is missing, or > I don't know how to make it work. > Specifically: when I start pdb on a script file, the source does not show in > an another window as it does with perldb and gdb. If I bring it up in an > another window, Your source will show up when you step into your program, e.g. by doing an "S" pdb command. > the ^X SPC set a break, but the subsequent gud-next commands do not move the > execution cursor in the source file window. I never use gud's commands while in pdb mode because they didn't work - at least not as I expected - and I've already been familiar with pdb syntax. You'd better use pdb commands in its debugger window. Greetings, Heike From drew at gremlinhosting.com Thu Nov 18 04:00:32 2004 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 18 Nov 2004 09:00:32 +0000 Subject: TPG error when using 't' as the first letter of a token Message-ID: <1100768432.27722.4.camel@odin> Gentlemen, I'm running into a problem whilst testing the parsing of a language I've created with TPG . It seems that for some reason, TPG balks when I try to parse an expression whose first letter is 't' (or, in fact, at any time when 't' is at the beginning of a token). This doesn't happen with any other letter (as far as I know), nor if the 'T' is capitalised. My grammar looks like this: # Tokens separator space '\s+'; token Num '\d+(.\d+)?'; token Ident '[a-zA-Z]\w*'; token CharList '\'.*\''; token CatUnOp '~'; token CatOp '[/\^~]'; token MetaOp '[=\+\-!]'; token Date '\d\d-\d\d-\d\d\d\d'; token FileID '(\w+\.\w+)' ; # Rules START -> CatExpr '\?' '[' MetaExpr ']' | CatExpr | FileID ; CatExpr -> CatUnOp CatName | CatName (CatOp CatName)* | CatName ; CatName -> Ident #| '(' CatExpr ')' ; MetaExpr -> MetaCrit (',' MetaCrit)* ; MetaCrit -> Ident MetaOp Value ; Value -> CharList | Num | Date ; My test script like this: if __name__ == '__main__': """ For testing purposes only """ parseTests = ('This/is/a/simple/test', 'another/simple/test', "a/test/with/[author='drew']") for line in parseTests: try: print "\nParsing: %s \n%s\n" % (line,"="*(len(line)+9)) qp = MFQueryParser() print qp(line) except Exception, inst: print "EXCEPTION: " + str(inst) The output when using a letter which is not 't': Parsing: another/simple/test ============================ [ 1][ 2]START.CatExpr: (1,1) Ident another != CatUnOp [ 2][ 3]START.CatExpr.CatName: (1,1) Ident another == Ident [ 3][ 2]START.CatExpr: (1,8) CatOp / == CatOp [ 4][ 3]START.CatExpr.CatName: (1,9) Ident simple == Ident [ 5][ 2]START.CatExpr: (1,15) CatOp / == CatOp [ 6][ 3]START.CatExpr.CatName: (1,16) _tok_2 t != Ident [ 7][ 1]START: (1,15) CatOp / != _tok_1 [ 8][ 2]START.CatExpr: (1,1) Ident another != CatUnOp [ 9][ 3]START.CatExpr.CatName: (1,1) Ident another == Ident [ 10][ 2]START.CatExpr: (1,8) CatOp / == CatOp [ 11][ 3]START.CatExpr.CatName: (1,9) Ident simple == Ident [ 12][ 2]START.CatExpr: (1,15) CatOp / == CatOp [ 13][ 3]START.CatExpr.CatName: (1,16) _tok_2 t != Ident EXCEPTION: SyntacticError at line 1, row 16: Syntax error near t The output when using 't' as the first letter: Parsing: tanother/simple/test ============================= [ 1][ 2]START.CatExpr: (1,1) _tok_2 t != CatUnOp [ 2][ 3]START.CatExpr.CatName: (1,1) _tok_2 t != Ident [ 3][ 3]START.CatExpr.CatName: (1,1) _tok_2 t != Ident [ 4][ 2]START.CatExpr: (1,1) _tok_2 t != CatUnOp [ 5][ 3]START.CatExpr.CatName: (1,1) _tok_2 t != Ident [ 6][ 3]START.CatExpr.CatName: (1,1) _tok_2 t != Ident [ 7][ 1]START: (1,1) _tok_2 t != FileID EXCEPTION: SyntacticError at line 1, row 1: Syntax error near t I'm not sure whether this is something I'm doing wrong in my regular expressions or whether something is being escaped in the TPG code, or whether.... I just don't know! I'm going through the TPG code at the moment but am not very hopeful of finding the problem. Could someone possibly just let me know if I've made an obvious mistake somewhere? Many thanks, Andrew From rogerb at rogerbinns.com Mon Nov 22 11:33:37 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 22 Nov 2004 08:33:37 -0800 Subject: Wrapping a C library in Python References: Message-ID: "Roy Smith" wrote in message news:roy-24C5BE.07565522112004 at reader1.panix.com... > Since the handle is opaque, I don't need to know about the innards of > the structure at all. What I ended up doing was writing a little C > routine something like this: > > dm_handle *allocate_dm_handle () > { > return malloc (sizeof (struct dm_handle)); > } > > I then built a .so containing just that one routine, and used ctypes to > call it from Python to get my buffer. Congralutions on just manually re-inventing Swig :-) Unless your library is trivial (which this code indicates it is not), I would recommend also spending a little time with Swig. In many cases Swig can parse your header files and build the correct wrapper. The huge advantage of Swig is that you can use it to generate wrappers for a large number of languages. That comes in really helpful if you will also need wrappers for Java, TCL etc. Roger From sjmachin at lexicon.net Thu Nov 18 21:13:15 2004 From: sjmachin at lexicon.net (John Machin) Date: 18 Nov 2004 18:13:15 -0800 Subject: regex-strategy for finding *similar* words? References: <1100774319.18258.249.camel@bucket.localnet> Message-ID: Peter Maas wrote in message news:... > Christoph Pingel schrieb: > > Hi all, > > > > an interesting problem for regex nerds. > > I've got a thesaurus of some hundred words and a moderately large > > dataset of about 1 million words in some thousand small texts. Words > > from the thesaurus appear at many places in my texts, but they are often > > misspelled, just slightly different from the thesaurus. > > You could set up a list of misspelling cases, scan a word for it e.g. > citti and turn it into a regex by applying suitable misspelling cases > But this is cumbersome. It is probably better to use a string distance > defined by the least number of operations (add,delete, replace, exchange) > to map one string onto another. > > Search for '"Levenshtein distance" python' and find e.g. > > http://trific.ath.cx/resources/python/levenshtein/ Forget regexes. A string distance function is a helpful start. Firstly you need a method of parsing your input text into words or phrases. Secondly you need a fuzzy dictionary into which you load your thesaurus. This fuzzy dictionary will have a method like fuzzy_dict.approx_lookup('mispeled', 2) which would return you a list of words in the dictionary that had a (say) Levenshtein distance of 2 or less from your input word. Algorithms for fuzzy dictionaries: google for "Burkhard Keller tree" and "permuted lexicon". Alternatively you could look for a spelling checker with publicly available source and grab some ideas or even code. You might be interested in other string distance measures than Levenshtein distance e.g. the so-called Damerau distance which counts transpositions. There are faster algorithms available than the dynamic-programming one -- google "Heikki Hyyro". These allow you to preprocess your input word and then compare with multiple dictionary candidates in O(kn) instead of O(kmn) time where the input word has length m, and you compare with k dictionary words each of average length n. HTH, John From helten0007 at yahoo.com Tue Nov 23 14:28:13 2004 From: helten0007 at yahoo.com (Pete.....) Date: Tue, 23 Nov 2004 20:28:13 +0100 Subject: Transfer data from webpage form to database References: <41a36ab7$0$23056$ba624c82@nntp05.dk.telia.net> Message-ID: <41a38f13$0$23068$ba624c82@nntp05.dk.telia.net> Hi, yeah It's try I want to change it to a python.cgi.script. And thanks for your input..... I use the api pgsql So the first thing I do is to import the following and connect to the server: #!/pack/python-2.3.2/bin/python2.3 from pyPgSQL import PgSQL import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() ( I added this ) connect = PgSQL.connect(user="vvvvv", password="zzzzz", host="xxx.xxx.xx", database="yyyyy") Do I then have to write: PgSQL.query(''' INSERT into form Select persons.idpersons, person.username, persons.surname, phone.phone (And so on ) ( its what the specific tables are called in my database) From persons, phone ( And so on ) Where persons.name = 'Name'%s AND persons.surname ='Surname'%s AND persons.username = 'Username'%s ''' (And so on with the rest) % (form['name'].value, form['surname'].value, form['username'].value)) I dont think I get it quite right, any help would be highly appreciated. Thanks for all help... Below is the code from my webpage form:

Name:

Surname:

Username:

Password:

Adresse:

Zipcode:

City:

Phone:

Mail:

What is your profession?

Student Teacher Teacher Assistent

''' From wweston at att.net Mon Nov 29 13:54:52 2004 From: wweston at att.net (wes weston) Date: Mon, 29 Nov 2004 18:54:52 GMT Subject: Question on sorting In-Reply-To: <81a41dd.0411291029.4cff137d@posting.google.com> References: <81a41dd.0411291029.4cff137d@posting.google.com> Message-ID: <0gKqd.72252$7i4.43429@bgtnsc05-news.ops.worldnet.att.net> Lad wrote: > Hi, > I have a file of records of 4 fields each. > Each field is separated by a semicolon. That is > > Filed1;Ffield2;Field3;Field4 > > But there may be also empty records such as > ;;;; > (only semicolons). > > For sorting I used > ################# > lines = file('Config.txt').readlines()# a file I want to sort > lines.sort() > ff=open('ConfigSorted.txt','w')# sorted file > ff.writelines(lines) > ff.close() > ############### > It was sorted but empty records were first. I need them to be last(at > the end of the file). How can I do that? > > Thanks for help > Lad Lad, The sort call can have a function name as an arg. You could do: def mycompare(s1,s2): #return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie #if s1==";;;;" and s2<>";;;;": return 1 lines.sort(mycompare) wes From gh at ghaering.de Sun Nov 28 13:35:15 2004 From: gh at ghaering.de (Gerhard Haering) Date: Sun, 28 Nov 2004 19:35:15 +0100 Subject: Psycopg2 mirror availability In-Reply-To: References: Message-ID: <20041128183515.GA13896@mylene.ghaering.de> On Sun, Nov 28, 2004 at 03:41:10PM -0200, Jorge Godoy wrote: > John Fabiani writes: > > > I don't think there is a mirror. I also can confirm that the site appears > > to be down. > > Oh, I thought it was a problem with my own connection. No, I'm waiting for fog's response too, because pysqlite (only Subversion until now) is also hosted there and I wanted to commit a few changes and make a release ... -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tz at ingenion.de Wed Nov 17 06:37:32 2004 From: tz at ingenion.de (Thomas Zehbe) Date: Wed, 17 Nov 2004 12:37:32 +0100 Subject: Arbitrary errors with c++, python, and simple mapi Message-ID: <200411171237.32419.tz@ingenion.de> Hi all, I?m programming a wxWidgets application using MSVC++ 6.0 on WinXp, SP1, reportlab 1.19 and simple mapi. I programmend python modules, which call the reportlab modules. My python modules are called from C++ using the API. Everything works fine until I did the first call to a function in the mapi32.dll. The loading of the dll doesn?t matter, but any call to the mapi, i.E. MAPLogon, leads to arbitrary errors calling the Py-API. Example. pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict, func); Doing this before a mapi call and calling PyDict_Keys(pDict) returns a list of 91 keys including the function func. Doing it after a mapi call PyDict_Keys(pDict) returns a list of only 15 Keys without the function func. Doing the calls before and after a mapi call, a callable pFunc is returned in both cases, but the pFunc retrieved after the mapi call doesn?t work anymore. Calling pValue = PyObject_CallObject(pFunc, pArgs); returns 0x0 and no pdf file is generated. Seems that the MS dlls are peeking and poking around in the python interpreter memory. Has anybody seen this happen, too? How can I debug it. All print statements from within the python modules seem to go to /dev/null, as do if (pErr = PyErr_Occurred()) PyErr_Print(); Any help would be appreciated. Thanks Thomas -- Thomas Zehbe INGENION GmbH Luther Weg 50 31515 Wunstorf Tel 05031-902042 Fax 05031-902049 www.ingenion.de From belred1 at yahoo.com Thu Nov 18 09:21:58 2004 From: belred1 at yahoo.com (Bryan) Date: Thu, 18 Nov 2004 14:21:58 GMT Subject: Named tuples In-Reply-To: References: <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> <10pntj5m0spvl3f@corp.supernews.com> <419c20da.344317031@news.oz.net> Message-ID: Carlos Ribeiro wrote: > On 18 Nov 2004 12:58:49 GMT, Duncan Booth wrote: > >>Carlos Ribeiro wrote: >> >> >> >> >>>There are a few requirements that can be imposed to avoid problems. >>>First, __names__ is clearly a property, acessed via get & set (which >>>allows to trap some errors). It should accept only tuples as an >>>argument (not lists) to avoid potential problems with external >>>references and mutability of the names. As for the validation, I'm not >>>sure if it's a good idea to check for strings. maybe just check if the >>>'names' stored in the tuple are immutable (or perhaps 'hashable') is >>>enough. >>> >> >>Your idea of a __names__ attribute suffers from a problem that the common >>use case would be to return a tuple with appropriate names. Right now you >>can do that easily in one statement but if you have to assign to an >>attribute it becomes messy. >> >>An alternative would be so add a named argument to the tuple constructor so >>we can do: >> >> return tuple(('1', '2'), names=('ONE', 'TWO')) >> >>and that would set the __names__ property. If you allow this then you can >>make the __names__ property readonly and the problem of introducing a cycle >>in the __names__ attributes goes away. > > > I think that a better way to solve the problem is to create a names > method on the tuple itself: > > return ('1', '2').names('ONE', 'TWO') > > It's shorter and clean, and avoids a potential argument against named > parameters for the tuple constructor -- none of the standard > contructors take named parameters to set extended behavior as far as I > know. > but doesn't this feel more pythonic and more consistant? return ('ONE':'1', 'TWO':'2') From richardjones at optushome.com.au Sun Nov 21 18:19:05 2004 From: richardjones at optushome.com.au (richard) Date: Mon, 22 Nov 2004 10:19:05 +1100 Subject: OSDC timetable is up, with plenty of Python talks Message-ID: <41a1226e$0$31138$afc38c87@news.optusnet.com.au> The Open Source Developers' Conference is on next week (Dec 1 - 3) in Melbourne (Australia) and the conference timetable is now available: As you can see, there are going to be plenty of Python talks, including a keynote by Anthony Baxter. And I'll be talking about Roundup :) Registrations are still open so I'd encourage you to come along and hear some great local Python talks. Richard From deetsNOSPAM at web.de Tue Nov 16 07:26:55 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 16 Nov 2004 13:26:55 +0100 Subject: Pictograms and Python References: <81a41dd.0411160125.1aa4c7c1@posting.google.com> Message-ID: Lad wrote: > Hi, > did anyone try to convert a Pictogram ( = a picture with text) to text? > Lad >From this and your last post I assume that you want to perform some registration stuff that is protected against scripts like yours using images with distorted characters that a human beeing can decipher and enter, but that are hard to identify using OCR techniques. They're called a CAPTCHA. As these protections are there for a good reason and I personally loathe spam, I hope you neither succeed nor get help from this community. In the (I believe unlikely) case of your plans to automate access to that site are of good intentions, I'm sure you can make a deal with the people running that service so that you can access it through some RPC mechanism. -- Regards, Diez B. Roggisch From vinay_sajip at red-dove.com Wed Nov 3 17:08:41 2004 From: vinay_sajip at red-dove.com (Vinay Sajip) Date: Wed, 03 Nov 2004 22:08:41 +0000 Subject: ANN: New configuration module released In-Reply-To: References: <2e37dc1.0411030650.ff44840@posting.google.com> Message-ID: <418956E9.8000600@red-dove.com> Neal D. Becker wrote: > Looks good so far. > > The boost c++ library (about to be released) has a new program_options > parser. One feature I appreciate in the design, is that the source of > options is seperated from the rest of the design. This means that, out of > the box, it reads options from command line, from config files, and from > env variables. Probably not hard to extend if anyone could think of a > reason. > > I believe a decent config module should at least handle both config files > and command line options. ENV variables are a nice touch too. > Python already has the optparse module for command-line options, and it's pretty good. I'll be looking at ways in which access to command-line options parsed via optparse can be made available through the config API, without duplication of code. Regards, Vinay Sajip From dave at pythonapocrypha.com Thu Nov 11 16:52:10 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 11 Nov 2004 14:52:10 -0700 Subject: How to load new class definitions at runtime? In-Reply-To: <4193DCEB.2040004@pythonapocrypha.com> References: <864d37090411111306159e40e8@mail.gmail.com> <4193DCEB.2040004@pythonapocrypha.com> Message-ID: <4193DF0A.9090204@pythonapocrypha.com> Dave Brueck wrote: > 1) No module level code. Modules can have optional Setup() and > Teardown() functions that get called if present (the most typical use > case is to pass state from the old version of the module to the new > version - the return value from Teardown gets passed to the new module's > Setup function). A slight clarification: at the module level we allowed imports and definition of module global variables of course, just not code that had external side effects. So e.g. if a module always had its own worker thread running, it would get started in the Setup method and stopped in Teardown. -Dave From mauriceling at acm.org Tue Nov 9 22:55:27 2004 From: mauriceling at acm.org (Maurice LING) Date: Wed, 10 Nov 2004 03:55:27 GMT Subject: possible to pass python objects into java without jython? In-Reply-To: References: Message-ID: <4191912d$1@news.unimelb.edu.au> > > The simple answer is no. The complex answer is maybe, but not without > some work on your part. > > As part of JPype I made the opposite : allow Python to use Java classes. > That was easy as python is very dynamic. > > Going the other way around .... I don;t see how. The java part must want > to receive a specific Java type. Even if that type is Object (the root > of all object types in Java), tehre is no way for Python object to be > one of those. > > Case #1 : the "main" program is in Python, and the Java type to be > received is a Java interface. In that specific case, JPype > (http://jpype.sourceforge.net) can help you. You can "wrap" your pO into > the correct Java type and apss it in. > > Otherwise, as has been mantioned before, you will need some kind of > remoting mechanism. Corba might provide a middle ground, or XML-RPC/SOAP. > > Good luck. > > Steve Hi, Referring to this scenario again..... pA.py contains imports (something non-pure python) def A(n): ...(does something)... returns pO pB.py comtains import pA def B(n): (does something) x = pA.A(n) (does more things) Perhaps if we lax the problem a little and allow Jython to be in consideration and pB.py is implemented in Jython (as jyB.py), then using jythonc to convert it into a Java package (jyB.jar containing jython.jar, jyB.class and jyB$Inner.class). Am I then able to import jyB in my Java codes? Is it possible to use Jython as the middle ground, instead of CORBA or SOAP etc etc? Thanks Maurice From jeff at ccvcorp.com Fri Nov 19 19:24:21 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 19 Nov 2004 16:24:21 -0800 Subject: Global variables in modules/functions In-Reply-To: <419e9e02$1@nntp0.pdx.net> References: <419e9e02$1@nntp0.pdx.net> Message-ID: <10pt3ejp6abnq72@corp.supernews.com> Scott David Daniels wrote: > The easiest way to do this is to create a module named "globals", and > have any modules wanting to work like: ... except that you might want to use a different name, to avoid shadowing the globals() builtin function. :) Jeff Shannon Technician/Programmer Credit International From andrea.valle at unito.it Mon Nov 1 16:09:03 2004 From: andrea.valle at unito.it (andrea valle) Date: Mon, 1 Nov 2004 22:09:03 +0100 Subject: name of an instance In-Reply-To: References: <40a939c9.0410291820.fada696@posting.google.com><40a939c9.0410310827.112f13a1@posting.google.com><864d370904103113373b9698f0@mail.gmail.com> <6FAE7CBE-2BF1-11D9-841C-0003939C968C@unito.it> Message-ID: <427C4D12-2C4A-11D9-B6B3-0003939C968C@unito.it> Thanks, That was a possibility. But my idea was to not requiring the instance to know explicitly about its name. I solved passing my receiving object not the instance's name, but the instance directly. -a- On 1 Nov 2004, at 20:03, Terry Reedy wrote: > > "andrea valle" wrote in message > news:6FAE7CBE-2BF1-11D9-841C-0003939C968C at unito.it... >> How do I access the name of an instance? > > By giving __init__ a name param that you store as self.name so that the > instance really has a name. (def and class statements do something > similar) > --- > class MyClass: > def __init__(self, name='No name'): > self.name = name > def __str__(self): return self.name > > Terry J. Reedy > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From niels_bohr at uol.com.br Sun Nov 7 00:44:50 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 03:44:50 -0200 Subject: PEP new assert idiom In-Reply-To: <7xr7n62t0v.fsf@ruckus.brouhaha.com> References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> Message-ID: <1099806290.11311.102.camel@localhost.localdomain> > Some time ago I found myself proposing a new "Validate" statement, > which would work exactly like "assert", except: > > 1) it would throw a ValidationError instead of AssertionError > if the condition failed > > 2) it would NOT be turned into a no-op by the optimizing compiler. > [...] This sounds great. I like the validate syntax. This also sounds very useful to me. If it doesn't go mainstream, it should, at least be a parameter controlled at runtime: >>> import validate >>> validate.always_compile_assertions = True # this name sucks! I know! Ideally, for me, python would support a decent DPC-like semantics: >>> class foo_bar: >>> contract, 'invariant': >>> assert (something always true), 'Errormsg1' >>> assert (more imutable truths), 'Errormsg2' >>> >>> def foo(self, var1, var2): >>> contract, 'pre': >>> # var1 and var2 are avaiable in this scope >>> assert expr, 'Error string1' >>> assert expr1, expr2, 'Error string2' >>> >>> contract, 'pos': >>> # var1, var2, avaiable. 'old' is 'self' before calling foo >>> # foo.return stands for the output of function foo (or None) >>> # foo.error is any the exception the function had trown >>> assert self.bar > old.bar >>> assert foo == some result, 'Error string' >>> if foo.error == some Exception: >>> assert (condition to trow that exception), 'Error' >>> >>> (function implementation) The (python) implementation of this syntax can be something like this. If dbc is enable, foo method becames: >>> def foo(self, var1, var2): >>> try: >>> contract invariant block >>> ... >>> except AssertionError, x: >>> contractViolations.log('invariant', x) >>> >>> try: >>> pre contract block >>> ... >>> except AssertionError, x: >>> contractViolations.log('pre', x) >>> try: >>> foo.value = __old_foo(var1, var2) >>> finally error, error_msg: >>> if error: foo.value = None >>> foo.error = error >>> try: >>> post contract block >>> except AssertionError, x: >>> contractViolations.log('pos', x) >>> if error and not contract.fail_silently: >>> raise error, error_msg The program executes normally, then, if non fatal errors happens, contracViolations.report() will print a nice formated report of what was violated, similar to what unittest module does. This is not pure DBC I guess, but is nice. Thanks, Fabio From steve at ferg.org Wed Nov 3 09:04:44 2004 From: steve at ferg.org (Stephen Ferg) Date: 3 Nov 2004 06:04:44 -0800 Subject: Python needs a CPyAN References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: > Lots of people *want* a PyPAN; the number of people willing to work on it is about zero. Admitted. Or perhaps those with the skills needed for the work aren't able to undertake such a big job without financial support. That's why I proposed that PSF put out a special RFP for grant money to seed the work. My whole post was an argument for that proposal. Here's the argument in a nutshell. ********************************************** PSF's mission is (among other things) to support Python's long-term sucess. Popularity is part of what it means to be successful. Popularity is important to the Python community because it means jobs for Python developers, and usage of Python by organizations that need it. Python will never catch up to Perl in popularity without CPAN-like support. Therefore, Support for CPAN-like capabilities for Python is critical to Python's long-term success. Therefore, in keeping with its mission, PSF should offer grants specifically targeted at producing a CPyAN. *********************************************** This issue should be of critical interest to all Python developers, because it means the difference between the existence and the non-existence of opportunities for developers to use Python on the job. From t-meyer at ihug.co.nz Sun Nov 14 23:38:30 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 15 Nov 2004 17:38:30 +1300 Subject: IMAP4 example in docs causes memory error for me (OS X 10.3, In-Reply-To: Message-ID: [Problems with IMAP4, OS X 10.3 and FETCH] > seems like i have a slight work around to this issue, which is to use > try and except and to also reinit the imap instance every > time you want to get a message... this limits the error to only larger > messages. but it's still weird. Some SpamBayes users reported this problem (using the SpamBayes IMAP filter) a while back. Googling about, it appeared that Apple made some changes with 10.3 so that malloc doesn't like giving out large chunks of memory (none of the problems were specifically with Python). I don't have a Mac to test whether that's the case, though. It does seem that the best solution would be to wrap the code to catch MemoryErrors, and if they occur, try getting the message in chunks. Not a simple solution, though. If you do find more information, please post it here, as I (and maybe others) would be interested. FWIW, SpamBayes just skips any messages that cause this problem, which is a solution, but not a great one. =Tony.Meyer From ialbert at mailblocks.com Wed Nov 3 10:20:26 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 03 Nov 2004 10:20:26 -0500 Subject: Should I learn Python? In-Reply-To: <624a388a.0411021328.5ac41f4c@posting.google.com> References: <624a388a.0411021328.5ac41f4c@posting.google.com> Message-ID: Sam wrote: > Should I learn Python? I think learning a new langauge every once in while can be extremely beneficial even if one does not actually switch to it > 1. What can I do with Python that I can't do with php? You cannot write Python code in php. > 2. Do you use both PHP and Python in conjunction with each other? No and probably very few do. > 3. In what way could I utilize Python to compliment existing sites or > apps built with PHP? Implementing more complex algorithms is a lot easier with python. You still need a way to interface between the two though. Istvan. From philippecmartin at sbcglobal.net Sun Nov 7 18:17:49 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 7 Nov 2004 17:17:49 -0600 Subject: parsing pyton code Message-ID: <200411071717.49440.philippecmartin@sbcglobal.net> >>Check the source of the 'code' module, especially the runsource() >>method of the InteractiveInterpreter class. ?Also, see these docs >> >>/Jean Brouwers >>ProphICy Semiconductor, Inc. code.InteractiveInterpreter.compile() did the trick - thank you PS: 17 years of C/C++, 3 months of Python .... 17 years wasted ? boy I _love_ this language/environment. Philippe From andymac at bullseye.apana.org.au Sat Nov 27 21:23:00 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 28 Nov 2004 13:23:00 +1100 (EST) Subject: C API PyErr_Clear vs PyObject_HasAttrString In-Reply-To: <41A88448.4010501@jessikat.fsnet.co.uk> References: <41A88448.4010501@jessikat.fsnet.co.uk> Message-ID: <20041128125705.B63894@bullseye.apana.org.au> On Sat, 27 Nov 2004, Robin Becker wrote: > I'm trying to understand why this code causes a seg fault second time > through; the code is part of a setattr and is testing if the value is an > integer or has red, green and blue attributes. This code later goes on > to raise a ValueError if that's not the case. > > if((i = PyArg_Parse(value,"i",&cv))){ > c->value = cv; > c->valid = 1; > return 1; > } > > rgb = PyObject_HasAttrString(value,"red") > && PyObject_HasAttrString(value,"green") > && PyObject_HasAttrString(value,"blue"); > PyErr_Clear(); > > > ...... > PyErr_SetString(PyExc_ValueError, "bad color value"); > > > Both calls should fail and raise ValueError, but the second call causes > a seg fault in Python 2.3.4 (not in 2.2 and earlier). > > In 2.3.4 I found that moving the PyErr_Clear() before the calculation of > rgb fixes the problem. > > I assume the problem is that something in the rgb calculation is failing > because the python error flag is set. Is that a bug in the > implementation of PyObject_HasAttrString or is it my fault for not > knowing which API calls need a cleared error flag? Rule: if you call a Python API function, _always_ check its return status (unless documented as void). if it fails, check for an exception. if you want to ignore the exception, clear the exception, otherwise cleanup and bailout. This is a paraphrase (from memory) of a previous reply from Tim Peters. Notwithstanding this, segfaulting in a Python API function is not welcome (especially one documented as always succeeding!). I had a look at the source (from a CVS checkout this morning), and the only thing that looks like a source of such trouble would be an extension class with a tp_getattr implementation. If you are using such a beast, you might want to look at the tp_getattr implementation first. Otherwise I'd suggest filing a bug report on SF. BTW, have you tried this with 2.4c1? ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From has.temp2 at virgin.net Wed Nov 17 18:21:00 2004 From: has.temp2 at virgin.net (has) Date: 17 Nov 2004 15:21:00 -0800 Subject: EVIL FBI SADISTS should be HUNTED, KIDNAPPED and TORTURED for 3 YRS References: <8880818c.0411170340.726aeb0d@posting.google.com> Message-ID: <69cbbef2.0411171521.26067ced@posting.google.com> victorn234 at 138mail.com (Keith) wrote in message news:<8880818c.0411170340.726aeb0d at posting.google.com>... > Someone emailed and requested me to post it on Usenet newsgroups. Hey numnuts, don't you know EVIL FBI SADISTS have already WIRETAPPED your USENET client?!?!!!!! TURN OFF YOUR COMPUTER, LOCK ALL DOORS and HIDE IN THE CELLAR NOW!!!!!!!!!! From steven.bethard at gmail.com Wed Nov 3 20:03:54 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 01:03:54 +0000 (UTC) Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: JCM myway.com> writes: > > > Definition 1 is the definition most commonly used in Programming > > Languages literature.... However, for > > all intents and purposes, it is only applicable to statically typed > > languages; no one on the list could come up with a dyamically typed > > language that allowed bit-reinterpretation. > > Assembly language. The types of values are implied by what > instructions you use. I'm sure some people would argue that assembly language is untyped (not statically or dynamically typed) and that the operations are defined on bits, but this is definitely the best example I've seen. Thanks! Steve From pf_moore at yahoo.co.uk Thu Nov 4 15:26:29 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Thu, 04 Nov 2004 20:26:29 +0000 Subject: LRU cache (and other things missing from the standard library ...) References: Message-ID: Gerhard Haering writes: > I recently implemented a LRU cache. And I wondered why such a useful class is > not already in the standard library. The only thing I found was a cookbook > entry but the comments said it was problematic. [...] > I've already started translating it into C (*) , which speeds it up by between > factor 5 to 8. Maybe a candidate for the standard library once it's finished? Would this be a suitable addition for the collections module (which currently only has deque in it)? I'm not sure if a LRU cache counts as a "collection" in that sense. I looked at the code briefly, but don't really follow it yet... Paul. -- One of the lessons of history is that nothing is often a good thing to do and always a clever thing to say. -- Will Durant From David Sat Nov 6 15:32:48 2004 From: David (David) Date: Sat, 06 Nov 2004 13:32:48 -0700 Subject: JMS for CPython via JPype? References: <1b2k1czwwox4i$.ae466jlsmeu2$.dlg@40tude.net> Message-ID: On Sat, 06 Nov 2004 13:19:49 -0500, Steve Menard wrote: > >Dave, > >This example is amazing! would you be willing to contribute it to a >Jpype examples/recipe repository? I think such a place would be great >for those starting to use JPype. And as my documentation is not so good >(yet), good examples can only help. > >Thanks. > >Steve Menard Consider it contributed. I'm glad to (finally) give something back to c.l.py! Dave From craig at postnewspapers.com.au Fri Nov 19 05:53:57 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 19 Nov 2004 18:53:57 +0800 Subject: How to sort a list of tuples In-Reply-To: <1100859769.700610@eng-ser6> References: <1100859769.700610@eng-ser6> Message-ID: <1100861637.22341.4.camel@bucket.localnet> On Fri, 2004-11-19 at 18:22, Valkyrie wrote: > I have a list of tuples, and one of the fields in the tuple is score. So how can > I sort the list by the score? Assuming the score field is index 1 of each tuple: def cmp(a,b): if a[1] < b[1]: return -1 elif a[1] > b[1]: return 1 else: return 0 my_tuple_list.sort(cmp) (technically the elifs could be ifs, and the final else could be omitted in favour of just 'return 0', but for clarity the above is IMO best). see 'help(list.sort)' for more information. To whoever added this fantastic feature, thanks and more thanks. It's saved me so much work at times that it's just crazy. -- Craig Ringer From mailto.anand.hariharan at gmail.com Tue Nov 30 14:23:01 2004 From: mailto.anand.hariharan at gmail.com (Anand Hariharan) Date: 30 Nov 2004 11:23:01 -0800 Subject: ANNOUNCE: Ice 2.0 released References: <22868227.0411300634.1d333921@posting.google.com> <0YidnREmZ8xECDHcRVn-oA@speakeasy.net> Message-ID: <22868227.0411301123.c18dec9@posting.google.com> Marc Laukien wrote in message news:<0YidnREmZ8xECDHcRVn-oA at speakeasy.net>... > > (...) > > Am interested to know, what "percentage" (*) of the code in your CVS > > repository has been contributed by people other than the group > > mentioned in the quote above? Obviously, you do not allow anonymous > > CVS write access. Perhaps, one wishing to improve Ice (a freedom > > granted by GPL) and who does not work for ZeroC has to mail his/her > > improvements to your maintainers? > > (...) > > 100% of the Ice source code has been developed by ZeroC employees. > > Note that this does of course not apply for third-party code that is > being used by Ice, such as BZIP2, Berkeley DB, OpenSSL, etc. > Consider the *hypothetical* situation where an individual or a group of people re-write large portions of Ice. This could enhance the value of Ice (obviously to some, if not all), or this could conflict with the ideologies of Ice (again, not in everyone's point of view). How will ZeroC react to this? I believe whichever road you take, ZeroC is going to find itself in problems. If ZeroC merges the changes made by this/these person(s), how can ZeroC now sell it under a commercial license, as closed source (violation of GPL)? If you refuse to merge the changes, you have just given them a strong impetus to fork. History shows XEmacs and EGCS as two such examples. Guess what I am primarily interested in finding out is rooted in what I said earlier: > > Interesting to see this blend of GPL and an alternative for > > closed-source software. What were the ideas behind going the GPL way? How did ZeroC plan on benefiting from it? Were there any qualms within ZeroC in going GPL? Note that I am not saying GPL and commercial software don't go together (I do believe though that LGPL and commercial software don't go together). I am well aware of Free software being "Free speech, not free beer". What if you did not provide Ice as a free download, but a price based on your current licensing policy(*). However, the download would give one the complete source, and the freedom to modify and redistribute it (at whatever price so long as the complete source code with the GPL notice is released). (*): All of this is hypothetical. Am not making a business proposition here. You do not, because that would discourage Ice from becoming ubiquitous, from paving way for becoming a potential de-facto standard. Then, why not simply advertise Ice as being commercial (with unlimited free trial plus source code)? Doing so, would get you the extensive peer review that you are currently benefitting from. What do you gain by going GPL? The freedom to modify and/or redistribute is (apparently) pretty restricted anyway. > > PS: Please feel free to set FU-Ts as appropriate. > > What are FU-Ts? > "Follow-up To:". Most news clients will allow sending a post to multiple groups, restricting any possible responses to certain groups alone. A poster who is replying can over-ride it, of course. sincerely, - Anand From jeff at ccvcorp.com Mon Nov 15 20:09:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 15 Nov 2004 17:09:41 -0800 Subject: save a dictionary in a file In-Reply-To: References: <2vsa8hF2oa58tU1@uni-berlin.de> <10pi8f8ivf320a1@corp.supernews.com> Message-ID: <10piklanchlkm42@corp.supernews.com> Josiah Carlson wrote: >Jeff Shannon wrote: > > >>Luis P. Mendes wrote: >> >> >> >>>my program builds a dictionary that I would like to save in a file. >>> >>> >>As others have said, there should be no reason to convert to a list >>before pickling -- AFAIK, there's no ban against pickling dictionaries. >> >>You might also look into the Shelve module, which implements a >>filesystem-persisting object with dictionary access syntax. (And which, >>IIRC, uses pickled dictionaries under the covers.) >> >> > >It doesn't. It uses a bsddb database. > >A bsddb (really anydbm which can give you bsddb) database is merely a >string key->string value mapping (for btree and hash mappings). You >access it via string keys, and its values are automatically translated >to/from strings via Pickle. The only way you actually pickle and >unpickle dictionaries is by having a dictionary in a value. > > Ah, my mistake. (I've never really had call to use shelve *or* pickle, and was going off of (apparently erroneous) memories of conversations in c.l.py.) Still, it does seem that shelve would probably fit the O.P.'s needs... Jeff Shannon Technician/Programmer Credit International From bvande at po-box.mcgill.ca Thu Nov 18 23:16:30 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 18 Nov 2004 23:16:30 -0500 Subject: Identifying exceptions that can be raised In-Reply-To: References: Message-ID: <419D739E.5030300@po-box.mcgill.ca> dkcpub said unto the world upon 2004-11-18 22:38: > I'm very new to Python, but I couldn't find anything in the docs or faq > about this. And I fished around in the IDLE menus but didn't see anything. > > Is there a tool that can determine all the exceptions that can be raised > in a Python function, or in any of the functions it calls, etc.? > > /Dan Hi Dan, Do you mean all the exceptions that exist? If so, while I don't know Python well enough to vouch for its completeness, check out . If you mean you want a list of exceptions that a given function could raise, well, never mind :-) Best, Brian vdB From timr at probo.com Wed Nov 24 01:13:20 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 23 Nov 2004 22:13:20 -0800 Subject: Microsoft Patents 'IsNot' References: <16798.16559.745209.751967@montanaro.dyndns.org> <16798.19563.729805.103774@montanaro.dyndns.org> Message-ID: Carlos Ribeiro wrote: > >(btw, do I automatically assign to Microsoft the property of any idea >that I eventually communicate to them? I'm curious). Did you sign the NDA? Then you might have done exactly that. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From 18k11tm001 at sneakemail.com Tue Nov 30 14:22:26 2004 From: 18k11tm001 at sneakemail.com (Russ) Date: 30 Nov 2004 11:22:26 -0800 Subject: Python 2.4c1 vs. 2.4 Message-ID: My sysadmin recently installed 2.4c1 on our network. Should we now install 2.4, or is it the same as 2.4c1? Thanks. From jbore at tjtech.com Wed Nov 17 18:32:47 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Wed, 17 Nov 2004 23:32:47 GMT Subject: ANN Python IRCD Message-ID: I would like to let everyone know about, and release onto the world, my python IRCD. The goals of it were to be small and light, not a full IRC protocol implementation. To that end, it's under 500 lines of code and just one file. It's stable, and seems ready for others to use, I'll probably spend the next few releases working on more comments and adding a few more basic functions. I Hope others find it useful.. http://pyircd.sf.net jb From jcarlson at uci.edu Tue Nov 16 20:40:31 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 17:40:31 -0800 Subject: global event listeners In-Reply-To: <1100638869.786109.237720@c13g2000cwb.googlegroups.com> References: <1100638869.786109.237720@c13g2000cwb.googlegroups.com> Message-ID: <20041116173311.F97F.JCARLSON@uci.edu> "Hunter Peress" wrote: > > I want to do things directly before an object is changed. eg is there > something like: > > > a= "hi" > > objectChangeListener(a,lambda(previous_value,new_value):\ > global_counter.append(previous_value) ; return new_value) > > so then this global_counter var will increment whenever a is changed. > PS: im not looking to hear "know your codebase better" You cannot do precisely what you want to do. I'm sorry. You can do something similar. class counter(object): def __init__(self, value): self.__value = value self.counter = 0 def get_v(self): return self.__value def set_v(self, val): self.__value = val self.counter += 1 value = property(get_v, set_v) >>> a = counter(1) >>> a.value = 10 >>> a.value = 5 >>> a.counter 2 >>> a.value 5 >>> a.value = 0 >>> a.value 0 >>> a.counter 3 >>> Properties are your friend. - Josiah From michele.simionato at gmail.com Wed Nov 10 07:31:52 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Nov 2004 04:31:52 -0800 Subject: property for class objects References: Message-ID: <4edc17eb.0411100431.464f6050@posting.google.com> Steve Menard wrote in message news:... > I am not discarding this solution completely. It migth be that defining > those 2 (class and metaclass) isnt too heavy. Someone needs to clue me > in on this or I have to do some benchmarking myself. Do your benchmark but I do not expect it to be heavy. > Hopefully, tehre is a cleaner way to solve this. > Look at descriptors: http://users.rcn.com/python/download/Descriptor.htm Michele Simionato From bokr at oz.net Wed Nov 24 11:14:49 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 24 Nov 2004 16:14:49 GMT Subject: read(1) returns string of length 2 References: Message-ID: <41a4aed7.904954415@news.oz.net> On Wed, 24 Nov 2004 12:03:41 GMT, "wolfgang haefelinger" wrote: >Greetings, > >I'm trying to read (japanese) chars from a file. While doing so >I encounter that a char with length 2 is returned. Is this to be >expected or is there something wrong? > >Basically it's this what I'm doing: > >import codecs >f = codecs.open("ident.in",'rb','Shift-JIS') ## japanses codecs installed > >c = f.read(1) >while c: > if len(c)==1: > print hex(ord(c)), > else: > print "{", > for x in c: print hex(ord(x)), > print "}", > c = f.read(1) > >This is my input (file is also attached): > >$ od -tx1 ident.in >0000000 8d 87 8c 76 8e 9e 8a d4 3b 0d 0a >0000013 > >This is what I'm getting: > >$ python ident.py ## python 2.3.4 >on Windows >0x5408 0x8a08 0x6642 0x9593 { 0x3b 0xd } 0xa > >"Python" believes that there are 6 chars on the stream while there are >actually 7 chars. > >My naive assumption was that f.read(1) returns always a char of length 1 (or >zero). On my 2.4b1 it does, see below. > >Remark: >The input is believed to be "SJIS" but I haven't found a Python codecs for >this. >Therefore I'm using Shift-JIS. Of course this could be the problem. Note >that >when feeding Java with my input "correct" using SJIS, chars are spit out: > > c=21512 c=35336 c=26178 c=38291 c=59 c=13 c=10 : 7 char(s) > >References: >I downloaded Japanese codecs from here (version: 1.4.10) > http://www.asahi-net.or.jp/~rd6t-kjym/python/ > >Thanks for any hints, >Wolfgang. I added a print line and dropped the ending commas on your print chunks, but otherwise didn't (I think ;-) change your code: Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import codecs >>> f = codecs.open("ident.in",'rb','Shift-JIS') ## japanses codecs installed >>> c = f.read(1) >>> while c: ... print repr(c), len(c), '=>', ... if len(c)==1: ... print hex(ord(c)) ... else: ... print "{", ... for x in c: print hex(ord(x)), ... print "}" ... c = f.read(1) ... u'\u5408' 1 => 0x5408 u'\u8a08' 1 => 0x8a08 u'\u6642' 1 => 0x6642 u'\u9593' 1 => 0x9593 u';' 1 => 0x3b u'\r' 1 => 0xd u'\n' 1 => 0xa I reproduced your binary file: >>> for c in open('ident.in','rb').read(): print ('%02x'% ord(c)), ... 8d 87 8c 76 8e 9e 8a d4 3b 0d 0a What version/platform are you using? Perhaps you can upgrade? Regards, Bengt Richter From steven.bethard at gmail.com Mon Nov 22 13:34:31 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 Nov 2004 18:34:31 GMT Subject: Question about classes In-Reply-To: <1101141738.LDtCTAQKBaFZGDwtJwHeqQ@teranews> References: <1101104418.G+/GLqdG7XJQNil1Jd3gOQ@teranews> <1101141738.LDtCTAQKBaFZGDwtJwHeqQ@teranews> Message-ID: Ben wrote: > On Mon, 22 Nov 2004 06:39:53 +0000, Steven Bethard wrote: > >> >>> class C(object): >>... def __init__(self, x): >>... if x != 0: >>... self.x = x >>... else: >>... self.x = 5 >>... >> >>> c = C(0) >> >>> c.x >>5 >> >>> c = C(8) >> >>> c.x >>8 > > > Steve, > > That's exactly what I wanted. Thank you very much. I'll keep the class one > in mind too. You're welcome. Depending on your goal here, you might also find that default argument values are helpful: >>> class C(object): ... def __init__(self, x=5): ... self.x = x ... >>> c = C() >>> c.x 5 >>> c = C(8) >>> c.x 8 >>> c = C(0) >>> c.x 0 Steve From jcarlson at uci.edu Sat Nov 6 18:18:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 06 Nov 2004 15:18:59 -0800 Subject: checking a thread has started In-Reply-To: References: <20041106092443.F851.JCARLSON@uci.edu> Message-ID: <20041106151355.F859.JCARLSON@uci.edu> Deepak Sarda wrote: > > On Sat, 06 Nov 2004 09:30:59 -0800, Josiah Carlson wrote: > This seems like a way to workaround the problem. I'll try it on Monday > and get back if it works. But this does bring up the point that > threading.Thread() should provide some mechanism by which a thread's > inability to start should be known. a return value or something. (I am > a newbie to threads - python is the first language I am trying threads > in so please educate me if I have wrong notions! :-) If a thread doesn't start due to lack of resources, I think it should be raising an exception. As an aside, I wrote a little script that creates 1000 threads, does a busy loop for a short time, then exits; it had no problems with a few hundred threads at a time (though it was a bit slow), and I didn't see any exceptions. Perhaps I should have been incrementing a counter when it started and finished. > > As an aside, are you sure you need 15 threads? Seems a little over the > > top to me. > > I do. This program sits on top of a cluster and ferries jobs to the > compute nodes - an embarrassingly parallel problem with fifteen > subtasks. Sounds like a job for asyncore (if you can handle asynchronous servers/clients). - Josiah From skip at pobox.com Fri Nov 5 23:16:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Nov 2004 22:16:41 -0600 Subject: generic way to access C++ libs? In-Reply-To: References: Message-ID: <16780.20521.237302.882056@montanaro.dyndns.org> Diez> A c++ object created by g++ is total garbage passed to a VC lib Diez> that appears to use the same objects denoted by some headerfile. Sure, but the name mangling schemes are certainly well-defined. The GNU c++filt program on my Mac understands the following formats according to its --help output: none,auto,gnu,lucid,arm,hp,edg,gnu-v3,java,gnat I don't know what most of them are, but I guess c++filt does. I imagine something like ctypes could be trained to know how to decipher the signatures as well. There's still the problem of templates. Skip From aleaxit at yahoo.com Wed Nov 3 17:17:16 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 3 Nov 2004 23:17:16 +0100 Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <41882354$0$14963$626a14ce@news.free.fr> Message-ID: <1gmp77p.rndaoq3zftnxN%aleaxit@yahoo.com> Steven Bethard wrote: > Some programmers may actually want "a" + 10 == 10. Some people may actually want to drink poisoned kool-aid and join the great wise extraterrestrials on their comet in the skies. That doesn't mean I will look with favour upon those who aid and abet such goals. Alex From ialbert at mailblocks.com Tue Nov 2 13:26:27 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 02 Nov 2004 13:26:27 -0500 Subject: ruby on rails ... python on ? In-Reply-To: References: Message-ID: John wrote: > Why do you say that? I could agree if Zope could be programmed in many > languages. Then not tending to any language would be a benefit. On the what I am trying to say is that a creating a web site is not the same thing as implementing an algorithm or solving a problem that fits a computational paradigm like say Object Oriented approach. Parts of it, the core functionality maybe but when it comes to the interface and behavior and human interactions all that goes out the window. It becomes an indeterministic business: this how it works today, and it is all wired together in a way that makes most sense from usability perspective today. This last mile, the one that interfaces with humans, parameter reading and validation, security management, request filtering, and response rendering should be written specifically with this in mind and it has to be supported it in an entirely transparent and independent manner. Istvan From deetsNOSPAM at web.de Wed Nov 3 12:15:33 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 03 Nov 2004 18:15:33 +0100 Subject: Python CGI - Accepting Input, Invoking Another Process, Ending CGI References: <99351542.0411030837.beea2c7@posting.google.com> Message-ID: > Based on previous suggestions from this group, I'm attempting to write > a python CGI that takes input from an HTML form, invokes a second > python script using this input, tells the user that their process has > started, ends the cgi output and later emails the results of the > invoked script. > > My problem is that no mater how I invoke the 2nd script (spawnlp with > P_NOWAIT, system with &, etc..) the CGI caller continues to run until > it finishes. If you press the stop button or close the browser > certain portions of the 2nd script finish but not all of it. In > paticular the 2nd script uses teTex (invoked by os.system) to process > some tex files, this always errors out if the browser is closed or > stopped. Did you try to daemonize your script? That will decouple it from the running process, so maybe that helps. In the aspn cookbook there is a good recipe for daemonizing. -- Regards, Diez B. Roggisch From jerry at jerrysievers.com Sun Nov 21 13:13:06 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 21 Nov 2004 13:13:06 -0500 Subject: thread; interrupt_main() doesn't seem to work? Message-ID: Fellow Pythonists; According to the docs +-----------------+ |interrupt_main(|)| +-----------------+ Raise a KeyboardInterrupt in the main thread. A subthread can use this function to interrupt the main thread. New in version 2.3. Therefore, I was expecting this short test prog to run and then finish with the KeyboardInterrupt exception at the bottom in the pause routine. It doesn't stop there but I can do a manual keyboard interrupt and get the expected bactrace and program exit. --- from signal import pause from socket import socket from thread import start_new_thread, interrupt_main from time import sleep def go(): print 'go' while f.readline(): print 'line' print 'empty' interrupt_main() print 'done' s = socket() s.connect(('localhost', 80)) f = s.makefile() print 'connected' start_new_thread(go, ()) sleep(2) s.shutdown(2) pause() # expecting to get KeyboardInterrupt exception here --- connected go empty done ...hangs here as if interrupt_main() does nothing. Manual Control-C required to wake up from pause() and exit. Traceback (most recent call last): File "test.py", line 23, in ? pause() # expecting to get KeyboardInterrupt exception here KeyboardInterrupt Python 2.3.3 on RedHat 7x. Wondering what's wrong? Thanks -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From danperl at rogers.com Thu Nov 4 15:48:20 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 4 Nov 2004 15:48:20 -0500 Subject: New configuration module released References: <2e37dc1.0411030650.ff44840@posting.google.com><4d2dnXe5XY7bmxTcRVn-rw@rogers.com> <2uv9goF2f3161U1@uni-berlin.de> Message-ID: Thanks for the suggestion. What are you using for a python implementation? I saw that there is PyYAML and Syck (multi-language, including python). Dan "Reinhold Birkenfeld" wrote in message news:2uv9goF2f3161U1 at uni-berlin.de... > Dan Perl wrote: > >> It's just an idea and I haven't put a lot of thought in it myself, but >> what >> about using XML for the configuration syntax? > > I'm currently using YAML for configuration syntax. I don't need object > references as in the OP's module, so I'm happy with it. > > It's also easy to change for users. > > Reinhold > > > -- > [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer > jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen > jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- > mitteln inkompatibel. -- Florian Diesch in dcoulm From wh2005 at web.de Sun Nov 21 06:09:30 2004 From: wh2005 at web.de (wolfgang haefelinger) Date: Sun, 21 Nov 2004 11:09:30 GMT Subject: unicode question References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> <41A061E1.8050203@v.loewis.de> Message-ID: Hi Experts, I'm actually not a Python expert so please bear with me and my naive questions and remarks: I was actually thinking that print x is just kind of shortcur for writing (simplifying bit): import sys if not (isinstance(x,str) or isinstance(x,unicode)) and x.__str__ : x = x.__str__() sys.stdout.write(x) Or in words: if x is not a string type but has method __str__ then print x behaves like print x.__str__() Given this assumption I'm wondering then why print x.__str__() works but print x does not? Is this a bug?? Cheers, Wolfgang. ""Martin v. L?wis"" wrote in message news:41A061E1.8050203 at v.loewis.de... > Kent Johnson wrote: >> Martin v. L?wis wrote: >> >>> wolfgang haefelinger wrote: >>> >>>> I wonder especially about case 2. I can see that "print y" makes a call >>>> to >>>> Y.__str__() . But Y.__str__() can be printed?? So what is 'print' >>>> exactly doing? >>> >>> >>> >>> It looks at sys.stdout.encoding. If this is set, and the thing to print >>> is a unicode string, it converts it to the stream encoding, and prints >>> the result of the conversion. >> >> >> I hate to contradict an expert, but ISTM that it is >> sys.getdefaultencoding() ('ascii') that is the problem, not >> sys.stdout.encoding ('cp437') > > It seems we were answering different parts of the question. I answered > the part "What is 'print' exactly doing"; you answered the part as to > what the problem with str() conversion is (although I'm not sure whether > the OP has actually asked that question). > > Also, the one case that is interesting here was not in your experiment: > try > > print gamma > > This should work, regardless of sys.getdefaultencoding(), as long as > sys.stdout.encoding supports the characters to be printed. > > Regards, > Martin From M.Waack at gmx.de Sun Nov 28 08:49:18 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sun, 28 Nov 2004 14:49:18 +0100 Subject: files in non-blocking mode? References: Message-ID: Uwe Mayer wrote: > Hi, > > I want two python programs to communicate over stdIO channels. The > one executes the other via the popen3 function: > > amc = Popen3("./amc/amc.py", True, 0) > line = stdin.readline() > amc.tochild.write(line) > amc.tochild.flush() > print amc.fromchild.readlines() > > The problem is that although amc.tochild gets flushed the data > never reaches the client until the .tochild fd is closed. Is there > any way to put IO channels into non-blocking mode in python? How do you read the data in the client? Maybe you're using a line buffered read? Does your code work if the server includes a trailing CR and/or NL in the string before it calls the flush? Mathias From rtilley at vt.edu Thu Nov 4 19:21:33 2004 From: rtilley at vt.edu (Brad Tilley) Date: Thu, 04 Nov 2004 19:21:33 -0500 Subject: win 2003 server In-Reply-To: <0-GdnfNAPrb1XxfcRVn-sw@powergate.ca> References: <0-GdnfNAPrb1XxfcRVn-sw@powergate.ca> Message-ID: <418AC78D.50804@vt.edu> Peter Hansen wrote: >> Does Python run on Windows Server 2003? >> >> http://www.python.org/download/download_windows.html only lists the >> following: >> >> Python for Windows 95, 98, NT, 2000, ME, XP > > > I'm fairly sure "Windows Server 2003" is in no way significantly > different from one or more of the above items you list. That's the list from Python's Windows Download page... not my list. > If you have a copy, downloading and installing a copy of Python > would be the most direct route to proving that theory. I'm buying a new server. I want to make sure Python will run on the OS. From peter_ammon at rocketmail.com Mon Nov 15 19:08:00 2004 From: peter_ammon at rocketmail.com (Peter Ammon) Date: Mon, 15 Nov 2004 16:08:00 -0800 Subject: nonblocking read() Message-ID: I would like to read from a pipe in which data may arrive slowly. From experimenting, it looks like os.read() will block until it returns the maximum amount of data you asked for, in the second parameter to read(), or until it hits EOF. I cannot find a way to return only the data that the file object has immediately available. If no data is available, blocking is OK. The only workaround I can think of is to call select() in a loop, reading and storing one byte each time, and then returning them when select() indicates that the pipe is not ready for reading. Are there better approaches? Thanks, -Peter From news at NOwillmcguganSPAM.com Fri Nov 26 13:48:08 2004 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 26 Nov 2004 18:48:08 +0000 Subject: Number of colors in an image In-Reply-To: References: Message-ID: <41a77a69$0$1067$db0fefd9@news.zen.co.uk> Laszlo Zsolt Nagy wrote: > Hello, > > How can I determine the number of colors used in an image? I tried to > search on Google but I could figure out. I read the PIL handbook but I > do not see how to do it. Can anyone help? You may get a better response on how to do it in Python, but the following C++ code should be easy to translate if necessary. All it requires is a get pixel function. int CImage::CountUsedColours() const { if ( !IsValid() ) { Error( errImageInvalid ); return 0; } const int TableSize= ( 256 * 256 * 256 ) / 8; byte CountTable[ TableSize ]; memset( &CountTable[0], 0, TableSize ); for( int Y= 0; Y < GetHeight(); Y++ ) { byte* pColour= (byte*)GetLinePointer( Y ); int WidthCount= GetWidth(); while( WidthCount-- ) { const CColour colPix= GetPixel( pColour ); const int Offset= (int)colPix.R << 16 | (int)colPix.G << 8 | (int)colPix.B; CountTable[ Offset >> 3 ] |= 1 << ( Offset & 7 ); pColour+= GetBPP(); } } int ColourCount= 0; for( int n= 0; n < TableSize; n++ ) { const int CountBits= CountTable[n]; ColourCount+= ( CountBits & 1 ); ColourCount+= ( CountBits >> 1 ) & 1; ColourCount+= ( CountBits >> 2 ) & 1; ColourCount+= ( CountBits >> 3 ) & 1; ColourCount+= ( CountBits >> 4 ) & 1; ColourCount+= ( CountBits >> 5 ) & 1; ColourCount+= ( CountBits >> 6 ) & 1; ColourCount+= ( CountBits >> 7 ); } OK(); return ColourCount; } Regards, Will McGugan From nicolas.riesch at genevoise.ch Tue Nov 9 10:41:18 2004 From: nicolas.riesch at genevoise.ch (nico) Date: 9 Nov 2004 07:41:18 -0800 Subject: unicode string literals and "u" prefix References: <418fed14$0$156$9b622d9e@news.freenet.de> Message-ID: Thank you a lot for your answer. I understand better, now. Nevertheless, all this unicode issue is quite confusing for beginners ( I started to learn Python two month ago... ). And it seems that I am not the only one in this case. In fact, I just came across this discussion of april 2003 "[Zope3-dev] i18n, unicode, and the underline" http://mail.zope.org/pipermail/zope3-dev/2003-April/006410.html. Working for an insurance company, most of our data contain french accented characters. So, we are condemned to work essentially with unicode strings. In fact, it is hard to find examples where plain ascii strings would be useful in our case. Even data we retrieve from databases are returned to us as unicode strings. That's why I tried to find a way to get rid of all those "u" prefixes instead of systematically putting it in front of each unicode string litteral, which is somewhat "noisy". That's also because I am afraid that sometime someone will forget this "u" prefix, and errors will be detected in a far more later stage, or too late. A way of defaulting all string literal as unicode would have been a relief. It would be good if we could just write a declaration at the beginning of the source file like # strings_are_unicode_by_default We would write unicode strings without "u" prefix like this: s="?l?ment" and if we really must have plain ascii strings, we could explicitely prefix them with "a", for instance s=a"my plain ascii string". Thus, everybody would be happy, and there will be no incidence about all the already written codes or librairies. But there must be issues I am not aware of, I suppose... I think you have the same problem when you write strings in german language. But if it is no problem for you to prefix your strings with "u" like in : s=u"Vielen Dank f?r Ihre Antwort" then we can live with it too, for the next twenty years. Sometimes, I feel like an ethnical minority, when I see in a well-known book about Python that "Because Unicode is a relatively advanced and rarely used tool, we will omit further details in this introductory text." Working in a language with accented characters is definitively bad luck. Freundliche Gr?sse Nicolas Riesch From missive at frontiernet.net Sat Nov 27 11:07:41 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 27 Nov 2004 16:07:41 GMT Subject: Introduction/box References: <25dfq09do1vvpd62b6bkjn73np33m3761j@4ax.com> Message-ID: On 2004-11-26, Christos TZOTZIOY Georgiou wrote: > On Fri, 26 Nov 2004 22:21:45 +0000, rumours say that cm012b5105 > might have written: > >>Hello every body this is my first post i would just like to say im new to to >>python iv tried out several different tutorials.And i think its great anyway >>i would like to ask a question if i may i want to know how to make a >>box /square i was hoping some one would tell me. That way i would have >>something to work off,iv just downloaded pygame and i haqve done all my >>practice using "idle" thanks > > I know almost nothing about PyGame, but a quick search using Google > brought this up: > > http://aspn.activestate.com/ASPN/Mail/Message/pygame-users/2031142 > > It could help. Hmm... That's me wrote that, and I can't make heads or tails of it ;o) You might want to try pygsear (an extension package that uses pygame): http://www.nongnu.org/pygsear/ To make a box you could then do: >>> from pygsear.Drawable import Square >>> s = Square(side=100) >>> s.center() >>> s.udraw() >>> From uche at ogbuji.net Fri Nov 12 17:52:41 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 12 Nov 2004 14:52:41 -0800 Subject: Comparing two minidom objects References: <727daa7e.0411081033.276d5eba@posting.google.com> Message-ID: skip at pobox.com (Skip Montanaro) wrote in message news:<727daa7e.0411081033.276d5eba at posting.google.com>... > I'd like to compare two xml.dom.minidom objects, but the naive attempt fails: > > >>> import xml.dom.minidom > >>> d1 = xml.dom.minidom.parse("ES.xml") > >>> d2 = xml.dom.minidom.parse("ES.xml") > >>> d1 == d2 > False > > My goal is to decide whether or not I need to prompt the user to save config > information at the end of a program run by generating a minidom object then > comparing it with the last saved version. http://uche.ogbuji.net/tech/akara/nodes/2004-11-08/domlette-whitespace Last heading. Short answer: use c14n (xml.dom.ext.c14n in PyXML), or an XML smart tree compare function, such as the one that comes with 4Suite. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com A hands-on introduction to ISO Schematron - http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html Schematron abstract patterns - http://www.ibm.com/developerworks/xml/library/x-stron.html Wrestling HTML (using Python) - http://www.xml.com/pub/a/2004/09/08/pyxml.html XML's growing pains - http://www.adtmag.com/article.asp?id=10196 XMLOpen and more XML Hacks - http://www.ibm.com/developerworks/xml/library/x-think27.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ From arsalan_zaidi at hotmail.com Thu Nov 25 20:01:05 2004 From: arsalan_zaidi at hotmail.com (Arsalan) Date: 25 Nov 2004 17:01:05 -0800 Subject: Packing up zope+products as an exe? Message-ID: <583afd79.0411251701.28d8ca60@posting.google.com> Hi. Is it possible to bundle up a couple of products + zope as a single, easily distributable .exe? Something like py2exe, but for zope. And cross-platform (i.e. an .exe for Win* and binary for *nix) I want my users (esp windows ones) to be able to start up my zope stuff locally with just a click... Thanks in advance --Arsalan http://www.achates.biz From a.clarke11 at ntlworld.com Thu Nov 11 20:52:26 2004 From: a.clarke11 at ntlworld.com (Tony Clarke) Date: 11 Nov 2004 17:52:26 -0800 Subject: pickle: huge memory consumption *during* pickling References: Message-ID: <3353cd1e.0411111752.2d3175d3@posting.google.com> Hans Georg Krauthaeuser wrote in message news:... > Dear all, > > I have a long running application (electromagnetic compatibility > measurements in mode-stirred chambers over GPIB) that use pickle > (cPickle) to autosave a class instance with all the measured data from > time to time. > > At the beginning, pickling is quite fast but when the data becomes more > and more pickling slows down rapidly. >(Snip) > My feeling is that I'm doing something wrong. But my python knowlegde is > not so deep to see what that is. > > Is there an other way to perform an autosave of an class instance? Shelve? > > System: python 2.3.4, Win XP, 1.X GHz class PC, 512 MB ram > > Best redards > Hans Georg The tutorial books I read (including the Python Bible, I think) said that pickle shouldn't be used for large objects, so I try to limit it to smaller objects in small applications. I always wondered what they meant by large objects, maybe this is an illustration of that? :) Would it not be possible to save your data as a file, (or use a class method to download the stored data to a file) on your disc? You could always reload it from there for further use. Or split the class into several smaller ones, each of which might be more efficient at using pickle? Regards Tony Clarke From ialbert at mailblocks.com Wed Nov 10 13:56:27 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 10 Nov 2004 13:56:27 -0500 Subject: "Rails"-like thing for Python? In-Reply-To: References: Message-ID: <6vWdnbCSlZHH-Q_cRVn-rQ@giganews.com> Jeff Blaine wrote: > Specifically, I mean a generalized framework for > rapidly performing web application building. These are just words that you read on a page. Does it work that way? Is it all it is claiming to be? I'm a little skeptical. > I am curious if there is anything like the Rails framework for > Python? There are many excellent frameworks for python that may seem to be more modest by their descriptions but work exceedingly well nonetheless. Istvan. From falted at pytables.org Fri Nov 5 15:26:09 2004 From: falted at pytables.org (Francesc Altet) Date: Fri, 5 Nov 2004 21:26:09 +0100 Subject: ANN: PyTables 0.9 released Message-ID: <200411052126.09409.falted@pytables.org> Announcing PyTables 0.9 ----------------------- I'm proud to announce the availability of the newest and most powerful incarnation of PyTables ever . On this release you will find a series of exciting new features, being the most important the indexing capabilities, in-kernel selections, support for complex datatypes and the possibility to modify values in both tables *and* arrays. What is ------- PyTables is a hierarchical database package designed to efficiently manage extremely large amounts of data (supports full 64-bit file addressing). It features an object-oriented interface that, combined with C extensions for the peformance-critical parts of the code, makes it a very easy to use tool for high performance data saving and retrieving. It is built on top of the HDF5 library and the numarray package, and provides containers for both heterogeneous data (Tables) and homogeneous data (Array, EArray). It also sports a container for keeping lists of objects of variable length on a very efficient way (VLArray). A flexible support of filters allows you to compress your data on-the-flight by using different compressors and compression enablers. Moreover, its powerful browsing and searching capabilities allow you to do data selections over tables exceeding gigabytes of data in just tenths of second. Changes more in depth --------------------- New features: - Indexing of columns in tables. That allow to make data selections on tables up to 500 times faster than standard selections (for ex. doing a selection along an indexed column of 100 milion of rows takes less than 1 second on a modern CPU). Perhaps the most interesting thing about the indexing algorithm implemented by PyTables is that the time taken to index grows *lineraly* with the length of the data, so, making the indexation process to be *scalable* (quite differently to many relational databases). This means that it can index, in a relatively quick way, arbitrarily large table columns (for ex. indexing a column of 100 milion of rows takes just 100 seconds, i.e. at a rate of 1 Mrow/sec). See more detailed info about that in http://pytables.sourceforge.net/doc/SciPy04.pdf. - In-kernel selections. This feature allow to make data selections on tables up to 5 times faster than standard selections (i.e. pre-0.9 selections), without a need to create an index. As a hint of how fast these selections can be, they are up to 10 times faster than a traditional relational database. Again, see http://pytables.sourceforge.net/doc/SciPy04.pdf for some experiments on that matter. - Support of complex datatypes for all the data objects (i.e. Table, Array, EArray and VLArray). With that, the complete set of datatypes of Numeric and numarray packages are supported. Thanks to Tom Hedley for providing the patches for Array, EArray and VLArray objects, as well as updating the User's Manual and adding unit tests for the new functionality. - Modification of values. You can modifiy Table, Array, EArray and VLArray values. See Table.modifyRows, Table.modifyColumns() and the newly introduced __setitem__() method for Table, Array, EArray and VLArray entities in the Library Reference of User's Manual. - A new sub-package called "nodes" is there. On it, there will be included different modules to make more easy working with different entities (like images, files, ...). The first module that has been added to this sub-package is "FileNode", whose mission is to enable the creation of a database of nodes which can be used like regular opened files in Python. In other words, you can store a set of files in a PyTables database, and read and write it as you would do with any other file in Python. Thanks to Ivan Vilata i Balaguer for contributing this. Improvements: - New __len__(self) methods added in Arrays, Tables and Columns. This, in combination with __getitem__(self,key) allows to better emulate sequences. - Better capabilities to import generic HDF5 files. In particular, Table objects (in the HDF5_HL naming schema) with "holes" in their compound type definition are supported. That allows to read certain files produced by NASA (thanks to Stephen Walton for reporting this). - Much improved test units. More than 2000 different tests has been implemented which accounts for more than 13000 loc (this represents twice of the PyTables library code itself (!)). Backward-incompatible API changes: - The __call__ special method has been removed from objects File, Group, Table, Array, EArray and VLArray. Now, you must use walkNodes() in File and Group and iterrows in Table, Array, EArray and VLArray so as to achieve the same functionality. This will provide better compatibility with IPython as well. 'nctoh5', a new importing utility: - Jeff Whitaker has contributed a script to easily convert NetCDF files into HDF5 files using Scientific Python and PyTables. It has been included and documented as a new utility. Bug fixes: - A call to File.flush() now invoke a call to H5Fflush() so to effectively flushing all the file contents to disk. Thanks to Shack Toms for reporting this and providing a patch. - SF #1054683: Security hole in utils.checkNameValidity(). Reported in 2004-10-26 by ivilata - SF #1049297: Suggestion: new method File.delAttrNode(). Reported in 2004-10-18 by ivilata - SF #1049285: Leak in AttributeSet.__delattr__(). Reported in 2004-10-18 by ivilata - SF #1014298: Wrong method call in examples/tutorial1-2.py. Reported in 2004-08-23 by ivilata - SF #1013202: Cryptic error appending to EArray on RO file. Reported in 2004-08-21 by ivilata - SF #991715: Table.read(field="var1", flavor="List") fails. Reported in 2004-07-15 by falted - SF #988547: Wrong file type assumption in File.__new__. Reported in 2004-07-10 by ivilata Where PyTables can be applied? ------------------------------ PyTables is not designed to work as a relational database competitor, but rather as a teammate. If you want to work with large datasets of multidimensional data (for example, for multidimensional analysis), or just provide a categorized structure for some portions of your cluttered RDBS, then give PyTables a try. It works well for storing data from data acquisition systems (DAS), simulation software, network data monitoring systems (for example, traffic measurements of IP packets on routers), very large XML files, or for creating a centralized repository for system logs, to name only a few possible uses. What is a table? ---------------- A table is defined as a collection of records whose values are stored in fixed-length fields. All records have the same structure and all values in each field have the same data type. The terms "fixed-length" and "strict data types" seem to be quite a strange requirement for a language like Python that supports dynamic data types, but they serve a useful function if the goal is to save very large quantities of data (such as is generated by many scientific applications, for example) in an efficient manner that reduces demand on CPU time and I/O resources. What is HDF5? ------------- For those people who know nothing about HDF5, it is a general purpose library and file format for storing scientific data made at NCSA. HDF5 can store two primary objects: datasets and groups. A dataset is essentially a multidimensional array of data elements, and a group is a structure for organizing objects in an HDF5 file. Using these two basic constructs, one can create and store almost any kind of scientific data structure, such as images, arrays of vectors, and structured and unstructured grids. You can also mix and match them in HDF5 files according to your needs. Platforms --------- I'm using Linux (Intel 32-bit) as the main development platform, but PyTables should be easy to compile/install on many other UNIX machines. This package has also passed all the tests on a UltraSparc platform with Solaris 7 and Solaris 8. It also compiles and passes all the tests on a SGI Origin2000 with MIPS R12000 processors, with the MIPSPro compiler and running IRIX 6.5. It also runs fine on Linux 64-bit platforms, like AMD Opteron running GNU/Linux 2.4.21 Server, Intel Itanium (IA64) running GNU/Linux 2.4.21 or PowerPC G5 with Linux 2.6.x in 64bit mode. It has also been tested in MacOSX platforms (10.2 but should also work on newer versions). Regarding Windows platforms, PyTables has been tested with Windows 2000 and Windows XP (using the Microsoft Visual C compiler), but it should also work with other flavors as well. Web site -------- Go to the PyTables web site for more details: http://pytables.sourceforge.net/ To know more about the company behind the PyTables development, see: http://www.carabos.com/ Share your experience --------------------- Let me know of any bugs, suggestions, gripes, kudos, etc. you may have. Bon profit! -- Francesc Altet From donn at u.washington.edu Mon Nov 22 12:30:13 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 22 Nov 2004 09:30:13 -0800 Subject: Buffer problem on SunOS References: Message-ID: In article , gaool at caramail.com (gaool) wrote: ... > If the responses of the send command are big, it fill the buffer and I > can see as much lines of the response as the buffer size. And I don't > see the rest of my response. > > Apparently, it doesn't depend on the buffer size argument of Pipedream > module. > > In fact, it seems that there is a SunOS buffer but I don't know its > size and what I have to do to set it or to delete it. I'm not acquainted with this "Pipedream" module, but you may be interested to know that the UNIX operating system provides a system level read(2) function that does not buffer any input. If you apply this function to a pipe file descriptor, it will return with whatever data was in the pipe, or block if there is no data. That function is available in the posix module, a.k.a. os module. There's a pretty good chance however that it won't help, because the data is indeed sitting in a buffer on the other side of the pipe. That isn't a SunOS buffer per se, except inasmuch as it's provided by the C stdio library functions that your application probably calls for output. If it can be rewritten to flush its output regularly, that will help. Otherwise the only thing you can do is try to create a "pseudotty" instead of a pipe, because standard buffering policy changes to line buffered on a tty. There are modules for this, but you may find an openpty() function in the posix module that will work for your purposes. In any case this is not a simple solution, nor a cheap one in terms of system resources. Donn Cave, donn at u.washington.edu From steven.bethard at gmail.com Mon Nov 1 15:32:04 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 1 Nov 2004 13:32:04 -0700 Subject: sublcassing dict without losing functionality Message-ID: I'd like to subclass dict to disallow overwriting of keys, something like: >>> class SafeDict(dict): ... def __setitem__(self, key, value): ... if key in self: ... raise KeyError('cannot assign value %r to key %r, value %r' ... 'already exists' % (value, key, self[key])) ... super(SafeDict, self).__setitem__(key, value) ... The problem is, dict doesn't appear to call __setitem__ in any of the __init__ forms, so none of the following raise errors as I'd like them to: >>> SafeDict({'one':1}, one=2) {'one': 2} >>> SafeDict([('one', 1), ('one', 2)]) {'one': 2} >>> SafeDict([('one', 1), ('one', 2)], one=3) {'one': 3} >>> SafeDict(('one', x) for x in (1, 2)) {'one': 2} etc. Is there a simple way to override this behavior in dict without having to rewrite __init__? There are so many cases in dict.__init__ that I'm hesitant to try to reproduce them all... Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From austin at maxtronic.com.tw Mon Nov 1 00:48:57 2004 From: austin at maxtronic.com.tw (Austin) Date: Mon, 1 Nov 2004 13:48:57 +0800 Subject: How to change the combo box lists as my wish Message-ID: <4185ce3d$1@news.seeder.net> ................. self.diskList = ['3','4','5'] self.cB = wxComboBox(self,-1,wxDefaultPosition,wxDefaultSize,self.diskList) ................. The code is executed initially. If i want to update only the diskList, what could i do? From jim at zope.com Mon Nov 15 16:01:10 2004 From: jim at zope.com (Jim Fulton) Date: Mon, 15 Nov 2004 16:01:10 -0500 Subject: Zope 3.0, and why I won't use it In-Reply-To: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> Message-ID: exarkun at intarweb.us wrote: > On 14 Nov 2004 11:09:38 -0800, hwlgw at hotmail.com (Will Stuyvesant) wrote: > >>Hello all, >> ... >>What amazed me is they write that they "added types to the variables >>and hope that it will be added to the Python project too". We didn't say that. A reporter said that. As Martijn pointed out, this was probably a missunderstanding of our work on interfaces. > > > Guido has repeatedly stated that a future version of Python will include static type support. The Zope project has driven numerous past changes to Python. What's funny about this? For the record, I'm against static typing for Python, although, if Guido decides he wants it, I have an open mind. :) Jim -- Jim Fulton mailto:jim at zope.com Python Powered! CTO (540) 361-1714 http://www.python.org Zope Corporation http://www.zope.com http://www.zope.org From apardon at forel.vub.ac.be Wed Nov 17 06:48:40 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Nov 2004 11:48:40 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: Op 2004-11-17, Tim Peters schreef : > [Uncle Timmy, explains why Python requires so little of platform > threads] > > [Antoon Pardon] >> I don't fault the current Queue implementation. I think your arguments >> are very strong > > I don't <0.5 wink>. Threading support in Python is forever frustrated > by the seeming need not to make trouble for the oddball thread > implementations we have but aren't even sure anyone uses anymore. For > example, the Python core could benefit from exploiting > platform-supplied thread-local-storage gimmicks. But we never move in > that direction, because the prospects of implementing it for all the > existing thread_PLATFORM.h wrappers appear too dim. Instead we rolled > our own implementation of thread-local storage, again building on no > more than "the Python lock". It's not particularly efficient, and > especially not after I fixed a critical thread race in it just a few > weeks ago, effectively serializing all lookups. > > If Python *could* assume, e.g., that only pthreads boxes and Windows > are still interesting (it's clearly impossible that we could get away > with supporting a set that doesn't include those two; it's not clearly > impossible that we could get away with supporting only those two), > then we could assume a much richer set of platform-supplied threading > primitives to build on. Couldn't it be possible to have a general solution that works on any kind of box and provide (or let interested parties provide) an implementation that is better suited for particular boxes? >> But by limiting the signal module as it is now you make >> it that much harder for people on posix systems to come up for a >> different implementation on those systems. > > Who's "you"? It can't be me. Since I normally run on Windows, I pay > no attention to the signal module, let alone stay up nights plotting > to make it harder to live with. Guido is another matter; search > Google for, e.g, quotes like [ quotes from Guido ] Sorry about that, that was the general you meaning those that decide what gets into python and what not. And yes I understand Guido has some religious convictions and these influence on what he allows in python and what not. > I confess I had a similar hatred of signals in my Unixish days (they > weren't portable, weren't reliable, & usually created debugging > nightmares much worse than the problems uses of signals were > introduced "to solve"), but Guido is the one who'll stab you in the > back today. I'll just cheer him on . Look, I understand perfectly. Use of signals is never my first choice. However there sometimes seem to be circumstances when signals are the lesser evil. My impression is also that the python people seem to have some obligation to help in debugging peoples programs. This is laudable in general but I also have the impression that this obligation puts limits on what they want to allow in the language. If I hear people argueing about why some things are missing I get the impression something like the following argument line is followed I don't want to be bothered by the mess that can originate from ill use of such a feature, I don't want to look trough code that doesn't work from someone who doesn't understand how to use this feature properly. So we don't include the feature in the language (or only put the C-function in). And that is something I find regretable. >> The problem I have with the current implementation is not so much one >> of burden on the system but one of possible "starvation" of a thread. >> >> Suppose we have a number of consumers on a Queue, some simply >> block and others use timeouts. The current implementation disfavors >> those threads with a timeout too much IMO, because the block >> threads ask for the lock continuosly while the timeout threads only >> ask for the lock periodically. > > That's certainly true. OTOH, I've never written, or worked with, an > app where, for a given Queue, some threads used timeouts but others > didn't. It seems strained to me. Then again, I'm not sure I've ever > worked on a real app where any thread used a timeout gimmick with a > Queue. Sure but simple Locks can't have a timeout. So if you only need locks with a timeout then you use Queues that can only have 1 element. I agree that having multiple thread accessing the same queue some with a timeout and others not, is strange. But I think it is less strange if you have multiple threads accessing the same lock, some with timeouts and others not. -- Antoon Pardon From aleaxit at yahoo.com Tue Nov 16 13:45:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 16 Nov 2004 19:45:29 +0100 Subject: adaptation References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> <1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com> <1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> <419A16CE.3050907@bellsouth.net> Message-ID: <1gncxxb.10h9cii1kmx5jN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > Well, my name is not Alex, and my answer will probably fall short of a > comprehensive definition :-) But let's see if I can help here... I think you did a great job! May I recommend some further reading...: http://www.python.org/peps/pep-0246.html http://www.aleax.it/os04_pydp.pdf http://peak.telecommunity.com/protocol_ref/module-protocols.html > Adaptation is the act of taking one object and making it conform to a > given protocol (or interface). Adaptation is the key to make dynamic > code that takes parameters from arbitrary types work in a safe, well > behaved way. Hear, hear! > The basic concept underlying adaptation is the "protocol", also called > "interface" in some implementations. For all purposes of this > discussion, and for simplicity reasons, we can safely assume that > protocols and interfaces are equivalent. Right, but, for the curious...: "Interface" mostly describes a certain set of methods and their signatures; "Protocol" adds semantics and pragmatics -- some level of conceptualization of what the methods _do_ and constraints on how they are used (e.g. "after calling .close(), no other method can ever be called on the object any more"). This is a reasonably popular use of the words in question, though far from universal. > A protocol is a set of primitives that is supported by a given object. > For example: the iterator protocol defines the following primitives: > __iter__ and next() (as documented in > http://docs.python.org/lib/typeiter.html). Any object from any class > that implement these methods, regardless of its ancestors, is said to > support the iterator protocol. ...if the semantics and pragmatics are also respected, e.g.: x.__iter__() is x > Any object that supports the iterator protocol can be used whenever an > iterable is acceptable. This includes for loops and list > comprehensions. The biggest advantage of adaptation comes when one > realize how flexible this design is, specially when compared with > old-style type checking. In a old-style type checking environment, > parameters to a given routine must conform to the declared type of the > arguments. For iterators, it would mean that only objects descending > from some abstract class (let's say, "Iterable") would be accepted. > Now, even with multiple inheritance, this design is severely limited. In old-style Python, inheritance isn't really the issue (except for exceptions, where inheritance does matter). Rather, a protocol is defined by a given set of methods. An iterable is an object supplying a special method __iter__ which, called without arguments, returns an iterator (any object which respects the iterator protocol). A sequence besides being iterable supports __len__, AND __getitem__ with integer and slice arguments, and there is a rich semantic and pragmatic web of mutual constraints between behavior of __getitem__ and __len__ and iteration. A mutable sequence is a sequence which also supports __setitem__ (again with specific constraints wrt __getitem__, __len__...) and is also supposed to expose a rich set of other methods such as pop, append, extend, etc, etc. This IS great BUT limited by what the LANGUAGE designer(s) sanction(s) as 'blessed protocols'. There are quite a few, but they're never enough to cover the needs of an application or field of applications, of course. With protocols based on certain special methods, you have a great concept which however is not really extensible, nor flexible enough to help the authors of large frameworks and applications. Framework authors do define new protocols, of course -- they can't help doing that. "X must be an object supplying methods 'foo' and 'bar' with the following constraints...:". This is OK for somebody who's writing an application using just one framework -- they can code their classes to the framework's specifications. The problem comes in when you're writing an application that uses two or more frameworks... the two frameworks likely haven't heard of each other... one wants objects supplying 'foo' and 'bar, the other supplies objects supplying 'oof' and 'rab' instead, with subtly different semantics and pragmatics. So, what do you do then? You write adapters: wrappers over Y with its oof and rab which provide an X with its foo and bar. Python is _great_ at that kind of job! But, who applies the adapters, where, when? Well, unless we do get PEP 246 in... _you_, the application writer, are the only one who can. You'd like to spend your time developing your application, with frameworks to relieve you from some parts of the job, but to do that you also need to develop adapters _and_ tediously, boilerplatishly, apply them to every object from one framework that's going over to the other, etc. Basically, you risk ending up with very *thick glue* (cfr Eric Raymond's excellent "The Art of Unix Programming", great book also available online for free) -- throughout your application, there will be knowledge about the details of all frameworks you're using, spread in thick layers of glue. > Now, back to Python world. In many situations, there is no need for > adaptation; the object itself supports the protocol, and can be > supplied directly. But there are situations when the object itself > can't be immediately used; it has to be adapted, or prepared, to > support the protocol. Another situation is when an object is passed to > a routine that *doesn't* support the required protocol; this is an > error, that can be catched by the adapt() framework in a superficially > similar but fundamentally different approach from type checking (and > that's whats Alex has been pointing out). Oh yes, VERY different. Let me try an analogy... A policeman's job is to ensure you respect the law. He does that by trying to catch you violating the law, and punishing you for that. A civics teacher's job is to ensure you respect the law. He does that by teaching you the law, explaining its rationale, engaging you in discussion to find instances where your spontaneous behavior might violate the law, and working out together with you how to adapt your behavior and your instincts so that the law gets respects. Type checking is a policeman. Adaptation is a civics teacher. > The adapt protocol (as presented on PEP246 - > http://www.python.org/peps/pep-0246.html) defines a very flexible > framework to adapt one object to a protocol. The result of the ...and yet the text of PEP 246 is still missing the specs about registering "third party adapters". Phil Eby's PyProtocols is much better that way!!! (I promise I'll do something about PEP 246 updating: just as soon as I'm done with the 2nd ed of the cookbook....!!!!). > adaptation (if possible) is an object that is guaranteed to support > the protocol. So, using adapt(), we can write code like this: > > def myfunc(obj): > for item in adapt(obj, Iterable): > ... Hmmm, yes, we can. It's a standard protocol so not the best of examples, but still, it may be meaningful. > Finally, one may be wondering, is there any situation when an object > needs to be "adapted"? Why don't just check for the availability of > the interface? There are many reasons to use the adapt framework. The > protocol checking is one of the reasons -- it allows errors to be > catched much earlier, and at a better location. Another possible > reason is that complex objects may support several protocols, and > there may be name clashes between some of the methods. One such > situation is when an object support different *versions* of the same > protocol. All versions have the same method names, but semantics may > differ slightly. The adapt() call can build a new object with the > correct method names and signatures, for each protocol or version > supported by the object. Finally, the adaptation method can optionally > build an opaque "proxy" object, that hides details of the original > methods signature, and it's thus safer to pass around. The main motivation I'd give is that different frameworks not knowing about each other may define [1] what the object supplies and [2] what the object is REQUIRED to supply -- there are often discrepancies, and an adapter in-between is gonna be required. With 246 (once suitably updated;-) we can write the adapter ONCE, register it in a suitable global registry, and 'adapt' will just find it. Oh bliss -- as long as adapt DOES get called all over the place!-) > Well, that's a broad overview of the subject. There is a lot of stuff > to learn, and using adaptation properly is something that takes some > time. Hope it helps. My compliments for your excellent presentation! I hope my enrichment of it may have proved useful rather than distracting.... Alex From lbates at syscononline.com Tue Nov 2 13:49:53 2004 From: lbates at syscononline.com (Larry Bates) Date: Tue, 02 Nov 2004 12:49:53 -0600 Subject: dicts & lists together In-Reply-To: References: Message-ID: Brad Tilley wrote: > I have a dict that associates strings to numbers like this {'abc': 1, > 'xyz':2, '123':3,...} I am then given a list of strings ['abc', 'xyz', > '123',...] and asked to associate a number to each string in the list > according to the string's value in the dict. I am at a loss as to how to > do this, can someone show me where to start? >>> xdict={'abc': 1, 'xyz':2, '123':3} >>> xlist=['abc', 'xyz', '123'] >>> tlist=[xdict.get(v, None) for v in xlist] >>> print tlist [1, 2, 3] Larry Bates Syscon, Inc. From peter at engcorp.com Tue Nov 16 22:27:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Nov 2004 22:27:54 -0500 Subject: ctypes, accessing uInt32 and pointer to uInt32 In-Reply-To: References: Message-ID: Andrew Markebo wrote: > I am taking the first steps letting python access a c-function in a > .dll-file, but need some help getting it right. WHat am I missing? For posterity: this was also asked, and answered, in the ctypes mailing list. (The answer was, roughly, "__stdcall means use windll, not cdll".) -Peter From wolfgang.keller.nospam at gmx.de Mon Nov 29 12:28:07 2004 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Mon, 29 Nov 2004 18:28:07 +0100 Subject: Parallel Python on PowerMac? Message-ID: <1p1mclu2nq7e8$.1o0rc9ygt2rdy$.dlg@40tude.net> Hello, as I might get a dual-G5 PowerMac someday in the not to distant future, I was wondering what options are available for making Python benefit from the second CPU? Running two interpreters and using Pyro would not be the most efficient (and easiest) way, I guess? TIA, Best regards Wolfgang Keller From svenn.are at bjerkem.de Wed Nov 10 02:57:09 2004 From: svenn.are at bjerkem.de (Svenn Are Bjerkem) Date: Wed, 10 Nov 2004 08:57:09 +0100 Subject: Help on installing PyQt on MacOSX 10.3 needed In-Reply-To: References: <2vcc6oF2i91ltU1@uni-berlin.de> Message-ID: Kevin Walzer wrote: > Svenn Are Bjerkem wrote: > > | > | you are perfectly right. I went back to the documentation and paid a bit > | more attention and with your information in mind, I now see that it is > | talking about a selfcontained python with pyqt. I guess that I want to > | use the qt bindings *dynamically*. That means that I have to find a way > | to tell Python where to find the pyqt that I installed. > | > | In tcl I would either have installed into a directory in auto_path or I > | would have extended auto_path. How is this done in Python? > | > > PyQt is installed in the site-packages directory on OS X--there's > nothing special you need to do, it "just works" and loads up fine. Well, then I must have done something wrong since I get the error message that there is no module called qt available. On the command line of Python I did import sys and print sys.path to get the built-in search path. I checked the location where make install put the pyqt build vs the list of directories in sys.path and found that Python *should* be able to find pyqt. (There is a README file in that directory saying that this is the place to put third-party files, but I don't know if I have to do anything special in that sites.py which is mentioned in that README file) When I do import qt on the Python commandline, which file(s) in the third-party directory will be searched for first? If I knew that I could check if make install was successful generating all needed files. -- Svenn From snesbitt at cobaltgroup.com Mon Nov 22 18:00:46 2004 From: snesbitt at cobaltgroup.com (Stephen Nesbitt) Date: Mon, 22 Nov 2004 15:00:46 -0800 Subject: Introspection Question: Determining subclass name in base class Message-ID: <200411221500.46534.snesbitt@cobaltgroup.com> All: Here's my implementation problem. I have a base class which has the responsibility for providing entry into the logging system. Part of the class responsibility is to ensure that lagger names are consistent. For all intents and purposes this class should be considered abstract and will always be subclassed. What I want to do is the following: - allow the logger name to set explicitly. I've accomplished this by adding a loggerName parameter to __init__ in the base class. - if the loggerName variable is None, then set it to the name of the subclass for which we are initing. There seem to be two issues here. 1) determining the subclass name inside the _init__method in the abstract base class. All my efforts so far have resulted in the name of the base class rather than the calling subclass. 2) setting the default of a parameter to a function. Can anyone help? Thanks! -steve -- Stephen Nesbitt Senior Configuration Management Engineer The Cobalt Group 206.219.8271 snesbitt at cobaltgroup.com From usenet_spam at janc.invalid Mon Nov 22 19:09:37 2004 From: usenet_spam at janc.invalid (JanC) Date: Tue, 23 Nov 2004 00:09:37 GMT Subject: instant messenging References: <2004112108293216807%craig@yumaca> Message-ID: Lucas Raab schreef: > Ah, could you possibly have a zip file?? I looked on your site and > downloaded the BZ2 file, but I'm not sure how to extract it. I have > Cygwin for another application, but I don't know how to get the files > out the BZ2. So either a ZIP file or instructions on extracting files in > BZ2 files would be greatly appreciated. I think Cygwin has bzip2 & tar to extract files from .bz2 archives? If you prefer a GUI application, try 7-Zip: (version 3.13, don't use 4.x yet) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From apm35 at student.open.ac.uk Tue Nov 30 17:37:35 2004 From: apm35 at student.open.ac.uk (apm) Date: 30 Nov 2004 14:37:35 -0800 Subject: ANNOUNCE: Ice 2.0 released References: <22868227.0411300634.1d333921@posting.google.com> <0YidnREmZ8xECDHcRVn-oA@speakeasy.net> Message-ID: Marc Laukien wrote in message news:<0YidnREmZ8xECDHcRVn-oA at speakeasy.net>... > 100% of the Ice source code has been developed by ZeroC employees. Fixes, bug reports, and enhancement requests have come in from Open Source developers around the world, as can be seen from the forums on the ZeroC web site. Regards, Andrew Marlow From exarkun at divmod.com Thu Nov 18 01:06:52 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 18 Nov 2004 06:06:52 GMT Subject: imaplib ... understanding the result from a fetch of RFC822s In-Reply-To: <419bb3a7$0$259$edfadb0f@dread12.news.tele.dk> Message-ID: <20041118060652.27631.789348231.divmod.quotient.1921@ohm> On Wed, 17 Nov 2004 21:26:35 +0100, Max M wrote: >I am using the fetch command from the imaplib to fetch messages. I get a > result, but I am a bit uncertain as to how I should interpret it. > > The result is described at http://pydoc.org/2.3/imaplib.html as:: > > (typ, [data, ...]) = .fetch(message_set, message_parts) > > In RFC 2060 it says: "The data items to be fetched can be either a > single atom or a parenthesized list." > > So I do a fetch like: > > mailconn.uid('fetch', '1:*', '(RFC822)') > > As a result I receive the following results (from 2 different servers): > > # mailserver 1 > messages = [ > ('1 (UID 2 RFC822 {616}', "Received: from SNIP..."), > ')', > ('2 (UID 4 RFC822 {626}', "Received: from SNIP..."), > ')', > ] > > # mailserver 2 > > messages = [ > ('1 (RFC822 {1155}', "Return-path: SNIP..."), > ' UID 1)', > ('2 (RFC822 {977}', "Return-path: SNIP..."), > ' UID 2)', > ('3 (RFC822 {1016}', "Return-path: SNIP..."), > ' UID 3)', > ('4 (RFC822 {1153}', "Return-path: SNIP..."), > ' UID 4)', > ('5 (RFC822 {732}', 'Mime-Version: SNIP...'), > ' UID 5)', > ] > > It's just a long list which seems to have the structure: > > list = [ > (envelope start, rfc288-message), envelope-end, > (envelope start, rfc288-message), envelope-end, > (envelope start, rfc288-message), envelope-end, > ] > > To me this is an odd format. It's sort of a parenthesized list, but not > really. > > I guess that I can iterate it like: > > for ((envelopeStart, msg), envelopeEnd) in range(0, len(messages), 2): > # do stuff > > But I feel a bit uncertain that it won't break in some edge cases. > > Does anybody have a clue as to why imaplib returns results like that? > Parsing IMAP4 is rather involved. imaplib does a minimal job of it, and leaves many of the details up to you. For a more complete parser, see Twisted's IMAP4 support: http://www.twistedmatrix.com/ Jp From roy at panix.com Fri Nov 5 08:48:36 2004 From: roy at panix.com (Roy Smith) Date: Fri, 05 Nov 2004 08:48:36 -0500 Subject: ?? Modules for GPIB and Ethernet ?? References: <21240387.0411041337.7b17172b@posting.google.com> <0-GdnfBAPrZPXBfcRVn-sw@powergate.ca> <21240387.0411050533.4d145e2a@posting.google.com> Message-ID: In article <21240387.0411050533.4d145e2a at posting.google.com>, justinhsia at yahoo.com (Chaser) wrote: > I have an equipment that's controlled through ethernet. (The control > program is currently written in C++.) I guess my really difficulty > is, how do I send commmands to that devise through ethernet using > Python? You havn't given enough information to give a good answer, but I'll take a shot. First, you need to know what kind of protocol your device talks. It's virtually certain that the device implements some kind of custom application-level protocol on top of some standard transport layer such as TCP/IP. Assuming that's the case, you need to: 1) Find the documentation for the application-level protocol it talks. 2) Find out the IP address (or hostname) of the device. >From within Python, you will need to create a socket, connect the socket to your device using the connect() method, and then use the send() and recv() methods to talk to the device. You'll need to implement the application-layer protocol yourself. The details of how to use sockets in Python (i.e. connect(), send(), recv(), etc) are documented in "7.2 socket -- Low-level networking interface" of the Python Library Reference. To really understand what section 7.2 is talking about, however, you need to have a general feel for how network communication works in general. Fortunately, the introduction to section 7.2 contains some pointers to some good general reference books. From bowman at montana.com Tue Nov 2 09:05:02 2004 From: bowman at montana.com (bowman) Date: Tue, 02 Nov 2004 07:05:02 -0700 Subject: Matching Control Characters References: Message-ID: <2upifrF2d4fc5U3@uni-berlin.de> Greg Lindstrom wrote: > > Thank-you. That does the trick! If you would be so kind, where does one > look up the escape values for control sequences? As they say: Build a man > a > fire and he's warm for a day. Set a man on fire and he's warm for the > rest of his life. If you are on a *nix box, try 'man ascii'. The applicable part is: C program '\X' escapes are noted. Oct Dec Hex Char Oct Dec Hex Char ------------------------------------------------------------ 000 0 00 NUL '\0' 100 64 40 @ 001 1 01 SOH 101 65 41 A 002 2 02 STX 102 66 42 B 003 3 03 ETX 103 67 43 C 004 4 04 EOT 104 68 44 D 005 5 05 ENQ 105 69 45 E 006 6 06 ACK 106 70 46 F 007 7 07 BEL '\a' 107 71 47 G 010 8 08 BS '\b' 110 72 48 H 011 9 09 HT '\t' 111 73 49 I 012 10 0A LF '\n' 112 74 4A J 013 11 0B VT '\v' 113 75 4B K 014 12 0C FF '\f' 114 76 4C L 015 13 0D CR '\r' 115 77 4D M 016 14 0E SO 116 78 4E N 017 15 0F SI 117 79 4F O 020 16 10 DLE 120 80 50 P 021 17 11 DC1 121 81 51 Q 022 18 12 DC2 122 82 52 R 023 19 13 DC3 123 83 53 S 024 20 14 DC4 124 84 54 T 025 21 15 NAK 125 85 55 U 026 22 16 SYN 126 86 56 V 027 23 17 ETB 127 87 57 W 030 24 18 CAN 130 88 58 X 031 25 19 EM 131 89 59 Y 032 26 1A SUB 132 90 5A Z 033 27 1B ESC 133 91 5B [ 034 28 1C FS 134 92 5C \ '\\' 035 29 1D GS 135 93 5D ] 036 30 1E RS 136 94 5E ^ 037 31 1F US 137 95 5F _ 040 32 20 SPACE 140 96 60 ` From ianb at colorstudy.com Tue Nov 2 18:07:03 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 02 Nov 2004 17:07:03 -0600 Subject: HTML to Text renderer Message-ID: <41881317.2070803@colorstudy.com> Does anyone know of a module that can render HTML to text? Just a subset of HTML, really; I'd like to compose emails using

tags and whatnot, fill in all the values in the email template, then apply word wrapping and other formatting. Also, it'll make using Zope Page Templates with email easier. Even if all it supports is

and
that would be enough, but I'm hoping there's something even more complete out there. I don't need something as general as, say, Lynx; these templates would be written with a specific renderer in mind. Thanks. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From Kingdom.Lin at yeah.net Sun Nov 21 00:41:27 2004 From: Kingdom.Lin at yeah.net (Donnie Leen) Date: Sun, 21 Nov 2004 13:41:27 +0800 Subject: Is Python/C api thread safety enough? Message-ID: <20041121054129.298591E4008@bag.python.org> Thanks for help. If the long-running function comes from third-party library such as zlib.compress(), we don't know wether the function is safety for python thread, it may cause error, how could we avoid this if we have to use it? ================================== >Casper wrote: >> Can sombody tell me is this possible? Thanks first. > >If you're going to call the Python C/API, you need to be holding the GIL. So you >either can't release it, or the long-running function has to use >PyGILState_Ensure when it needs to call the Python C/API. > >Cheers, >Nick. >-- >http://mail.python.org/mailman/listinfo/python-list > Donnie Leen From db3l at fitlinxx.com Mon Nov 29 19:14:54 2004 From: db3l at fitlinxx.com (David Bolen) Date: 29 Nov 2004 19:14:54 -0500 Subject: Number of colors in an image References: Message-ID: Christos "TZOTZIOY" Georgiou writes: > A set seems more appropriate in this case: > > color_count = len(set(izip(r, g, b))) # untested code Well, while potentially premature optimization, I was trying for performance in this case. In Python 2.3, the sets module is coded in Python, and just wraps a dictionary, and when handed an iterable, ends up looping (in Python) with individual dictionary key assignments. Although I didn't specifically test sets, when I did a loop like that myself, it was 5-6 times slower than directly building the dictionary. That might change in 2.4 with the built-in set - it's still a wrapper around dict but knows it's just directly setting items to a true value so can avoid dealing with the tuples that dict does (not to mention I don't have to build the extra tuple). Although I expect the direct support in PIL 1.1.5 that Fredrik posted about will be best. > >For a greyscale, or single banded image, it should be faster just to > >use the built-in PIL "histogram" method and take the length of the > >resulting list. > > More like the count of non-zero elements in the histogram; I believe the > length of the resulting list will be constant (ie 256). Oops, definitely yes. -- David From jhujsak at neotopica.com Wed Nov 17 20:06:56 2004 From: jhujsak at neotopica.com (Jon) Date: 17 Nov 2004 17:06:56 -0800 Subject: Parallel processing References: <5c882bb5.0411170239.2e5f61e2@posting.google.com> Message-ID: <51e59f27.0411171706.22a60438@posting.google.com> Josiah Carlson wrote in message news:... > bearophileHUGS at lycos.com (bearophile) wrote: > > > > Hello, this is a small tutorial page about NESL, an easy parallel > > programming language: > > http://www-2.cs.cmu.edu/~scandal/nesl/tutorial2.html > > > > Its syntax shares some similarities with python one, for example: > > > > function factorial(n) = > > if (n <= 1) then 1 > > else n*factorial(n-1); > > > > {factorial(i) : i in [3, 1, 7]}; > > > > This computes "in parallel, for each i in the sequence [3, 1, 7], > > factorial i" > > > > > > {sum(a) : a in [[2,3], [8,3,9], [7]]}; > > > > sum of sequences is already a parallel operation, so this is a nested > > parallelism example. > > The look of a language has nothing to do with its parallelizability. It > just so happens that the designers of NESL had a similar language design > ideas as the designers of Python. > > > > So it seems to me that Python can be already fit to be interpreted in > > parallel, for multicore CPUs, Playstation Cell-like processors, etc. > > (few things have to be changed/added in the syntax to make it fit for > > parallelism). > > There are various other reasons why Python is not as parallelizable as > you would think. Among them is the semantics of scoping, and whether > there is shared or unshared scope among the processors/nodes. If shared, > then any operation that could change scopes would need to be distributed > (ick), or if unshared, then you are basically looking at an > automatically distributed tuplespace (LINDA). It gets even uglier with > certain kinds of generators. > > Regardless of which one is the case, heavy modifications to Python would > necessarily need to be done in order to make them happen. > > > - Josiah Even considering the above caveats, one can still employ Python based interpretive layers such as pyMPI over quite solid parallel computing tools such as MPI. See http://pympi.sourceforge.net/. --Jon From lbates at syscononline.com Wed Nov 24 09:51:20 2004 From: lbates at syscononline.com (Larry Bates) Date: Wed, 24 Nov 2004 08:51:20 -0600 Subject: Book recommendation In-Reply-To: <30ictaF2vhlgoU1@uni-berlin.de> References: <30ictaF2vhlgoU1@uni-berlin.de> Message-ID: If you are running on Windows, "Python Programming on Win32" is a must buy/read. I also liked "Python Bible" a lot. Larry Bates Madhusudan Singh wrote: > Hi > > I am trying to teach myself Python. I have extensive prior programming > experience in Fortran, a little in C/C++, Pascal, etc. > > So far, I have been reading online tutorials at www.python.org and a book I > found at the library - Martin Brown's The Complete Reference Python. Is > there a standard classic book to learn from that I could buy ? > > Say something like Metcalf and Reid's Fortran 90/95 Explained or Kernighan > and Ritchie's The C Programming Language. > > From geskerrett at hotmail.com Tue Nov 30 09:57:21 2004 From: geskerrett at hotmail.com (Geoffrey) Date: 30 Nov 2004 06:57:21 -0800 Subject: Struggling with struct.unpack() and "p" format specifier Message-ID: <6b26402d.0411300657.d575d75@posting.google.com> Hope someone can help. I am trying to read data from a file binary file and then unpack the data into python variables. Some of the data is store like this; xbuffer: '\x00\x00\xb9\x02\x13EXCLUDE_CREDIT_CARD' # the above was printed using repr(xbuffer). # Note that int(0x13) = 19 which is exactly the length of the visible text # In the code I have the following statement; x = st.unpack('>xxBBp',xbuffer) This throws out the following error; x = st.unpack('>xxBBp',xbuffer) error: unpack str size does not match format As I read the documentation the "p" format string seems to address this situation, where the number bytes of the string to read is the first byte of the stored value but I keep getting this error. Am I missing something ? Can the "p" format character be used to unpack this type of data ? As I mentioned, I can parse the string and read it with multiple statements, I am just looking for a more efficient solution. Thanks. From wh2005 at web.de Sat Nov 20 12:40:38 2004 From: wh2005 at web.de (wolfgang haefelinger) Date: Sat, 20 Nov 2004 17:40:38 GMT Subject: unicode question Message-ID: Hi, I wonder whether someone could explain me a bit what's going on here: import sys # I'm running Mandrake 1o and Windows XP. print sys.version ## 2.3.3 (#2, Feb 17 2004, 11:45:40) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] ## 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] print "sys.getdefaultencoding = ",sys.getdefaultencoding() # This prints always "ascii" .. ## just a class class Y: def __str__(self): return self.c ## define unicode character (ie. string) gamma = u"\N{GREEK CAPITAL LETTER GAMMA}" y = Y() y.c = gamma ## works fine: prints greek capital gamma on terminal on windows (chcp 437). ## Mandrake 1o nothing gets printed but at least no excecption gets thrown. print gamma # (1) ## same as before .. print y.__str__() # (2) ## encoding error print y # (3) ?????????????? ## ascii encoding error .. sys.stdout.write(gamma) # (4) I wonder especially about case 2. I can see that "print y" makes a call to Y.__str__() . But Y.__str__() can be printed?? So what is 'print' exactly doing? Thanks for any help, Wolfgang. From steven.bethard at gmail.com Tue Nov 30 11:39:42 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 30 Nov 2004 16:39:42 GMT Subject: pre-PEP generic objects In-Reply-To: References: Message-ID: Peter Otten wrote: > Steven Bethard wrote: > >>def __eq__(self, other): >> """x.__eq__(y) <==> x == y""" >> return (isinstance(other, self.__class__) >> and self.__dict__ == other.__dict__) > > This results in an asymmetry: > [snip] > > Whether this is intended, I don't know. If someone can enlighten me... > > In any case I would prefer self.__class__ == other.__class__ over > isinstance(). Unintended. I'll switch to self.__class__ == other.__class__ or type(self) == type(other) Any preference? Steve From esj at harvee.org Mon Nov 1 23:20:56 2004 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 01 Nov 2004 23:20:56 -0500 Subject: saved sys.path In-Reply-To: <1gmlelr.q7q1rz5rc37oN%aleaxit@yahoo.com> References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> <1gmlelr.q7q1rz5rc37oN%aleaxit@yahoo.com> Message-ID: <41870B28.9050600@harvee.org> Alex Martelli wrote: > The modifications to sys.path performed by .pth files are visible to all > applications. A single application may (however it chooses to do so) > find out or determine a path it wants only for its own imports, and ...historical record deleted > Python is not particularly > different, from the point of view of "where does an app find its own > configuration information", from most other languages. from historical perspective, I understand and appreciate your explanation. However, just because it's historically accurate, does it mean we should keep doing things the same old way? In natlink, Joel Gould's python extensions to NaturallySpeaking, he made each speech recognition grammar environment either globally accessible or command specific. He used the expedient technique of using the same name as the command for the Python file containing the grammar associated with that command. He also used another simple technique, prefacing a filename with an "_" to indicate a globally visible grammar and code. Turns out this was a frightfully useful technique as it allows for partitioning grammars. Unfortunately, because of path problems it's difficult to share modules between various grammars. It seems to me that a similar technique would serve for our purposes. A file, command_name.path, would contain all of the search as necessary for a command called by the same name. this technique would allow for a common platform independent method of finding application-specific modules and automatically generated paths for site-specific relocation/configuration. As I write this, it occurs to me that a provisional body of code to experiment with the technique would possibly serve the community well. I will generate something tomorrow for public scrutiny as I am up past my bedtime. Thank you for triggering the idea. From anthonybaxter at gmail.com Tue Nov 30 08:51:13 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Wed, 1 Dec 2004 00:51:13 +1100 Subject: RELEASED Python 2.4 (final) In-Reply-To: <8sGdnQjN6qGu7THcRVn-3A@rcn.net> References: <8sGdnQjN6qGu7THcRVn-3A@rcn.net> Message-ID: On Tue, 30 Nov 2004 08:05:55 -0500, Dave Merrill wrote: > Newb question: Is it possible/recommended to have multiple versions of > Python installed simultaneously? Earlier, I installed 2.4rc1, and a number > of things in my 2.3.3 install stopped working. Are there known techniques > for managing multiple versions? If you're building from source, use 'make altinstall' rather than 'make install'. This will install Python as $prefix/bin/python2.4, and leave the 'python' executable alone. From aleaxit at yahoo.com Mon Nov 1 03:14:49 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 1 Nov 2004 10:14:49 +0200 Subject: question de bonne doc References: <418505b9$0$3662$8fcfb975@news.wanadoo.fr> Message-ID: <1gmkhbc.yxlo8f10l5uq5N%aleaxit@yahoo.com> orionlux wrote: ... > les livres o'reilly sur python sont decevant Vous n'aimez pas "Python en Concentr?"? Je ne l'ai pas traduit moi-m?me, bien sur -- mon Fran?ais, qui me vient encore d'une ?cole superieure du temps de ma jeunesse, n'aurait surement pas suffit -- mais il me parait n?anmoins bien traduit, et l'original Anglais, "Python in a Nutshell", a eu une tres bonne r?ception. J'aimerai bien de recevoir des critiques (je ne lis pas les groupes Fran?ais, seulement comp.lang.python; merci donc de m'envoyer une copie des message par courier ?lectronique!) pour m'aider a travailler mieux lors de la prochaine ?dition. Merci beaucoup, Alex From irmen at -nospam-remove-this-xs4all.nl Sat Nov 13 20:28:26 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 14 Nov 2004 02:28:26 +0100 Subject: Is there something like tcl "send" command in Python In-Reply-To: References: Message-ID: <4196b4ba$0$37789$e4fe514c@news.xs4all.nl> Peter Gordon wrote: > Is there somethin like tcl "send" command in Python. I would like to > be able to exucate calls in a python program on one machine from > another machine. After you added some infrastructure such as Pyro (http://pyro.sourceforge.net), you can essentially invoke methods on objects on arbitrary machines. --Irmen From onurb at xiludom.gro Tue Nov 2 17:41:18 2004 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 02 Nov 2004 23:41:18 +0100 Subject: Python needs a CPyAN In-Reply-To: References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: <41880b1a$0$19736$626a14ce@news.free.fr> Michael Str?der a ?crit : > Peter Hickman wrote: > >> >> Just today we required a module that was not installed on our system. >> >> sudo perl -MCPAN -e 'install Data::Pager' >> >> And it was installed with all it's dependencies. > > > I'd rather call that a security and maintenance nightmare... We had some program (can't remember if it was spamassassin or an antivir, I'm not the sysadmin !-) gone mad and all our customers mails blocked for a full day because of such a wonderfull update of a perl module... From siona at chiark.greenend.org.uk Tue Nov 9 08:38:47 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Nov 2004 13:38:47 +0000 (GMT) Subject: MySQLdb installation References: <418f99db$0$175$9b622d9e@news.freenet.de> <418fba73$0$161$9b622d9e@news.freenet.de> <418fcca7$0$165$9b622d9e@news.freenet.de> Message-ID: <-ji*zidzq@news.chiark.greenend.org.uk> T. Kaufmann wrote: >Diez B. Roggisch wrote: >> Install the package mysql-devel. >I can't find it!? "libraries and header files" on MySQL downloads. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From Pieter.Claerhout at Creo.com Wed Nov 17 03:47:59 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 17 Nov 2004 09:47:59 +0100 Subject: win32 extentions-- installer not compatible with python 2.3 Message-ID: Yes, you can, but the version you downloaded is linked against Python 2.2 (the last part of the filename). You need to download the one linked against Python 2.3. Cheers, pieter Creo EMEA S.A. pieter claerhout | product support prinergy & synapse link | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: python-list-bounces+pieter.claerhout=creo.com at python.org [mailto:python-list-bounces+pieter.claerhout=creo.com at python.org] On Behalf Of mr_ravi_patil at yahoo.com Sent: 17 November 2004 07:44 To: python-list at python.org Subject: win32 extentions-- installer not compatible with python 2.3 Hello, I am using NT4 and downloaded the following Windows installations: 1. Python-2.3.4 2. pywin32-203.win32-py2.2 Url: http://sourceforge.net/projects/pywin32/ I installed Python 2.3.4 succesfully. But when I run the win32 extentions installer, it returns a failure message "Python 2.2 required". So does this mean that I cannot use win 32 extentions Python2.3? -- http://mail.python.org/mailman/listinfo/python-list From pastor.gabriel at wanadoo.fr Sun Nov 21 07:12:44 2004 From: pastor.gabriel at wanadoo.fr (gabriel) Date: Sun, 21 Nov 2004 13:12:44 +0100 Subject: xmlrpclib - error marshalling new-style classes In-Reply-To: <16794.9227.867964.224036@montanaro.dyndns.org> References: <24053689.1100608423575.JavaMail.www@wwinf0602> <16794.9227.867964.224036@montanaro.dyndns.org> Message-ID: <200411211312.44570.pastor.gabriel@wanadoo.fr> I have proposed a patch, see patch 1070046 http://sourceforge.net/tracker/index.php?func=detail&aid=1070046&group_id=5470&atid=305470 Gabriel > Gabriel> I'm trying to send object using xmlrpclib, but it seems that > Gabriel> classes inheriting from object cannot be marshalled. > ... > Gabriel> Am I doing something wrong or is it a bug in xmlrpclib ? > > A limitation perhaps. Can you investigate in xmlrpclib and submit a patch > or at least submit a bug report to SourceForge? > > Skip From andy at removethis.coolioh.com Mon Nov 8 20:20:40 2004 From: andy at removethis.coolioh.com (Andy) Date: Mon, 08 Nov 2004 20:20:40 -0500 Subject: AX.25 modules for python? References: Message-ID: Eric S. Johansson wrote: > Andy wrote: >> I am considering writing some Linux based client applications for amateur >> radio in python as a learning exercise however, I have not been able to >> find ax.25 python modules. Can anyone point me to work that has already >> been done in this area? The only option I have found so far is to use >> SWIG and build my own wrappers for the ax.25 modules, but that seems >> beyond my current level of expertise :-) >> >> I have had success with python server applications using ax25d, stdin, >> and stdout, but examples of python ax.25 server applications would also >> be welcomed. > > I don't believe there are any ax.25 modules. too small a community if > you're looking for amateur radio operators who are also python > programmers. I know of 2. ;-) > > I have a friend who is working on some wavelet image compression and > data transmission schemas. He's really really good at the lower levels > but human factors are best described as not his forte. > > ---eric, ka1eec Eric, I fear that you are correct about the size of the community of interest. As my python knowledge matures I may take a stab at creating an ax.25 module in the hope that others with more skill will take pity on me and help out. Andy, K3JSE From mederis at hotmail.com Tue Nov 9 09:53:58 2004 From: mederis at hotmail.com (Marc Ederis) Date: 9 Nov 2004 06:53:58 -0800 Subject: sockets: How to know when your data is sent Message-ID: Hello, I'm having a problem with sending data with sockets over a dial-up connection. When I use the send function, it will happily send a buffer of a megabyte and more in one shot. But of course, the data is still in the network buffer... Meaning you can't disconnect for awhile (but for how long...). The problem is, how can I know when it's done? Is there a way to be notified when the data has truly been sent? I tried using setsockopt and SO_SNDBUF to reduce the send buffer size, thinking that the data would actually send in smaller increments, instead of putting the whole thing in a buffer and taking it out of my hands... No luck. It all works, mind you, but I'm left clueless as to when the data is really off my computer! I'm just following the example in the Python sockets How-To. Here's the send function: def mysend(msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, \\ "socket connection broken" totalsent = totalsent + sent Is there something I'm missing, or is there a better way to do this? Thanks, -Marc From faassen at infrae.com Mon Nov 15 10:23:31 2004 From: faassen at infrae.com (Martijn Faassen) Date: Mon, 15 Nov 2004 16:23:31 +0100 Subject: Zope 3.0, and why I won't use it In-Reply-To: References: Message-ID: <4198C9F3.9090209@infrae.com> Nicholas Wieland wrote: [snip] > Sorry, probably I'm just tired (work to buy coffee <-> drink coffee to > work inifite loop, as usual :p), but I can't find where exactly they > made such a claim. I'm really interested in this because a friend of > mine (Volonghi) asked me exactly the same question... I think that > "someone - somewhere" misunderstood what interfaces are, but I'm not > sure. The only thing I'm sure is that I'm writing components for ZopeX3 > in plain old good Python from milestone 3 :) This zdnet article made such a claim: http://news.zdnet.co.uk/software/applications/0,39020384,39173322,00.htm I think it's just a case of a journalist trying to make comprehensible with that Zope 3 interfaces do. """ Zope developers have also extended the Python programming language so that variable types are specified, rather than being loosely typed, said Richter. He hopes that these changes will eventually be given to the Python project. """ That or Stephan Richter didn't explain it very well. :) Interfaces are just annotations for classes and don't change the dynamic typed nature of Python at all. Interfaces do allow for powerful introspection (which the component architecture builds), and they also function as API specification. Regards, Martijn From wgshi at namao.cs.ualberta.ca Fri Nov 26 14:29:02 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Fri, 26 Nov 2004 19:29:02 +0000 (UTC) Subject: dictionary initialization References: Message-ID: Caleb, In article , Caleb Hattingh wrote: > ... >And then have x=1? Is this the question of debate here? One line of >initialisation to specify the type? Right. > >IF this is the point you are making, and the awk functionality >demostrated in this particular example is a really significant >feature for you in your specific problem domain, then I must concede >that awk is probably right for you, and you shouldn't waste your >time with Python. Thanks for the advice. I'll stay with awk and shell for most of my text processing (simple but, hey, 90% of the time I'm not doing anything complex) and go Python for binary data processing and larger projects. BTW, I think learning Python is a good use of my time. Weiguang From nchackowsky at gmail.com Sun Nov 14 22:28:10 2004 From: nchackowsky at gmail.com (Nick) Date: Sun, 14 Nov 2004 21:28:10 -0600 Subject: Combining arbitrary lists Message-ID: <41982269$1_1@alt.athenanews.com> Given that n = [ [1, 2, 3], [4, 5, 6], [7, 8] ] then the following code produces what I expect for x in n[0]: for y in n[1]: for z in n[2]: print [x, y, z] --output-- [1, 4, 7] [1, 4, 8] [1, 5, 7] [1, 5, 8] ... [3, 6, 8] -- -- How can I do this for an arbirary length of n? This reminds me of those horrible fraction questions in 1st year comp. sci. x = 1 + 1/(1 + 1/(1 + 1/(..... )))))... which leads me to suspect that the simplest solution is recursive... hmmm... I'll take any suggestions. Muchos Gracias Nick. From peter at engcorp.com Sat Nov 27 12:59:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 27 Nov 2004 12:59:00 -0500 Subject: dictionary initialization In-Reply-To: References: Message-ID: Caleb Hattingh wrote: > IF this is the point you are making, and the awk functionality > demostrated in this particular example is a really significant feature > for you in your specific problem domain, then I must concede that awk > is probably right for you, and you shouldn't waste your time with Python. Unfortunately for the logic, if one finds something like that to be a "really significant feature ... [in a] specific problem domain", then with Python you can of course create your own custom data type which behaves exactly as desired. And in fact it is likely that there is additional behaviour that could be added that would make the Python approach to the problem *even simpler than the awk approach*, but maybe that's getting too much of a good thing... Of course, this capability prevents one from whining about how wonderful a specialized limited-purpose tool is compared to that waste of space called Python, but if it weren't for people like that Usenet would have no traffic and we'd all have lives instead. -Peter From steven.bethard at gmail.com Mon Nov 22 23:32:57 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 23 Nov 2004 04:32:57 GMT Subject: Is there a consensus on how to check a polymorphic instance? In-Reply-To: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> Message-ID: Mike Meng wrote: > I'm a newbie Python programmer with a C++ brain inside. I have a > lightweight framework in which I design a base class and expect user to > extend. In other part of the framework, I heavily use the instance of > this base class (or its children class). How can I ensure the instance > IS-A base class instance, since Python is a fully dynamic typing > language? The short answer is that if you want to ensure an instance is-a subclass of the base class, you should use isinstance: >>> class HasF(object): ... def f(self): ... raise NotImplementedError ... >>> class SubHasF(HasF): ... def f(self): ... return self.__class__ ... >>> class NonsubHasF(object): ... def f(self): ... return self.__class__ ... >>> isinstance(SubHasF(), HasF) True >>> isinstance(NonsubHasF(), HasF) False However it's often not necessary to go this route. Consider: >>> class HasNoF(object): ... pass ... >>> def use_c(c): ... try: ... f = c.f ... except AttributeError: ... raise TypeError('argument to use_c must have an f method') ... return f() ... >>> use_c(SubHasF()) >>> use_c(NonsubHasF()) >>> use_c(HasNoF()) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in use_c TypeError: argument to use_c must have an f method Is it really necessary that the classes passed to your equivalent of 'use_c' are actually subclasses of your equivalent to 'HasF'? Or is it just necessary that they support the appropriate methods? If it's the second, I would just test for the appropriate methods and catch the AttributeErrors (and possibly the TypeError that's thrown if 'f' isn't callable). If you can give a little more detail on your particular example, I (and others) can probably give you more helpful suggestions... Steve From Scott.Daniels at Acm.Org Fri Nov 19 18:55:01 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Nov 2004 15:55:01 -0800 Subject: Python switch for syntax checking In-Reply-To: <10pt03bdpp7gp89@corp.supernews.com> References: <419e6581$1@nntp0.pdx.net> <419e6c1b.494654145@news.oz.net> <10pt03bdpp7gp89@corp.supernews.com> Message-ID: <419e9ab6$1@nntp0.pdx.net> Jeff Duffy originally wrote: > I've been wondering why python itself doesn't provide a switch to > check a file for valid syntax.... > Jeff Shannon wrote: > Bengt Richter wrote: >> On Fri, 19 Nov 2004 12:08:00 -0800, Scott David Daniels >> wrote: >>> First, "python MyApp.py" does a syntax check anyway. If MyApp is >>> not a main program, all you get is the syntax check. As for main >> >> ??? What does "not a main program mean"? I'm not sure what you mean, > > I believe that Scott is referring to the difference between a file run > from the commandline, in which __name__ is set to "__main__", and a file > that's imported as a module, in which __name__ is set to the name of the > module, which is normally the filename minus the .py[c|o|d] extension. > I do mean something like that. Essentially, I mean "if the file is meant to be imported, rather than run." > Of course, this would also imply that Scott is presuming that one is > following the good programming practice of not putting any significant > code (other than function, class, and global variable definitions) at > module level, except where protected by an 'if __name__ == "__main__":' > statement. That *is* good practice, and most people do it, but it's not > required so perhaps not a safe presumption... Remember, I am explaining why we normally don't have a syntax-check-only option, and my thesis is that there is no perceived need on the part of the core implementers. --Scott David Daniels Scott.Daniels at Acm.Org From guettli at thomas-guettler.de Tue Nov 23 10:27:09 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 23 Nov 2004 16:27:09 +0100 Subject: Help for a newbie in Python and ZODB References: <39eca62c.0411212341.330dabdc@posting.google.com> <39eca62c.0411222353.4ad4f2bc@posting.google.com> Message-ID: Am Mon, 22 Nov 2004 23:53:17 -0800 schrieb Jean-Louis Nespoulous: > Thanks, but I'll use ZODB as server and I'll get and retreive objet > from a distance client using XML-RPC, do you think it's possible > easily? > Jean-Louis If you want XML-RPC, you need some http server. This means you need quixote or something similar. You can look at the Publisher of Dulcinea. It does retry a request if you get a conflict error. I recommend you to just take the start_request of Dulcinea and write a small quixote Publisher yourself. Then return XML which is valid according to the xml-rpc spec. HTH, Thomas From tzot at sil-tec.gr Thu Nov 18 12:45:16 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 18 Nov 2004 19:45:16 +0200 Subject: PIL for Python 2.4? References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> Message-ID: On Thu, 18 Nov 2004 11:21:09 -0500, rumours say that Christopher Boumenot might have written: >You can download Microsoft's C/C++ compiler for free. (It's command >line only, but good enough.) > >http://msdn.microsoft.com/visualc/vctoolkit2003/ Thank you! Thank you! Thank you! Now that you told me I remembered I'd read about it and completely forgot... ...and thank you! -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From ruses at users.ch Wed Nov 17 06:26:23 2004 From: ruses at users.ch (not [quite] more i squared) Date: Wed, 17 Nov 2004 12:26:23 +0100 Subject: jython, pyrex, python.net... Message-ID: <419B355F.6090401@users.ch> Shouldn't there be a group working on endowing Python with an optiomal annotations syntax making trivial the (reversible) cross-language source-to-source translation from(/to) java or c# to(/from) equivalent python-jvm or python.net ? Annotated-python-as-a-jvm/net-bridge-ly yours, Morris Carr? -- PS OK, I guess annotations management is a MOP issue. I guess ideally, "meta-python" should stipulate any implementation over a foreign vm/runtime should display the "delta-MOP" of the underlying object system. The zope database for instance would have a "delta-MOP". Jython is essentially someone's (Jim Huguenin's ?) invention of expressing the (python) delta-MOP of the JVM into (Java) code using Java's reflexion API while interpreting Python as a side-effect ;) From TheDolphin at ivonet.nl Tue Nov 9 13:55:10 2004 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Tue, 9 Nov 2004 19:55:10 +0100 Subject: Escape chars in string References: <418fd4fb$0$147$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <4191128e$0$772$3a628fcd@reader10.nntp.hccnet.nl> "Jeff Epler" wrote in message >Python 2.3 has a 'string-escape' codec. If you have a string like '\\t' >(a literal backslash followed by a t) and want to turn it into the >string '\t' (a tab character), you can use it for that purpose: > >>> r"a\tb".decode("string-escape") > 'a\tb' >Jeff Thanx! exactly what i needed Ivo. From bockman at virgilio.it Sun Nov 7 04:10:32 2004 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sun, 07 Nov 2004 09:10:32 GMT Subject: checking a thread has started References: Message-ID: On Sat, 06 Nov 2004 21:58:29 +0800, Deepak Sarda wrote: > > My question is: how do I check whether a call to the start() method was > successful? If there is a mechanism by which I can get this information - > I can try restarting/recreating the thread. > I'm not aware of any method in the standard library to do this. But you could try using events for this purpose, doing soomething like this: class MyThread( threading.Thread ): def __init__(self, id ): threading.Thread.__init__(self) self.idx = id self.actually_started = threading.Event() def run(self): self.actually_started.set() # signals that the thread is started # thread processing goes here print time.time(), "Thread %s started" % self.idx time.sleep(3.0) print time.time(), "Thread %d completed" % self.idx # # you could try this to serialize the thread creation # without adding the sleep. It should be faster. # def start_threads_serially( num_threads, max_wait = 2.0): res = [] for i in range(num_threads): t = MyThread(i) t.start() # wait that the thread is started before # starting the next one t.actually_started.wait( max_wait ) res.append(t) return res # selftest :-) if __name__ == '__main__': threadlist = start_threads_serially(100) for t in threadlist: t.join() if __name__ == '__main__': threadlist = start_threads_serially(10) for t in threadlist: t.join() From bjourne at gmail.com Fri Nov 26 16:04:44 2004 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 26 Nov 2004 22:04:44 +0100 Subject: dictionary initialization In-Reply-To: References: Message-ID: <740c3aec04112613043a0b0d2b@mail.gmail.com> > >>> del x > >>> x *= 5 > > x should be bound to an object of what type? > > - 0 because x initialized to 0 by default and 0*5==0? > - '' because x initialized to '' by default and ''*5==''? > - [] because.... > > I think this is NOT a problem of explicit/implicit, is just a problem where > Python can not guess what the user wants... Maybe Python can't guess it, but *I* can guess, with 99% certainity, that the user wants x to be 0. :) -- mvh Bj?rn From mwm at mired.org Thu Nov 11 14:22:31 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 11 Nov 2004 13:22:31 -0600 Subject: distutils and Debian References: <4192AD69.5040707@sympatico.ca> Message-ID: Robert Kern writes: > And as I said, your interpretation has nothing to do with the way > Debian and other Linux/BSD/what-have-you distributions use the suffix > in their package names. BSDs in general use "-devel" to mean the development branch of the software in question, *not* the tools for those installing software from some place other than the standard packages distribution. The Python port installs all of python, including Tkinter. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From guettli at thomas-guettler.de Thu Nov 25 10:34:59 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Nov 2004 16:34:59 +0100 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: Message-ID: Am Thu, 25 Nov 2004 15:43:53 +0100 schrieb Nico Grubert: > Hi there, > > Background of this question is: > I want to convert all words except 'and' / 'or' / 'and not' from > a string into '**'. You can give re.sub() a function import re ignore=["and", "not", "or"] test="test and testing and not perl or testit or example" def repl(match): word=match.group(1) if word in ignore: return word else: return "*%s*" % word print re.sub(r'(\w+)', repl, test) Result: *test* and *testing* and not *perl* or *testit* or *example* HTH, Thomas From ialbert at mailblocks.com Fri Nov 26 23:35:52 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 26 Nov 2004 23:35:52 -0500 Subject: I installed Zope X3 on Windows 2003, but how to start it? In-Reply-To: <1101446514.209755.293770@f14g2000cwb.googlegroups.com> References: <1101446514.209755.293770@f14g2000cwb.googlegroups.com> Message-ID: McMeng at gmail.com wrote: > I am new to Zope. I downloaded the Zope X3 Windows installer and > install it, everything is okay. But how to start it? I typed You'll need to make a zope instance then start that. Read the "Notes on Windows" section on this page: http://dev.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/ZopeX3300 Istvan. From sean.berry2 at cox.net Sun Nov 7 20:33:39 2004 From: sean.berry2 at cox.net (news.west.cox.net) Date: Sun, 7 Nov 2004 17:33:39 -0800 Subject: Stop spaces from appearing when printing to file References: <418ec9ff$1_2@newspeer2.tds.net> Message-ID: > The spaces are a feature of print. To avoid them, use string formatting to > create a single output string. > >> print >> x,';',object,";",AN_string,";",ascii,";",sum > > Try > print >> x, ';%s;%s;%s;%s' % (object, AN_string, ascii, sum) > > Kent > or.... print x + ';' + object + ";" + AN_string + ";" + ascii + ";" + sum From michele.simionato at gmail.com Fri Nov 5 05:52:35 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 Nov 2004 02:52:35 -0800 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> Message-ID: <4edc17eb.0411050252.2d6c811b@posting.google.com> "Diez B. Roggisch" wrote in message news:... > I'd suggest using ZODB instead of directly pickling - then every cgi can > open the database with its own connection. ZODB will manage concurrency > issues. Ok, but then I guess you need an external long-living process keeping the DB open for you. If the cgi script opens and close the database by itself, the only thing the ZODB buys for you is raising IOError: [Errno 11] Resource temporarily unavailable (not unexpectedly). Here is what I tried: $ cat concurrency.py import ZODB from ZODB.FileStorage import FileStorage def openzodb(dbname): db = ZODB.DB(FileStorage(dbname + ".fs")) conn = db.open() return db, conn, conn.root() if __name__ == "__main__": print "Opening the db ..." db, conn, root = openzodb("x") print "Storing something ..." root["somekey"] = "somedata" get_transaction().commit() print "Closing the db ..." conn.close(); db.close() $ echo Makefile default: python concurrency.py& python concurrency.py $ make python concurrency.py& python concurrency.py Opening the db ... Opening the db ... Traceback (most recent call last): File "concurrency.py", line 12, in ? db, conn, root = openzodb("x") File "concurrency.py", line 6, in openzodb db = ZODB.DB(FileStorage(dbname + ".fs")) File "/opt/zope/lib/python/ZODB/FileStorage.py", line 232, in __init__ Storing something ... self._lock_file = LockFile(file_name + '.lock') File "/opt/zope/lib/python/ZODB/lock_file.py", line 62, in __init__ lock_file(self._fp) File "/opt/zope/lib/python/ZODB/lock_file.py", line 42, in lock_file fcntl.flock(file.fileno(), _flags) IOError: [Errno 11] Resource temporarily unavailable Closing the db ... BTW, it is clear from the traceback than internally ZODB uses fcntl and probably a custom solution based on it would be simpler than installing the ZODB (unless the OP has some reason to want it). But I guess you had in mind something different, care to explain? Michele Simionato From gustavo.cordova at q-voz.com Tue Nov 30 09:44:27 2004 From: gustavo.cordova at q-voz.com (=?UTF-8?B?R3VzdGF2byBDw7NyZG92YSBBdmlsYQ==?=) Date: Tue, 30 Nov 2004 08:44:27 -0600 Subject: Protecting Python source In-Reply-To: References: <41ab74f4$0$85031$a1866201@visi.com> Message-ID: <41AC874B.4030602@q-voz.com> Peter Maas wrote: > Grant Edwards schrieb: > >> On 2004-11-29, Peter Maas wrote: >> >>> If the "reverse engineering" argument boils down to "protecting source >>> doesn't make sense" then why does Microsoft try so hard to protect >>> its sources? >> >> To avoid embarassment. > > :) This cannot be the whole truth otherwise they wouldn't release > embarrasing binaries. BWAAHHAHAHA!!! Damn you!! Coke is so hard to clean off a keyboard!! Good laugh, thankyou so much :-D -- Gustavo C?rdova Avila *Tel:* +52 (81) 8130-1919 ext. 127 Integraciones del Norte, S.A. de C.V. Padua #6047, Colonia Sat?lite Acueducto Monterrey, Nuevo Le?n, M?xico. From peter at engcorp.com Thu Nov 4 19:08:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Nov 2004 19:08:42 -0500 Subject: win 2003 server In-Reply-To: References: Message-ID: <0-GdnfNAPrb1XxfcRVn-sw@powergate.ca> Brad Tilley wrote: > Does Python run on Windows Server 2003? > > http://www.python.org/download/download_windows.html only lists the > following: > > Python for Windows 95, 98, NT, 2000, ME, XP I'm fairly sure "Windows Server 2003" is in no way significantly different from one or more of the above items you list. It's not like Microsoft has gone and developed yet another operating system! It's a certainty that its biggest feature is that it will confuse some corporate buyers into "upgrading", thus boosting MS revenue for another quarter... If you have a copy, downloading and installing a copy of Python would be the most direct route to proving that theory. -Peter From peter at engcorp.com Wed Nov 17 13:01:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Nov 2004 13:01:41 -0500 Subject: thread, threading; how to kill a thread? In-Reply-To: References: Message-ID: Jerry Sievers wrote: > Wondering if there is a simple way from a main python program to kill > a running thread? No. > I see with the 'threading' module the way daemonic > threads behave when the main program finishes. This is one of several approaches, any of which -- or none of which -- might be suitable for you. What drives your need for this behaviour? The answer will determine the best approach. > All I am trying to do is stop that thread immediatly from the main Define "immediately". In answering please consider issues such as threads that are blocked in kernel calls, such as receiving data on a socket, as well as data integrity issues (e.g. what happens if by "immediately" you mean "at the end of the current bytecode instruction", and if that implies that you may have system data structures that are corrupted?). > Didn't notice anything obvious in the docs like a 'kill' method or > similar. I don't necessarily want the main program to exit, just to > kill one or more threads. Searching the list/newsgroup archives with Google will reveal past discussions and possibly some useful responses. -Peter From zanesdad at bellsouth.net Tue Nov 2 12:13:34 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 02 Nov 2004 12:13:34 -0500 Subject: extending file? In-Reply-To: References: <8vudnfFCkdgUDBrcRVn-jA@powergate.ca> <41879811.40002@bellsouth.net> Message-ID: <4187C03E.60608@bellsouth.net> So, with everything being said that's been said, here's are two questions for myself and for Chris Cioffi: 1. How difficult would it be to modify file.readline() so it would read until a specific character rather than the standard end of line character(s)? 2. What would be the best way to go about the above? If anyone has any ideas, I think we would both listen with great interest. Jeremy Jones From steven.bethard at gmail.com Fri Nov 19 19:37:44 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 20 Nov 2004 00:37:44 GMT Subject: generic object - moving toward PEP In-Reply-To: References: Message-ID: Robert Brewer wrote: > Steven Bethard wrote: >> >>> x = bunch(a=bunch(b=1, c=10), d=100) >> >>> x.a.b >>1 >> >>> x.d >>100 [snip way to write this without a bunch class] > > No, it would be written: > >>>>x = dict(a=dict(b=1, c=10), d=100) I understand your point of course, but note that your code does not produced the desired behavior: >>> x = dict(a=dict(b=1, c=10), d=100) >>> x.a.b Traceback (most recent call last): File "", line 1, in ? AttributeError: 'dict' object has no attribute 'a' Instead of having a class-like object, you (obviously) have nested dicts and therefore have to access them with [] (or the like): >>> x['a']['b'] 1 Note that this is what point 3 was about: "Allows simple conversion from dict-style access to attribute access". Of course, whether or not you want attribute access instead of []-style access is a design decision. Heck, I could avoid ever writing a class again by just using dicts instead -- forcing all the users of my "classes" to use []-style access instead of attribute-style access. The power is there -- that's basically what __dict__ is doing anyway, right? It's not something *I* would do, but it's a design decision to be made nonetheless. Providing a 'bunch' (or equivalent) class allows one to make this design decision (attribute access vs. []-style access) without having to declare a class every time. > If you're returning a value that needs to be unpacked positionally, use > a tuple. If it needs to be unpacked lexically, use a dict. I have yet > to see an example where it's advantageous to support both This doesn't really have anything to do with the proposal. We're not suggesting a named-tuple here (though see a recent (current?) thread that is). The 'bunch' class, or whatever you want to call it, is intended to support dotted-attribute access, in contrast to dict's sequential [] access. Steve From wgshi at namao.cs.ualberta.ca Thu Nov 11 14:07:31 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Thu, 11 Nov 2004 19:07:31 +0000 (UTC) Subject: crc32 to be used as hash Message-ID: Hi there, I'm thinking of using binascii.crc32 as a hash-function when I read in the reference http://www.python.org/doc/current/lib/module-binascii.html: crc32( data[, crc]) Compute CRC-32, the 32-bit checksum of data, starting with an initial crc. This is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. CRC32 has been shown in the (Internetworking) literature that it can be used as a good hash function. I'm wondering what's the concern here. Thanks Weiguang From mperpick at wgen.net Tue Nov 23 17:21:49 2004 From: mperpick at wgen.net (Matthew Perpick) Date: Tue, 23 Nov 2004 17:21:49 -0500 Subject: problems uploading zipfile with cgi Message-ID: Hello All, trying to upload a zip file to a python cgi-script and I am having some trouble. the form has enctype="multipart/form-data". i can access the file as a string like this: zip = form.keys['zip_file'].value but I cannot seem how to create a ZipFile object from this data. It only wants a filename or a "file-like object" in the constructor. can anyone help? I am a little bit lost. Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From postmaster at earthlink.net Wed Nov 10 06:59:16 2004 From: postmaster at earthlink.net (Daniel T.) Date: Wed, 10 Nov 2004 11:59:16 GMT Subject: How to find MAC address and uids? Message-ID: I'm writing a script for work and to finnish it, I need two bits of information which I'm having trouble finding. 1) How can I programatically find the MAC address of the machine? Is it stored in a file I can look into? (MacOS X) 2) If I have a user name in a string how do I get his UID? Thanks to anyone that can help. From deetsNOSPAM at web.de Wed Nov 3 12:46:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 03 Nov 2004 18:46:49 +0100 Subject: Extending Python questions References: Message-ID: > myshell.openconnection('www.yahoo.com',12,2000) > > It's not only the problem of comfort - it's a problem of changing > *some* scripts. And there's more than that - my shell functions > already know how to handle it's arguments (which's number may vary), > it doesn't need python to do that. All it needs is a pointer to a > string representing the arguments (in our case "www.yahoo.com 12 > 2000"). I've tried using PyArg_UnpackTuple but without success. Then don't specify the arguments separately, but instead make it one string argument, and pass it to your command: myshell.openconnection('www.yahoo.com 12 2000') > So I have two questions: > 1. Is it possible to move the calls to a upper level (i.e. call > "openconnection" and not "myshell.openconnection") ? from myshell import * > 2. Is is possible to remove the brackets and commas? (i.e. > "www.yahoo.com 12 2000" instead of ('www.yahoo.com',12,2000)? No. Thats too much of tinkering with pythons parser - you'd render all other python sources useless, which I suspect outnumber your scripts by a degree or two... :) > final goal is to use the original commands if possible. > thanks in advance, What do you use python for in the first place, if you want to keep everything as it is? What you can do is to read your scripts _using_ python instead of _passing_ them to python - then you can control the syntax of your scripting language. The main loop could look like this: import myshell for line in sys.stdin.readlines(): command, rest = line.split()[0], " ".join(line.split()[1:]) getattr(myshell, command)(rest) -- Regards, Diez B. Roggisch From nun at example.com Thu Nov 25 17:15:11 2004 From: nun at example.com (Mitja) Date: Thu, 25 Nov 2004 23:15:11 +0100 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: Message-ID: On Thu, 25 Nov 2004 15:43:53 +0100, Nico Grubert wrote: > Example: > I have the following string: "test and testing and not perl or testit or > example" > > I want to convert this string to: > '*test*' and '*testing*' and not '*perl*' or '*testit*' or '*example*' A compact, though not too readable a solution: foo="test and testing and not perl or testit or example" ' '.join([ ("'*"+w+"*'",w)[w in ('and','or')] for w in foo.split() ]).replace("and '*not*'","and not") -- Mitja From spam at phpgeek.dk Fri Nov 12 08:40:31 2004 From: spam at phpgeek.dk (Johan Holst Nielsen) Date: Fri, 12 Nov 2004 14:40:31 +0100 Subject: Regarding color conversion (RGB->CMYK) Message-ID: <4194bd54$0$75308$edfadb0f@dread15.news.tele.dk> Hi all, I hope someone can help me. I have do do a color conversion from RGB to CMYK. It's harder than I thought :D Anyway, here is my problem. I tried some differents ways to do it - I have a TIFF RGB file that I need to convert to CMYK colorspace. First of all I tried ImageMagick - it works - or it doesn't. Its give me an CMYK TIFF - but with way wrong colors :( Nothing seems to be quite right in that picture - tried google - and it seems that other people have the same problem as me :( After that my thoughts was on PIL (Python Imaging Library). The colors was better - but to bright - cause it didn't include K (so it was basicly a RGB=>CMY conversion - Black is 100% Cyan, Magenta and Yellow). I tried some googling - and again - some people said that PIL shouldn't be used for images that should be printed "professional". Now, I don't have any clue about what I need to do? Is there another way to solve my problems? Any tools that can convert somehow? Or any kind of examples I can try to read? It have to run on a Linux box - Python, Perl, PHP, bash whatever :( Though about GIMP - but can find any information about how I can do a conversion in command-line? Any one having knowlegde about this? Looking forward to hear from you and I will appreciate any kind of help. With Best Regards, Johan Holst Nielsen From hancock at anansispaceworks.com Tue Nov 23 19:04:56 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 23 Nov 2004 18:04:56 -0600 Subject: Enumerating Classes in Modules In-Reply-To: References: Message-ID: <200411231804.56547.hancock@anansispaceworks.com> On Wednesday 17 November 2004 05:00 pm, Rob Snyder wrote: > I have a situation where I need to be able to have a Python function that > will take all the modules in a given directory and find all the classes > defined in these modules by name. Ultimately, I would need to loop through > all of these, instantiating each of the classes in turn and calling a > pre-known method of each. > > Finding the name of each module is not a problem, but loading the classes > out the module once I know the name is where I'm lost. > > The idea is basically to support "plug-ins" for an application I'm building. > I want the end user to be able to sub-class an example plug in class, then > throw the implementation in a given directory, where I'll find it > automatically when I need it. > > I *am* still relatively new to Python, so I fully appreciate that I may be > simply going about this all the wrong way. Any guidance or redirection > anyone can provide would be appreciated. You've probably heard all you needed to, but I can show you how I did it: When I started working on VarImage, I just wanted it to do resizing, but I quickly realized I wanted to support a wide variety of image filtering operators, so I devised a plugin system, very similar to what you describe. The full source can be had at: http://sourceforge.net/projects/narya-project But the plugin finding code ( Operators/__init__.py ) just does this: # Find and load all available plugin modules: operator_path = os.path.abspath(__path__[0]) for module_file in filter( lambda n: n[-3:]=='.py' and n not in ('__init__.py', 'Operators.py'), os.listdir(operator_path)): #print "Loading %s" % module_file f, e = os.path.splitext(module_file) __import__(f, globals(), locals(), []) The magic actually happens in the Operators/Operators.py file where I define a dictionary called "Ops" that holds all the plugin objects as they are loaded. Abridgement of part of my "Operator" class: Ops = {} class Operator: """ Image operator object. """ def __init__(self, id, func, ...): self.id = id self.op = func # [... stuff to do with actually using the operator ...] # Register: Ops[id] = self I didn't want the plugin author to have to understand OOP -- just write a function with the right profile. So I use an instantiation of the class to build each operator plugin class instance based on the function they provide. All the plugin author has to do is call this class at the end of their module, with the appropriate function as argument (example from Operators/pil_crop.py): The essentials are just: import Operators def trim(...): "Documentation text which my help method reads" return ... Operator('trim', trim, 0, 1, (int,)) This says to define an operator with name "trim", calling the function trim, which can take a minimum of 0 arguments and a maximum of 1 argument, which must be an int. (not really type-checking, it just says what it should use to convert the string it will get before calling this function). I think the main conceptual difference here is that instead of trying to use magical class discovery methods, I just let the plugin author tell me which functions he wants me to make into operators, and try to make that as simple as possible. Does this help you at all? Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From timr at probo.com Fri Nov 5 00:19:19 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 04 Nov 2004 21:19:19 -0800 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > >I'd suggest using ZODB instead of directly pickling - then every cgi can >open the database with its own connection. ZODB will manage concurrency >issues. Holy moley, isn't that something like recommending a turbocharged, 12-cylinder, air-conditioned SUV as a cell phone charger? Sure, Zope is the answer, but only if you phrase the question very, very carefully. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleaxit at yahoo.com Sun Nov 7 02:40:35 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 Nov 2004 08:40:35 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> Message-ID: <1gmvgrq.es8uri1pf1hb4N%aleaxit@yahoo.com> Tim Roberts wrote: > Maurice LING wrote: > > > >I've already said the following and was not noticed: > > > >1. it is a disk intensive I/O operation. > >2. users delay is not in the equation (there is no user input) > >3. I am not interested in the amount of time needed to develop it. But > >only interested execution speed. > > It is fabulous that you are able to enumerate your list of requirements so > completely. I'm quite serious; many people embark on even complicated > projects without a clear understanding of the tradeoffs they will > encounter. > > However, given that set of needs, why would you mess with an "exotic" > language at all? Why wouldn't you just write straight to the metal in C++ > or C? Perhaps because point 3 has _never_ been true as stated? Nobody would really be happpy to take 40 years more to develop a program in order to shave a second off each hour-long run (well, maybe somebody _has_ taken that choice 30 years ago, and we'll see their program in 10 more years). There is always, at some point, a tradeoff - the only issue is where. Otherwise, "to the metal" would be assembly or microcode, btw. If a program is anyway spending its time waiting for disk, network, or other I/O, the benefits of compressing the already-small CPU part are tiny, by Amdahl's Law. On the other hand, ease of experimentation with different program architectures -- for example trying to overlap some of the I/O waits rather than serialize them -- could still help. Alex From eddie at replicon.com Tue Nov 16 13:26:22 2004 From: eddie at replicon.com (Eddie Parker) Date: Tue, 16 Nov 2004 11:26:22 -0700 Subject: Should I learn Python? In-Reply-To: Message-ID: <20041116182642.EB9281E4006@bag.python.org> I disagree. That's completely subjective. To swing the "Force" back to neutrality, I'll add my own subjectivity. I find PHP useful for what it does. Properly structured code is just as maintainable as Python code, particularly with PHP 5 being more object-oriented (or so I hear). I think of PHP as more of a "specifically engineered to the web" language (just odd that it doesn't support UTF easily, however, it's a good web language, 'on the cheap'). Python does admirably, particularly boasting it's own BaseHTTPServer, in case you don't want to rely on mod_python and the like. I haven't benchmarked the two, so I can't speak about performance, but I generally prefer PHP for web scripting, and Python for client side coding. That said, I agree that it's subjective. Probably the only thing I could say about why you should use Python over PHP, definitively, is the Unicode support. Other good reasons, however, include robust object support, a fully featured "Batteries Included" approach -- you can get everything you need done with Python (much like PHP, but MUCH wealthier), and a good community. Pro's for PHP, however? I *love* their documentation site. The ability to go to www.php.net/WhatI'mSearchingFor is icing on the cake, but the static pages, with user commentary at the bottom are excellent (I was glad to see that PostGreSQL opted to do similar, too), and, pardon the frankness, much nicer looking then Python's. But I think both languages are pretty equal in terms of ability to do things, and I don't find I'm lacking in either. Minor discrepancies at best -- but then again, I wouldn't say I have high demands on either system, at this point. :) Cheers! -e- -----Original Message----- From: python-list-bounces+eddie=replicon.com at python.org [mailto:python-list-bounces+eddie=replicon.com at python.org] On Behalf Of Y2KYZFR1 Sent: November 16, 2004 11:00 AM To: python-list at python.org Subject: Re: Should I learn Python? sam at three60.com (Sam) wrote in message news:<624a388a.0411030512.3cf84547 at posting.google.com>... > So you're saying, in order to write smart, clean, well structured, > readable code, and have fun doing so, I'm going to have to drop PHP > and use Python? > > I'm not really interested in finding a replacement for PHP, it works > just fine for me. > > I apologize for not phrasing my questions clearly, I wasn't looking > for critisisms of PHP or why I shouldn't use it. What i'm really > after, is given that I use PHP to develop sites currently, what types > of situations would/could i use Python in web development? Is there a > point when learning Python, that I'll say to myself "why use php?". > Thanks learn python and you will answer your own question, php is just about 1 rung above perl in maintainability -- http://mail.python.org/mailman/listinfo/python-list --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 From bjourne at gmail.com Sun Nov 28 16:10:31 2004 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 28 Nov 2004 22:10:31 +0100 Subject: The use of : In-Reply-To: References: <89cc6e1f.0411251858.40b6bbc7@posting.google.com> <89cc6e1f.0411260953.4b6b98e7@posting.google.com> <41aa1abb$0$25542$636a15ce@news.free.fr> <30ukhmF357ptdU1@uni-berlin.de> Message-ID: <740c3aec041128131039686d4c@mail.gmail.com> In the faq, http://www.python.org/doc/faq/general.html#why-are-colons-required-for-the-if-while-def-class-statements, it is stated that the colon is there "primarily to enhance readability (one of the results of the experimental ABC language)." But can that statement really be backed up? Has someone made a study or something? I always thought the rule was "the less useless symbols, the higher the readability." I.e: if (a == b) { print a } is less readable than: if a == b: print a Because it contains more non-significant symbols (, ), { and } that "steal" the programmers attention. But consider def f(x, y, z) print x, y, z to def f(x, y, z): print x, y, z IMHO, the colon-less variant is more readable than the one with the colon. -- mvh Bj?rn From carribeiro at gmail.com Wed Nov 24 04:40:57 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 24 Nov 2004 07:40:57 -0200 Subject: Is there a consensus on how to check a polymorphic instance? In-Reply-To: <1101268711.261729.54980@c13g2000cwb.googlegroups.com> References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101189570.958016.283130@f14g2000cwb.googlegroups.com> <-sSdnZs3heYawz7cRVn-iA@rogers.com> <1101268711.261729.54980@c13g2000cwb.googlegroups.com> Message-ID: <864d3709041124014054130d9f@mail.gmail.com> On 23 Nov 2004 19:58:31 -0800, Mike Meng wrote: > > I come from a very conservative background in software development > > and strong checks are deeply rooted in my mind. > > So do I, Dan. > > I just can't imagine a `wild' object whose interface is valid can > truely do the right things. While in fact, when I typing this word, I > realize we can't ensure the internal protocol will be obeyed even when > the object IS-A base class instance. > > Maybe it's time to rethink. I understand, and I found myself using isinstance more often that I would like to admit. Being trained in OO Pascal & Delphi it comes as no surprise... > It seems to me the virtue of dynamic langauge is, if it looks like a > cat, it's a cat. But the problem is still there: how do you know what > it looks like before you treat it as a cat? isinstance(), , as Steve > state, is too rigid. Time for adapt(), I think... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From peter at somewhere.com Thu Nov 18 07:58:48 2004 From: peter at somewhere.com (Peter Maas) Date: Thu, 18 Nov 2004 13:58:48 +0100 Subject: Python client lib for PostgreSQL8 Message-ID: I just tried to connect to a PostgreSQL8 beta2 database server with pyPgSQL 2.4 and got a libpq.DatabaseError telling "Ivalid format for PgVersion construction". Is there already a PyPgSQL version in CVS or another client library that handles PostgreSQL 8? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From deetsNOSPAM at web.de Tue Nov 2 13:02:43 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 02 Nov 2004 19:02:43 +0100 Subject: function object and copies of variables References: <20041102174025.GA26478@marge.cehill.co.uk> Message-ID: f = [] for i in [0, 1]: f.append(lambda a = i: a) for j in f: print j() -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Mon Nov 15 18:05:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 16 Nov 2004 00:05:04 +0100 Subject: Set like feature References: <1100552512.672456.317420@c13g2000cwb.googlegroups.com> Message-ID: <1gnbhc1.xndkcm1qpqfjsN%aleaxit@yahoo.com> Mitja wrote: > > each element on a column by column basis. > > > > I am using python2.2 so no sets. Can anyone think of an efficient way > > to do this? > > If I understand the problem correctly, splitting the lines up and sorting > them before comparison _is_ much better than a naive approach, though I > don't know if that's what's best. Splitting, sure. Sorting would destroy the 'column by column basis'. Alex From Scott.Daniels at Acm.Org Wed Nov 17 15:31:41 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 17 Nov 2004 12:31:41 -0800 Subject: arrays In-Reply-To: References: Message-ID: <419bc81d$1@nntp0.pdx.net> Robert Kern wrote: > Rahul Garg wrote: >> 1. I will mostly be storing floating point numbers in 2 dimensional >> arrays which i will pass to a custom module written in C. The >> application is for scientific computing purposes.I just need python + >> wxPython for the GUI. >> >> 2.I am not using Numarray because i dont expect to do many operations >> on the matrices in Python itself. Most of that stuff will be handled >> in my C module. > > You still might want to use numarray or Numeric in this case. The memory > representation of a numarray/Numeric array is the same as in C. You > won't have to duplicate memory and waste time converting between a > memory block of doubles and lists of lists of Python floats. If you want to refer to a block of memory that you share with your C code (especially if the C code controls the memory, you might also want to check out my "Blocks and Views" code at: http://members.dsl-only.net/~daniels/block.html -Scott David Daniels Scott.Daniels at Acm.Org From tony.ha at philips.com Fri Nov 12 08:31:30 2004 From: tony.ha at philips.com (Tony Ha) Date: Fri, 12 Nov 2004 13:31:30 -0000 Subject: Plone and mod_python References: <7l1ld.13845$3_.7287@ns2.gip.net> Message-ID: <_W2ld.13847$3_.7301@ns2.gip.net> Hello Thornsten and Bruno Thanks very much for the explanations, from your answers, it looks like, it is better to use "Plone + Apache". Is this means I need to install Apache, then Plone, and configure Apache or Plone to talk to each other? But under the plone.org downloads it offer a bundle installer for Window XP. Does this mean the bundle will use Zope and the built-in Medusa as the web server? and I do not need Apache? "Thorsten Kampe" wrote in message news:gr3aeg0wjjx.dlg at thorstenkampe.de... > * Tony Ha (2004-11-12 11:42 +0100) > > Can some one explain what are the differences between "plone" and "Apache + > > mod_python"? > > Plone is a content management system (CMS) based on the Content > Management Framework (CMF) based on the Zope web application server > > > From plone.org. It says "Plone is powerful and flexible. It is ideal as an > > intranet > > and extranet server" does this mean if I use "plone" I do not need to > > install > > "Apache + mod_python"? > > Plone (in specific Zope) needs a web server to serve HTML pages. You > can use the builtin Medusa for that or Apache for larger environments. > mod_perl enables Apache without Zope to execute Python scripts (CGI). > > Thorsten From philippecmartin at sbcglobal.net Fri Nov 26 06:57:58 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 26 Nov 2004 05:57:58 -0600 Subject: Delphi underrated, IDE clues for Python Message-ID: <200411260557.58986.philippecmartin@sbcglobal.net> I like eric3 (http://www.die-offenbachs.de/detlev/eric3.html) very much but it's a QT 'aware' environment and I need Tkinter for portability/$ reasons. So I'm back to lovely emacs (thanks again and again Mr. RS) and snavigator (http://sourceforge.net/projects/sourcenav) when it comes to heavy project browsing. My needs in GUI are trivial enough; so I'm perfectly happy now. Regards, Philippe From grante at visi.com Tue Nov 16 23:24:22 2004 From: grante at visi.com (Grant Edwards) Date: 17 Nov 2004 04:24:22 GMT Subject: Rounding curiosity References: <20041116182254.6cb5a603.bartley9@pacbell.net> Message-ID: <419ad276$0$1581$a1866201@visi.com> On 2004-11-17, PyBo wrote: > What's wrong with this picture? Wrong is in the mind of the beholder. ;) >>>> x = 500000000.0 >>>> y = x / (1024 * 1024) >>>> y > 476.837158203125 >>>> z = round(y, 2) >>>> z > 476.83999999999997 > > I have tried this and get the same result using different > CPU's and operating systems. There's a reason for that: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate http://docs.python.org/tut/node15.html > Obviously, '476.83999999999997' is not rounded to two decimal > places. Of course it isn't. Computers don't use decimal. They use binary: aye, there's the rub... > Or am I doing something wrong? You're using binary floating point math without understanding it. If you tell us what you're actually trying to accomplish, we can probably tell you how to do it. If you're just worried about how it looks on the screen: >>> print "%0.2f" % round(5e8/(1024*1024),2) 476.84 If you want the computer to fib for you, it will. :) -- Grant Edwards grante Yow! PUNK ROCK!! DISCO at DUCK!! BIRTH CONTROL!! visi.com From deetsNOSPAM at web.de Thu Nov 4 07:52:37 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 04 Nov 2004 13:52:37 +0100 Subject: SystemError: com_backpatch: offset too large References: <781f5e76.0411032335.57bf5ae4@posting.google.com> Message-ID: > http://groups.google.com/groups?hl=fr&lr=&client=firefox-a&threadm=mailman.165.1085189105.6949.python-list%40python.org&rnum=1&prev=/groups%3Fq%3Dcom_backpatch%26hl%3Dfr%26lr%3D%26client%3Dfirefox-a%26sa%3DN%26tab%3Dwg > > There is a solution? > Do i to give up python and return to php? > I can't believe that a program with 10000 lines only adding strings can't be written in a more concise way, which would most probably solve your problem. So I suggest you post some parts of your code so that we can have a look at it and suggest a solution. Apart from that, it seems that if you insist on doing things the way you do them ringht now, you'll have to stick with php. Sad to admit that, but it appears to be that way... -- Regards, Diez B. Roggisch From atterdan at yahoo.com Fri Nov 5 04:46:20 2004 From: atterdan at yahoo.com (John Doe) Date: Fri, 05 Nov 2004 09:46:20 GMT Subject: recursion in __cmp__ References: <3da35075.0411050045.379477af@posting.google.com> Message-ID: Really Victor, no one comments on old versions. Try it on 2.3. Dan On Fri, 05 Nov 2004 00:45:28 -0800, Victor Safronovich wrote: > please comment this > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >>>> class A: > def __cmp__(self, other): > print '%s|%s' %(`self`, `other`) > return cmp(self, other) > >>>> a = A() >>>> cmp(a,A()) > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120> > 0 >>>> cmp(a,5) > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > <__main__.A instance at 0x00989838>|5 > 0 From pepe_0816 at yahoo.com.tw Sun Nov 28 07:04:32 2004 From: pepe_0816 at yahoo.com.tw (˝âşë) Date: 28 Nov 2004 12:04:32 GMT Subject: =?iso-8859-1?q?=A9=CA=AB=BD=AB=BD=BC=F6=BDu?= Message-ID: ?????????? +86 13180152666 From lisawill4u at yahoo.com Sat Nov 20 15:35:53 2004 From: lisawill4u at yahoo.com (CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS!) Date: Sat, 20 Nov 2004 20:35:53 GMT Subject: CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! Message-ID: <04112015355317948@news-server.cfl.rr.com> An HTML attachment was scrubbed... URL: From maarten at remove_this_ws.tn.tudelft.nl Tue Nov 23 04:06:33 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Tue, 23 Nov 2004 10:06:33 +0100 Subject: PyTables:Installing hdf5 References: <37ee60c8.0411120648.3a2ad4c6@posting.google.com> Message-ID: prashna wrote: > Hi Maarten, > I am completely new to VC++ environment and trying to learn HDF5 > format. > I copied the entire directory from > ftp://ftp.ncsa.uiuc.edu/HDF/HDF5/current/bin/windows/ and also > ftp://ftp.ncsa.uiuc.edu/HDF/lib-external/zlib/and > ftp://ftp.ncsa.uiuc.edu/HDF/lib-external/szip/ > I have followed all the steps that was explained in COMPILE.txt for > static libraries.But still, I am getting the following error... > > Linking... > LINK : fatal error LNK1104: cannot open file "libm.lib" > Error executing link.exe. Dunno have no recent experience with VC++. Just google on "libm visual c++" and follow the first link. Maarten -- =================================================================== Maarten van Reeuwijk Thermal and Fluids Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From mrjean1ATcomcastDOTnet at no.spam.net Sun Nov 28 12:35:03 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Sun, 28 Nov 2004 17:35:03 GMT Subject: files in non-blocking mode? References: Message-ID: <281120040936372124%mrjean1ATcomcastDOTnet@no.spam.net> Try setting the unbuffered mode for the spawned process by using "python -u ./amc/amc.py" /Jean Brouwers In article , Uwe Mayer wrote: > Sunday 28 November 2004 14:49 pm Mathias Waack wrote: > > > Uwe Mayer wrote: > >> I want two python programs to communicate over stdIO channels. The > >> one executes the other via the popen3 function: > >> > >> amc = Popen3("./amc/amc.py", True, 0) > >> line = stdin.readline() > >> amc.tochild.write(line) > >> amc.tochild.flush() > >> print amc.fromchild.readlines() > >> > >> The problem is that although amc.tochild gets flushed the data > >> never reaches the client until the .tochild fd is closed. Is there > >> any way to put IO channels into non-blocking mode in python? > > > How do you read the data in the client? Maybe you're using a line > > buffered read? Does your code work if the server includes a trailing > > CR and/or NL in the string before it calls the flush? > > Yes, I used > > line = stdin.readline() > > and made sure the sending client had a newline ("\n") char appended to the > text. Still, the receiving client's readline() function does not return. > > Uwe From __peter__ at web.de Mon Nov 22 03:37:10 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Nov 2004 09:37:10 +0100 Subject: generic object implementation References: <8W9od.373195$wV.310530@attbi_s54> Message-ID: Steven Bethard wrote: > So I'm trying to get a prototype implementation of the 'generic object' > type. (I'm currently calling it 'bunch', but only because I can't > really think of anything better.) I'd like some feedback on what Me neither. I called my bunch equivalent Struct, but that name seems ambiguous because of the struct module. > methods it needs to support. Ideally I'd keep this as minimal as > possible... > > Remember that the goal of the 'generic object' type is to allow the > programmer to make the design decision that attribute-style access is > more appropriate than []-style access. Given that, my feeling is that > the 'generic object' type should *not* support __(get|set|del)item__ , > though I'm still undecided on __len__, __iter__, __contains__, items, > keys, values, etc. Please, no. (except __iter__(), maybe) > > Here's what I have currently: > > import operator as _operator > > class bunch(object): > def __init__(self, **kwds): > self.__dict__.update(kwds) > > def __eq__(self, other): Maybe just return (type(self) == type(other) and self.__dict__ == other.__dict__) as you won't get properties right anyway. Not sure whether that should be enforced, but subclassing bunch doesn't seem a good idea to me. > if not isinstance(other, bunch): > return False > attrs = set(self.__dict__) > if attrs != set(other.__dict__): > return False > for attr in attrs: > if not getattr(self, attr) == getattr(other, attr): > return False > return True > > def __repr__(self): > return '%s(%s)' % (self.__class__.__name__, > ', '.join('%s=%r' % (k, v) > for k, v in self.__dict__.items())) > > def update(self, other): > self.__dict__.update(other.__dict__) I don't think update() is necessary, but if so, I'd rather have (untested) def update(self, *other, **kw): if other: if len(other) != 1: raise TypeError other = other[0] if isinstance(other, bunch): other = other.__dict__ self.__dict__.update(other) self.__dict__.update(kw) i. e. something matching 2.4's dict.update() functionality as closely as possible (and appropriate). > > @classmethod > def frommapping(cls, mapping, > getkeys=iter, getitem=_operator.getitem): > result = bunch() Substitute bunch with cls throughout. Should there also be a getpairs argument that would yield (key, value) pairs? > for key in getkeys(mapping): > value = getitem(mapping, key) > try: > value = bunch.frommapping(value) > except TypeError: > pass > setattr(result, key, value) > return result Seeing how many aspects are to consider with such a simple thing as a bunch, it would really be a benefit if one standard approach were available to substitute all the ad hoc solutions currently out there in the wild. Good luck with your effort. Peter From normanb at DOGcomsine.co.uk Fri Nov 5 10:53:04 2004 From: normanb at DOGcomsine.co.uk (Norman Barker) Date: Fri, 5 Nov 2004 15:53:04 +0000 (UTC) Subject: Python compressed URL post Message-ID: Hi, I have spent most of the day on this so any help would be appreciated. I have set up mod_deflate in Apache so that any input marked content-type gzip from the client is automatically decompressed before being forwarded on to the server-side java servlet. The idea is that I compress a file on the client write it to the stream and then it reaches the servlet decompressed through Apache. At the moment when I try to open the URL it fails with an internal server error, which I guess is because my code is wrong import httplib, urllib2, StringIO, gzip httplib.HTTPConnection.debuglevel = 1 filename = 'd:/myproject/schemas/samples/request.xml' file = open(filename, 'r') buf = file.read() print 'decompressed request buffer size is ', len(buf) zbuf = StringIO.StringIO() zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9) zfile.write(buf); zfile.close() print 'compressed request file size is ', len(zbuf.getvalue()) request = urllib2.Request('http://localhost/cocoon/compressed.xml',zbuf.getvalue()) opener = urllib2.build_opener() request.add_header('User-Agent', 'A User') request.add_header('Accept-Encoding', 'gzip, deflate') request.add_header('Content-Type', 'application/xml') request.add_header('Content-Encoding', 'gzip') request.add_header('Content-Length', str(len(zbuf.getvalue()))) ## fails here f = opener.open(request) compresseddata = f.read() print 'Compressed response length ', compresseddata.size compressedstream = StringIO.StringIO(compresseddata) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() print 'Decompressed response length ', len(data) print data Many thanks, Norman Barker -- Take the DOG out to reply From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue Nov 16 08:10:15 2004 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 16 Nov 2004 08:10:15 -0500 Subject: Identifying bundles in MacOS X References: <2vt7veF2nues7U1@uni-berlin.de> <2vtsp6F2nlt2cU1@uni-berlin.de> Message-ID: In article <2vtsp6F2nlt2cU1 at uni-berlin.de>, Brion Vibber wrote: > Michael J. Fromberger wrote: > > Actually, Apple's developer documentation seems to imply that there > > is a "bundle bit" in the Finder info (or possibly the extended > > Finder info) for directories, and that if this bit is set, the > > Finder will treat the folder as a bundle. > > It's worse than that... the bundle bit _might_ or _might not_ matter, > since it's not always present, and some extensions are known or not > or... ugh. The plot thickens! > I'm not sure if there's a standard Python module to expose Launch > Services, but here's a C snippet; use it as you like: > [...] Thank you very much for your advice, and for the sample code -- I will play around with this snippet, and see I can get what I need. It looks promising! If it works out, it will not be so difficult to add it as an extension module. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From justinhsia at yahoo.com Thu Nov 4 16:37:03 2004 From: justinhsia at yahoo.com (Chaser) Date: 4 Nov 2004 13:37:03 -0800 Subject: ?? Modules for GPIB and Ethernet ?? Message-ID: <21240387.0411041337.7b17172b@posting.google.com> Hi folks, Just wondering if anyone knows where I can find modules for NI-488.2 GPIB and for a generic ethercard? Thanks. From steve at holdenweb.com Tue Nov 16 07:25:30 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Nov 2004 07:25:30 -0500 Subject: int literals and __class__ (WAS: Is a list an instance of a class?) In-Reply-To: References: <4197c013$1_1@newspeer2.tds.net> Message-ID: <_qmmd.10659$nj.4248@lakeread01> Steven Bethard wrote: > Dan Bishop yahoo.com> writes: > >>You don't have to ask *that* nicely. >> >> >>>>>1 .__class__ # notice the space >> >> > > > Why does this work? Or, perhaps my real question is why *doesn't* it work > without the space? Pointers to the appropriate point in the docs would be > fine... I assume it's something about making parsing easier...? > > Thanks, > > Steve > Yup, it's because a dot immediately following an integer would be parsed (strictly "lexed", I suppose) as a floating point constant,m aking the __class__ a syntax error. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From martin at v.loewis.de Sat Nov 20 18:52:40 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Nov 2004 00:52:40 +0100 Subject: Microsoft Patents 'IsNot' In-Reply-To: <864d370904112015007de3eaf4@mail.gmail.com> References: <16798.16559.745209.751967@montanaro.dyndns.org> <419E6C13.1040508@v.loewis.de> <419fc77d$0$198$9b622d9e@news.freenet.de> <864d370904112015007de3eaf4@mail.gmail.com> Message-ID: <419FD8C8.1090208@v.loewis.de> Carlos Ribeiro wrote: > I'm curious. I know that Python is not going to enter into a > 'patent-filling' frenzy anytime soon. But isn't the 'is not' trick > also patentable on it's own? If the Microsoft patent is granted, then Python's approach would certainly patentable as well. > 1) I always found the "is not" with two tokens a novelty -- I knew no > other language before where this spelling was acceptable. But I am no > "linguist" (in the CS sense), either. It really is new in this context. However, there are many "similar" notations. - SQL is full of multiple-keyword constructs. E.g. constraint_declare :: = [ CONSTRAINT constraint_name ] PRIMARY KEY ( col1, col2, ... ) | FOREIGN KEY ( col1, col2, ... ) REFERENCES f_table [ ( col1, col2, ... ) ] [ ON UPDATE triggered_action ] [ ON DELETE triggered_action ] | UNIQUE ( col1, col2, ... ) | CHECK ( expression ) [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ NOT DEFERRABLE | DEFERRABLE ] triggered_action :: = NO ACTION | SET NULL | SET DEFAULT | CASCADE So "ON DELETE SET NULL" are really two "things" only, not four things. - in particular, for WHERE clauses, they have expression NOT BETWEEN expression AND expression expression NOT LIKE "string literal" expression IS NOT NULL (notice that IS NOT can only be combined with NULL here) expression NOT IN value - likewise, COBOL has many compound keywords: ADD id-1 TO id-2 ON SIZE ERROR impstmt-1 ADD id-1 TO id-2 NOT ON SIZE ERROR impstmt-2 [notice how this features a four-word keyword] MERGE fname-1 ON ASCENDING KEY id-1 COLLATING SEQUENCE IS EBCDIC USING fname-2 GIVING fname-3 [the only multi-work keyword here is "COLLATING SEQUENCE IS". "EBCDIC" is a parameter to that (with "ASCII" the other alternative); ON ... KEY can use either ASCENDING or DESCENDING] - C has had "unsigned long" for quite some time, and now also has "unsigned long long". > 2) Some people seem to think that the better way to defend Open Source > applications against silly patents is to fill a lot of patents in > behalf of open projects, as a defensive measure. I don't have any clue > as to whether this would be effective in practice or not, but anyway, > it seems interesting. I think it would be a waste of resources. Defense is only needed when there is an actual threat, at which point, if the patent is silly, litigation can be started. This is something the PSF could do should the need arise. Regards, Martin From saint_infidel at hotmail.com Thu Nov 4 15:45:03 2004 From: saint_infidel at hotmail.com (infidel) Date: 4 Nov 2004 12:45:03 -0800 Subject: Exception during win32all installation Message-ID: <1099601103.164951.130720@z14g2000cwz.googlegroups.com> I just uninstalled all previous versions of Python from my machine (2.3.4 and 2.4a1) and installed 2.4b2. Now when I try to install the win32 extensions (builds 202 and 203), the installer displays this:

Running the pre-installation script failed
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "", line 3, in ?
File "C:\Python24\Lib\os.py", line 133
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep,
altsep,
^
SyntaxError: invalid syntax

The installer appears to be complaining about the parentheses in the import statement, but the interactive interpreter has no problems with importing the os module. Is the installer using an older version of python internally? From roy at panix.com Tue Nov 23 08:36:07 2004 From: roy at panix.com (Roy Smith) Date: Tue, 23 Nov 2004 08:36:07 -0500 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> <545cb8c2.0411221645.442bb88a@posting.google.com> <41A339A8.90908@holdenweb.com> Message-ID: In article <41A339A8.90908 at holdenweb.com>, Steve Holden wrote: > I think some people just deal with uncertainty better than others. Java > is indeed a slog, and being forced to write exception handlers for > errors I never expect to occur and was quite happy to see my program > fail under was one of the least attractive things about it. Java doesn't actually force you to handle the errors. You can always just declare your method to throw those exceptions you don't handle. That's a pain in the butt too, it's just a slightly smaller pain than catching them. I agree with you that exception handling is Java is one of the (many) low points of the language. From exarkun at divmod.com Mon Nov 22 09:35:55 2004 From: exarkun at divmod.com (Jp Calderone) Date: Mon, 22 Nov 2004 14:35:55 GMT Subject: Trouble with psyco In-Reply-To: <6.1.2.0.2.20041122020641.042be500@rcblue.com> Message-ID: <20041122143555.17481.1424076765.divmod.quotient.1242@ohm> On Mon, 22 Nov 2004 02:07:46 -0800, Dick Moores wrote: >psyco is acting a bit psycho for me. > > Please see my spinForWeb.py at > > When psyco is in use, entering an integer somewhere between 2000 and 2500 > causes my computer to freeze. Not really freeze but the program doesn't > finish, and I have to quit with a ^Q. > > psyco is really impressive, but I'm disappointed that I can't demonstrate > (to friends) counting with it to numbers above 2 billion. > > If I remark out the "psyco.bind(spin)" line, there's no problem no matter > what integer I enter. Can someone explain what the problem with psyco is? > > Windows XP, Python 2.3.4 > > Thanks, I added a print to your inner loop: while k < max: k += 1 if not (k % 1000000L): print 'at', k Progress is regularly reported, but it is quite, quite slow. So the problem is not that psyco is breaking your program. Neither is it speeding anything up though, and in fact seems to be slowing it down over some sets of data. When you cross sys.maxint (a bit above 2 billion, usually), internally Python stops storing integers as platform-native data types and switches to a data type which can grow almost without bound. Since this new data type isn't native to your architecture, every operation on it is vastly slower, but Python must switch because the platform-native data type cannot take on the values you are asking. Python works very hard to make each loop around its evaluator. You're asking it to get around quite a few times, doing very little _actual_ work each time. This is one of the worst cases for performance in Python. With the psyco version, the call to spin() is effectively made into a single operation, as far as the interpreter loop is concerned. That's part of why it's so much faster - instead of one loop around the interpreter per "k += 1", it's just one loop around the interpreter. Big difference. But you've discovered one of the costs associated with this - Control-C generally sends SIGINT to the process: Python notices this and sets a flag which will _later_ cause KeyboardInterrupt to be raised. In this case, with psyco enabled, "later" happens when spin() returns, because calling spin() was just one operation, as far as Python is concerned. Without psyco, "later" happens very frequently, almost constantly even, and so Control-C generally has an instant effect. Hope this helps, Jp From Scott.Daniels at Acm.Org Tue Nov 2 10:03:33 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 02 Nov 2004 07:03:33 -0800 Subject: [wx] Simple image editor In-Reply-To: References: Message-ID: <4187a6ac$1@nntp0.pdx.net> Michele Petrazzo wrote: > ... if I have a lot of "objects", I must attempt [to] redraw all. One simplification that can speed things up tremendously (in the case that you can ignore write order), is to have a "selected" object, and an image of "everything else" on which you draw the "selected" object as you move it around. -Scott David Daniels Scott.Daniels at Acm.Org From mike at hobbshouse.org Thu Nov 4 18:03:29 2004 From: mike at hobbshouse.org (Michael Hobbs) Date: Thu, 04 Nov 2004 23:03:29 -0000 Subject: strong/weak typing and pointers References: <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> <10ol7sqdr84k619@corp.supernews.com> Message-ID: <10olda19ictjb0@corp.supernews.com> Steven Bethard wrote: > The reason for this is that at any given time in OCaml, the sequence of bits is > only interpretable as *one* of the two types, never both. If you have a good > example of using a union (in C probably, since OCaml wouldn't let you do this I > don't think) where you want to treat a given sequence of bytes as both types *at > once*, that would be great! This example is a little weak, but may be sufficient. The in_addr structure used for sockets usually uses a union to provide different views to the underlying 32-bit address. You can access the address as 4 8-bit values, 2 16-bit values, or 1 32-bit value. Most code these days only use the 4 8-bit representation, but the interface is there. Another possible example comes from the Windows API. Some of the functions take an arbitrary length structure. If you want to make a simple call to the function, you pass a small structure. If you want to make a more complex call to the function, you pass a larger structure that has more fields tacked on to the end. Usually, the first field in the structure is an int that specifies how large the structure is. It is used as sort of a crude version of OO in C. I'm not sure if these are the kinds of examples you're looking for. I don't know how anyone would be able to use a sequence of bytes as two types of data at once. There is almost always some sort of indicator that specifies how to interpret the bytes; otherwise, it is just garbage. -- Mike From mr_ravi_patil at yahoo.com Wed Nov 17 22:09:26 2004 From: mr_ravi_patil at yahoo.com (SoftwareTester) Date: 17 Nov 2004 19:09:26 -0800 Subject: psSerial: how to write a single byte value to the serial port? References: <5a050156.0411170057.6c27a6a4@posting.google.com> <419b2f5f.282498301@news.oz.net> <5a050156.0411171153.6f04b454@posting.google.com> Message-ID: <5a050156.0411171909.2c7d500@posting.google.com> "Diez B. Roggisch" wrote in message news:... > > I assume the string print ser.write() will append null characters to the > > end. > > Why do you assume that? Its not said anywhere, and its wrong. A string > consists only of the characters you can "see" - if python usues C > convention for 0-termination or othear means is an implementation detail > none of your concern. > > > byte = chr(0x40) > > ser.write(byte) > > >>> type(byte) > > > Its a string as well. I am concerned because I do not know the effect of writing null character to the device connected to the serial byte. I wish to send a single byte to the serial port and nothing more. Thanks. From endavis at gmail.com Mon Nov 15 13:30:18 2004 From: endavis at gmail.com (Eric Davis) Date: Mon, 15 Nov 2004 13:30:18 -0500 Subject: save a dictionary in a file In-Reply-To: <2vsa8hF2oa58tU1@uni-berlin.de> References: <2vsa8hF2oa58tU1@uni-berlin.de> Message-ID: <4198F5BA.4010805@gmail.com> Luis P. Mendes wrote: > Hi, > > my program builds a dictionary that I would like to save in a file. > > My question is what are the simple ways to do it? > > The first solution I've thought of is to transform the dictionary in a > list, with the key being the first element on that list, and the value > as the second. Then I could use pickle to do the write and read > operations. It seems simple and easy. > > Is there a more commonly used form to do it, yet in a simple way? > > Luis Look at the pickle or ConfigParser modules. Both of these will do what you are looking for in different ways. Eric From danperl at rogers.com Wed Nov 24 01:02:05 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 24 Nov 2004 01:02:05 -0500 Subject: protocols, inheritance and polymorphism References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> <786dnYZkrq-ieT7cRVn-tw@rogers.com> <1101273995.954137@yasure> Message-ID: "Donn Cave" wrote in message news:1101273995.954137 at yasure... > Quoth "Dan Perl" : > | "Donn Cave" wrote in message > | news:donn-D778C1.17100223112004 at gnus01.u.washington.edu... > | > I'm very sympathetic to the advantages of static typing > | > (NB, I read here that Python is strongly, though dynamically, > | > typed. It is not statically typed.) Rather than embrace > | > subtype polymorphism through inheritance, however, I see it > | > as evidence that no one has figured out how to make static > | > typing really work with OOP. There has to be a better way > | > to do it. > | > | You're right, I should have said statically typed instead of strongly > typed. > | > | But did you really mean "no one has figured out how to make *static* > typing > | really work with OOP" or did you mean *dynamic* typing? > > Static. I figure dynamic & OOP get along fine -- as Smalltalk showed, > along with I believe Objective C and of course Python. Static typing > and Functional Programming seem to go hand in glove, cf. Haskell type > classes. Static OOP seems to invite inelegant and unsound compromises. It's hard to argue against Smalltalk. I haven't used it for many years so I don't remember it but it was THE language of choice for an OOP course I took oh so many years ago. And I still see it mentioned as a model for OOP. I never learned Objective C so I cannot argue with that either. Unfortunately, as much as I am learning to like Python, I don't think I see it as a picture perfect OOP language. It may be a controversial opinion but I am not at all satisfied with encapsulation in Python (you cannot hide any of a class's implementation). Can you elaborate on problems that static languages have with OOP? We have been touching on parametric polymorphism and that is a valid point. I also see multiple inheritance as being very poorly implemented in C++ and Java to the point where books on C++ that treat the subject discourage you from using it and Java has effectively designed it out of the language (you can implement many interfaces but you can extend only one class). What do you have in mind? Dan > Donn Cave, donn at u.washington.edu From richardblackwood at cloudthunder.com Sat Nov 6 09:23:45 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sat, 06 Nov 2004 09:23:45 -0500 Subject: Python OS Message-ID: <418CDE71.4080303@cloudthunder.com> Is it possible to prototype an operating system in Python? If so, what would such a task entail? (i.e. How would one write a boot-loader in Python?) - Richard B. From deetsNOSPAM at web.de Mon Nov 22 09:09:30 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 22 Nov 2004 15:09:30 +0100 Subject: split large file by string/regex References: <41A1EF3E.1080409@holdenweb.com> Message-ID: > Depends on your definition of "simple", I suppose. The problem with > *not* using a lexer is that you'd have to examine the file in a sequence > of overlapping chunks to make sure that a regex could pick up all > matches. For me that would be more complex than using a lexer, given the > excellent range of modules such as SPARK and PLY, to mention but two. At least spark operates on whole strings if used as lexer/tokenizer - you can of course feed it a lazy sequence of tokens by using a generator - but that's up to you. -- Regards, Diez B. Roggisch From jelle.feringa at ezct.net Tue Nov 9 08:26:08 2004 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Tue, 9 Nov 2004 14:26:08 +0100 Subject: newbie question | shell scripting [html-removed] In-Reply-To: <777056A4A8F1D21180EF0008C7DF75EE03317167@sunbelt.org> Message-ID: <20041109132613.840AE1E4002@bag.python.org> I appreciate your comments! Its my intention to make a nice class-based module interface to my software, radiance. Though classes will help structure the interface, it wont resolve that my for loop creates more than one process. Which seems quite a fundamental problem, and is far beyond my (yet!) modest python skill. Hence my post. True, string interpolation is more elegant. I'll update this. I agree with your architectural comment. That's why I want to resolve my processes problem before moving the interface to a class based module. Cheers, Jelle. Btw: I haven't been able to find many resources on shell scripting. So far 'Programming Python 2nd edition' has been a great help. Any online tutorials you could recommend? > -----Original Message----- > From: Sells, Fred [mailto:fred at adventistcare.org] > Sent: Tuesday, November 09, 2004 1:49 PM > To: 'Jelle Feringa // EZCT / Paris' > Subject: RE: newbie question | shell scripting [html-removed] > > 1. if you're just learning to program, figuring out how to kill processes > on > windows from within Python may be more than you want to try right now. > > 2. take a look at the % operator, especially when used with a dictionary, > it > will make the code snippet you included much more readable. > > 3. If you are new to programming, take the time to get familiar with > Object > Oriented programming. It is actually easier than standard programming, > just > requires a different perspective. > > 4. My rule of thumb is that a python file should only be one page when > printed; two at most. To achieve this I do not use many comments but do > use > meaningful variable and method names. > > I realize I'm not answering your questions, but as an architect you should > know you have to first check out the foundation before adding a floor ;) From steve at holdenweb.com Fri Nov 12 11:57:48 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Nov 2004 11:57:48 -0500 Subject: modifying static (local) method variables In-Reply-To: References: Message-ID: <726ld.196$nj.146@lakeread01> t scytale wrote: > i am using a mutable default paramater to simulate a static method variable. > i notice that > - assigning to the var inside the method causes it to return to the > default value at each call. > - appending to the var gives the expected behaviour (the value is > preserved to the next call > > why is this? > Because an assignment to an argument inside the method merely rebinds the local variable for the remainder of that execution. Mutating the referenced object ensures that the changed value is available to further calls. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From paul at subsignal.org Wed Nov 3 17:39:16 2004 From: paul at subsignal.org (paul koelle) Date: Wed, 03 Nov 2004 23:39:16 +0100 Subject: recursive method in __init__ Message-ID: <2ut50iF2ev7vvU1@uni-berlin.de> hi all, I thought it would be nice to have instances that can "live" somehow in the "background" and do some tasks without being told so. The problem in the code below is: calling new_host = Host(ip, mac, collector) never "returns" because the the self.update() method gets called recursively. Im pretty sure I have to restructure the code and call the update() method from outside but I ask out of curiosity and to get some ideas how to do such things elegantly. thanks Paul class Host(object): def __init__(self, ip, mac, collector): '''ip and mac are strings, collector is a Collector() class instance from the loganalyze module''' re_ip = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') print "New host instance created" if not re_ip.match(ip): raise ValueError('Invalid IP address.') else: self._ip_addr = ip self._mac_addr = mac self.collector = collector # traffic counter self._minutes = [] self._additional_ips = [] self.update() def update(self): '''adds a dict with traffic for this host every minute''' print "Method update of class Host called" data = self.collector.get(self._ip_addr) if data: self.minutes.append(data) time.sleep(60) self.update() From elbertlev at hotmail.com Thu Nov 18 12:34:37 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 18 Nov 2004 09:34:37 -0800 Subject: Named tuples References: <30001hF2ptnqcU1@uni-berlin.de> <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> <10pntj5m0spvl3f@corp.supernews.com> <419c20da.344317031@news.oz.net> Message-ID: <9418be08.0411180934.522e7ce5@posting.google.com> Carlos Ribeiro wrote in message news:... > On Thu, 18 Nov 2004 05:04:16 GMT, Bryan wrote: > There are a few requirements that can be imposed to avoid problems. > First, __names__ is clearly a property, acessed via get & set (which > allows to trap some errors). It should accept only tuples as an > argument (not lists) to avoid potential problems with external > references and mutability of the names. As for the validation, I'm not > sure if it's a good idea to check for strings. maybe just check if the > 'names' stored in the tuple are immutable (or perhaps 'hashable') is > enough. With on changes to the language the same can be achived by using db_row module From deetsNOSPAM at web.de Mon Nov 8 17:12:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 23:12:21 +0100 Subject: Determining combination of bits References: <8KQjd.121796$hj.4674@fed1read07> <418ff674$1@nntp0.pdx.net> Message-ID: > A lapse of mind? >>>> n = 6 >>>> n & (-n) > 2 > > You probably meant n&1 or perhaps n%2. No, the exact right thing: 6 is binary 110 with the least significant bit beeing 10 thus the decimal value of 2. Albeit I have to admit that I didn't know the trick. -- Regards, Diez B. Roggisch From kbk at shore.net Wed Nov 24 01:23:33 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 24 Nov 2004 01:23:33 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200411240623.iAO6NXE3029528@h006008a7bda6.ne.client2.attbi.com> Patch / Bug Summary ___________________ Patches : 254 open ( +8) / 2700 closed ( +1) / 2954 total ( +9) Bugs : 784 open (+14) / 4629 closed (+15) / 5413 total (+29) RFE : 156 open ( +0) / 135 closed ( +0) / 291 total ( +0) New / Reopened Patches ______________________ os.path.exists returns False if no permission (2004-11-17) http://python.org/sf/1068277 opened by Robert Brewer small update for pdb docs (2004-11-17) CLOSED http://python.org/sf/1068456 opened by Ilya Sandler incomplete support for AF_PACKET in socketmodule.c (2004-11-19) http://python.org/sf/1069624 opened by Gustavo J. A. M. Carneiro xmlrpclib - marshalling new-style classes. (2004-11-20) http://python.org/sf/1070046 opened by Gabriel Pastor Add BLANK_LINE to token.py (2004-11-20) http://python.org/sf/1070218 opened by logistix bug#1021756: more informative error message (2004-11-23) http://python.org/sf/1071739 opened by Christos Georgiou raise error for common mistake with subprocess (2004-11-23) http://python.org/sf/1071755 opened by Nick Craig-Wood a new subprocess.call which raises an error on non-zero rc (2004-11-23) http://python.org/sf/1071764 opened by Nick Craig-Wood Add support for db 4.3 (2004-11-23) http://python.org/sf/1071911 opened by Michal Čihař Patches Closed ______________ small update for pdb docs (2004-11-18) http://python.org/sf/1068456 closed by rhettinger New / Reopened Bugs ___________________ subprocess is not EINTR-safe (2004-11-17) http://python.org/sf/1068268 opened by Peter ?strand linecache.py::update_cache strips directory info from files (2004-11-18) http://python.org/sf/1068477 opened by Tim Leslie confusing new method names for lists (2004-11-18) CLOSED http://python.org/sf/1068590 opened by McErnie TclError not a subclass of StandardError (2004-11-18) http://python.org/sf/1068881 opened by Russell Owen segfault on printing nested sequences of None/Ellipsis (2004-11-19) http://python.org/sf/1069092 opened by Jonas K?lker PyThreadState_SetAsyncExc segfault (2004-11-18) http://python.org/sf/1069160 opened by Tim Peters OS X (Panther) Framework Install causes version mismatch (2004-11-18) http://python.org/sf/1069198 opened by Dusty Harr "Python/C API Reference Manual" lost one Function (2004-11-19) CLOSED http://python.org/sf/1069287 opened by Raise L. Sail C:\Python24\Lib\compileall.py returns False (2004-11-19) http://python.org/sf/1069409 opened by PieterB import on Windows: please call SetErrorMode first (2004-11-19) http://python.org/sf/1069410 opened by Dimitri Papadopoulos Python 2.4c1 does not have universal newline support (2004-11-19) http://python.org/sf/1069433 opened by PieterB setup.py fails - cannot find byteyears.py (2004-11-20) http://python.org/sf/1070121 reopened by bcannon setup.py fails - cannot find byteyears.py (2004-11-20) CLOSED http://python.org/sf/1070121 opened by crescentd endianness detection fails on IRIX 5.3 (2004-11-20) http://python.org/sf/1070140 opened by Georg Schwarz urllib2 authentication redirection error(?) (2004-11-21) http://python.org/sf/1070735 opened by Allan B. Wilson urllib2 authentication redirection error(?) (2004-11-22) http://python.org/sf/1071147 opened by Allan B. Wilson os.walk example for deleting a full tree is sometime wrong (2004-11-22) CLOSED http://python.org/sf/1071087 opened by Olivier Bornet some latex reject the pdfinfo macro while generating html (2004-11-22) http://python.org/sf/1071094 opened by Marc-Antoine Parent Documented grammar for List displays incorrect (testlist) (2004-11-22) http://python.org/sf/1071248 opened by Lenard Lindstrom email: no way to add additional parameter to Content-Type (2004-11-22) CLOSED http://python.org/sf/1071459 opened by Tessa Lau test_sutil fails on cygwin (2004-11-23) http://python.org/sf/1071513 reopened by tebeka test_sutil fails on cygwin (2004-11-23) http://python.org/sf/1071513 opened by Miki Tebeka test_tcl fails on cygwin (2004-11-23) CLOSED http://python.org/sf/1071514 opened by Miki Tebeka test_subprocess fails on cygwin (2004-11-23) http://python.org/sf/1071516 opened by Miki Tebeka moneyfmt recipe in decimal documentation has error (2004-11-23) CLOSED http://python.org/sf/1071566 opened by Anna Ravenscroft coercing decimal to int doesn't work between -1 and 1 (2004-11-23) http://python.org/sf/1071588 opened by Anna Ravenscroft Windows msi doesn't install site-packages directory (2004-11-23) http://python.org/sf/1071594 opened by Anna Ravenscroft configure problem on HP-UX 11.11 (2004-11-23) http://python.org/sf/1071597 opened by Harri Pasanen difflib HTML support description incorrect (2004-11-23) CLOSED http://python.org/sf/1072124 opened by Dan Gass bad arg type to isspace in struct module (2004-11-23) http://python.org/sf/1072182 opened by Greg McFarlane re module segfaulting in large regular expression (2004-11-23) http://python.org/sf/1072259 opened by Erik Demaine Bugs Closed ___________ Obsolete info in Tutorial 9.1 (2004-11-15) http://python.org/sf/1067018 closed by rhettinger Small typo (2004-11-15) http://python.org/sf/1067023 closed by rhettinger subprocess works poorly on Windows with Python 2.3 (2004-10-29) http://python.org/sf/1057048 closed by astrand Overflow error seek()ing with float values > (2 ** 31) - 1 (2004-11-16) http://python.org/sf/1067728 closed by rhettinger Typo about PyErr_WriteUnraisable() (2004-11-14) http://python.org/sf/1066036 closed by rhettinger confusing new method names for lists (2004-11-18) http://python.org/sf/1068590 closed by rhettinger "Python/C API Reference Manual" lost one Function (2004-11-19) http://python.org/sf/1069287 closed by bcannon test_socket fails (2004-11-06) http://python.org/sf/1061429 closed by bcannon setup.py fails - cannot find byteyears.py (2004-11-20) http://python.org/sf/1070121 closed by bcannon setup.py fails - cannot find byteyears.py (2004-11-20) http://python.org/sf/1070121 closed by bcannon os.walk example for deleting a full tree is sometime wrong (2004-11-22) http://python.org/sf/1071087 closed by tim_one Ctrl-C doesn't work with sleepy main thread (2004-01-12) http://python.org/sf/875692 closed by kbk email: no way to add additional parameter to Content-Type (2004-11-23) http://python.org/sf/1071459 closed by bwarsaw test_sutil fails on cygwin (2004-11-23) http://python.org/sf/1071513 closed by jlgijsbers test_tcl fails on cygwin (2004-11-23) http://python.org/sf/1071514 closed by bcannon moneyfmt recipe in decimal documentation has error (2004-11-23) http://python.org/sf/1071566 closed by rhettinger difflib HTML support description incorrect (2004-11-23) http://python.org/sf/1072124 closed by jlgijsbers From imbosol at aerojockey.com Tue Nov 16 03:08:00 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 16 Nov 2004 00:08:00 -0800 Subject: determining the number of output arguments References: Message-ID: <60dfb6f6.0411160008.314cf6b7@posting.google.com> Darren Dale wrote in message news:... > I want to extend the capabilities of an existing function without breaking > backward compatibility. I used nargin and nargout (number of arguments in > and out) pretty extensively in Matlab. Well, it's already been said that it's not possible without some black magic. There are other ways to accomplish what you want, more or less, if you're open to other ideas. When I find that I want to add to a function, I typically do one of two things: 1. Add a flag in the argument list with a default value, like this: def function(a,b,c,new_behavior=False): pass Adds new capibilities, does not affect backwards compatibility. It's also more explicit; you can see that something different is going on from the call. Having the number of return arguments determine the function's behavior seems just a tad sneaky and backhanded to me. 2. Instead of adding capabilities to the function, refactor and write an new function. That is, take the stuff the stuff that's needed for both the old and new capabilities, and put it into its own function. Then write two functions, one for the new and one for the old capability, both of which call the refactored function. Oftentimes, it just makes more sense for two different capabilities to be in two different functions. [And nowhere is the need for this more apparent than in the libraries that ship with Matlab. I use Matlab quite a bit at work, and nothing about it annoys me more than the way they overload library functions to the extreme (and that's saying a lot). It's quite useful in some cases, but why exactly do they need to cram 50 different nonlinear programming methods, with all sorts of individualized options and constraints, into one function? (And this is AFTER they refactored the optimization toolbox.)] -- CARL BANKS From jcarlson at uci.edu Mon Nov 1 15:55:26 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 01 Nov 2004 13:55:26 -0700 Subject: LRU cache (and other things missing from the standard library ...) In-Reply-To: <20041101184758.GA7167@mylene.ghaering.de> References: <20041101184758.GA7167@mylene.ghaering.de> Message-ID: <20041101133948.0C4A.JCARLSON@uci.edu> Gerhard Haering wrote: > I recently implemented a LRU cache. And I wondered why such a useful class is > not already in the standard library. The only thing I found was a cookbook > entry but the comments said it was problematic. The comments were in regards to it not updating a cache entry on read. It has since been changed to update on read, as mentioned in the comments, and an underlying bug has also been fixed. > Btw. my implementation is currently at > http://initd.org/svn/initd/pysqlite/trunk/misc/lru.py Does anybody see any > problems with this code? I have not run your code, but it only offers get and display methods. While getting with your provided factory is certainly sufficient for adding items to the LRU, you do not offer a mechanism for removing items from the cache (if an item changes), nor iterating through items in the cache (which may be necessary). > I've already started translating it into C (*) , which speeds it up by between > factor 5 to 8. Maybe a candidate for the standard library once it's finished? Maybe, maybe not. There hasn't been much demand for the original recipe that mirrors a dictionary interface, and I wouldn't imagine that this new implementation would be of high demand either. - Josiah From donn at drizzle.com Sun Nov 28 13:57:52 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 28 Nov 2004 18:57:52 -0000 Subject: files in non-blocking mode? References: None Message-ID: <1101668271.956473@yasure> Quoth Uwe Mayer : | Hi, | | I want two python programs to communicate over stdIO channels. The one | executes the other via the popen3 function: | | amc = Popen3("./amc/amc.py", True, 0) | line = stdin.readline() | amc.tochild.write(line) | amc.tochild.flush() | print amc.fromchild.readlines() | | The problem is that although amc.tochild gets flushed the data never reaches | the client until the .tochild fd is closed. Is there any way to put IO | channels into non-blocking mode in python? The readlines() function on the last line there will return only when its file closes. You don't want non-blocking mode, or unbuffered file objects. As long as both ends are careful to 1) flush the output buffer after each line of output, and 2) read only one line at a time, with readline(), the two will get along fine. Donn Cave, donn at drizzle.com From ptmcg at austin.rr._bogus_.com Tue Nov 16 13:00:38 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 16 Nov 2004 18:00:38 GMT Subject: Idiom for default values when unpacking a tuple References: Message-ID: "Jeff Epler" wrote in message news:mailman.6434.1100624680.5135.python-list at python.org... So is there any easy way for the pad function to figure out for itself that the target length is 3, without my having to tell it so? -- Paul From donn at u.washington.edu Thu Nov 18 12:09:55 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 18 Nov 2004 09:09:55 -0800 Subject: imaplib ... understanding the result from a fetch of RFC822s References: <419bb3a7$0$259$edfadb0f@dread12.news.tele.dk> Message-ID: In article <419bb3a7$0$259$edfadb0f at dread12.news.tele.dk>, Max M wrote: > I am using the fetch command from the imaplib to fetch messages. I get a > result, but I am a bit uncertain as to how I should interpret it. > > The result is described at http://pydoc.org/2.3/imaplib.html as:: > > (typ, [data, ...]) = .fetch(message_set, message_parts) > > In RFC 2060 it says: "The data items to be fetched can be either a > single atom or a parenthesized list." > > So I do a fetch like: > > mailconn.uid('fetch', '1:*', '(RFC822)') > > As a result I receive the following results (from 2 different servers): > > # mailserver 1 > messages = [ > ('1 (UID 2 RFC822 {616}', "Received: from SNIP..."), > ')', > ('2 (UID 4 RFC822 {626}', "Received: from SNIP..."), > ')', > ] ... > Does anybody have a clue as to why imaplib returns results like that? It has to parse the response that far, in order to read the whole thing. That '{616}' is as you probably surmised the length of the following text, spanning more than a single line, so imaplib needs that number. The intent is not to provide you with a fully parsed IMAP4 response, you're just getting the data and whatever parsing was needed along the way. In a perversely ideal sense, it might have been better to put the pieces back together and just give you the response as one string. Donn Cave, donn at u.washington.edu From orionlux at voila.fr Mon Nov 1 06:01:52 2004 From: orionlux at voila.fr (orionlux) Date: Mon, 01 Nov 2004 12:01:52 +0100 Subject: question de bonne doc References: <418505b9$0$3662$8fcfb975@news.wanadoo.fr> <1gmkhbc.yxlo8f10l5uq5N%aleaxit@yahoo.com> Message-ID: <4186179a$0$31207$8fcfb975@news.wanadoo.fr> j ai deja achet? des livres O'Reilly qui m ont donn? entiere satisfaction et cet editeur est tres serieux cependant quand je disais que "Python en concentr?" "?tait d?cevant c ?tait ? mon point de vue , parce que moi je cherchais un livre plein d exemples de code, c est tout. Cependant je serai peut etre amen? ? l acheter quand j aurai progress? en langage python car ce livre me semble une bonne reference generale orionlux Alex Martelli wrote: > orionlux wrote: > ... >> les livres o'reilly sur python sont decevant > > Vous n'aimez pas "Python en Concentr?"? Je ne l'ai pas traduit > moi-m?me, bien sur -- mon Fran?ais, qui me vient encore d'une ?cole > superieure du temps de ma jeunesse, n'aurait surement pas suffit -- mais > il me parait n?anmoins bien traduit, et l'original Anglais, "Python in a > Nutshell", a eu une tres bonne r?ception. > > J'aimerai bien de recevoir des critiques (je ne lis pas les groupes > Fran?ais, seulement comp.lang.python; merci donc de m'envoyer une copie > des message par courier ?lectronique!) pour m'aider a travailler mieux > lors de la prochaine ?dition. > > > Merci beaucoup, > > Alex From menard.nospam.steve at gmail.nospamisaid.com Wed Nov 24 16:50:54 2004 From: menard.nospam.steve at gmail.nospamisaid.com (Steve Menard) Date: Wed, 24 Nov 2004 16:50:54 -0500 Subject: Python 2.4 and Visual C++ Express In-Reply-To: References: <9APod.4998157$ic1.468025@news.easynews.com> <30ji62F31ppn0U1@uni-berlin.de> Message-ID: <30kdu7F30o7vnU1@uni-berlin.de> Jive wrote: > "Steve Menard" wrote in message > news:30ji62F31ppn0U1 at uni-berlin.de... > >>Jive wrote: >> >>>Are you saying that Python 2.4 will not compile under MS VC++ 6.0? > > That's > >>>horrifying. Say it isn't so!!! I have just ported Python to an > > embedded > >>>system using VC++ 6.0. It will always be compiled using 6.0, for two >>>reasons: 1) I cannot afford the manhours for changing compilers, and 2) > > Bill > >>>Gates has enough money already, alright? I would hate to think that I > > am > >>>now stuck at Python 2.3 for eternity. >>> >> >>That is not what I am saying. The "what's new in Python" claims python >>2.4 will >>compile with both versions 6 and 7.1 of Microsoft's compiler. >> >>However, the standard download, that most users will have, will be >>compiled using the 7.1. And so any binary packages to be installed on a >>2.4 dist will also have to be compiled with 7.1. >> >> >>Steve >> > > > Do you mean if I install 2.4, I will have to find VC++ 7.1 versions of all > the extensions > I may be using? If so, that's still borderline horrible, but I guess > Microsoft is the culprit. Annow > for something completely the same. > > Will 7.1 extensions work with a Python.exe compiled under 6.0? > > In any case, I think it would be a Good Thing if the Pythonistas provided a > download of 2.4 > compiled under VC++ 6.0, in addition to the 7.1 one. > > I don't suppose it will do any good to rant about Microsoft. I believe it's > been done. > > > We can rant all we want, but let's be realistic : Version 6.0 is ancient! It is the version I was using at work almost 8 years ago! Would you hold that python on Linux should compile with an 8 year old version of GCC? At one point, a break must happen ... At least there seems a way to use MS's free 7.1 toolkit to compile, something that was'nt possible with version 6. Lastly, about existing extensions. Extension are python version specific. An extension compiled for python 2.3 will NOT work with python 2.4, no matter what. My guess is that soon after the release of Python 2.4, maintainers of existing packages will distribute them in 2.3 and 2.4 forms. My hope is that distuil will be intelligent enough to chose the right compiler when both will be present. I am one of those maintainers, and I do not want to have to jump through hoops to get my modules to compile ... Steve From niels_bohr at uol.com.br Sun Nov 7 15:42:14 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 18:42:14 -0200 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: <1099860134.4481.24.camel@localhost.localdomain> what about: >>> fat = lambda n: reduce(lambda x,y: x*y, range(1,n)) >>> int = lambda f,a,b,dx: sum([f(x) for x in arange(a,b,dx)])*dx/(b-a) Thoss (poorly) implements the factorial and integration function in just one line. So what does my pet examples show us? Nothing! The same goes for yours. So your poor affirmation about java compactness is the mere statement that the only kind of code you can produce is autoexec.bat sorting and the kinds. Every language has it's pros and cons, and having a compact expressive syntax is NOT one place where Java outshines python, ask any serious person. > > You lost. > You Pythonistas are a bunch of losers. > And your language is dog-slow. > Eeeeeek. > > And try to write Eclipse with your Mickey-Mouse-language! > > > Pythogoras > > > From ben.champion at gmail.com Fri Nov 19 14:41:43 2004 From: ben.champion at gmail.com (Ben Champion) Date: 19 Nov 2004 11:41:43 -0800 Subject: How can I store a result in a Matrix? Message-ID: <2617fd5d.0411191141.29b92814@posting.google.com> I am new to Python so please excuse me if this sounds simple! Before I explain what i want to do let me write some code in matlab which demonstrates what I would like to acheive, using the Fibonnachi series as an example: a = 1 b = 1 for i = 1:10 z = a + b a = b b = z y(i) = z end This gives me the variable y with values 2 3 5 8 13 21 34 55 89 144 which is essentially a matrix which i can plot against another matrix xof the same dimensions In python I have a = 1 b = 1 for i in range(1, 11) z = a + b a = b b = z which gives me all the values I need, but i do not know how to store the values of z in a single matrix. I have looked at several online resources and played about with the array commands but cant get it to work. If someone could point me to a relevant webpage or suggest code that will work I would be very grateful Thanks Ben From deetsNOSPAM at web.de Wed Nov 10 06:26:04 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 10 Nov 2004 12:26:04 +0100 Subject: html parsing? Or just simple regex'ing? References: Message-ID: > For the target database, unfortunately, the only interface we have access > to, is http+html based. There's same javascript involved too, but > hopefully we won't have to interact with that. Argl. That sounds like royal pain in somewhere... > So, I've got Basic AUTH going with http, but now I'm faced with the > following questions, due to the fact that I need to pull some lists out of > HTML, and then make some changes via POST or so, again over HTTP: > > 1) Would I be better off just regex'ing the html I'm getting back? (I > suppose this depends on the complexity of the html received, eh?) > > 2) Would I be better off feeding the HTML into an HTML parser, and then > traversing that datastructure (is that really how it works?)? I personally would certainly go that way - the best thing IMHO would be to make a dom-tree out of the html you then can work on with xpath. 4suite might be good for that. While this seems a bit overengineered at first, using xpath allows for pretty strong queries against your dom-tree so even larger changes in the "interface" can be coped with. And writing htmlparser based class isn't hard, either. > > 3) When I retrieve stuff over http, it's clear that the web server is > sending some kind of odd gibberish, which the python urllib2 API is > passing on to me. In a packet trace, it looks like: > > Date: Wed, 10 Nov 2004 01:09:47 GMT^M > Server: Apache/1.3.29 (Unix) (Red-Hat/Linux) mod_perl/1.23^M > Keep-Alive: timeout=15, max=98^M > Connection: Keep-Alive^M > Transfer-Encoding: chunked^M > Content-Type: text/html^M > ^M > ef1^M > ^M > ^M > ^M > > ...and so on. It seems to me that "ef1" should not be there. Is that > true? What -is- that nonsense? It's not the same string every time, and > it doesn't show up in a web browser. A webserver serving http doesn't care what you return - remember that http can also be used to transfer binary data. So the problem is not the apache, but whoever wrote that webapplication. Is it cgi based? For the ignoring part: Webbrowser tend to be very relaxed about html documents format, otherwise a lot of the web would be "unsurfable". So I'm not to astonished that they ignore that leading crap. -- Regards, Diez B. Roggisch From meyer at acm.org Wed Nov 3 05:14:28 2004 From: meyer at acm.org (Andre Meyer) Date: Wed, 03 Nov 2004 11:14:28 +0100 Subject: Python for PDAs/Mobile phones? Message-ID: Hi Pythoneers Some time ago there was an annoucement* of Python being implemented for Nokia phones. Is that project still alive? What are the options for running Python on mobile phones or PDAs? Thanks for your help Andre * http://www.mobileburn.com/news.jsp?Id=732 http://www.theregister.co.uk/2004/01/21/nokia_prefers_python_to_perl/ http://arki.uiah.fi/Documents/2004_06_11_pyth-20040521T215043 From carribeiro at gmail.com Wed Nov 3 08:45:07 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 3 Nov 2004 11:45:07 -0200 Subject: cherrypy/cheetah vs twisted/nevow In-Reply-To: <418818ca$0$19452$626a14ce@news.free.fr> References: <418818ca$0$19452$626a14ce@news.free.fr> Message-ID: <864d37090411030545481ff517@mail.gmail.com> On Wed, 03 Nov 2004 00:39:59 +0100, bruno modulix wrote: > Carlos Ribeiro a ?crit : > (snip) > > I'm yet to study nevow, but I'm getting more and more interested. I > > have my own approach to separation; I use to think about a third > > entity, "structure", as being independent from code & ui. The > > structure is the common part; it's the "glue" between ui and code; and > > it's the first part to be designed. > > Err... I may have missed something obvious, but doesn't this smells like > a good old MVC ?-) In a way, you're right. The problem is that none of the templating models that I know of completely separates the 'M' from the 'V'. Simple templates (PSP, for example) tend to bundle view & parts of the model together. There is no easy way to take them apart. The 'structure', as I call it, is not exactly a 'model' (imho the model includes other information that belongs in the DB design, but I may be wrong here), but it allows for a better separation. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From exarkun at divmod.com Fri Nov 26 16:52:39 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 26 Nov 2004 21:52:39 GMT Subject: dictionary initialization In-Reply-To: Message-ID: <20041126215239.17481.891692245.divmod.quotient.7079@ohm> On Fri, 26 Nov 2004 16:34:42 -0500, "Terry Reedy" wrote: > > "BJ???rn Lindqvist" wrote in message > news:740c3aec04112613043a0b0d2b at mail.gmail.com... > > >>> del x > > >>> x *= 5 > > > Maybe Python can't guess it, but *I* can guess, with 99% certainity, > > that the user wants x to be 0. :) > > However, it is 'obvious' to me that the 'proper' initialization is 1 and > the intended result should be 5. Or that the programmer forgot something > and that the proper response is to raise an error, as Python does. Wanting > 5 * undisclosed something to be 0 strikes me as unlikely and a distant > third since x = 0 is much easier to say. > > Also: 'x op= y' is defined as being semantically equal to 'x = x op y' > except for the single rather than double evaluation of x. No it isn't. It makes no difference in this case, but in others it is relevant: x = y = [] x += [1] vs x = y = [] x = x + [1] Jp From artyprog at wanadoo.fr Sun Nov 7 19:06:58 2004 From: artyprog at wanadoo.fr (salvatore) Date: Mon, 08 Nov 2004 01:06:58 +0100 Subject: Python OS In-Reply-To: References: Message-ID: <418eb899$0$18184$8fcfb975@news.wanadoo.fr> http://unununium.org/ Regards From mfuhr at fuhr.org Tue Nov 2 23:05:51 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 2 Nov 2004 21:05:51 -0700 Subject: getting socket.bind() exception, but no actual error References: <1224a8f9.0411011045.6740c5d8@posting.google.com> <1224a8f9.0411021007.26ec80da@posting.google.com> <4187d4fc$1_4@omega.dimensional.com> <8BWhd.30793$SW3.23350@fed1read01> Message-ID: <4188591f$1_2@omega.dimensional.com> Steve Holden writes: > Michael Fuhr wrote: > > > clarence at silcom.com (Clarence Gardner) writes: > > > >>And the whole point of the test in the exception handling suite (checking > >>for "in use") is to repeat the bind until that's not the case. This is, of > >>course, in a program in development which sometimes is not able to be > >>restarted right away after a problem. > > > > Why not? Because you get "Address already in use" exceptions due > > to old connections still being in the TIME_WAIT state? If so, are > > you aware that server processes should usually set the SO_REUSEADDR > > socket option before calling bind()? Or is there some other reason > > that bind() fails? > > There is some other reason: the exception argument is (errno 22, Invalid > argument), which is clearly not "Address in use". The retry loop likely isn't solving this problem but is rather causing it. The code originally posted was: sockobj=socket(AF_INET,SOCK_STREAM) while True: try: sockobj.bind(('',4321)) except socketerror,e: print e if str(e).find('in use') == -1: break print '.' time.sleep(1) sockobj.listen(5) Think about what happens if bind() succeeds: the code never breaks out of the while loop, so it attempts to call bind() again. On most systems that will cause the second call to bind() to fail with EINVAL, or "Invalid argument". You could break out of the loop when bind() succeeds, but the loop should be unnecessary if you set the SO_REUSEADDR socket option before calling bind(), like this: sockobj.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) Any decent network programming book (e.g., _UNIX Network Programming_, Vol 1, by W. Richard Stevens) will explain that servers should set SO_REUSEADDR before calling bind(). -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From nicolas.riesch at genevoise.ch Mon Nov 8 09:00:28 2004 From: nicolas.riesch at genevoise.ch (nico) Date: 8 Nov 2004 06:00:28 -0800 Subject: unicode string literals and "u" prefix Message-ID: In my python scripts, I use a lot of accented characters as I work in french. In order to do this, I put the line # -*- coding: UTF-8 -*- at the beginning of the script file. Then, when I need to store accented characters in a string, I used to prefix the literal string with 'u', like this: mystring = u"pr?nom" But if I understand well, prefixing a unicode string literal with 'u' will eventually become obsolete ( in python 3.0 ? ), as all strings will be unicode in a more or less distant future. So, to write "clean" script code, is it a good idea to write a script like this ? ---- myscript ---- #! /usr/local/bin/python -U # -*- coding: UTF-8 -*- s = 'h?l?ne' print len(s) print s ------------------- The second line says that all string literals are encoded in UTF-8, as I work with an editor that saves all my files as UTF-8. Normally, I should write s = u'h?l?ne' but the -U python option make python considers string literals as unicode string. ( I know the -U option can disappear in a next python version, but is not better to delete the "-U" option at the top of the scripts than all "u" unicode prefixes, when python will consider all strings as unicode ?... ) Finally, I write print s instead of print s.encode('utf-8') as I used to because I want this script to work on computer with other encodings. It seems that "print" encodes by default with the shell current encoding. Is this the best way to deal with accented characters ? Do you think that a script written like this will still work with python 3.0 ? Any comment ? From i_hate at spams.biz Tue Nov 30 09:09:36 2004 From: i_hate at spams.biz (i_hate at spams.biz) Date: Tue, 30 Nov 2004 15:09:36 +0100 Subject: private attributes in __slots__ and pickle References: <41ac7e5f$0$13412$636a15ce@news.free.fr> Message-ID: <41ac7ed0$0$13412$636a15ce@news.free.fr> i_hate at spams.biz wrote: > Hello, > I've just discovered the hard way that classes declaring private variables > (beginning with two underscore) can not be pickled ; double underscored I meant "declaring private attributes in __slots__" ; sorry. > attributes are just not returned by __reduce__. > > That's very annoying. > > Objects should be serializable transparently so why such obstacles ? From __peter__ at web.de Mon Nov 1 18:56:43 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Nov 2004 00:56:43 +0100 Subject: sublcassing dict without losing functionality References: <4aki52-fg7.ln1@valpo.de> Message-ID: Steven Bethard wrote: > simple. Modifying and using UserDict would give me some 60+ lines of code Not tested beyond what you see: >>> import UserDict as userdict >>> class Dict(userdict.DictMixin, dict): ... def __setitem__(self, key, value): ... if key in self: raise ValueError("key already exists") ... super(Dict, self).__setitem__(key, value) ... def __init__(self, other=None, **kw): ... super(Dict, self).__init__() ... self.update(other, **kw) ... >>> d = Dict({"one": 1}, one=2) Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __init__ File "UserDict.py", line 155, in update self.update(kwargs) File "UserDict.py", line 147, in update self[k] = v File "", line 3, in __setitem__ ValueError: key already exists >>> d["one"] = 3 Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __setitem__ ValueError: key already exists >>> Peter From carribeiro at gmail.com Mon Nov 8 07:16:25 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 8 Nov 2004 10:16:25 -0200 Subject: Email "portal" in Python? In-Reply-To: References: Message-ID: <864d37090411080416210b0546@mail.gmail.com> On 7 Nov 2004 20:19:56 -0800, Peter Clark wrote: > Think of something like MyYahoo: a personalized portal with news > aggregator, weather forecast, comics, etc. Now instead of visiting a > web site, think of all of it being sent daily as an email. It does > have a web interface, but mostly for selecting your content: this is > my location for weather, these are the news feeds I'm interested in, > these are the comics I like, save my preferences, and the server takes > care of the rest. Does such a thing exist? (Even in other non-Python > languages?) I've tried Freshmeat, and the other usual sources, but so > far, nothing. If there isn't any such creature, I'll write my own, but > I wanted to first check that I'm not re-inventing the wheel. What you are looking for is a *good* content management system, integrated with a mailing list manager. Perhaps there is something along these lines for Zope/Plone, but even if it exists, you'll probably need to customize it heavily. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From philippecmartin at sbcglobal.net Tue Nov 16 15:55:29 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 16 Nov 2004 14:55:29 -0600 Subject: Should I learn Python? Message-ID: <200411161455.29415.philippecmartin@sbcglobal.net> Richard Blackwood wrote: >> I would bet that you are exaggerating slightly, no? I wish I were, can you grasp the feeling of loss involved here ? Philippe From drew at gremlinhosting.com Sun Nov 21 15:23:30 2004 From: drew at gremlinhosting.com (Andrew James) Date: Sun, 21 Nov 2004 20:23:30 +0000 Subject: Small Database Needed In-Reply-To: <20041121145440.85318.qmail@web14004.mail.yahoo.com> References: <20041121145440.85318.qmail@web14004.mail.yahoo.com> Message-ID: <1101068610.15793.9.camel@odin> Kevin, There are several RDBMs packages you could look at, but for your particular use SQLite (http://www.sqlite.org/) seems like far and away the best solution for you. Its feature set isn't comprehensive (but definitely usable), and includes the the list you specified below. The major advantages this would provide for your particular use are blinding speed, small size and ability to be embedded within your program (makes distribution so much easier). Hope you find your solution, Andrew On Sun, 2004-11-21 at 06:54 -0800, Kevin McBrearty wrote: > Hello All, > > I'm looking at implementing DB in my program for > analysis of CAD (STL Files). This database will > require the basic functionality. > > Query > Sort > Delete/Add Records > > > I did some looking at the DB packages out there. But, > I'm not interseted in setuping up some huge thing. It > would be great if it is fast, but I can live with a > sub-optimal solution for the present. My interest is > in getting it up and running. > > Since, I'm new to Python so please don't hold back on > the comments. > > Regards, > Kevin > > > > __________________________________ > Do you Yahoo!? > Meet the all-new My Yahoo! - Try it today! > http://my.yahoo.com > > -- Andrew James From ola.natvig at infosense.no Thu Nov 25 04:40:51 2004 From: ola.natvig at infosense.no (Ola Natvig) Date: Thu, 25 Nov 2004 10:40:51 +0100 Subject: XUL Parser? In-Reply-To: References: <41A4B77C.3010703@advfn.com> Message-ID: <3ulg72-8e7.ln1@pluto.i.infosense.no> Andrew James wrote: > Alex, > This is a very cool idea. I've been working with XUL for a little while > now and I'd like to be able to work with it in Python.... all steam > ahead! > > Andrew > > On Wed, 2004-11-24 at 16:31 +0000, Alex Stapleton wrote: > >>Is there a Python XUL parser which will create GUIs in a Mozilla like >>fashion for me? I've had a poke around but the closest I could find was >>Luxor, and thats Jython bound (which isn't feasible.) >> >>If not is anyone interested in helping design and implment one? I'm >>rather keen on seeing a python XUL module which supports multiple widget >>systems (wxPython, Qt , GTK+ etc) wxPython has a XUL like system (not as sleek at XUL but quite usable) it's called XRC and allows you to specify your own witgets to. Take a look in the wxPython demo. It should be possible to implement a XSLT engine to transform Mozilla style XUL to a customized wxPython XRC dialect, I don't think performance mush of a brag... -- -------------------------------------- Ola Natvig infoSense AS / development From benji at benjiyork.com Fri Nov 12 23:39:28 2004 From: benji at benjiyork.com (Benji York) Date: Fri, 12 Nov 2004 22:39:28 -0600 Subject: permuting letters and fairy tales In-Reply-To: <60dfb6f6.0411121732.2e0ac82c@posting.google.com> References: <67lld8kr76.fsf@aster.homelinux.net> <60dfb6f6.0411121732.2e0ac82c@posting.google.com> Message-ID: <41959000.903@benjiyork.com> Carl Banks wrote: > My thought is that, the brain doesn't read the word as a whole as they > claim, but neither does it pay too much attention to the _exact_ > ordering. The basics of written word recognition theory are laid out in a good paper at "Microsoft typography". See http://www.microsoft.com/typography/ctfonts/WordRecognition.aspx or http://tinyurl.com/4qrnk for the full paper. -- Benji York benji at benjiyork.com From jfouhy at paradise.net.nz Tue Nov 9 21:31:52 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 9 Nov 2004 18:31:52 -0800 Subject: Floating point -> string conversions References: <1gmxb89.r6ndtk17sltbgN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gmxb89.r6ndtk17sltbgN%aleaxit at yahoo.com>... > John Fouhy wrote: > ... > > Why do the string and default floating point representations get rounded? > > > > (and is this documented anywhere?) > Sure, right in the "Tutorial (start here)" for example. > http://www.python.org/dev/doc/devel/tut/node16.html > Alex I knew I should have looked in the tutorial, rather than just the "numeric types" section of the library reference :-/ Actually, that page doesn't mention that '%f' will give you a different rounding again... -- John. From nmkolev at uni-bonn.de Wed Nov 10 16:08:58 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Wed, 10 Nov 2004 22:08:58 +0100 Subject: Combine two dictionaries into a list of 3-tuples Message-ID: Hi all, Continuing the search for interesting challenges with lists, tuples and dictionaries I am looking for a way to do the following. one = { 'a' : 1, 'b' : 2, 'c' : 3 } two = { 'a' : [4,5,6], 'b' : [8,9,10], 'c' : [11,12,13] } The goal is [('a', 1, [4,5,6]), ('b', 2, [8,9,10]), ('c', 3, [11,12,13])] My attempts so far: [(t, c, l) for t, c in one.items() if (t, l) in two.items()] gives me a 'l is not defined' --------------- [(t, c, l) for t, c in one.items() for (t, l) in two.items()] gives me a lot more than I need :-) --------------- Many thanks in advance! Cheers, -- Nickolay From jdhunter at ace.bsd.uchicago.edu Mon Nov 15 13:48:21 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Nov 2004 12:48:21 -0600 Subject: arrays In-Reply-To: (codedivine@gmail.com's message of "15 Nov 2004 10:42:11 -0800") References: Message-ID: >>>>> "Rahul" == Rahul Garg writes: Rahul> Hi. Is there someway i can get something similar to Rahul> multi-dimensional arrays in python.I dont want to use Rahul> Numarray Yes, you can use lists of lists for example. x = [ [None for i in range(10)] for j in range (12)] x[1][2] = 1 But it would help if you stated what your requirements are for the multi-dim array, what kind of objects you want to store in them, what kind of operations you need to be able to do, what your performance requirements are, and why you don't want to use numarray or Numeric for that matter. JDH From greg at cosc.canterbury.ac.nz Thu Nov 4 20:21:31 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 05 Nov 2004 14:21:31 +1300 Subject: strong/weak typing and pointers In-Reply-To: References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> Message-ID: <2v02svF2gjirkU1@uni-berlin.de> Diez B. Roggisch wrote: > I can remeber abusing 32bit pointers in 68k processors by > altering the most-significant byte. Apple did this in early versions of the Memory Manager of classic MacOS, using the upper 8 bits of a Handle for various flags. You weren't supposed to make any assumptions about what the upper byte contained, but of course some people did... and their applications broke when 32-bit addressing came in... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From niels_bohr at uol.com.br Sun Nov 7 15:09:33 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 18:09:33 -0200 Subject: PEP new assert idiom In-Reply-To: <1gmvm6b.131yfhfvdcrzpN%aleaxit@yahoo.com> References: <1gmurvv.1meude125h1zrN%aleaxit@yahoo.com> <1gmvgit.vzj5g4hv9dsrN%aleaxit@yahoo.com> <1gmvm6b.131yfhfvdcrzpN%aleaxit@yahoo.com> Message-ID: <1099858173.4481.10.camel@localhost.localdomain> [...] > > Nope, comma can never be used as implicit line continuation in Python > (that's different from some other languages). The opened and yet > unclosed parentheses are what cause several physical lines to be part of > the same logical line -- not commas, nor other operator or punctuation. > [...] > You may be associating "commas continue lines" with "function arguments" > because function definitions and calls DO use parentheses, and separate > arguments with commas. But it's really not an ideal mental model. You're right, that's a subtle misconception that don't give syntax errors so I never realize to be the case ;-) I was writing multiple line dictionaries like this: >>> dic = { \ ... key: value ... key2: value2 } The backslash is completely uncecessary (and ugly!). Thanks for clarification, -Fabio From rkern at ucsd.edu Wed Nov 24 12:29:44 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 24 Nov 2004 09:29:44 -0800 Subject: Vtk In-Reply-To: References: Message-ID: 3d wrote: > Hi, > > you have a information on the Vtk and its installation to use it with > python on windows? One easy way to get Python, VTK and a bunch of other goodies is to download the Enthought Edition of Python. http://www.enthought.com/downloads/downloads.htm There's an updated release coming out soon; I think next week or so. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From Scott.Daniels at Acm.Org Thu Nov 18 20:44:17 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Nov 2004 17:44:17 -0800 Subject: arrays In-Reply-To: <419bc81d$1@nntp0.pdx.net> References: <419bc81d$1@nntp0.pdx.net> Message-ID: <419d62d9$1@nntp0.pdx.net> Scott David Daniels wrote: > If you want to refer to a block of memory that you share with your C > code (especially if the C code controls the memory, you might also want > to check out my "Blocks and Views" code at: > > http://members.dsl-only.net/~daniels/block.html To follow up on my own post, once you have a View v of, say, 100 floating point data entries: >>> multidim = [v[x : x+1] for x in range(0, 100, 10)] >>> revdim = [v[x : 100 : 10] for x in range(10)] >>> v[27] 43.6 >>> multidim[2][7] 43.6 >>> revdim[7][2] 43.6 >>> multidim[2][7] = 19.1 >>> multidim[2][7] 19.1 >>> revdim[7][2] 19.1 >>> v[27] 19.1 That is, you maintain the mapping to the original memory when taking strides. All subscript operations change how the memory is referenced, not take copies of the memory. --Scott David Daniels Scott.Daniels at Acm.Org From br_y at yahoo.de Mon Nov 22 10:26:42 2004 From: br_y at yahoo.de (Birgit Rahm) Date: Mon, 22 Nov 2004 16:26:42 +0100 Subject: [Beginner] delete items of [] also from memory References: <41a1a1da$0$8190$8fcfb975@news.wanadoo.fr> <41a1e5b9$0$9075$8fcfb975@news.wanadoo.fr> Message-ID: > What makes you think the memory is not given back to the system? Does the memory > occupied by your script increase and increase, or do you just see the memory > occupied by your script remain constant when you do the del a[:]? In the latter > case, it may be perfectly normal: it is quite frequent that the memory freed by > an operation is not returned immediatly to the system, but kept for future use > by the program. > ok, I think that helped me to understand what's going on in my program and why the memory is not freed immediately. I will take del A[0:]. Thanks to all, Birgit From steve at holdenweb.com Tue Nov 2 20:39:46 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Nov 2004 20:39:46 -0500 Subject: sh: test: argument expected In-Reply-To: References: Message-ID: Iv?n Cabria wrote: > Hi, > > I am a new user of python. I ran > a python script and I got the > following message: > > sh: test: argument expected > > I found that this error came from a > line in the script: > energy = atoms.GetPotentialEnergy() > > I looked for a solution to this > problem in Internet and I found > (http://www.experts-exchange.com/Operating_Systems/Unix/Q_20706303.html) > that the problem was that the variable > was not initialised. I also found > that the bash shell initialises the variables > automatically and the Bourne shell (sh) does not. > (http://www.experts-exchange.com/Operating_Systems/Unix/Q_20706303.html) > > I suppose that 'sh:' in the error message > means that the script is using the Bourne shell, > and hence, I understand the message error. > > However, I was using the bash shell in the computer > I ran the script, not > the Bourne shell (sh). Hence, I do not > understand the 'sh:' in the error message. > Could be that python scripts are using by default the > Bourne shell? > > The first line of the python script is: > #!/usr/bin/env python > > Thanks in advance. > > Question 1: if you run the script using "python scriptname.py" does the error go away? If so then your script is being executed by the shell and not by the python interpreter. Question 2: Are there any blank lines or empty spaces before #!/usr/bin/env python ? regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From jblaine at mitre.org Wed Nov 10 13:06:11 2004 From: jblaine at mitre.org (Jeff Blaine) Date: Wed, 10 Nov 2004 13:06:11 -0500 Subject: "Rails"-like thing for Python? Message-ID: Like many people, I've recently been turned onto "Ruby On Rails" (I believe it was a Slashdot article release announcement recently) and didn't know it existed before then. I've been writing Python code for 6 years now, on and off, and I have to say I am leaning more and more toward at least learning Ruby and doing my next few projects with it. I am curious if there is anything like the Rails framework for Python? Specifically, I mean a generalized framework for rapidly performing web application building. One that does it consistently, well, etc. Zope is far from what I mean. From f.geiger at vol.at Fri Nov 5 03:51:31 2004 From: f.geiger at vol.at (F. GEIGER) Date: Fri, 5 Nov 2004 09:51:31 +0100 Subject: Umlauts, encodings, sitecustomize.py Message-ID: I'm on WinXP, Python 2.3. I don't have problems with umlauts (?, ?, ? and their uppercase instances) in my wxPython-GUIs, when displayed as static texts. But when filling controls with text containing umlauts, or in the Python console, or when writing to files umlauts are escaped: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> "?" '\x84' >>> I have defined a sitecustomize.py with these lines in it import sys sys.setdefaultencoding("iso-8859-1") What else do I have to adjust? Kind regards Franz GEIGER From FBatista at uniFON.com.ar Thu Nov 11 16:31:21 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 11 Nov 2004 18:31:21 -0300 Subject: I don't quite get this "string".find() Message-ID: [Grant Edwards] #- > I don't know why the function was set up this way. #- However, an empty #- > string can be found in an infinite number of places within #- any other #- > string. #- #- How so? There aren't an infinite number of places _in_ a #- finite-length string. Beware! You can not deal with infinities (in strings, for example, or surviving inside a black hole) unless you are Tim Peters. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Nov 16 03:47:46 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Nov 2004 09:47:46 +0100 Subject: determining the number of output arguments References: Message-ID: Darren Dale wrote: > I want to extend the capabilities of an existing function without breaking > backward compatibility. I used nargin and nargout (number of arguments in > and out) pretty extensively in Matlab. Here is another alternative to achieve backward compatibility: class Result(object): def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d def __iter__(self): yield self.a yield self.b yield self.c def old(): return 1, 2, 3 def new(): return Result(1, 2, 3, 4) # the old function a, b, c = old() print a, b, c # the new function, called by old code a, b, c = new() print a, b, c # the new function, called by new code r = new() print r.a, r.b, r.c, r.d If old code doesn't always immediately unpack, you can implement __getitem__(), too, or subclass tuple: class Result(tuple): def __new__(cls, *items): items = list(items) if len(items) == 3: d = None elif len(items) == 4: d = items[-1] items = items[:-1] else: raise ValueError result = tuple.__new__(cls, items) result.d = d return result a = property(lambda self: self[0]) b = property(lambda self: self[1]) c = property(lambda self: self[2]) In effect you are switching to an object-oriented interface while staying compatible with old code. This makes future updates a breeze, e. g. if the calculation of d is costly you could defer it until really needed: class Result(object): ... d = property(lambda self: max(self.a, self.b, self.c) + 42) Peter From huw.davies at kerberos.davies.net.au Thu Nov 4 06:23:30 2004 From: huw.davies at kerberos.davies.net.au (huw.davies at kerberos.davies.net.au) Date: 4 Nov 2004 11:23:30 GMT Subject: Ranting about the state of Python IDEs for Windows References: <864d3709040913131077f1732d@mail.gmail.com> Message-ID: Jorge Godoy wrote: > I guess I heard something like that from a client of mine. He told me > about Sun X Terminals with memory cards. You plug your card and there > you are. You go out for lunch, take your card with you, and when you > come back you can choose any other workstation available: just plug your > card and resume your work. > > Of course, for it to work I would need a new machine :-) > There's already some support for it in KDE. It always opens the > programs I was running before exiting and for the ones with support, it > even opens the locations (e.g. directories on konsoles I have, tabs on > Firefox/Mozilla, etc.). You can do this today with any Linux box and VNC. There's a good article on how to set this up in The Linux Journal. It used to be available on-line but it looks like it's been limited to subscribers only now. I set this up and used it for a while but I'm now using a laptop (Mac Powerbook) for my Python stuff. Just close the lid when you've finished and open it up again to continue.... .sig lost after the last hard drive failure :-( From theller at python.net Fri Nov 12 06:03:23 2004 From: theller at python.net (Thomas Heller) Date: Fri, 12 Nov 2004 12:03:23 +0100 Subject: ZIP files References: <808f000f.0411100805.7bff7e5d@posting.google.com> <6f402501.0411120120.3f5147d6@posting.google.com> <1gn4y9w.3frb611oy9y8pN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Michael Foord wrote: > >> Hmmm... does this mean that >> >> open(filename, 'w').write(filedata) >> >> is unsafe ? It's so much more convenient when the object is only going >> to be used for the single action. > > It's not exactly unsafe -- but you do risk, depending on what > implementation of Python you're dealing with, that the file object will > just stay open until some unknown time in the future (no later than the > end of your program's run;-). This may potentially lead to problems if > your program is long-running or open lots of files, etc. > > def write_data(filename, data, flags='w'): > fileobject = open(filename, flags) > try: fileobject.write(data) > finally: fileobject.close() > > needs to be coded once, and then makes the operation just as convenient > as doing it inline... I'd suggest to expand this a bit, and make it working correctly on windows too, where binary files must be opened with the 'b' flag: def _write_data(filename, data, flags): fileobject = open(filename, flags) try: fileobject.write(data) finally: fileobject.close() def write_data(filename, data, flags="wb"): _write_data(filename, data, flags) def write_text(filename, text, flags="w"): _write_data(filename, data, flags) plus the corresponding read_data() and read_text() functions. Hm, add an encoding for unicode, maybe... Cookbook recipe, or standard lib? Thomas From johng2001 at rediffmail.com Mon Nov 1 22:18:58 2004 From: johng2001 at rediffmail.com (John) Date: 1 Nov 2004 19:18:58 -0800 Subject: ruby on rails ... python on ? References: Message-ID: > yeah, zope. > > It is so good it does not even look like python on the > surface ... one of the biggest mistakes in developing > web-frameworks is over-emphasizing the underlying > programming language. > > A good web-framework should not look like > Ruby or Python, that is not what these languages were > designed for. Why do you say that? I could agree if Zope could be programmed in many languages. Then not tending to any language would be a benefit. On the contrary, I see things like ZODB making things that are not Pythonic, look Pythonic and that is considered a good feature. A Python only framework not feeling like Python was a deterrent for me to learn Zope well. From me at privacy.net Wed Nov 24 06:48:56 2004 From: me at privacy.net (Dan Sommers) Date: 24 Nov 2004 06:48:56 -0500 Subject: Is there a consensus on how to check a polymorphic instance? References: <1101189570.958016.283130@f14g2000cwb.googlegroups.com> <-sSdnZs3heYawz7cRVn-iA@rogers.com> <1101268711.261729.54980@c13g2000cwb.googlegroups.com> Message-ID: On 23 Nov 2004 19:58:31 -0800, "Mike Meng" wrote: First off, I have only been following this thread on and off, so if I'm repeating things, I apologize. > It seems to me the virtue of dynamic langauge is, if it looks like a > cat, it's a cat ... Google for "duck typing." > ... But the problem is still there: how do you know what it looks like > before you treat it as a cat? isinstance(), , as Steve state, is too > rigid. You don't. Python also takes a "we're all adults here" philosophy. If your API specifies "cat," and I pass your function an "InterfaceAdapter," it's *my* problem. If you're truly paranoid, make sure that your arguments at least have the methods you're going to use: # write 'foo' to the file-like object x; don't bother if x is not # sufficiently file-like def f( x ): try: x.write except AttributeError: pass else: x.write( 'foo' ) # this works, too, but doesn't scale well (i.e., if 'foo' is some # other non-trivial (maybe non-trusted) operation that can raise # AttributeError): def f( x ): try: x.write( 'foo' ) except AttributeError: pass Regards, Dan -- Dan Sommers Never play leapfrog with a unicorn. From levub137 at wi.rr.com Sun Nov 28 07:48:38 2004 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 28 Nov 2004 12:48:38 GMT Subject: ANN: rpncalc-1.0 RPN Calculator For Python Message-ID: Module that adds an interactive Reverse Polish Notation (RPN) interpreter to Python. This interpreter allows the use of Python as an RPN calculator. You can easily switch between the RPN interpreter and the standard Python interpreter. Home page: http://calcrpnpy.sourceforge.net/ From sean_mcilroy at yahoo.com Mon Nov 22 19:15:15 2004 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 22 Nov 2004 16:15:15 -0800 Subject: drag and drop graphics in tkinter? Message-ID: The subject line essentially says it all. Is there a way to do it? If so, where do I look to find out how? Any help will be much appreciated. Thx, STM From __peter__ at web.de Fri Nov 19 07:55:34 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Nov 2004 13:55:34 +0100 Subject: avoiding nested try/excepts References: Message-ID: Steven Bethard wrote: > (1) Should I really worry about localizing try-except blocks? and, if so Not when the error-handling doesn't take advantage of the greater locality. > (2) Is there a cleaner way to do this kind of thing? I've always thought that catching an exception was the clean way that replaces dealing with functions returning error codes. > Note that I can't edit the g or k functions, so I can't move the > try-except blocks inside. If you cannot modify, you can still wrap them: >>> def catch(*exceptions): ... def make_catcher(f): ... def catcher(*args): ... try: ... return f(*args) ... except exceptions: ... print "caught it" ... return catcher ... return make_catcher ... >>> @catch(ZeroDivisionError) ... def f(a, b): return a / b ... >>> f(1, 2) 0 >>> f(1, 0) caught it >>> You may guess at what line in the above it dawned on me that you'd be better off with individual wrappers than a generalized decorator... Peter From elie at flashmail.com Wed Nov 3 12:30:41 2004 From: elie at flashmail.com (Eli Daniel) Date: 3 Nov 2004 09:30:41 -0800 Subject: Extending Python questions Message-ID: Hi, I am relative new to Python. Please tell me if the following is possible. I have a command line shell written in C. This shell executes some commands which I would like to import to the python shell. Here is an example command from my shell: openconnection www.yahoo.com 12 2000 So I've created a dll (myshell_d.dll) according to the manual ("Extending Python with C or C++") and it works. The problem is the syntax I have to use now is myshell.openconnection('www.yahoo.com',12,2000) It's not only the problem of comfort - it's a problem of changing *some* scripts. And there's more than that - my shell functions already know how to handle it's arguments (which's number may vary), it doesn't need python to do that. All it needs is a pointer to a string representing the arguments (in our case "www.yahoo.com 12 2000"). I've tried using PyArg_UnpackTuple but without success. So I have two questions: 1. Is it possible to move the calls to a upper level (i.e. call "openconnection" and not "myshell.openconnection") ? 2. Is is possible to remove the brackets and commas? (i.e. "www.yahoo.com 12 2000" instead of ('www.yahoo.com',12,2000)? My final goal is to use the original commands if possible. thanks in advance, Eli From ncoghlan at email.com Fri Nov 26 11:16:05 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sat, 27 Nov 2004 02:16:05 +1000 Subject: Few things In-Reply-To: <5c882bb5.0411251641.6177ee9d@posting.google.com> References: <5c882bb5.0411251641.6177ee9d@posting.google.com> Message-ID: <41a756c6$0$25782$5a62ac22@per-qv1-newsreader-01.iinet.net.au> bearophile wrote: > I think a better syntax for such multiline strings can be something > like: remove from all the beginnings of the lines successive to the > first one a number of spaces equal to the position of ''' in the > soucecode. Indeed, a similar rule is used by docstring parsing tools (e.g. the builtin help() function). The raw text is kept around, but the display tools clean it up according to whatever algorithm best suits their needs. >>> def foo(): ... '''This is just a ... silly text''' ... >>> print foo.__doc__ This is just a silly text >>> help(foo) Help on function foo in module __main__: foo() This is just a silly text Raw docstrings are rarely what you want to be looking at. The best place for info on recommended docstring formats is: http://www.python.org/peps/pep-0257.html If you absolutely, positively need the raw docstrings to be nicely formatted, then line continuations can help you out: >>> def bar(): ... "This is actually "\ ... "all one line\n"\ ... "but this is a second line" ... >>> print bar.__doc__ This is actually all one line but this is a second line I'd advise against actually doing this, though - it's non-standard, handling the whitespace manually is a serious pain, and most docstring parsers clean up the indentation of the conventional form automatically. Cheers, Nick. From shashishekar.jagadish at hp.com Thu Nov 18 01:55:45 2004 From: shashishekar.jagadish at hp.com (shashi) Date: 17 Nov 2004 22:55:45 -0800 Subject: Need help with Serial port communication Message-ID: I am trying to implement the following -> Capability to interact with server during boot via serial port -> Cause server to crash (TOC) on command. The setup is we are managing many servers, and remotely rebooting and configuring the servers, when rebooting we would like to control the booting process (intel machine). For non Intel machine (HP-UX to be specific) we can do that using GSP (Telnet). Need help or ideas how it could be done on intel machines (Linux & Windows) using serial port. Thank you. shashi From jzgoda at gazeta.usun.pl Wed Nov 24 15:37:18 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 24 Nov 2004 21:37:18 +0100 Subject: asynchat and threading In-Reply-To: References: Message-ID: Anthony Baxter wrote: >>I've embarked on a small learning project, trying to get a better grasp of >>the asyncore and asynchat modules. The project involves building a simple >>instant messenger application for use on our LAN - nothing heavy duty, as >>99% of my reason for doing this is just to learn. > > I can only paraphrase what I said in a recent python-dev thread - > absolutely *no-one* should be starting new projects using asyncore and > asynchat. Use twisted, instead - it's cleaner, saner, has an active > development community, and is in all ways a better solution than the > asyncore approach. > > asyncore based code causes bleeding from the eyes and brain leakage > through the ears. Well, when writing simple (when I write "simple" I mean "really simple") server or client for some simple ("really simple") protocol, Twisted may be big overhead. I remember somebody said that if you need multiprotocol application server then go with Twisted, but if you need client or server for simple conversational protocol (like HTTP or NNTP), asyncore/asynchat should be sufficient. That doesn't mean I downplay Twisted. I really like it. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From sw at wordtech-software.com Wed Nov 10 05:17:36 2004 From: sw at wordtech-software.com (Kevin Walzer) Date: Wed, 10 Nov 2004 05:17:36 -0500 Subject: ANN: PyQt-Mac installer available Message-ID: <5Vlkd.1069$yk5.385@fe37.usenetserver.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 PyQt-Mac is a binary installer of the various components of Qt and PyQt for Mac OS X. Included are the following: ? * A complete build of Qt/Mac with QScintilla support. ? * A compiled binary of Sip, the application that converts Qt's C++ base into Python bindings. ? * PyQt. ? * Eric 3, an integrated development environment (IDE) for Python written with the PyQt toolkit. These packages include both compiled binaries and complete source code. For more information, http://www.wordtech-software.com/pyqt-mac.html. - -- Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBkeqzJmdQs+6YVcoRApnZAJ4pc/sP2NmybJ6JOb3kSXUaGoBBygCcCHPx 6upq87BzVyaXLpQnyMztv2I= =57qD -----END PGP SIGNATURE----- From barry at python.org Mon Nov 29 02:16:15 2004 From: barry at python.org (Barry Warsaw) Date: Mon, 29 Nov 2004 02:16:15 -0500 Subject: Standalone email package 3.0 final Message-ID: <1101712575.19174.59.camel@presto.wooz.org> Python 2.4 final will probably be released in a few hours so this seems like a good time to release the standalone email package, version 3.0 final. Unless there's some last second snafu, this will be identical to the version released with Python 2.4. email 3.0 is compatible with Python 2.3 and 2.4. If you need to support earlier versions of Python, stick with email 2.5.5. For documentation (until Fred flips the "current" docs switch) and download links, please see the email-sig home page: http://www.python.org/sigs/email-sig Changes in email 3.0 include: * New FeedParser provides an incremental parsing API for applications that may need to read email messages from blocking sources (e.g. sockets). FeedParser is also more standards compliant than the old parser and is "non-strict", so that it should never raise parse errors when parsing broken messages. * The old Parser API is (mostly) supported for backward compatibility. * Previously deprecated API features have been removed, while a few more deprecations have been added. * Support for Pythons earlier than 2.3 have been removed. * Lots and lots of fixes. Feel free to join the email-sig mailing list for further discussion. -Barry -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 316 bytes Desc: This is a digitally signed message part URL: From bearsprite at gmail.com Thu Nov 25 22:11:55 2004 From: bearsprite at gmail.com (zhao) Date: 25 Nov 2004 19:11:55 -0800 Subject: Use Python library from C++ In-Reply-To: <89cc6e1f.0411241939.61a19596@posting.google.com> References: <89cc6e1f.0411241939.61a19596@posting.google.com> Message-ID: <1101438715.616658.236260@z14g2000cwz.googlegroups.com> swig is a interface of C/C++ to python, but not in reverse. In term of python document, there are extend and embed, and your need is embed. below is a short tutorial, maybe helpful: http://tutorials.impereonsoft.com/python/extemb.html if you work in windows, and you have install pywin32 package, it expose a com interface of python interpreter, so you also can use python's script or module in your application by this interface. if you use BCB, you can use a VCL component name "Python for Delphi". From ptmcg at austin.rr._bogus_.com Tue Nov 30 14:38:46 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 30 Nov 2004 19:38:46 GMT Subject: decorators ? References: Message-ID: "km" wrote in message news:mailman.6942.1101835501.5135.python-list at python.org... > Hi all, > was going thru the new features introduced into python2.4 version. > i was stuck with 'decorators' - can someone explain me the need of such a thing called decorators ? > tia > KM Here are some example on the Python Wiki: http://www.python.org/moin/PythonDecoratorLibrary I think memoize is my favorite so far. I'm not sure if the example behavior is all that clear. For a given set of arguments, the Memoize class keeps a dictionary of input arg values and return values. In subsequent calls, sets of args are looked up in the dictionary of previous calls - if the arg list is found, then the function is bypassed, and the cached return value is returned immediately. This can greatly speed up calls to functions that are very time-consuming, or recursive. This is why the Wiki page lists factorial() and fibonacci() examples. Of course, Memoize assumes that the return value is purely a function of the input args, and not subject to any external state. Of course, one could readily implement this behavior within the target functions. The beauty of the decorator is that this optimization is done *completely* outside the function itself, so the function remains fairly pure at the application level, and does not get cluttered with variables like "resultsCache" and so on. Also, in the interests of maximizing reuse and avoiding the bug-proneness of cut-and-paste, isolating Memoize into a reusable decorator helps avoid introducing bugs (vs. hard-coding this optimization into successive functions - did you remember to initialize the dictionary?), and leverages any optimizations or bug-fixes. (I focused on Memoize, but these comments apply to any of the decorators on this wiki page.) -- Paul From jeff at ccvcorp.com Fri Nov 19 18:27:04 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 19 Nov 2004 15:27:04 -0800 Subject: Python switch for syntax checking In-Reply-To: <419e6c1b.494654145@news.oz.net> References: <419e6581$1@nntp0.pdx.net> <419e6c1b.494654145@news.oz.net> Message-ID: <10pt03bdpp7gp89@corp.supernews.com> Bengt Richter wrote: >On Fri, 19 Nov 2004 12:08:00 -0800, Scott David Daniels wrote: > > > >>First, "python MyApp.py" does a syntax check anyway. If MyApp is >>not a main program, all you get is the syntax check. As for main >> >> >??? What does "not a main program mean"? I'm not sure what you mean, e.g., > > I believe that Scott is referring to the difference between a file run from the commandline, in which __name__ is set to "__main__", and a file that's imported as a module, in which __name__ is set to the name of the module, which is normally the filename minus the .py[c|o|d] extension. Of course, this would also imply that Scott is presuming that one is following the good programming practice of not putting any significant code (other than function, class, and global variable definitions) at module level, except where protected by an 'if __name__ == "__main__":' statement. That *is* good practice, and most people do it, but it's not required so perhaps not a safe presumption... Jeff Shannon Technician/Programmer Credit International From steve at holdenweb.com Tue Nov 23 08:26:21 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Nov 2004 08:26:21 -0500 Subject: unicode question In-Reply-To: <41a28c3d.765024687@news.oz.net> References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> <41A061E1.8050203@v.loewis.de> <41a0ab62$0$151$9b622d9e@news.freenet.de> <41a1d80d.718896828@news.oz.net> <41a27514$0$179$9b622d9e@news.freenet.de> <41a28c3d.765024687@news.oz.net> Message-ID: <41A33A7D.7090506@holdenweb.com> Bengt Richter wrote: > On Tue, 23 Nov 2004 00:24:09 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: > > >>Bengt Richter wrote: >> >>>So, bottom line, as Wolfgang effectively asked by his example, why does print try to coerce >>>the __str__ return value to ascii on the way to the ouput encoder, when there is encoding info >>>in the unicode object that it is happy to defer reencoding of for sys.stdout.encoding? >> >>[See my other posting:] >>Because print invokes str() on its argument, unless the argument is >>already a byte string (in which case it prints it directly), or a > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- effectively an assumption that > bytestring.decode('some_unknown_encoding').encode(sys.stdout.encoding) > has already been done, it seems (I'm not arguing against). > > >>Unicode string (in which case it encodes it with the stream encoding). >>It is str(y) that fails, not the printing. >> > > Yes, I think my turgid post did demonstrate that, among other things ;-) > > So how about changing print so that it doesn't blindly use str(y), but instead > first tries to get y.__str__() in case the latter returns unicode? > Then print y can succeed the way print y.__str__() does now. > > The same goes for str.__mod__ -- it apparently knows how to deal with '%s'% unicode(y) > so why shouldn't '%s'%y benefit when y.__str__ returns unicode? > > I.e., str doesn't know that printing and '%s' can use unicode to good effect > if it available, so for print and str.__mod__ blindly to use str() intermediately > throws away an opportunity to do better ISTM. > > Regards, > Bengt Richter Am I the only person who found it scary that Bengt could apparently casually drop on a polynomial the would decode to " L?wis"? feel-dumb-just-being-in-the-same-newsgroup-ly y'rs - steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From rdm at rcblue.com Mon Nov 22 05:07:46 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon, 22 Nov 2004 02:07:46 -0800 Subject: Trouble with psyco Message-ID: <6.1.2.0.2.20041122020641.042be500@rcblue.com> psyco is acting a bit psycho for me. Please see my spinForWeb.py at When psyco is in use, entering an integer somewhere between 2000 and 2500 causes my computer to freeze. Not really freeze but the program doesn't finish, and I have to quit with a ^Q. psyco is really impressive, but I'm disappointed that I can't demonstrate (to friends) counting with it to numbers above 2 billion. If I remark out the "psyco.bind(spin)" line, there's no problem no matter what integer I enter. Can someone explain what the problem with psyco is? Windows XP, Python 2.3.4 Thanks, Dick Moores rdm at rcblue.com From zach at cs.uni-bonn.de Fri Nov 5 11:45:24 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 5 Nov 2004 16:45:24 GMT Subject: generic way to access C++ libs? Message-ID: Is there any generic way to use C++ libraries from within Python. I seem to recall that there are tools to generate wrappers for C-libraries semi-automatically. But those were still way too cumbersome, IMHO. What I would like to have is some module (or whatever), with which I can say "load this C++ library", and then, "create that C++ object" or "call method x of C++ object y". Without doing anything else (such as recompiling the library or generating wrappers). I agree that templates could pose a major problem, so I would be happy if it worked with pre-instantiated templates. Is there anything? Gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From duncan.booth at suttoncourtenay.org.uk Fri Nov 19 10:57:58 2004 From: duncan.booth at suttoncourtenay.org.uk (Duncan Booth) Date: Fri, 19 Nov 2004 15:57:58 -0000 Subject: Class Encapsulation Errors in Python 2.3.3 In-Reply-To: <864d370904111907431909378e@mail.gmail.com> References: Message-ID: <419E1806.3419.2EED40D8@localhost> > On 19 Nov 2004 10:44:56 GMT, Duncan Booth > wrote: > Jeff Shannon wrote: > > > The problem here is that default values > in functions/methods are > > evaluated at *compile* time. > > Actually, > no. The default values in functions/methods are evaluated when > the def > statement is *executed* not when anything is compiled. If you > execute > the def multiple times the default values are recalculated each > time. > > Be careful :-) default values are calculated when the def statement is > executed.... which is not the same as to say that they are calculated > every time the function is called. > I actually thought I had stated the case fairly clearly, but I suppose understanding what you think you have said isn't the same as communicating it to the audience. :) -- Duncan Booth duncan.booth at suttoncourtenay.org.uk From steve at ferg.org Tue Nov 16 20:29:09 2004 From: steve at ferg.org (Stephen Ferg) Date: 16 Nov 2004 17:29:09 -0800 Subject: seeking a new host for the "Python Grimoire" Message-ID: The "Python Grimoire" was developed and released by Andrew M. Kuchling in May, 1999. However, it never reached a stage where Andrew felt that it was ready for publication, and eventually he withdrew it. I had found the Grimoire helpful when I was learning Python, however, and I persuaded Andrew to allow me to take over maintenance of the Grimoire in August, 2002. Since then it has been available at: http://www.ferg.org/grimoire/grimoire.html I am no longer able, however, to devote the time necessary to maintain the Grimoire and bring it up to date, so I am planning to take it down from my Web site. If you would like to take over the hosting and maintenance of the Grimoire, please contact me, Steve Ferg, at steve at ferg.org. From peter at engcorp.com Wed Nov 3 15:24:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Nov 2004 15:24:37 -0500 Subject: threads and exception in wxPython In-Reply-To: References: <6_qdnQZOZ_YYZRXcRVn-sw@powergate.ca> Message-ID: Thomas Heller wrote: > Peter Hansen writes: >>I have a test case here which is failing, however, because >>the exception is *not* being delivered asynchronously for >>some reason, but appears in the thread only when the thread >>is already terminating itself. > > Can it be that the exception is delivered asynchronously, but still has > to be checked by some code somewhere (my guess would be ceval.c)? > It seems sys.setcheckinterval() plays a role here. Exactly! That is definitely it. I was sitting in a small loop doing a time.sleep() every so often, and during the entire test that thread probably executed only about forty or fifty bytecodes. Your technique with the "busy loop" works, as does setting sys.setcheckinterval() to a much smaller value than the default 100. Thanks Thomas! -Peter From aleaxit at yahoo.com Mon Nov 1 06:01:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 1 Nov 2004 13:01:07 +0200 Subject: question de bonne doc References: <418505b9$0$3662$8fcfb975@news.wanadoo.fr> <1gmkhbc.yxlo8f10l5uq5N%aleaxit@yahoo.com> <4186179a$0$31207$8fcfb975@news.wanadoo.fr> Message-ID: <1gmkp2e.o08a66kodcjxN%aleaxit@yahoo.com> orionlux wrote: > j ai deja achet? des livres O'Reilly qui m ont donn? entiere satisfaction > et cet editeur est tres serieux > cependant quand je disais que "Python en concentr?" "?tait d?cevant c ?tait > ? mon point de vue , parce que moi je cherchais un livre plein d exemples > de code, c est tout. Cependant je serai peut etre amen? ? l acheter quand j > aurai progress? en langage python car ce livre me semble une bonne > reference generale Ah, je vois, merci. Oui, la s?rie O'Reilly "en Concentr?", m?me que la s?rie "in a Nutshell" en Anglais, c'est plus pour reference, avec peux d'examples de code. Le "Cookbook" c'est l'envers, mais je ne croix pas qu'il ait ?t? traduit, malheuresement. Essayez alors http://fr.diveintopython.org/index.html, "Plongez au coeur de Python", peut-?tre vous le trouverez satisfaisant. Alex From square690410 at yahoo.com.tw Tue Nov 2 06:33:40 2004 From: square690410 at yahoo.com.tw (Leon) Date: Tue, 2 Nov 2004 19:33:40 +0800 Subject: how to use httplib module http authentication?? Message-ID: I use sniffer look,it's status is 200,but run getresponse() can occur error ResponseNotReady I try wait it by 5 seconds,but still occur error ResponseNotReady source code.... import httplib,threading def waitSeconds(): sResponse = httpClient.getresponse() print sResponse.reason authHeader = {'Authorization':'Basic TGVvbjoxMjM='} httpClient = httplib.HTTPConnection('172.16.66.116') httpClient.request('GET','/') sResponse = httpClient.getresponse() httpClient.request('GET','/','',authHeader) runWait = threading.Timer(5,waitSeconds) runWait.start() From steve at holdenweb.com Tue Nov 2 20:44:34 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Nov 2004 20:44:34 -0500 Subject: Send HTML e-mail in Python? In-Reply-To: References: Message-ID: Max wrote: > I am looking for some simple example code on generating SMTP e-mail > messages in Python. I have a script that sends system reports to me at > a central e-mail address, and it works fine using smtplib with plain > text messages. I would like to enhance this script to send HTML > formatted messages instead. > > Simply sending a text message with HTML tags does not work. The e-mail > client displays the message as plain text with visible . You probably didn't include a "Content-Type: text/html" header in the RFC822 headers. If that wasn't the problem I do have some code that works, but I'd have to strip out client-specific features before I posted it. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From merkosh at hadiko.de Sun Nov 28 08:34:46 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 28 Nov 2004 14:34:46 +0100 Subject: files in non-blocking mode? Message-ID: Hi, I want two python programs to communicate over stdIO channels. The one executes the other via the popen3 function: amc = Popen3("./amc/amc.py", True, 0) line = stdin.readline() amc.tochild.write(line) amc.tochild.flush() print amc.fromchild.readlines() The problem is that although amc.tochild gets flushed the data never reaches the client until the .tochild fd is closed. Is there any way to put IO channels into non-blocking mode in python? Thanks Uwe From jacek.generowicz at cern.ch Mon Nov 8 10:24:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Nov 2004 16:24:19 +0100 Subject: generic way to access C++ libs? References: <1gmxizh.3rip5na92f0nN%aleaxit@yahoo.com> <1gmxn7d.19o8q51jt2gu5N%aleaxit@yahoo.com> <1gmxube.1skk9cj1uago53N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Jacek Generowicz wrote: > ... > > > Anyway, if my guess is correct that the demand for such a 'c++types' > > > is really burning only on Windows, > > > > What's behind this guess ? > > The fact that Windows is the only widespread OS where getting a compiler > isn't as easy as installing it, for free, off the OS media. Ah, indeed. Once again my unusual environment stops me from seeing the blatantly obvious :-) > > And I also suspect that, in practice, there will be a fairly low > > limit on the size of library that Boost can wrap, because of > > compile-time memory consumption. ISTRT wrapping about 20-30 > > methods taken from about 5 classes used up half a Gb of RAM. So > > you probably don't want the throw Boost at a whole library > > indiscriminantly. > > Wow -- THAT bad?! Eeek. I went back and checked. 38 methods (4 classes) 2 non-member functions. 4 instantiations of std::vector, with just one method each. Compiling this with 256Mb RAM made the machine unusable for about 10 mins. Upgrading to 768Mb RAM, made it not need to swap ... but it still wasn't a breeze. Sorry, can't be bothered to check exactly how much memory it does use. From piet at cs.uu.nl Thu Nov 4 08:54:41 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 04 Nov 2004 14:54:41 +0100 Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: >>>>> Steven Bethard (SB) wrote: SB> (1) A language is "weakly-typed" if it allows code to take a block of SB> memory that was originally defined as one type and reinterpret the bits SB> of this block as another type. [...] SB> Definition 1 is the definition most commonly used in Programming SB> Languages literature, and allows a language to be called "weakly-typed" SB> based only on the language definition. However, for all intents and SB> purposes, it is only applicable to statically typed languages; no one SB> on the list could come up with a dyamically typed language that allowed SB> bit-reinterpretation. Not in the language, but through library modules like struct. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From jstroud at mbi.ucla.edu Fri Nov 19 15:01:53 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 19 Nov 2004 12:01:53 -0800 Subject: Microsoft Patents 'IsNot' In-Reply-To: <20041119192934.EB3A81E4009@bag.python.org> References: <20041119192934.EB3A81E4009@bag.python.org> Message-ID: <200411191201.53889.jstroud@mbi.ucla.edu> Anybody want to go in on patenting WhileNot IfNot AreNot (users would probably have to license both IsNot and AreNot) UntilNot (borrowing from perl) UnlessNot (ibid) NotGreaterThan (shorthand !>) NotLessThan (shorthand !<) ? -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From jerf at jerf.org Tue Nov 16 06:40:06 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 16 Nov 2004 06:40:06 -0500 Subject: determining the number of output arguments References: <1gnbg4k.13z20mj1w1o0ysN%aleaxit@yahoo.com> Message-ID: On Mon, 15 Nov 2004 19:44:06 -0800, Josiah Carlson wrote: >> I think it would be better to have a way to say 'and all the rest'. >> Lacking that, some automated way to count how many items are being >> unpacked on the LHS is probably second-best. > > Is it worth a keyword, or would a sys.getframe()/bytecode hack be > sufficient? Who needs a keyword? a, b, *c = [1, 2, 3, 4] a, b, *c = [1, 2] In the latter case I'd expect c to be the empty tuple. Clear parallels to function syntax: >>> def f(a, b, *c): ... print c ... >>> f(1, 2, 3, 4) (3, 4) >>> f(1, 2) () No parallel for **, but... *shrug* who cares? From niels_bohr at uol.com.br Sat Nov 6 01:17:29 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sat, 06 Nov 2004 04:17:29 -0200 Subject: Has anyone released a Python "mock filesystem" for automated testing? In-Reply-To: References: Message-ID: <1099721849.12507.9.camel@localhost.localdomain> Em Qui, 2004-11-04 ?s 21:31 -0500, Peter Hansen escreveu: > The term "mock filesystem" refers to code allowing unit > or acceptance tests to create, read and write, and manipulate > in other ways "virtual" files, without any actual disk > access. Everything is held in memory and therefore fast, > without risk of damaging real files, and with none of the > messiness of leftover files after testing. Maybe StringIO is a good start point. Depending on what you need (if it's just read/write), everything is already there. Fabio From mdoukidis at gmail.com Tue Nov 30 03:47:53 2004 From: mdoukidis at gmail.com (Mark Doukidis) Date: 30 Nov 2004 00:47:53 -0800 Subject: Python on Nokia Phones ? Message-ID: <8d851104.0411300047.1ea17809@posting.google.com> Is it DEAD ? An exciting prospect when I first heard of Nokia's proposal. I thought there would be a few more postings here since the idea first surfaced around Jan 2004. Maybe I missed something. Can anyone on the pilot program make a comment ? Please give me reason to hope ? Mark From amirbud at yahoo.com Tue Nov 23 07:41:06 2004 From: amirbud at yahoo.com (Alex) Date: 23 Nov 2004 04:41:06 -0800 Subject: Filling Forms ( What is the best way to Print on Forms) Message-ID: Please advice: I have some DMV forms that I would like to print on to fill the answers, is there any good software to do this with? Any free software to do this? I need to align it so the prints go on the designated response areas! Thanks a Million! Alex 11-23-04 ------------------------------------------------------------------------------ From behnel_ml at dvs1.informatik.tu-darmstadt.de Wed Nov 3 04:18:46 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 03 Nov 2004 10:18:46 +0100 Subject: SOAPpy and .NET - Help In-Reply-To: References: Message-ID: Richard Kessler schrieb: > The .NET service works fine responding to a SOAP request going over HTTP > using httplib, but will not accept a call from SOAPpy. It is generally a good idea in these cases to check what passes the wire. Take an HTTP monitor (ethereal or whatever) and look at the messages that are transported from one end to the other in both cases. After all, SOAP was intended to be a readable protocol... Stefan From anthonybaxter at gmail.com Tue Nov 30 07:42:06 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Tue, 30 Nov 2004 23:42:06 +1100 Subject: asynchat and threading In-Reply-To: References: <4edc17eb.0411241036.72eed3ef@posting.google.com> <41a505c2$0$20660$9b622d9e@news.freenet.de> Message-ID: On Mon, 29 Nov 2004 23:24:54 -0500, Caleb Hattingh wrote: > I heartily support something like this, but alas I have not the time to > help out with it. I like the Enthought python distribution because it > installs several packages in one shot. A pity there isn't a similar thing > for python addons in Linux (or is there?). Plenty of people would like to see this. Alas, no-one has stepped forward to do the work (or, if you have money but no time, to offer to fund the work). Python runs on volunteers - no-one's done this yet, so it's not happened. From roy at panix.com Fri Nov 26 17:59:15 2004 From: roy at panix.com (Roy Smith) Date: Fri, 26 Nov 2004 17:59:15 -0500 Subject: network programming without goto (refactoring) References: <10qfcmta665kbeb@corp.supernews.com> Message-ID: In article <10qfcmta665kbeb at corp.supernews.com>, Jeff Shannon wrote: > In Python, exceptions use 'raise', not 'throw'... Doh! I guess it shows that I've been doing a lot of C++ lately :-) From bjourne at gmail.com Fri Nov 5 20:40:00 2004 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 6 Nov 2004 02:40:00 +0100 Subject: How come wxPython isn't in the standard library? Message-ID: <740c3aec041105174020578272@mail.gmail.com> See: http://www.wxpython.org/quotes.php. especially: "wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first." - Guido van Rossum Guess, that answers my question, but isn't "Tkinter was there first" a very bad answer? :) It is kinda ugly too, so I wonder why it can't be replaced? Or maybe another GUI library could complement it. IMHO, having a good GUI library in the stdlib would make distributing GUI apps much easier. Windows users (and many Linux users) doesn't like searching the net to find and download lots of dependancies. -- mvh Bj?rn From deetsNOSPAM at web.de Sat Nov 6 09:58:51 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 06 Nov 2004 15:58:51 +0100 Subject: Python OS References: Message-ID: > I know, I read them. The conclusion was that indeed, it can and in fact > has been done. Hm. I'll reread them myself and see if what has been achieved in this field. But I seriously doubt that someone took a python interpreter and started writing an OS. I can imagine having an OS _based_ on python, where the os api is exposed using python - but still this requires a fair amount of lowlevel stuff that can't be done in python itself, but must be written in C or even assembler. > More what I meant was whether I can _prototype_ an OS in Python (i.e. > make a virtual OS). > P.S. If one can program interrupt routines in C, they can do the same > in Python. Show me how you set the interrupt jumptables to your routines in python and how you write time-critical code which has to be executed in a few hundred cpu-cycles. And how good that works together with the GIL. -- Regards, Diez B. Roggisch From batista.ric at iol.pt Thu Nov 4 11:42:12 2004 From: batista.ric at iol.pt (Ricardo Batista) Date: Thu, 4 Nov 2004 16:42:12 -0000 Subject: dijkstra algorithm by object oriented Message-ID: Ok. you are right. I don't express my self in a rigth way. I just want an idea to begin my work. For example, how many classes do i implement. I have an idea to create three classes, class Graph, class Vertex, class edge. But i don't know if i'm going in the rigth way. This is the help i need. Thanks. -----Mensagem original----- De: python-list-bounces+batista.ric=iol.pt at python.org [mailto:python-list-bounces+batista.ric=iol.pt at python.org]Em nome de Peter Hansen Enviada: quinta-feira, 4 de Novembro de 2004 15:08 Para: python-list at python.org Assunto: Re: dijkstra algorithm by object oriented Ricardo Batista wrote: > I need that someone help me. > > I need to program the dijkstra algorithm by object oriented. > > I'll send my code. Thanks, but you haven't asked a question. Thus it sounds as though you are simply asking for someone to make your code work correctly. Or maybe you're asking for someone to convert it from the style shown to an object oriented approach. Either way, it sounds a lot like this is a homework question for school, so I really hope nobody is going to just do the work for you, since you won't learn anything that way. Please reconsider what you are trying to do and ask a specific question, demonstrating that you have made a reasonable attempt to solve the problem yourself first. -Peter -- http://mail.python.org/mailman/listinfo/python-list --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01-11-2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01-11-2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01-11-2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01-11-2004 From roy at panix.com Mon Nov 22 08:46:39 2004 From: roy at panix.com (Roy Smith) Date: Mon, 22 Nov 2004 08:46:39 -0500 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: I wrote: >> You're saying you should write the code without even looking at >> the documentation. Peter Hansen wrote: > Did I say that somewhere? You said, "Perhaps it's actually documented... I don't know and didn't bother looking." If I misinterpreted your statement, I apologize. > In other words, the documentation in this case happens to align > with the actual behaviour of file objects. > > Now I ask you, how often does documentation either not mention > the fact at all (which was the topic of this thread until now), > or -- perhaps less common with standard library code, but widespread > with other code -- mention things that are inaccurate and wrong? Of course there is bad documentation in the world. If the documented and actual behavior of the code differ, there's clearly a bug somewhere. It could be that the documentation is wrong, or it could be that the code is wrong. Both happen. Both kinds of bugs should be fixed when they are discovered. > In other words, which should one trust more, the documentation > or the actual observed behaviour? Well, that's an interesting question, and I'm not sure there's a simple answer to it. Certainly, if my testing determines that read() throws ValueError under certain situations which are not documented, it would be foolish for me to pretend that it didn't happen because the documentation doesn't say so. But on the other hand, if I discovered that math.pi had the value 3, I would be equally foolish to write code which depended on that behavior. > Ultimately, however, this is a silly argument, because neither > you nor I write code solely in the manner I described, nor > in the manner you appear to be recommending (i.e. going exclusively > based on the documentation), so I'm not even sure why you > wrote... I never recommended going exclusively from the docs. I started out by saying: > I'm a big fan of test-driven development, but not to the extent that I > feel I can ignore reading the documentation to see how something is > supposed to work. Anyway, it would look like both of us have unintentionally misinterpreted what each other has said. I think in the end we both agree that reading the docs is important, and testing is important too. Both give us information which is unavailable from the other. From Scott.Daniels at Acm.Org Tue Nov 2 09:48:53 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 02 Nov 2004 06:48:53 -0800 Subject: saved sys.path In-Reply-To: References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> <1gmlelr.q7q1rz5rc37oN%aleaxit@yahoo.com> Message-ID: <4187a33c$1@nntp0.pdx.net> Eric S. Johansson wrote: > Alex Martelli wrote: > >> The modifications to sys.path performed by .pth files are visible to all >> applications. A single application may (however it chooses to do so) >> find out or determine a path it wants only for its own imports, and > ...historical record deleted >> Python is not particularly different, from the point of view of "where >> does an app find its own configuration information", from most other >> languages. > > from historical perspective, I understand and appreciate your > explanation. However, just because it's historically accurate, does it > mean we should keep doing things the same old way? > There is a danger to watch out for here. A great Python success is that it works in and on the local OS. I have always felt that languages as otherwise successful as APL and Smalltalk have failed by defining their own conventions (for file storage and such), rather than respecting the local conventions. Python attempts the local dance, and it is locality, not history, that affects the details of the dance. Mac people (for example) won't care about the "Python convention" initially and might reject Python because "it doesn't put information in the right place." There is a line here to be careful about. History is not an arrow, but an exploration of possibilities. I mention this not as a "killer rebuttal," but as a "there be dragons here." -Scott David Daniels Scott.Daniels at Acm.Org From gerrit at nl.linux.org Fri Nov 26 12:41:35 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 26 Nov 2004 18:41:35 +0100 Subject: dictionary initialization In-Reply-To: References: Message-ID: <20041126174135.GA2853@nl.linux.org> Peter Hansen wrote: > >In my example, it was b[1]+=1. "+=1" should at least tell Python two > >things: this is an add operation and one of the operands is an > >integer. > > Why would it tell Python that? Well, the rhs of 'foo+=1' is always an integer. Gerrit. -- Weather in Lulea / Kallax, Sweden 26/11 17:20: -8.0?C wind 6.7 m/s NW (34 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From romankaminski at lucent.com Thu Nov 4 09:24:44 2004 From: romankaminski at lucent.com (Roman Kaminski) Date: 4 Nov 2004 06:24:44 -0800 Subject: How to use sys.stdout References: Message-ID: "Leon" wrote in message news:... > what does it have properties ? > what does it have method ? > how to use they ? or where can find any information > > please help me An example: s:/home/rkam>python Python 2.3.3 (#1, May 3 2004, 20:19:41) [GCC 3.3.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> dir( sys.stdout) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init_ _', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr __', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mod e', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'se ek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] >>> sys.stdout.write( 'hello world\n') hello world >>> http://www.python.org/doc/current/lib/module-sys.html Good luck, Roman Kaminski From foo at bar.com Wed Nov 10 20:02:48 2004 From: foo at bar.com (Steve Menard) Date: Wed, 10 Nov 2004 20:02:48 -0500 Subject: property for class objects In-Reply-To: <4192594f.112495279@news.oz.net> References: <4191edee.85006843@news.oz.net> <4192594f.112495279@news.oz.net> Message-ID: Bengt Richter wrote: > On Wed, 10 Nov 2004 08:28:22 -0500, Steve Menard wrote: > [...] > >>I wasnt aware of those descriptors (I am just now delving in the "meta" >>side of things), and it looks promising. So thanks for taking the time >>to tlel me about it :) >> >>Static variables are not just constants however, and the __set__ has to >>work as normal. I did a quick test and it seems by mistake you can even >>erase the descriptor with a new value .. not good. >> > > Yes, the __set__ only gets called for instance attributes, unless there > is something intercepting the class attribute setattr. > > >>At least I can use this for the constant static values (which probably >>comprises the bulk) and use the __setattr__ to prevent overwriting them. >> > > If they're actually constant, why couldn't they be plain old class variables > protected by __setattr__? > > You're right about constants. I could convert them at class-definition time instead of access-time. Thus only the case of non-constant static members do I need to find a solution ... >>Steve >> >>Still looking for a more complete solution howeber > > Don't know what syntax restrictions you have, but if you are trying to simulate > shared static value assignment via an apparent instance attribute assignment, e.g., > > inst.static = value > > why do you need to write > > InstClass.static = something > Static members are not common in Python. They are however fairly common in Java. So I was hoping to preserve the InstClass.value = something > at all? You could always make a dummy instance to use when all you > wanted to do was access the shared statics, e.g., > > shared = InstClass() > ... > shared.static = something > > or even a dynamically created throwaway instance, as in > > InstClass().static = something > This is not an option, as some Java classes that mutable static variables are not instantiatable. > If you wanted to designate certain names for shared statics to be stored > as class variables, you could do something like (only tested as you see here ;-): > > >>> class HasStatics(object): > ... static_names = 'sa sb sz'.split() > ... def __setattr__(self, name, value): > ... if name in self.static_names: setattr(type(self), name, value) > ... else: object.__setattr__(self, name, value) > ... > >>> hs = HasStatics() > >>> vars(hs) > {} > >>> hs.x = 123 > >>> vars(hs) > {'x': 123} > >>> hs.sa = 456 > >>> vars(hs) > {'x': 123} > >>> HasStatics.sa > 456 > >>> hs.sa > 456 > >>> vars(HasStatics).keys() > ['__module__', '__setattr__', '__dict__', 'sa', '__weakref__', '__doc__', 'static_names'] > > static_names would be faster as a dict of the names (with ignored values), or possibly now > a set. > This is what I do now. However, this break with the following situation : class A(object) : # class has a property called foo class B(A) : ... B.foo As each class only contain it's static variables and not it's ancestors. I bypass this problem by accumlating all static variables in each class, including the static variables of all bases. It works, but then dir() reports variable that are not really there. thanks for the suggestions, Steve > Regards, > Bengt Richter From rkern at ucsd.edu Sat Nov 13 05:36:43 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 13 Nov 2004 02:36:43 -0800 Subject: Regarding color conversion (RGB->CMYK) In-Reply-To: References: <4194bd54$0$75308$edfadb0f@dread15.news.tele.dk> Message-ID: Cy Edmunds wrote: > There is no simple way to convert RGB to CMYK for the simple reason that > CMYK is a device dependent color space. (Actually, unless it is calibrated > somehow RGB is a device dependent color space also.) A good way to do the > conversion is to get the ICC profile for the device that made the RGB and > another ICC profile for the device which will print the CMYK and convert one > to the other using a color management module -- aka a CMM. I don't know if > ImageMagick can do this for you or not but it would be very hard to get the > colors right any other way. LittleCMS has Python bindings. http://www.littlecms.com/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From apardon at forel.vub.ac.be Wed Nov 17 07:00:03 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Nov 2004 12:00:03 GMT Subject: Will python ever have signalhandlers in threads? References: <10pkiaqch4edo08@corp.supernews.com> Message-ID: Op 2004-11-16, Jeff Shannon schreef : > Antoon Pardon wrote: > >>Op 2004-11-15, Jp Calderone schreef : >> >> >>>You are correct, but why does it matter? The Queue class works. >>> >>> >> >>Does it? >> >>I'm not so sure. If two consumers ask simultaneously for an element >>from the same empty queue. One consumer simply blocking and the >>other using a timeout, I think that if an element is produced within >>the timeout period the chance for the element going to either consumer >>should be equal. I doubr very much we have that in the current >>situation. >> >> > > This is just my opinion, of course, but it seems to me that if you have > two completely different threads (as in, threads running different > functions, not merely separate instances of the same threaded function) > which are accessing the same queue in different ways, and presumably > doing different things with the queue's products (because why would you > access the queue differently if you weren't doing different things?), > then you've *already* got enough nondeterministic behavior that this > timeout issue isn't going to be a burden in practice. To be honest, I > find the thought of having different consumers which do different things > with a single queue's products to just scream out as a source of > hard-to-track problems -- how could one possibly get predictable > behavior from that? So yes, if you do that, you might get an odd > distribution of products -- but why would you want to do it? You are mostly right, but with one small caveat. There are no locks with a timeout in python. So if you want one of those the easiest way to simulate them is with queues with maximum 1 element. > I *do* understand about wanting to receive signals in (worker) threads, > but I don't understand how this particular behavior of queues could ever > be a practical problem in a real program. Of course, maybe I'm just > missing something, or maybe you're looking at this from a > theoretical-purity aspect... Well I must confess that theoretical-purity appeals to me. So I prefer a solution that always works, to one that only works for all practical purposes. So if signals to worker threads were allowed I certainly would feel the urge to rewrite the queue module for myself. Although that is now what I would use them for in the first place. -- Antoon Pardon From chrisks at NOSPAM.udel.edu Thu Nov 25 03:02:34 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Thu, 25 Nov 2004 08:02:34 GMT Subject: Use Python library from C++ In-Reply-To: <1101364143.006433.314340@z14g2000cwz.googlegroups.com> References: <89cc6e1f.0411241939.61a19596@posting.google.com> <1101364143.006433.314340@z14g2000cwz.googlegroups.com> Message-ID: zhao wrote: > Try boost.python and SWIG? > (boost.sourceforge.net, swig.sourceforge.net) > > Both provide a interface between C/C++ and python > if you want gui under python, you also can try wxpython or pygtk I thought SWIG ported C/C++ libraries to Perl, Python, Ruby, Tcl, etc? How would you use it to port Python into C/C++? I think what you're looking for is instruction on how to embed Python in your C/C++ application. From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Nov 3 19:01:46 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 4 Nov 2004 01:01:46 +0100 Subject: Python for PDAs/Mobile phones? References: Message-ID: <41897176$0$26951$8fcfb975@news.wanadoo.fr> Hi ! J'ai trouv? ces liens : http://feetup.org/blog/dev/python/symbianPython.html http://quizzebox.quintessenz.at/pipermail/sympython/ http://141.3.25.168:8080/symbian/ From jarrodhroberson at yahoo.com Sat Nov 13 13:44:20 2004 From: jarrodhroberson at yahoo.com (fuzzylollipop) Date: 13 Nov 2004 10:44:20 -0800 Subject: Python to measure HTTP and HTTPS performances: best way ??? In-Reply-To: <5c184570.0411120240.6ef29928@posting.google.com> References: <5c184570.0411120240.6ef29928@posting.google.com> Message-ID: <1100371460.649252.245890@f14g2000cwb.googlegroups.com> HTTPS is usually about 5x slower than HTTP on the exact same web server because of the encryption. Best to send a mid-sized JPG or PNG and time that. From fumanchu at amor.org Mon Nov 1 14:19:18 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 1 Nov 2004 11:19:18 -0800 Subject: re.compile Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32450EF@exchange.hqamor.amorhq.net> Brad Tilley wrote: > Is there a quick way to make re.compile show what it's looking for? > > x = re.compile('[a-z]') Probably. But there isn't a quick way to ask for it. Try explaining what you want more fully. FuManChu From __peter__ at web.de Wed Nov 24 03:10:59 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Nov 2004 09:10:59 +0100 Subject: namespace & imported modules References: <799208ed.0411232158.2a6d0782@posting.google.com> Message-ID: Jason wrote: > I've been having trouble understanding the difference between global > namespace within and between modules. For example, I can program a Did you know that global variables are only global to the module? > from subfile import thread1, thread2 # this should be the only This will bind the names thread1 and thread2 in the importing module, i. e. you have now two distinct thread1 variables no longer pointing to the same object after a thread1 = something assignment in one of the modules. Do import subfile instead and access the variables with qualified names subfile.thread1 = something in all modules except subfile.py, and everything should be OK. Peter From carribeiro at gmail.com Wed Nov 17 17:28:10 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 17 Nov 2004 20:28:10 -0200 Subject: seeking a new host for the "Python Grimoire" In-Reply-To: References: Message-ID: <864d370904111714287baae610@mail.gmail.com> On 17 Nov 2004 07:51:43 -0800, Stephen Ferg wrote: > STATUS UPDATE > > Talking to Richie Hindle has given me the idea of setting up the > Grimoire as a wiki on Python.org. > > I'm not a real sophisticated wiki user, but I can probably do it. > > I really like the idea of the Grimoire becoming community-maintained > documentation, something that I've advocated for a long time, and > something that I think we need more of. > > If the wiki idea doesn't work out, there are a couple of folks who > have volunteered to host the Grimoire in the future. A WIki is definitely the way to go. However, hosting it inside the main Python Wiki is problematic. Wikis aren't usually very bright when it comes to naming scopes :-) so it's probably better to have it implemented as a standalone Wiki. Anyway, having it on the Python Wiki is better than not having it at all. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From duncan.booth at invalid.invalid Tue Nov 30 07:17:06 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2004 12:17:06 GMT Subject: Restricted Execution on the cheap References: <-OOdncnDLL2e1jHcRVn-hw@lmi.net> Message-ID: David Pokorny wrote: > Suppose that one wants to set up a machine to accept python code from, > say, arbitrary email, and run it safely. Would the following > (somewhat draconian) precautions be sufficient? > [assume the Python code is in hack.py] > > grep exec hack.py ==> nothing > grep eval hack.py ==> nothing > etc... for 'import', 'builtin', 'globals','reload' > 'compile', 'file', 'open', 'input', 'locals', 'vars' > Assuming you think *very* hard about everything that someone might try. Your list above certainly isn't enough though. I'm pretty sure you also need to block getattr otherwise: >>> def f(): pass >>> getattr(getattr(f, 'shap_tybonyf'.decode('rot13'))['__ohvygvaf__'.decode('rot13')], 'x\x9cK\xce\xcf-\xc8\xccI\x05\x00\x0b\xaf\x02\xea'.decode('zip')) From ngps at netmemetic.com Fri Nov 26 14:38:24 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 26 Nov 2004 19:38:24 GMT Subject: asynchat and threading References: <4edc17eb.0411241036.72eed3ef@posting.google.com> <41a505c2$0$20660$9b622d9e@news.freenet.de> Message-ID: According to Martin v. L?wis : > AFAICT, the main complaint is that it is tied to the TCP transport, > the sockets API, and the select/poll API. IOW, it cannot easily: > - integrate TLS on top of TCP (because TLS might involve no-data > communications, e.g. when TLS negotation happens in the middle > of a TLS session), M2Crypto does SSL/TLS over Medusa/asyncore since 1999. ZServerSSL - SSL for Zope, which is Medusa-based - has been available since 1999 or 2000. I don't imagine a pure Python TLS implementation is impossible to layer over asyncore either. Cheers. -- Ng Pheng Siong http://sandbox.rulemaker.net/ngps -+- M2Crypto, ZServerSSL for Zope, Blog http://www.sqlcrypt.com -+- Database Engine with Transparent AES Encryption From steven.bethard at gmail.com Wed Nov 24 12:50:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 24 Nov 2004 17:50:52 GMT Subject: How to get an item from a simple set? In-Reply-To: <41a4bbce.908273778@news.oz.net> References: <41a4bbce.908273778@news.oz.net> Message-ID: <0S3pd.561504$mD.109270@attbi_s02> Bengt Richter wrote: > On Wed, 24 Nov 2004 15:40:30 GMT, Steven Bethard wrote: >> >>>>>[item] = s >>>>>item >> >>'foo' >> >>It's up to you whether you like the tuple or list syntax better. =) >> > > Thanks. I didn't realize a list format could be used to specify target names > like that. My intial reaction is a bendy feeling in my list expression syntax > recognizer, though. I'm not sure I like that on the left hand side. > It feels too much like __setitem__ on some implied object. The tuple syntax > on the left hand side is only for unpacking (unless you want to imagine invoking > an implied unnamed function, but that's a stretch IMO), so it doesn't trigger > that near-miss syntax recognition feeling. Yeah, I almost always prefer the tuple (comma) syntax, but occasionally I find the list syntax clearer, if, for example, I'm unpacking a nested single-item list: >>> t [['abcd'], 1, 2] >>> (x,), y, z = t >>> x, y, z ('abcd', 1, 2) The ,), in the tuple-only unpacking makes me uncomfortable for some reason. I feel marginally more comfortable with: >>> [x], y, z = t >>> x, y, z ('abcd', 1, 2) Of course, I generally feel uncomfortable if I have a weird unpacking thing like this anyway. It pretty much only comes up for me when I want to assign some default values in one branch of a try/except or if/else statement, e.g. try: x, y = s except ValueError: [x], y = s, None Steve From mwm at mired.org Fri Nov 5 18:00:42 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 05 Nov 2004 17:00:42 -0600 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> <6f402501.0411050228.aea8068@posting.google.com> Message-ID: fuzzyman at gmail.com (Michael Foord) writes: > "darkhorse" wrote in message news:<2uvedvF2g1pv3U1 at uni-berlin.de>... >> Hi all, >> >> While doing a quite big "set of programs" for a university subject I've >> found myself in the middle of a problem someone surely has had before, so >> I'm looking for some help. >> >> At one point, I call a python cgi that pickle.load's a file, adds or deletes >> a registry and dumps the result again in the file. >> I'm worried that the cgi could be called simultaneously from two or more >> different computers, thus most probably corrupting the files. I don't think >> I can use a mutex as it's two different instances of the program and not >> different threads, so I was thinking about locking the files between >> programs, but I really don't know how to do that. It's not a problem if >> there's no portable way of doing this, it's only going to be run on a linux >> based computer. >> Another solution I would accept is that the second called cgi detects that >> other instance is running and displays a message saying to try again later. >> Yes, not quite professional, but it'd do the job, after all this is just a >> little detail I want to settle for a quite picky professor and not a "real >> life" thing. >> I think that's all the background you need, if someone can answer with >> references on what should I look for or even better example code that would >> be simply great. >> Many thanks in advance. >> DH > > A simple solution that doesn't scale well is to create a file when the > access starts. You can check if the file exists and pause until the > other process deletes it - with a timeout in case the file gets keft > there due to an error. > > Obviously not an industrial strength solution, but it does work... To strengthen the solution, write the process id of the script (available via os.getpid()) to the file. If the file doesn't vanish before your timeout, you can check to see if the process is still around, and kill it. import time > import os > > def sleep(thelockfile, sleepcycle=0.01, MAXCOUNT=200): > """Sleep until the lockfile has been removed or a certain number > of cycles have gone. > Defaults to a max 2 second delay. > """ > counter = 0 > while os.path.exists(thelockfile): > time.sleep(sleepcycle) > counter += 1 > if counter > MAXCOUNT: f = file(thelockfile) pid = int(f.read()) f.close() p = os.popen("/bin/ps -p %s" % pid) l = p.read().split('\n') p.close() if len(l) > 2: os.kill(pid, 9) > def createlock(thelockfile): > """Creates a lockfile from the path supplied.""" f = file(thelockfile, 'w') f.write(str(os.getpid())) f.close() > > def releaselock(thelockfile): > """Deletes the lockfile.""" > if os.path.isfile(thelockfile): > os.remove(thelockfile) > > The sleep function waits until the specified file dissapears - or it > times out. > > Regards, > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From daniel.dittmar at sap.corp Mon Nov 29 09:02:05 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 29 Nov 2004 15:02:05 +0100 Subject: Closing files In-Reply-To: <1gnz2kq.1jnqpi01tkznh0N%news+0409@henrikholm.com> References: <1gnz2kq.1jnqpi01tkznh0N%news+0409@henrikholm.com> Message-ID: Henrik Holm wrote: > I have recently started playing around with Python. Some of the things > I have done have involved reading files. The way I do this is along the > lines of > > f = file('file.txt') > lines = f.readlines() > f.close() > > I have noticed that it is possible to do this in one line: > > lines = file('file.txt').readlines() > > My question is: does the file get closed if I do the reading in this > manner? The file gets closed in CPython because file objects are closed when the last reference to them gets deleted. (I guess when the .readlines () returns) When you use Jython or IronPython, the file will be closed sometime later when the file object gets garbage collected. This can lead to problems becaause the process might run out of file handles before the garbage collection and file locks are held a lot longer. This led to two camps. One camp thinks that the correct way would be f = file('file.txt') try: lines = f.readlines() finally: f.close() The other camp thinks that reference counting should be implemented in all Python implementations. And then there are a lot of people who think that changing all the readlines one liner would be quite easy should the need of a Jython port arrive, so why bother about it now? Daniel From lbates at syscononline.com Mon Nov 8 10:40:12 2004 From: lbates at syscononline.com (Larry Bates) Date: Mon, 08 Nov 2004 09:40:12 -0600 Subject: Email "portal" in Python? In-Reply-To: References: Message-ID: What you are describing is Zope (perhaps with Plone add-on). As with any "powerful" application framework it will require you to customize it for your purposes. www.zope.org www.plone.org Larry Bates Syscon, Inc. Peter Clark wrote: > Think of something like MyYahoo: a personalized portal with news > aggregator, weather forecast, comics, etc. Now instead of visiting a > web site, think of all of it being sent daily as an email. It does > have a web interface, but mostly for selecting your content: this is > my location for weather, these are the news feeds I'm interested in, > these are the comics I like, save my preferences, and the server takes > care of the rest. Does such a thing exist? (Even in other non-Python > languages?) I've tried Freshmeat, and the other usual sources, but so > far, nothing. If there isn't any such creature, I'll write my own, but > I wanted to first check that I'm not re-inventing the wheel. > > Thanks, > :Peter From jbellis at gmail.com Mon Nov 8 08:19:48 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 8 Nov 2004 05:19:48 -0800 Subject: Py2exe help for beginner In-Reply-To: <51908f36.0411080408.2772f6c4@posting.google.com> References: <51908f36.0411080408.2772f6c4@posting.google.com> Message-ID: <1099919988.846194.81310@f14g2000cwb.googlegroups.com> PeterFI wrote: > my setup.py looks like this > > from distutils.core import setup > import glob,os,sys > import py2exe > > > setup(name='MyIterator', > version='0.2', > author='P.P', > py_modules=["Iterator"]) > > it runs nicely but no exe is created? What am I missing? You're missing a "windows=" or "console=" argument. -Jonathan From frithiof.jensen at die_spammer_die.ericsson.com Mon Nov 1 05:00:28 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Mon, 1 Nov 2004 11:00:28 +0100 Subject: Linksys Router & Python References: Message-ID: "Brad Tilley" wrote in message news:cltjkt$4fi$1 at solaris.cc.vt.edu... > Is there any way to get a scaled down version of Python onto a Linksys > Wireless router? Are there any projects out there that are doing this? Probably - There are some Linux + development tools for the LinkSys WRT54G router. http://www.pbs.org/cringely/pulpit/pulpit20040527.html http://www.i-hacked.com/Computer_Components/Networking/Linksys_WRT54G_and_WRT54GS_Hacking.html Maybe the devices are somewhat identical: http://www.batbox.org/nslu2-linux.html > I've googled around a bit, but didn't find much. I want to keep the > router's software as it is, but I also would like to have some scripting > abilities on it as well (like email the router's IP addy every x hours), Those requirements are mutually exclusive. From jcarlson at uci.edu Tue Nov 16 12:22:48 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 09:22:48 -0800 Subject: simple symetric encryption advice In-Reply-To: References: Message-ID: <20041116091921.F970.JCARLSON@uci.edu> David Bear wrote: > > I would like some advice on what crypto lib to use. I am writing a cgi > app that will store sensative data in a backend postgresql server. I > have some simple numeric data I would like to make as safe as > possible, without too much overhead. > > The goal would be to store the information in a simple reversable > encrypted form. The encryption key would live only in the python app > that was accessing the data. So perhaps there are two general > questions that could be asked. > > 1) has anyone else done this, and was it worth the extra overhead in > terms of data security.. yes, I know the system will only be as secure > as the python code. > > 2) more important to me, what crypto lib would make sense to use. I > was looking at using symetric key ciphers because the data will need > to be decrypted as well. I looked at the rotor class but there's a big > note that it has been deprecated.. Anyone have a recommendation as to > something better? > > by better I would mean: 1) something reasonably fast, (retreiving 1000 > tupples of something should require much time to decrypt) 2) something > that the code is fairly well reviewed and tested -- (I know all python > modules are well reviewed and tested, but there must be some modules > that are more equal than others;)). Check out the pure Python TLS Lite and its AES or RC4 ciphers (no worries about compilation). They should be reasonable for most tasks, and if you need more speed, There's always using PyCrypto, OpenSSL and Cryptlib. - Josiah From aleaxit at yahoo.com Fri Nov 5 11:23:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 5 Nov 2004 17:23:36 +0100 Subject: inferred typing References: Message-ID: <1gmsg8y.1stp3lkqwq4qtN%aleaxit@yahoo.com> Gabriel Zachmann wrote: > Thanks for your responses. > > Both Boo and Starkiller sound quite interesting. > Boo seems to have some momentum, but what about Starkiller, once the PhD is > finished? > > Also, both are python compilers. Boo is a different language, pythonlike but not python. > I was hoping for something more like Hotspot for Java, i.e., > something which compiles parts of the python script that turn out not to be > really dynamic at run-time and that are executed a lot. > > Anything along those lines? psyco? > In addition, I am not sure that any effort that is not integrated into > mainstream Python will have a real chance to achieve widespread use ... I strongly doubt anything like a JIT will get integrated into mainstream Python before it's very solid, which probably requires it to get widespread first. Alex From tjreedy at udel.edu Fri Nov 26 16:14:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Nov 2004 16:14:17 -0500 Subject: dictionary initialization References: Message-ID: "Dan Perl" wrote in message news:ufmdneh24KVgEjrcRVn-pw at rogers.com... > > "Caleb Hattingh" wrote in message > news:opsh3pirx21js0xs at news.telkomsa.net... >> IF this is the point you are making, and the awk functionality >> demostrated in this particular example is a really significant feature >> for you in your specific problem domain, then I must concede that awk is >> probably right for you, and you shouldn't waste your time with Python. > > And just like that, the discussion turned religious. It's hard to assess > someone's tone when it comes in writing, but, Caleb, you sound sarcastic > and belligerent to me. To me, Caleb was being only slightly and possibly sarcastic in the process of giving friendly good advice to the effect of "better to use Awk and produce than to beat you head against a wall trying to change a basic Python design decision. Almost every design decision has plusses and minuses for designers and others to weigh. No matter what the designer decides, there will be users who weigh the factors enough differently to really wish that the decision was otherwise. In fact, there will probably be another language whose designer did decide otherwise. And in this case, with regard to the handling of uninitialized variables, there is. A Python religion fanatic might have made the opposite suggestion -- something like 'your factor weighting is wrong; see the light and bow to the superior wisdom of how Python does it'. Terry J. Reedy From atterdan at yahoo.com Fri Nov 5 04:28:35 2004 From: atterdan at yahoo.com (John Doe) Date: Fri, 05 Nov 2004 09:28:35 GMT Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> Message-ID: On Fri, 05 Nov 2004 05:58:09 +0000, Maurice LING wrote: > This may be a dumb thing to ask, but besides the penalty for dynamic > typing, is there any other real reasons that Python is slower than Java? > > maurice Hi Maurice, the issue is compiling and bytecode. Python and Java compile source to their own bytecodes. Bytecode is a binary that is portable between many Operating Systems. Some time in 1999 (I think) IBM developed a jit or Just In Time compiler for Java (Apple invented the JIT concept earlier to make 68000 code work on their new line of PowerPC Macs). The JIT compiler compiled java to both bytecode and native OS opcode. This offered increase speed on the second + runs. The binary was suppose to be compiled into a block containing bytecode and opcode. If the java runtime noted that the opcode segment was 'native', it was suppose to run it, over the bytecode. This gives the 'faster' perception. Of course some company, afraid their developers might build there GUI apps with java, over their native mode (thus making their application work anywhere Java worked) went ahead and developed a version of the java compiler that stripped out the bytecode. This made the binary smaller, but locked it to one OS/arch. You can guess about which corporation that was. Lawsuits followed. The company in question lost and decided to drop Java for their own version of Java, JavaLite, sometimes called 'see' 'sharp'. Now as to speed... If you want speed, develop in Python or Perl to get the form of your program. Development time is faster, even if the execution is slow. Both provide OOP bindings. Once the program is up and running, you can use profiling to determine which parts of your interpreted code is slowest and most often used. These you rewrite as C/C++ code and call them from within python. In this way version 1.0 is all python. v1.1 has 20% C++; v1.2 is 34% C++ ... until v2.0 is all C++. Each upgrades is faster, but does not introduce any new functionality and the risks that new functions imply. If you were faithful to this concept, version 3 requires you to use the oldest python branch who's functions will not be modified, to start development. Could be v1.1 or 1.9. C/C++ is for speed, not development. Dan Atterton atterdan at yahoo.com From daniel.dittmar at sap.corp Tue Nov 23 12:54:42 2004 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 23 Nov 2004 18:54:42 +0100 Subject: pyQt data aware objects for Windows In-Reply-To: <1101229709.560806.122070@z14g2000cwz.googlegroups.com> References: <1101229709.560806.122070@z14g2000cwz.googlegroups.com> Message-ID: Paul Drummond wrote: > Sorry if this is the wrong place to post - is there a pyQt newsgroup? > I know there is a mailing list but I hate them! http://www.gmane.org/ allows you to access many mailing list as newsgroups. You can add new mailing lists if they aren't registered yet, but you should probably check with the mailing list members first if it's ok. Daniel From reinhold-birkenfeld-nospam at wolke7.net Thu Nov 4 13:08:24 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 04 Nov 2004 19:08:24 +0100 Subject: New configuration module released In-Reply-To: References: <2e37dc1.0411030650.ff44840@posting.google.com><4d2dnXe5XY7bmxTcRVn-rw@rogers.com> Message-ID: <2uv9goF2f3161U1@uni-berlin.de> Dan Perl wrote: > It's just an idea and I haven't put a lot of thought in it myself, but what > about using XML for the configuration syntax? I'm currently using YAML for configuration syntax. I don't need object references as in the OP's module, so I'm happy with it. It's also easy to change for users. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From bh at intevation.de Tue Nov 30 05:24:41 2004 From: bh at intevation.de (Bernhard Herzog) Date: Tue, 30 Nov 2004 11:24:41 +0100 Subject: comment out more than 1 line at once? References: Message-ID: Riko Wichmann writes: > I'm using emacs (with python-mode) to do most of my editing. [...] > Maybe I just don't know to comment out whole blocks using editor > commands. comment-dwim (usually bound to M-; ) comments out the region if it's active, or, if the region is already commented, uncomments it. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From phil at riverbankcomputing.co.uk Tue Nov 30 10:23:56 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 30 Nov 2004 15:23:56 -0000 (GMT) Subject: threading, qt, and the freakout In-Reply-To: <604fc0ca.0411291928.4d59781d@posting.google.com> References: <604fc0ca.0411291928.4d59781d@posting.google.com> Message-ID: <61642.82.68.80.137.1101828236.squirrel@82.68.80.137> What versions of Python, PyQt, SIP, Qt? Qt imposes restrictions on which parts of the API can be called in different threads - check the Qt documentation. Python has bugs in its thread implementation. These (the ones that affect PyQt anyway) are fixed in Python 2.4. Also see the "Support for Threads" section in the PyQt documentation. Phil > Hey everyone, > > Why doesn't this work? The code speaks much more clearly than I do, > so i shortened it and pasted it below. Running this > and clicking on 'Break Me' will... freak out the window... > > But... only when the pushbutton_obj.setText("Updated") line > is in the thread. If I comment out the threading code > and uncomment the line below "#WORKS", the button text > updates fine. But in the thread it breaks... > > I feel like I'm being stupid here, so ANY suggestions are > much appreciated. > > Thanks all. > Ben Floyd > even at pondie.com > > > #############CUT############# > from qt import * > import sys > import threading > > class Form1(QMainWindow): > def __init__(self,parent = None,name = None,fl = 0): > QMainWindow.__init__(self,parent,name,fl) > self.setCentralWidget(QWidget(self,"qt_central_widget")) > self.pushButton1 = QPushButton(self.centralWidget(),"pushButton1") > self.pushButton1.setText("Break Me") > self.connect(self.pushButton1,SIGNAL("clicked()"),self.doSomething) > > def doSomething(self): > a = DoStuff() > a.go(self.pushButton1) > > class DoStuff: > def go(self, pushbutton_obj): > def runThread(): > #DOESNT WORK > pushbutton_obj.setText("Updated") > > go = threading.Thread(target=runThread) > go.start() > > #WORKS > #pushbutton_obj.setText("Updated") > > if __name__ == "__main__": > app = QApplication(sys.argv) > f = Form1() > f.show() > app.setMainWidget(f) > app.exec_loop() > -- > http://mail.python.org/mailman/listinfo/python-list > > From schwerdy at web.de Wed Nov 10 06:44:22 2004 From: schwerdy at web.de (schwerdy) Date: 10 Nov 2004 03:44:22 -0800 Subject: File Unlocking in __del__ does not work Message-ID: Hello developers! I'm using Python 2.3.4 under debian Sarge and want to write a small logger class. My source code reads: #*************************************************** import sys, time from fcntl import * class Log(object): """ Very Simple Logger Class """ def __init__(self, path): self.logfile = open(path, 'a') flock(self.logfile, LOCK_EX | LOCK_NB) # throw exept. if file locked def write(self, msg): self.logfile.write(time.strftime('%Y-%m-%d %H:%M:%S : ') + str(msg) + '\n') self.logfile.flush() def __del__(self): flock(self.logfile, LOCK_UN) self.logfile.close() l = Log('/var/log/myagi.log') log = l.write log("bla") #*************************************************** When I run the script, python says "Exception exceptions.TypeError: "'NoneType' object is not callable" in > ignored" It seems, as in the __del__ method, the flock function has gone (a debug line as "print flock" in the __del__ method prints "None"). does anybody know what is going on? best regards, Sebastian 'Schwerdy' Schwerdhoefer From apardon at forel.vub.ac.be Mon Nov 22 03:06:34 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Nov 2004 08:06:34 GMT Subject: Will python ever have signalhandlers in threads? References: Message-ID: Op 2004-11-21, Tim Peters schreef : > [Antoon Pardon] >> I'm talking about PyThreadState_SetAsyncExc only as a throw in >> response to your previous remark. The main subject is signals. > > OK. > ... > >> Well wether the work is done or not hardly seems to matter. The >> documentation as worded now seems to make it clear, this isn't >> going get into the language. > > But you're still talking about PyThreadState_SetAsyncExc here, right? Yes. > > Explained last time that it can't possibly "get into the language" in > the state it's in now. And my response to that is that the documentation suggests that that is not the main reason why it is not in the langauage. > The people who orginally did the work got > everything they wanted at the time: the C API function, and the > then-new thread.interrupt_main() function in Python. They didn't ask > for more than that, and they didn't work on more than that. > > Doing more work is a necessary prerequisite if people want more than > that in the language. Making the case that it should be in the > language is part of that work, but, if you haven't noticed, PEPs that > have working implementations fare much better than PEPs that don't. > Indeed, no PEP without an implementation has ever been released >. Look the documentation states this: To prevent naive misuse, you must write your own C extension to call this IMO this says the reason for not having it in the language has nothing to do with lack of implementation. In this case it seems lack of implementation is the consequence of Guido and others finding it to be too dangerous too be in the language. Not that a lack of implementation is the reason it didn't make the language yet. > ... > >> As I understand the doc, one doesn't plan to begin working on a >> Python-level feature and even if someone else implements it, it >> has no chance of getting in the language. > > Sorry, couldn't make sense of that sentence. That raising an exception from one thread in an other thread doesn't made the language is a so by design not by lack of implementation. As the documentation is now worded it suggest very strongly that if someone does implement it tomorrow it will simply rejected because they want to prevent naive missuse. >> As I read the docs it is not so much a question of the feature not >> being ready for the langauge, but a question of Guido not wanting the >> feature to be in the language. > > You're still talking about PyThreadState_SetAsyncExc? Yes. > I haven't asked > Guido about it, and I can't find any design discussion of that > function anywhere. Wel that sentence came in the documentation, I don't know, but something like: "To prevent ..." does sound like a design decision to me. > I think it got added during a European sprint. If > you want to know what he thinks, ask him. If you want a definitive > ruling, write a PEP. That seems a bit idiot to me. The information seems to be available in the documentation. So why should I ask? >> This just to show that having someone implement it, is not >> the biggest hurdle as your prevous remark seemed to suggest >> to me. > > An implementation is prerequisite to release, but isn't necessarily > sufficient. I explained in detail last time why the current C code > has no claim to being "an implementation" of a *Python*-level spelling > of this functionality, so neither a suitable implementation nor the > necessary design discusiion have been done in this case. > > If this is something you want, but you also want guaranteed acceptance > in advance of doing more than writing about it, that won't work. If > you ask Guido, and he can make time to answer, you may get guaranteed > rejection in advance -- or you may not. A PEP would be a good thing > to have in *either* case. I don't want guaranteed acceptance in advance. But if I have the impression that there is rejection in advance then there seems to be no point in starting. The documentation as worded now seems to imply such a rejection in advance. So for the sake of argument even if I wanted this, I would be reluctant to spend time in it, because I only have limited amounts of it and this battle seems to be lost from the beginning. I would think my time would be better spend fighting other battles. -- Antoon Pardon From jerry at jerrysievers.com Mon Nov 29 16:45:52 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 29 Nov 2004 16:45:52 -0500 Subject: slicing, mapping types, ellipsis etc. References: Message-ID: "Caleb Hattingh" writes: > I'm going to assume the following is self-explanatory - type the commands > in yourself. [snip] Yes, it certainly is self-explanatory. And, I appreciate your response. However, my question pertains to advanced use of the slicing features which I have found to be not totally explained in the docs. The use of [start:stop:step] on sequence types is NOT unclear to me at all. I'd like to know; 1. what the Ellipsis object or ... syntax is used for 2. what a slice [..., j:k:l] does 3. how slices are applied to object of mapping types Thank you -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From w0jrs at firepole.com Mon Nov 29 12:58:56 2004 From: w0jrs at firepole.com (Jamie Saker) Date: Mon, 29 Nov 2004 11:58:56 -0600 Subject: Python-list Digest, Vol 14, Issue 377 In-Reply-To: <20041129230428.3CBC71E401C@bag.python.org> References: <20041129230428.3CBC71E401C@bag.python.org> Message-ID: <200411291158.56931.w0jrs@firepole.com> On Mon, 29 Nov 2004 16:05:14 -0500, "Eric S. Johansson" wrote: > If I could simply do: py-get twisted or how about 'emerge twisted' works fine for me! When twisted2 comes out, emerge world will catch it for me too. Check out Gentoo at http://www.gentoo.org for more info, or on IRC at #gentoo Jamie Saker "Gentoo bumper sticker: I'd rather be compiling!" From niels_bohr at uol.com.br Sun Nov 7 03:04:22 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 06:04:22 -0200 Subject: PEP new assert idiom In-Reply-To: <7xy8hep325.fsf@ruckus.brouhaha.com> References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> <7xy8hep325.fsf@ruckus.brouhaha.com> Message-ID: <1099814662.15924.2.camel@localhost.localdomain> Em S?b, 2004-11-06 ?s 22:48 -0800, Paul Rubin escreveu: > "Raymond Hettinger" writes: > > Why do you need a statement for this? > > IMO, a plain function will do the trick: > > I do write such functions sometimes, but using a statement is more > natural. That's why the assert statement exists, for example. > > Because of that naturalness, the temptation to misuse the assert > statement is very great, and I find myself doing it all the time > thinking I'll clean it up later. So I think having a statement for > runtime checking would be in the correct spirit. If it wasn't that we should be programming in assembly as it's faster :) AFAIK all real world programming languages are turing equivalent, so sugar is what differentiates on of the other. I'd love to see that sugar in Python since defining assert functions is distracting. Fabio From skip at pobox.com Tue Nov 16 10:58:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Nov 2004 09:58:26 -0600 Subject: using python with -c (as a inline execution in shell) In-Reply-To: References: Message-ID: <16794.9122.322020.966021@montanaro.dyndns.org> les> python -c "from sys import stdin; for x in stdin: print x" les> gives a syntax error. les> Anyone one know how to do this? How about: % python -c 'from sys import stdin > for x in stdin: > print x > ' hi there bye hi there bye Skip From deetsNOSPAM at web.de Fri Nov 5 13:23:20 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 05 Nov 2004 19:23:20 +0100 Subject: generic way to access C++ libs? References: Message-ID: > let's assume we have a well-populatyed symbol table in the lib > (which is usually the case, or, at least, not too hard a restriction). So what? The names are mangled - and each one according to its compilers own rules. Even if symbols themselves are defined: there is no data type structure layout for structs and classes themselves stored in the symbol table. > that's not quite true. > actually, each platform (wintel, linux, ...) has a pretty well-defined > object file format (ELF under unix/linux, for instance). I did not talk about binary executable formats, but the memory layout of C++ objects. The c++ standard doesn't define where e.g. the vtable of an objects virtual method resides - or even if virtual methods have to be implemented by a vtable at first place. A c++ object created by g++ is total garbage passed to a VC lib that appears to > current icc/linux and gcc/g++ work pretty well together in most cases, and > icc/windows and cl, too. No, they don't - not for C++ code. Google for name mangling and the reasons why every compiler uses its own scheme. Intel claims that there is binary compatibility between them compiler and gcc, but thats only true for certain compiler versions - which usage you have no control of in your planned scenario. I suggest you first delve somewhat more on the subject of c++ code generation and difficulties observed by those trying to develop libraries for c++ (libs that are shipped to customer/users not for their own projects of course). Thats one major reason why there are only few c++ libs out there - the pains e.g. trolltech has to go through to not break binary compatibility between different versions can be observed here: http://developer.kde.org/documentation/library/kdeqt/kde3arch/devel-binarycompatibility.html -- Regards, Diez B. Roggisch From bokr at oz.net Wed Nov 17 05:36:06 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 17 Nov 2004 10:36:06 GMT Subject: global event listeners References: <1100671734.647623.206540@c13g2000cwb.googlegroups.com> <1100680355.351342.116920@z14g2000cwz.googlegroups.com> Message-ID: <419b2613.280118499@news.oz.net> On 17 Nov 2004 00:32:35 -0800, "Hunter Peress" wrote: > >Josiah Carlson wrote: >> "Hunter Peress" wrote: >> > >> > i suppose i could do this, and have an "if self.__name__ == >> > what_im_looking_for and type(self) == what_im_also_looking_for" >> > >> > next is how can i make every object in a given runtime inherit from >> > this class > >> >> class counter(object): >> counter = 0 >> def __init__(self, value): >> self.__value = value >> >> def get_v(self): >> return self.__value >> def set_v(self, val): >> self.__value = val >> counter.counter += 1 >> value = property(get_v, set_v) >> >> >>> a = counter(1) >> >>> b = counter(2) >> >>> a.counter >> 0 >> >>> b.counter >> 0 >> >>> a.value = 0 >> >>> a.counter >> 1 >> >>> b.counter >> 1 >> >>> >> >> >> - Josiah > >Well yes, but im looking for a non-1:1 way of making every object be a >child of this new class. i would have to do an insane amount of >regex.... ;-) > If you are willing to prefix your variables with a magic dotted prefix (can be one letter ;-) then you could do something like: >>> class Magic(dict): ... def __init__(self, ofinterest = ''): ... dict.__init__(self, [(name,[]) for name in ofinterest.split()]) ... def __setattr__(self, name, value): ... if name in self: ... self[name].append(value) ... object.__setattr__(self, name, value) ... >>> magic = Magic('a c x') >>> magic {'a': [], 'x': [], 'c': []} >>> vars(magic) {} >>> magic.b = 222 >>> vars(magic) {'b': 222} >>> magic {'a': [], 'x': [], 'c': []} >>> magic.a = 111 >>> vars(magic) {'a': 111, 'b': 222} >>> magic {'a': [111], 'x': [], 'c': []} >>> magic.a = 'after 111' >>> magic {'a': [111, 'after 111'], 'x': [], 'c': []} >>> vars(magic) {'a': 'after 111', 'b': 222} >>> magic.x = 'ex' >>> magic.y = 'wy' >>> vars(magic) {'a': 'after 111', 'x': 'ex', 'b': 222, 'y': 'wy'} >>> magic {'a': [111, 'after 111'], 'x': ['ex'], 'c': []} >>> for k,v in sorted(magic.items()): print '%5s assumed %s values: %s'%(k,len(v),v) ... a assumed 2 values: [111, 'after 111'] c assumed 0 values: [] x assumed 1 values: ['ex'] I don't know what you want to with this, so it's hard to tailor suggestions. You could obviously do a version that treated all attribute assignments as "of interest", e.g., >>> class Magic(dict): ... def __setattr__(self, name, value): ... self.setdefault(name, []).append(value) ... object.__setattr__(self, name, value) ... >>> m = Magic() >>> m {} >>> vars(m) {} >>> m.x = 111 >>> m.x = 222 >>> m.y = 333 >>> vars(m) {'y': 333, 'x': 222} >>> m {'y': [333], 'x': [111, 222]} >>> for k,v in sorted(m.items()): print '%5s assumed %s values: %s'%(k,len(v),v) ... x assumed 2 values: [111, 222] y assumed 1 values: [333] Regards, Bengt Richter From imbosol at aerojockey.com Fri Nov 5 10:15:10 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 5 Nov 2004 07:15:10 -0800 Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: <60dfb6f6.0411050715.601f381f@posting.google.com> Steven Bethard wrote in message news:... > Gabriel Zachmann writes: > > > > would sort of a summary of this thread be of any help? > > Here's a first stab at one: > > In summary, there are basically three interpretations of "weak-typing" discussed > in this thread: [snip] It seems to me that "weak/strong" description of typing is too overloaded to be very specific. Everyone seems to mean something different by "weak" typing. Some mean the ability to reinterpret bits. Some mean ability to do a lot of implicit conversions. Some (not anyone here, of course) mean dynamic typing. And I'm sure some mean something else. I recommend we stop using "weak/strong typing" as a technical term, and leave it to be a meaningless buzzword for the ignorant peasantry. Instead, we should define several other scales, with very specific names. I'll make some suggestions. One thing to keep in mind is that these are, in fact, spectra; many languages will not be one extreme or the other. Static/dynamic typing we already know about. About the ability to reintepret bits: it seems that the essence of this is that bits can be reinterpreted under different _circumstances_. So a good, specific name for this distinction might be "manifest/circumstantial typing". The words are a bit long, yes, but off-hand I can't think of any shorter words that are specific enough. Words like "loose", "flexible", etc. could mean a lot of things, just as "weak" does. "Circumstantial" is somewhat more specific, but still could mean a few different things. Maybe it should just be "bit-reinterpretable"? "Manifest" might not be a good word, either, since it's kind of discrete in meaning. Can something be "less manifest"? Suggestions welcome, of course. About the cramming of many different representations into a single type, abused to the extreme by Perl: we might call this "overloaded typing". Two things I don't like about it: first, it has a slightly negative connotation (I'd prefer that terminology be neutral, which is another reason I didn't like "strong/weak"), and second, it's not clear what the opposite aspect should be called. Perhaps we could coin some terms such as "polybasic/oligobasic/monobasic". (I would have suggested "polymorphic" but it was taken :). About the implicit type conversions: this I find the hardest to name. The best I can come up with is "coercive/restrictive". I think we need a better suggestion. I really think this label only make sense for predefined operations, and maybe some functions. If I write a function "def a(b): b=int(b); ...", is that coercive in the same spirit as "a" + 1 in Java? I would say not. In fact, I would say this isn't even a property of the typing. We should probably say that a language is a "type-coercive language" rather than that it has "coercive typing". Actually, we should say it's something else, cause I just don't like the term coercive. Maybe "type-general" vs "type-specific"? Seems to vague. "Type-tolerant" vs "type-picky"? I don't know. Suggestions? So, to summarize, I recommend we do away with "strong/weak." We replace it with four spectra, with some suggested names: static/dynamic manifest/circumstantial monobasic/polybasic coercive/restrictive* -- CARL BANKS From piet at cs.uu.nl Thu Nov 25 08:05:39 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 25 Nov 2004 14:05:39 +0100 Subject: Microsoft Patents 'IsNot' References: Message-ID: >>>>> Lenard Lindstrom (LL) wrote: LL> I would hope that a rewrite of Claim-2 of the patent is required before LL> the patent is accept (if it is not outright rejected). Claim-2 is too LL> vague to be meaningful. Proper definitions of "BASIC" and "derived" are LL> missing. I imaging the patent is intended to protect Visual Basic.NET LL> rather than restrict unrelated languages like Delphi and Python LL> anyways. If it would be applied to Python there would be enough prior art anyway. And they forgot to put the word 'invention' between quotes. How stupid can they become? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From gh at ghaering.de Mon Nov 8 06:03:27 2004 From: gh at ghaering.de (Gerhard Haering) Date: Mon, 8 Nov 2004 12:03:27 +0100 Subject: pep 8 converter? In-Reply-To: <418F503F.9050409@chamonix.reportlab.co.uk> References: <418F503F.9050409@chamonix.reportlab.co.uk> Message-ID: <20041108110327.GA7585@mylene.ghaering.de> On Mon, Nov 08, 2004 at 10:53:51AM +0000, Robin Becker wrote: > Is there a tool that checks/imposes PEP 8 (ie the right core coding > style?). It seems that bugfix patches which miss on style are rejected out > of hand. [...] I doubt that's the case. Care to provide an example? -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From reply at to-the-newsgroup.com Mon Nov 22 11:42:17 2004 From: reply at to-the-newsgroup.com (Ben) Date: Mon, 22 Nov 2004 09:42:17 -0700 Subject: Question about classes References: <1101104418.G+/GLqdG7XJQNil1Jd3gOQ@teranews> Message-ID: <1101141738.LDtCTAQKBaFZGDwtJwHeqQ@teranews> On Mon, 22 Nov 2004 06:39:53 +0000, Steven Bethard wrote: > If instead, you intended to set an instance variable, you might write it > like: > > >>> class C(object): > ... def __init__(self, x): > ... if x != 0: > ... self.x = x > ... else: > ... self.x = 5 > ... > >>> c = C(0) > >>> c.x > 5 > >>> c = C(8) > >>> c.x > 8 Steve, That's exactly what I wanted. Thank you very much. I'll keep the class one in mind too. --Ben --Ben From donn at u.washington.edu Tue Nov 16 19:54:15 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 16 Nov 2004 16:54:15 -0800 Subject: nonblocking read() References: <2vvjkoF2re95sU1@uni-berlin.de> Message-ID: In article <2vvjkoF2re95sU1 at uni-berlin.de>, paul koelle wrote: > Peter Ammon wrote: > > > Are there better approaches? Thanks, > > What is wrong with: > > fp = open('foo', 'r') > > while 1: > line = fp.readline() > if not line: > time.sleep(0.3) > continue > process(line) > > ?? A couple of things are wrong with it. The way I remember it, the question was about a pipe, created by popen(), not open(). When fp.readline() returns '', that means that the write end of the pipe has closed, and no more data is forthcoming. There's no use for the sleep or continue above, you may simply break from the loop at that point. Once those issues are taken care of, of course it's true, you can read lines from a pipe one by one with readline(). However, the question didn't mention lines, and instead asked about the read() method, so you have to wonder if perhaps the data in question is actually not line structured. If its structure is something other than lines (which readline() supports), or fixed length blocks (which read(n) supports), then I don't think you want to use file object methods to read it. Donn Cave, donn at u.washington.edu From michele.simionato at gmail.com Fri Nov 5 23:49:50 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 Nov 2004 20:49:50 -0800 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> <6f402501.0411050228.aea8068@posting.google.com> Message-ID: <4edc17eb.0411052049.7df47379@posting.google.com> fuzzyman at gmail.com (Michael Foord) wrote in message news:<6f402501.0411050228.aea8068 at posting.google.com>... > A simple solution that doesn't scale well is to create a file when the > access starts. You can check if the file exists and pause until the > other process deletes it - with a timeout in case the file gets keft > there due to an error. > > Obviously not an industrial strength solution, but it does work... > > import time > import os > > def sleep(thelockfile, sleepcycle=0.01, MAXCOUNT=200): > """Sleep until the lockfile has been removed or a certain number > of cycles have gone. > Defaults to a max 2 second delay. > """ > counter = 0 > while os.path.exists(thelockfile): > time.sleep(sleepcycle) > counter += 1 > if counter > MAXCOUNT: break > > def createlock(thelockfile): > """Creates a lockfile from the path supplied.""" > open(thelockfile, 'w').close() > > def releaselock(thelockfile): > """Deletes the lockfile.""" > if os.path.isfile(thelockfile): > os.remove(thelockfile) > > The sleep function waits until the specified file dissapears - or it > times out. I tried essentially the same solution in my experiments, but I was unhappy with it: it seems to work 99% of times, but occasionally you get strange things (for instance once I got "File not found" when trying to remove the lockfile, evidently it was already removed by another process; other times I got different strange errors). The issue is that it is very difficult to reproduce the problems, hence to fix them. Maybe Diez B. Roggisch is right and a real database server is the simplest solution. However my first attempt with ZEO didn't worked either: $ cat zeoclient.py import ZODB, ZEO from ZEO.ClientStorage import ClientStorage def openzeo(host, port): db = ZODB.DB(ClientStorage((host, port))) conn = db.open() return db, conn, conn.root() def store(): # I have a ZEO instance running on port 9999 print "Opening the db ..." db, conn, root = openzeo("localhost", 9999) print "Storing something ..." root["somekey"] = "somedata" get_transaction().commit() print "Closing the db ..." conn.close(); db.close() if __name__ == "__main__": store() $ echo Makefile default: python zeoclient.py& python zeoclient.py $ make python zeoclient.py& python zeoclient.py Opening the db ... Opening the db ... Storing something ... Storing something ... Closing the db ... Traceback (most recent call last): File "zeoclient.py", line 20, in ? store() File "zeoclient.py", line 15, in store get_transaction().commit() File "/usr/share/partecs/zope/lib/python/ZODB/Transaction.py", line 247, in commit ~/pt/python/zopexplore $ ~/pt/python/zopexplore $ vote(self) File "/usr/share/partecs/zope/lib/python/ZODB/Connection.py", line 699, in tpc_vote s = vote(transaction) File "/opt/zope/lib/python/ZEO/ClientStorage.py", line 841, in tpc_vote return self._check_serials() File "/opt/zope/lib/python/ZEO/ClientStorage.py", line 825, in _check_serials raise s ZODB.POSException.ConflictError: database conflict error (oid 0000000000000000, serial was 035900d31b7fedaa, now 035900d2f6cd8799) (it works with a single process instead). Maybe I misunderstood how ZEO is intended to be used, as usual it is difficult to found the relevant documentation :-( Maybe I should ask on another list ... Michele Simionato From Scott.Daniels at Acm.Org Fri Nov 19 15:08:00 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Nov 2004 12:08:00 -0800 Subject: Python switch for syntax checking In-Reply-To: References: Message-ID: <419e6581$1@nntp0.pdx.net> Jeff Duffy wrote: > I've been wondering why python itself doesn't provide a switch to check > a file for valid syntax. I know that you can currently call > python -c "import py_compile; py_compile.compile(r'MyApp.py')" > ... I suspect the reason is threefold. First, "python MyApp.py" does a syntax check anyway. If MyApp is not a main program, all you get is the syntax check. As for main programs, larger applications are often split into smaller files. I seldom have large main program files to check. Second, lots of extreme programmer (XP) practitioners hang out here, and even more who have adopted at leasrt some of the XP techniques. Those people tend to run unit tests rather than syntax checks. Third, pychecker provides better analysis if you want static analysis. I pretty much try to go the unit test way myself. While I would suggest you try it out, the three reasons above are meant to explain why nobody has put effort into a syntax check switch. --Scott David Daniels Scott.Daniels at Acm.Org From exarkun at divmod.com Mon Nov 1 16:09:26 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Mon, 01 Nov 2004 21:09:26 GMT Subject: "number-in-base" ``oneliner'' In-Reply-To: <4186990d.1364093693@news.oz.net> Message-ID: <20041101210926.9171.708427178.divmod.quotient.1494@ohm> On Mon, 01 Nov 2004 20:34:30 GMT, bokr at oz.net (Bengt Richter) wrote: > [snip] > > BTW, did you try the above? > >From a post (with broken subject line ;-) of Steven Bethard's, it seems to work. > I'll re-quote it here to give it context: > ---- > >Bengt Richter oz.net> writes: > >> > >> Well, I don't have 2.4 yet, but what does it do? > > >>>> [x for x in [0] for x in iter(lambda:x+1, 4)] > >[1, 2, 3] > >>>> list(x for x in [0] for x in iter(lambda:x+1, 4)) > >[1, 2, 3] > > >Looks like it does just what you'd hope it would do. =) > > >Steve > ---- > I didn't try it, but that looks like what it should do, and I'll take Steve's word for it that that's what it does indeed do :) Jp From apardon at forel.vub.ac.be Wed Nov 3 08:25:30 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Nov 2004 13:25:30 GMT Subject: threads and exception in wxPython References: Message-ID: Op 2004-11-02, Zunbeltz Izaola schreef : > > Hi, > > I've an wxPython windows that creates a thread. An object of this > thread raised an exception and i want to cach it in the main thread, > that of the windows (I want this becouse the first implementation > doesn't use thread). I know that exception can not be pass between > thread. Yes they can. Unfortunately in order to protect us from ourselves the powers that be, decided to only allow this to people who know C and have access to a C compilor. from http://docs.python.org/api/threads.html: int PyThreadState_SetAsyncExc( long id, PyObject *exc) Asynchronously raise an exception in a thread. The id argument is the thread id of the target thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; if it returns a number greater than one, you're in trouble, and you should call it again with exc set to NULL to revert the effect. This raises no exceptions. New in version 2.3. I find this most unfortunate, because in my view being naive is not in opposition with easily knowing to write a C extention. I also find it a bad idea to force people to know C for a feature which has some perfect uses for people who don't know C and normally have no need to know C. -- Antoon Pardon From brian at sweetapp.com Tue Nov 9 11:50:00 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 09 Nov 2004 17:50:00 +0100 Subject: Concise idiom to initialize dictionaries In-Reply-To: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> References: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> Message-ID: <4190F538.7050603@sweetapp.com> Frohnhofer, James wrote: > My initial problem was to initialize a bunch of dictionaries at the start of a > function. > > I did not want to do > def fn(): > a = {} > b = {} > c = {} > . . . > z = {} > simply because it was ugly and wasted screen space. > > First I tried: > > for x in (a,b,c,d,e,f,g): x = {} > > which didn't work (but frankly I didn't really expect it to.) > Then I tried: > > for x in ('a','b','c','d','e','f','g'): locals()[x]={} > > which did what I wanted, in the interpreter. When I put it inside a function, > it doesn't seem to work. If I print locals() from inside the function, I can > see them, and they appear to be fine, but the first time I try to access one > of them I get a "NameError: global name 'a' is not defined" > > Now obviously I could easily avoid this problem by just initializing each > dictionary, but is there something wrong about my understanding of locals, > that my function isn't behaving the way I expect? The locals dictionary should be considered read-only. Wouldn't having a list of dictionaries be a better strategy? Cheers, Brian From mwm at mired.org Sun Nov 7 20:00:18 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 07 Nov 2004 19:00:18 -0600 Subject: Python OS References: Message-ID: "Diez B. Roggisch" writes: >> OS's have been written for VMs (LISP and Forth) that didn't have the >> notion of interrupt before they were built. For LISPMs, interrupt >> handlers are LISP objects (*). Java may not be as powerful as LISP, >> but I'm pretty sure you could turn interrupts into method invocations >> without having to extend the VM. > How so? An interrupt is a address the processor directly jumps to by > adjusting its PC. The JVM doesn't even have the idea of function pointers. > Invoking a (even static) method involves several lookups in dicts until the > actual code pointer is known - and that's byte code then, not machine > code. No, that's how most modern machines generate interrupts. That doesn't mean the your JVM-based system would have to do it that way. An interrupt could trigger a lookup in a privlieged dict to find a code pointer. > As your examples show, one can implement a VM ontop of a considederably thin > layer of low level code and expose hooks that allow for system > functionality to be developed in a high-level language running bytecode. > Fine. Never doubted that. I've written myself C-wrappings that allowed > python callables to be passed as callbacks to the C-lib - no black magic > there. But that took some dozen lines of C-code, and time-critical > interrupts won't work properly if you allow their code beeing implemented > in a notably slower language. If you followed the link in my last post, you saw a paper on one of the early LISPMs, which put a virtual LISP machine in silicon. The same could be done for JVM. However, the success of LISPMs and Forth in silicon would contraindicate doing that. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jacek.generowicz at cern.ch Mon Nov 8 10:37:57 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Nov 2004 16:37:57 +0100 Subject: generic way to access C++ libs? References: Message-ID: Gabriel Zachmann writes: > > Looked at boost::python? > > Thanks a lot! > > That's a very neat tool (like everything from Boost ;-) ), > and pretty close to what I was envisioning, > except that one still has to sort of manually transform header files into > BOOST_PYTHON_MODULE declarations ... Then check out Pyste ... which should come with Boost itself. From peter at engcorp.com Wed Nov 24 10:24:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Nov 2004 10:24:21 -0500 Subject: Is there a consensus on how to check a polymorphic instance? In-Reply-To: <1101268711.261729.54980@c13g2000cwb.googlegroups.com> References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101189570.958016.283130@f14g2000cwb.googlegroups.com> <-sSdnZs3heYawz7cRVn-iA@rogers.com> <1101268711.261729.54980@c13g2000cwb.googlegroups.com> Message-ID: Mike Meng wrote: > It seems to me the virtue of dynamic langauge is, if it looks like a > cat, it's a cat. I think this is more accurately expressed as "if it *acts* like a cat, then you can treat it like a cat". Your version implies that you really do care what it _is_, which goes back to the static typing thinking again. > But the problem is still there: how do you know what > it looks like before you treat it as a cat? isinstance(), , as Steve > state, is too rigid. The argument is that you probably don't really need to know what it looks like *before* you try to use it, even if you think you do. The cases where you really do are probably those Alex Martelli's recipe (mentioned near the start of the thread) is intended to help. (Specifically, avoiding the situation where the object implements the required protocol only partially, but you don't find that out until you've already started using the object, possibly corrupting it in the process.) -Peter From zach at cs.uni-bonn.de Wed Nov 24 03:48:58 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 24 Nov 2004 08:48:58 GMT Subject: teaching OO Message-ID: This post is not strictly Python-specific, still I would like to learn other university teachers' opinion. Currently, I'm teaching "introduction to OO programming" at the undergrad level. My syllabus this semester consists of a bit of Python (as an example of a scripting language) and C++ (as an example of a compiled language). With C++, I go all the way up to meta-programming. My question now is: do you think I should switch over to Python completely (next time), and dump all the interesting issues involved in C++'s virtual classes, overloading, and templates? (In Python, all of that would just disappear ... ;-) ) (The opinion of the people on this NG might well be a little bit biased towards Python, but that's ok ;-).) Interested in all kinds of thoughts. Best regards, Gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From tim.peters at gmail.com Thu Nov 11 14:50:36 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 11 Nov 2004 14:50:36 -0500 Subject: crc32 to be used as hash In-Reply-To: References: Message-ID: <1f7befae041111115041e7423e@mail.gmail.com> [Weiguang Shi] > I'm thinking of using binascii.crc32 as a hash-function when I read in > the reference > http://www.python.org/doc/current/lib/module-binascii.html: > > crc32( data[, crc]) > > Compute CRC-32, the 32-bit checksum of data, starting with an > initial crc. This is consistent with the ZIP file checksum. > Since the algorithm is designed for use as a checksum algorithm, > it is not suitable for use as a general hash algorithm. > > CRC32 has been shown in the (Internetworking) literature that it can > be used as a good hash function. I'm wondering what's the concern > here. Sorry, I've no idea what "(Internetworking) literature" means. PythonLabs ran large-scale statistical tests of string hashing algorithms in 2000, using millions of strings taken from a large email corpus. binascii.crc32 delivered collision rates hundreds of standard deviations worse than a "truly random" 32-bit hash would have delivered. That's the concern. In the same tests, Python's builtin hash() was statistically indistinguishable from a random 32-bit hash function wrt # of collisions. BTW, it's possible to design CRC polynomials with better hash statistics, but that's not what binascii.crc32 was designed for. Like most CRC polynomials in wide use, it was designed to catch common forms of data corruption (single-bit errors, bursts of 0 or 1 bits at either end, stuff like that). From james.frohnhofer at csfb.com Tue Nov 9 11:40:48 2004 From: james.frohnhofer at csfb.com (Frohnhofer, James) Date: Tue, 9 Nov 2004 16:40:48 -0000 Subject: Concise idiom to initialize dictionaries Message-ID: <89D59C407D04D54AA82DC8BA312D430D10C61759@enyc11p32001.corpny.csfb.com> My initial problem was to initialize a bunch of dictionaries at the start of a function. I did not want to do def fn(): a = {} b = {} c = {} . . . z = {} simply because it was ugly and wasted screen space. First I tried: for x in (a,b,c,d,e,f,g): x = {} which didn't work (but frankly I didn't really expect it to.) Then I tried: for x in ('a','b','c','d','e','f','g'): locals()[x]={} which did what I wanted, in the interpreter. When I put it inside a function, it doesn't seem to work. If I print locals() from inside the function, I can see them, and they appear to be fine, but the first time I try to access one of them I get a "NameError: global name 'a' is not defined" Now obviously I could easily avoid this problem by just initializing each dictionary, but is there something wrong about my understanding of locals, that my function isn't behaving the way I expect? > -----Original Message----- > From: python-list-bounces+james.frohnhofer=csfb.com at python.org > [mailto:python-list-bounces+james.frohnhofer=csfb.com at python.org]On > Behalf Of Dennis Lee Bieber > Sent: Tuesday, November 09, 2004 10:31 AM > To: python-list at python.org > Subject: Re: Determining combination of bits > > > On Mon, 8 Nov 2004 21:18:36 -0800, "news.west.cox.net" > declaimed the following in comp.lang.python: > > > > Note: 2^1 = 2, so your dictionary is already in error... > > > > > > > The dictionary was filled with arbitrary values, not > > { x : 2^x } values like you might have thought. > > Well, you had stated "powers of two"... If all you wanted is a > bit mapping you could probably drop the dictionary and just use a list > of the values, indexed by the bit position, and my first attempt > logic... > > > > > It is actually more like {1:123, 2:664, 4:323, 8:990, 16:221... etc} > > > > > > CheckBoxes = [ "FirstChoice", > "SecondChoice", > "ThirdChoice", > "FourthChoice", > "FifthChoice", > "SixthChoice" ] > > > for num in [22, 25, 9]: > bit = 0 > while num: > if num & 1: > print CheckBoxes[bit], > bit = bit + 1 > num = num >> 1 > print > > SecondChoice ThirdChoice FifthChoice > FirstChoice FourthChoice FifthChoice > FirstChoice FourthChoice > > where "num" is the sum of the checkbox index values (or whatever > selection mechanism is used), assuming /they/ were set up in 2^(n+1) > scheme (n = bit position, starting with 0)... > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > -- > http://mail.python.org/mailman/listinfo/python-list > ============================================================================== This message is for the sole use of the intended recipient. If you received this message in error please delete it and notify us. If this message was misdirected, CSFB does not waive any confidentiality or privilege. CSFB retains and monitors electronic communications sent through its network. Instructions transmitted over this system are not binding on CSFB until they are confirmed by us. Message transmission is not guaranteed to be secure. ============================================================================== From carribeiro at gmail.com Wed Nov 17 20:23:02 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 17 Nov 2004 23:23:02 -0200 Subject: Named tuples In-Reply-To: <10pntj5m0spvl3f@corp.supernews.com> References: <30001hF2ptnqcU1@uni-berlin.de> <1gnf6b7.nnqkns1c991f3N%aleaxit@yahoo.com> <10pntj5m0spvl3f@corp.supernews.com> Message-ID: <864d3709041117172312f11d24@mail.gmail.com> On Wed, 17 Nov 2004 17:13:45 -0800, Jeff Shannon wrote: > Carlos Ribeiro wrote: > > >4. Named attribute access is supported by __getattr__. Names are > >looked up on the magic __names__ attribute of the tuple. > > > >5. On slicing, a named tuple should return another named tuple. This > >means that the __names__ tuple has to be sliced also. > > > > > > Hm. If __names__ is a tuple, then does that tuple have a __names__ > attribute as well? > > (In practice, I can't imagine any reason why tuple.__names__.__names__ > should ever be anything other than None, but the potential recursiveness > makes me nervous...) Humm. The worst case is if it's done in a circular fashion, as in: mytuple.__names__ = nametuple nametuple.__names__ = mytuple That's weird. The best that I can imagine now is that it would be illegal to assign a named tuple to the __names__ member of another tuple. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From duncan.booth at invalid.invalid Wed Nov 24 04:18:37 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Nov 2004 09:18:37 GMT Subject: HTML stylesheet expander? References: <8idd72-j1o.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Does anyone have any code or pointers to something > that can take some HTML with CSS style information > and expand it into HTML that works pre-CSS. > It can't be done in general since CSS has far more control over the styling than HTML ever gave you. However, if you are willing to restrict yourself to simple cases I would suggest you might be best loading the HTML into a browser and manipulating it there to find out what styles everything has. If you are using Windows then there is no problem: just drive IE remotely through COM and use Python to iterate over the document and pick out the runtime style attributes that you are interested in. If you are not using Windows, or you want portability, then you are probably best doing this in Javascript. From newsgroups at jhrothjr.com Tue Nov 2 21:36:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 2 Nov 2004 20:36:46 -0600 Subject: Python needs a CPyAN References: <10of7jtm07h7f77@news.supernews.com> Message-ID: <10ogh1upnubd1b0@news.supernews.com> "Istvan Albert" wrote in message news:g8ydnYY52sUUdBrcRVn-jQ at giganews.com... > John Hazen wrote: > >> Ummm... Care to let us in on it? > > typo, he probably meant > > "I can't think of a ..." You may think you're funny. You're not. John Roth From davidf at sjsoft.com Thu Nov 11 15:48:19 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 11 Nov 2004 22:48:19 +0200 Subject: I don't quite get this "string".find() In-Reply-To: References: Message-ID: Jaime Wyant wrote: > Will someone explain this to me? > > >>>>"test".find("") > > 0 > > Why is the empty string found at position 0? > It's found there because it is there! At any position, you can find an empty string because it is so short... David From steven.bethard at gmail.com Fri Nov 12 12:52:04 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 12 Nov 2004 17:52:04 +0000 (UTC) Subject: Strong types (.NET) versus weak types (Python) References: Message-ID: j_mckitrick bigfoot.com> writes: > > I recently took a one week course on .NET, and they emphasized over > and over again that the key is types. Everything is strongly typed > and enforced. > > Python is the exact opposite. Python is strongly typed by most normal definitions of "strongly typed" (though see http://www.python.org/moin/StrongVsWeakTyping for arguments about exactly what strong/weak typing means). I believe what you mean to say is that .NET is statically typed, in which case it's true that Python is the opposite -- dynamically typed. It's claimed by some that Python 3000 will have optional static type declarations, though only time will tell... It's far from trivial in a language like Python that allows you to do things like change an object's class at runtime. > I prefer Python, but is .NET likely to change this view of types? No. Static vs. dynamic typing is a major language decision and is usually hard to change, at least in any meaningful way. .NET could go to dynamic typing, but you would lose all the compile-time checking for very little gain -- AFAIK it doesn't provide any way to do the things that make dynamic typing most useful, like adding methods to an object, changing the class of an object, etc. at runtime. Steve From peter at engcorp.com Wed Nov 3 10:20:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Nov 2004 10:20:28 -0500 Subject: threads and exception in wxPython In-Reply-To: References: Message-ID: Peter Hansen wrote: > >>> asyncexc = ctypes.pythonapi.PyThreadState_SetAsyncExc > >>> exc = ctypes.py_object(ValueError) > >>> asyncexc(t.id, exc) > 1 > >>> t > > > Hmm... clearly that's not enough, but perhaps closer. But shortly after, trying to create a new thread, I got: >>> t3 = T() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in __init__ File "c:\a\python23\lib\threading.py", line 384, in __init__ self.__block = Condition(Lock()) File "c:\a\python23\lib\threading.py", line 148, in Condition return _Condition(*args, **kwargs) File "c:\a\python23\lib\threading.py", line 154, in __init__ if lock is None: ValueError >>> t3 = T() >>> t3 >>> t3.id 5740 >>> t So the exception managed to get to the new thread, even though I called SetAsyncExc *before* the thread was even created. Now _that's_ what I call "asynchronous". ;-) -Peter From JFeghhi at visa.com Thu Nov 4 15:59:03 2004 From: JFeghhi at visa.com (Feghhi, Jalil) Date: Thu, 4 Nov 2004 12:59:03 -0800 Subject: Storing objects in dictionary Message-ID: <8C53AAFA2050EE40BDCDB9455DA7D6340C6267@sw720ex020.visa.com> I am actually trying to store a FieldStorage object (which contains values of a post) into the session for later use. Something like session['data'] = data. I don't have the error message right now but something like "object cannot be set". -Jalil -----Original Message----- From: python-list-bounces+jfeghhi=visa.com at python.org [mailto:python-list-bounces+jfeghhi=visa.com at python.org]On Behalf Of Jeremy Jones Sent: Thursday, November 04, 2004 12:09 PM To: Feghhi, Jalil Cc: python-list at python.org Subject: Re: Storing objects in dictionary Feghhi, Jalil wrote: >I get an error storing an object in a dictionary. The dictionary and the object are both provided by mod_python. One is the session object (which is just a dictionary) and one is a FieldStorage object (I think it is a class but displays as a dictionary). My question is what is the requirement for an object to be able to store it in a dictionary? I am sure there is documentaion somewehre but I couldn't find it. > >Regards, > >-Jalil > > Are you trying to use the session object as a key in the dictionary or a value of a key? What error are you getting? You should be able to put anything into a dictionary (AFAIK) as a key, but only hashable objects can be put in as keys. Jeremy Jones -- http://mail.python.org/mailman/listinfo/python-list From irmen at -nospam-remove-this-xs4all.nl Sat Nov 6 17:10:11 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 06 Nov 2004 23:10:11 +0100 Subject: supressing '\n' at the end In-Reply-To: <337e6cd5.0411061352.62fe8bfc@posting.google.com> References: <337e6cd5.0411061352.62fe8bfc@posting.google.com> Message-ID: <418d4bc3$0$78753$e4fe514c@news.xs4all.nl> SunX wrote: > Gurus; > I need some help here. How do you supress the newline char. at the > end of a file.write(str(aString))? I know you can add a newline by > simply doing file.write(str(aString) + '\n'), but not > file.write(str(aString) - '\n'). Where does the \n come from? I presume the 'aString' object contains it. Then you can do: file.write(aString[:-1]) (but only if aString always contains a '\n' at the end, ofcourse) --Irmen From danperl at rogers.com Thu Nov 25 15:28:05 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 25 Nov 2004 15:28:05 -0500 Subject: dictionary initialization References: Message-ID: I don't know awk, so I don't know how your awk statement works. Even when it comes to the python statements, I'm not sure exactly what the intentions of design intention were in this case, but I can see at least one justification. Python being dynamically typed, b[1] can be of any type, so you have to initialize b[1] to give it a type and only then adding something to it makes sense. Otherwise, the 'add' operation not being implemented for all types, 'b[1]+1' may not even be allowed. You're saying that in awk a['hello'] is initialized to 0. That would not be justified in python. The type of b[1] is undetermined until initialization and I don't see why it should be an int by default. Dan "Weiguang Shi" wrote in message news:slrncqc9kq.hj3.wgshi at namao.cs.ualberta.ca... > Hi, > > With awk, I can do something like > $ echo 'hello' |awk '{a[$1]++}END{for(i in a)print i, a[i]}' > > That is, a['hello'] was not there but allocated and initialized to > zero upon reference. > > With Python, I got > >>> b={} > >>> b[1] = b[1] +1 > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 1 > > That is, I have to initialize b[1] explicitly in the first place. > > Personally, I think > > a[i]++ > > in awk is much more elegant than > > if i in a: a[i] += 1 > else: a[i] = 1 > > I wonder how the latter is justified in Python. > > Thanks, > Weiguang From mfuhr at fuhr.org Sat Nov 6 23:26:08 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 6 Nov 2004 21:26:08 -0700 Subject: checking a thread has started References: <418d3323$1_2@omega.dimensional.com> Message-ID: <418da3e0$1_4@omega.dimensional.com> Deepak Sarda writes: > The server is on Redhat with a custom 2.4.20 kernel. The script is not > running through mod_python - just a regular #!/usr/bin/python2.2 The shebang line doesn't control how the web server starts the script, so that doesn't tell us anything. Does the web server have mod_python installed at all? If so then it's possible that all files ending in .py or all files in a certain directory are run under mod_python. You can examine os.environ['GATEWAY_INTERFACE'] to see how your script is run: the value should be "CGI/1.1" if you're running via CGI and "Python-CGI/1.1" if you're under mod_python. This environment variable probably won't be set if you run the script from the command line, so use has_key() or trap KeyError to avoid exceptions. It may or may not matter whether you're running under mod_python, but let's find out for sure anyway. Then we can better understand the extent of relationship between your script and Apache. > I see what you mean and it's true that the script actually runs as a > local user. What do you mean "runs as a local user"? CGI programs usually run as whatever user the web server runs as, although it's possible to have them run as the script's owner (e.g., by setting up suEXEC). > But there is certainly a relation between the server and > the threads because in httpd.conf - there's a directive which says: > > StartServers 8 > > which means there are 8 idle server instances running at any given > time. That's not what StartServers means according to the Apache documentation: http://httpd.apache.org/docs/mod/core.html#startservers "The StartServers directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load, there is usually little reason to adjust this parameter." > Now I assume my main script call take up one instance. Then > when new threads are requested - each thread takes up an instance so > we have 7 new threads. Which is exactly what happens! That doesn't make sense given the description of StartServers. Besides, as I recall, Apache 1.3.27, which you said you were using, doesn't even use threads -- each instance of the web server is run in a separate process. Have you tested your hypothesis by altering the value of StartServers and checking whether your script behaves differently? StartServers is 5 on one of my machines, yet I just ran a few tests and successfully created 1000 threads under both CGI and mod_python. > The program _always_ successfully creates and completes execution of > exactly seven new threads leaving the remaining eight requested > threads in no man's land! How are you determining which threads are starting and which aren't? > So there must be some relation between apache and the script. Also, as > I said earlier, when run through a shell as the same user - the script > works perfectly fine. Something's going on but we lack sufficent evidence to say what. We haven't seen your code yet -- could you post the smallest possible script that demonstrates the problem? -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From eric_brunel at despammed.com Mon Nov 22 08:19:54 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 22 Nov 2004 14:19:54 +0100 Subject: [Beginner] delete items of [] also from memory In-Reply-To: References: <41a1a1da$0$8190$8fcfb975@news.wanadoo.fr> Message-ID: <41a1e5b9$0$9075$8fcfb975@news.wanadoo.fr> Birgit Rahm wrote: >> But... And if you try ? >> > > I tryed A = []. > And I think thats why my RAM is filling up. But I dont know if this is the > problem. So I asked. > Is del A[0:] the better or an equal solution? > Birgit Not exactly equal, but it depends on the context. Consider: a = [None] * 10000 b = a a = [] The first line creates a 10000 element list and adds a reference to it ("a"); the second adds a new reference to the list ("b"); the third removes a reference from the list and makes it point to a new empty list. So the 10000 element list still has a reference ("b"), and is not deleted from memory, since it can still be accessed via the variable b. OTOH, consider this: a = [None] * 10000 b = a del a[:] The two first lines are the same, but the third one does not just delete a reference to the 10000 element list; it actually deletes all elements from the list itself. So now, a *and* b point on the empty list, and the memory used by the original list is given back to the system (or should be... see further) What makes you think the memory is not given back to the system? Does the memory occupied by your script increase and increase, or do you just see the memory occupied by your script remain constant when you do the del a[:]? In the latter case, it may be perfectly normal: it is quite frequent that the memory freed by an operation is not returned immediatly to the system, but kept for future use by the program. BTW, I tried the following script, watching the memory consumption at each line: >>> a = [None] * 10000 >>> a = [] >>> b = [None] * 10000 >>> b = [] >>> c = [None] * 10000 >>> c = [] >>> d = [None] * 100000 The first line actually increase the memory allocated for the Python interpreter; the second one doesn't decrease it, but the third one does not increase it, because the memory occupied by the first 10000 element list was re-used for the second one. Same thing for the third 10000 element list (the one put in c). The last line *did* increase the consumed memory, because more space was needed for the 100000 element list. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From skip at pobox.com Wed Nov 10 14:57:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Nov 2004 13:57:41 -0600 Subject: [development doc updates] In-Reply-To: <20041110154700.5763718E89A@grendel.fdrake.net> References: <20041110154700.5763718E89A@grendel.fdrake.net> Message-ID: <16786.29365.808646.948039@montanaro.dyndns.org> Fred> Lots of changes to how tables are actually formatted, with much of Fred> the styling moved from the HTML to the CSS stylesheet. Fred> Tables also look nicer in supporting browsers. Any idea what browsers those would be? Fred> Please review the tables and report any strange presentations; be Fred> sure to include the specific browser (including platform and Fred> version!) in your report. Using Firefox 1.0PR on a Solaris system I checked out http://www.python.org/dev/doc/devel/lib/boolean.html There are no left, right or top borders. A PNG is at http://www.musi-cal.com/~skip/table.png Skip From dd55 at cornell.edu Sat Nov 13 18:03:34 2004 From: dd55 at cornell.edu (Darren Dale) Date: Sat, 13 Nov 2004 18:03:34 -0500 Subject: looking for a good introduction to OOP Message-ID: Hi, I would like to learn more about object oriented concepts, like design and techniques. I have experience with Matlab and Python, a little with C#, and almost none with C++. Could I get suggestions for some good books? C++ is not an obstacle, but Python based examples would be easier. Thanks, Darren From someone at somewhere.com Tue Nov 16 21:35:24 2004 From: someone at somewhere.com (PyBo) Date: Wed, 17 Nov 2004 02:35:24 GMT Subject: Rounding curiosity Message-ID: What is wrong with this picture: >>> x = 500000000.0 >>> y = x / (1024 * 1024) >>> y 476.837158203125 >>> z = round(y, 2) >>> z 476.83999999999997 Obviously, '476.83999999999997' is not rounded to two decimal places. Or am I doing something wrong? From gergina at abv.bg Sat Nov 27 16:36:26 2004 From: gergina at abv.bg (Nickolay) Date: 27 Nov 2004 13:36:26 -0800 Subject: executable from python cod References: <77969915.0411241036.553c3da3@posting.google.com> <77969915.0411261142.1bcca34c@posting.google.com> Message-ID: <77969915.0411271336.4783a876@posting.google.com> "Diez B. Roggisch" wrote in message > When it works - sure, I bet a lot of people are interested. Thanks for your opinion. I will continue work, but i have a "general question" - How name it? :) "bearophile" wrote in message > ... this is quite interesting. Can you tell us > some more about it? compiler is 32 bits,Intel family > How we can find/try it? In this momement only on my comuter ;) But when i ready with first version, i'll put message to many palces > How much language can it compile (can it use lists?) assembler, and basic code other languages - i have problem with classes > Is the compiler written in Python (this probably makes it simpler to > create)? No but may be will be. I wish to create an absolute free compiler and IDE with open source. that's all From pekka.niiranen at wlanmail.com Sun Nov 14 12:41:37 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sun, 14 Nov 2004 19:41:37 +0200 Subject: using python on the command line with 'here-documents' and pipes In-Reply-To: References: Message-ID: <419798D1.50104@wlanmail.com> Hi, This is from C:\Python23\Lib\site-packages\win32\Demos\pipes\cat.py: '''cat.py a version of unix cat, tweaked to show off runproc.py ''' import sys data = sys.stdin.read(1) sys.stdout.write(data) sys.stdout.flush() while data: data = sys.stdin.read(1) sys.stdout.write(data) sys.stdout.flush() # Just here to have something to read from stderr. sys.stderr.write("Blah...") # end of cat.py -pekka- calmar wrote: > Hi all, > > I would like to use python for a replacement for some binutils. I would > like to be able to pipe things into python. Actually I would not like > writing a 'script' to handle the input, but write the python commands > right onto the command line. > > It would be possible to use here-documents (for having the correct > identation during e.g while loops) for writing python code on > the fly, but then how and where to get the pipe output: > > echo -e 'line1\nline2' | python < > Does not really work... > > Would anybody have an idea how to use python like e.g. awk etc. As a > tool within, where I can handle the stdin data, and write the code right > there (e.g. with here documents)? > > > thanks a lot > calmar > From steven.bethard at gmail.com Tue Nov 2 13:55:34 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 18:55:34 +0000 (UTC) Subject: function object and copies of variables References: <20041102174025.GA26478@marge.cehill.co.uk> Message-ID: saticed.me.uk> writes: > > can a function object store values so this 3 liner can print 0 1 instead > of 1 1? > > f = [] > for i in [0, 1]: f.append(lambda: i) > for j in f: print j() Just thought I might give a little extra commentary on why Diez B. Roggisch's solution works. First, I'm going to write it in a more readable (IMHO) form[1]: >>> f = [] >>> for i in (0, 1): ... def func(i=i): ... return i ... f.append(func) ... >>> for j in f: ... print j() ... 0 1 Now, the problem you're running into here is that def (and lambda) in Python don't bind names in their body to values at the time at which the function is defined. If they did, the following would be invalid: >>> def f(): ... def g(): ... print j ... j = 1 ... g() ... >>> f() 1 because the name 'j' is not bound to a value until after g is defined. Instead, what happens is that the g() function doesn't try to look up a value for j until it reaches the statement 'print j'. Since g() is called after the name 'j' is bound to the value 1, when g() does finally look up a value for j, it is able to find one in the f function's scope. Back to your original question, what happens when you write: >>> f = [] >>> for i in (0, 1): ... def func(): ... return i ... f.append(func) ... >>> for j in f: ... print j() ... 1 1 (or the equivalent) is that the only i available to func is the one from the for loop, and this one has the value 1: >>> for i in (0, 1): ... pass ... >>> i 1 So, when func() is called by calling j(), func looks for i, finds it in the global scope, and uses that value, which is 1 both times that func() is called, because it is called after the end of the first for loop. Contrast this with: >>> for i in (0, 1): ... def func(): ... return i ... print func() ... 0 1 where the for-loop has not completed, and so i still has the value 0 the first time func() is called. Diez B. Roggisch's solution solves your problem by binding i to a value at the time that func is defined, taking advantage of the fact that default argument values are evaluated and bound at function definition time. Hope this is helpful. Steve [1] If you're really looking for the fewer lines, try: for j in [lambda i=i: i for i in (0, 1)]: print j() Not only is it more readable (IMHO), it's also probably faster since list comprehensions are almost always faster than a for-loop with an append. From erwan.adam at cea.fr Wed Nov 17 09:12:56 2004 From: erwan.adam at cea.fr (Erwan Adam) Date: Wed, 17 Nov 2004 15:12:56 +0100 Subject: [PyQt] How to get the QRect of a QMenuBar (QPopupMenu) item ? Message-ID: Hi all, I try to introduce tooltips in my application written in PyQt (more precisly, in the menubar of my application) but I can't find a way to get the QRect instance associated to a QMenuBar item (neither a QPopupMenu item) I need the QRect 'cause I followed the tooltip.py file given with pyqt to do the job with a re-implementation of "maybeTip( self, pos )". May be it is not the good solution ... Help is welcome ! Cheers, E.A. From jepler at unpythonic.net Thu Nov 18 09:28:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 18 Nov 2004 08:28:56 -0600 Subject: os.system vs os.system inside thread -> why is there any difference? In-Reply-To: References: Message-ID: <20041118142855.GD25465@unpythonic.net> On Thu, Nov 18, 2004 at 12:00:06AM +0100, przemas_r at o2.pl wrote: > Thanks for the answer. You're welcome. I'm sorry it didn't work out. I wrote a pair of standalone programs (no need for arping) to check this behavior. The bad news is that my program failed on 2.2.2 and 2.3.2. It only succeed on a CVS version of Python 2.4b2. To run the test, "python prz.py". It should print "0" twice, because each time "alarmed.py" should exit from within the SIGALRM signal handler. On 2.2 and 2.3, it prints "0" (works in the main thread) then "1" (doesn't work in another thread) Jeff Subprogram "alarmed.py": #------------------------------------------------------------------------ #!/usr/bin/python import signal, time, sys, os signal.signal(signal.SIGALRM, lambda *args: sys.exit(0)) os.kill(os.getpid(), signal.SIGALRM) sys.exit(1) #------------------------------------------------------------------------ Main program "prz.py": #------------------------------------------------------------------------ import threading import os import signal def system(s): p = os.fork() if p == 0: os.execvp("/bin/sh", ['sh', '-c', s]) os._exit(99) else: p, status = os.waitpid(p, 0); return os.WEXITSTATUS(status) class T(threading.Thread): def run(self): print system("python alarmed.py") t = T() t.run() t = T() t.start() t.join() #------------------------------------------------------------------------ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From anthonybaxter at gmail.com Wed Nov 24 20:39:35 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Thu, 25 Nov 2004 12:39:35 +1100 Subject: asynchat and threading In-Reply-To: <41a505c2$0$20660$9b622d9e@news.freenet.de> References: <4edc17eb.0411241036.72eed3ef@posting.google.com> <41a505c2$0$20660$9b622d9e@news.freenet.de> Message-ID: On Wed, 24 Nov 2004 23:05:56 +0100, Martin v. L?wis wrote: > AFAICT, the main complaint is that it is tied to the TCP transport, > the sockets API, and the select/poll API. IOW, it cannot easily: > - integrate TLS on top of TCP (because TLS might involve no-data > communications, e.g. when TLS negotation happens in the middle > of a TLS session), > - integrate other transports, such as serial ports on Windows, > - integrate other multi-endpoint wait APIs, such as IO completion > ports on Windows NT+, or kqueue on BSD. - work with other event loops, such as GUI toolkits There's also the problem that asyncore is more or less orphaned - there's no-one on the python development team who supports it fully. Bugs in it tend to get treated poorly. I wrote the original transport layer for pythondirector with asyncore. Under any sort of load, it just starts to lose, bigtime. Random errors, sockets getting lost, and the like. Switching to twisted made it go much, much faster. Well, to be fair, when I first ported to twisted, there was a nasty performance problem - this was relatively easy to track down and fix, and it's been fixed for a long time now. Trying to fix asyncore was a nightmare. The other thing to recommend twisted over asyncore is that twisted provides a fuller set of tools for programming in an async manner, such as Deferreds. With asyncore, you're kinda left on your own to do all this yourself. twisted is too large to go into the python core as is - in addition, there's a mismatch between Python's release cycle speed and twisted's release cycle speed (although the current delayed-until-who-knows-when Twisted 2.0 might be a harbinger of twisted slowing down to Python's speed ) It's possible that in the future a small core of twisted could end up in the stdlib - this topic's come up a couple of times on the twisted list (most recently, a couple of months ago). I wonder if the asyncore docs couldn't grow a 'See also' that points at twisted, though... From frithiof.jensen at die_spammer_die.ericsson.com Thu Nov 25 06:12:50 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Thu, 25 Nov 2004 12:12:50 +0100 Subject: Microsoft Patents 'IsNot' References: Message-ID: "Carlos Ribeiro" wrote in message news:mailman.6721.1101208339.5135.python-list at python.org... > With patents will become impossible to implement > software that is compatible with MS offerings. In the end, all that is achieved is to be in the position that DEC, IBM, and countless others placed themselves in: Sealed in behind proprietary connectors, standards and protocols and finding that they forgot to leave airholes in that box ;-) Just about *every* proprietary standard ever invented eventually is subverted and die because nobody wants the hassle and risk of dealing with it, it gets in the way of "The Job" whereas the Generic *facilitates* "The Job". > With patents, Microsoft can also strike back at open-source with an > economical argument: "I am the innovator and those guys are copying my > innovation and dumping the market with cheap copies". Its a good > argument for courts, and one that a conservative administration (read > Bush) is ready to buy. T-Rex was pretty fearsome too for a while but it did not cut much ice when the ecosystem changed! From Scott.Daniels at Acm.Org Fri Nov 19 13:13:14 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Nov 2004 10:13:14 -0800 Subject: Events In-Reply-To: References: Message-ID: <419e4a9e$1@nntp0.pdx.net> factory wrote: > Anyone want to comment on what they think of this following bit of a > simple event framework? > Are there any really obvious things I should be doing with this code > that stop me from getting bitten on the arse in the future? ... > class FoobarTalker( Talker ): > importantEvent= 42 > > def SomethingHappened( self, something ): > self.Talk( FoobarTalker.importantEvent, something ) ... Rather than making events be numbers (simple discrete things), I suspect that you'd be happier with a hierarchy. This way You can listen to "all kinds of events." Python gives you a nice way to define hierarchies in classes, so you could use classes directly as your events, or make your events instances (and thus allow data to be attached to the event). Certainly if you are attaching data, and possibly even if you you are not, you may want to provide a means of retrieving "the current event." You could even look at the history of exceptions in python for a model of what you might want. So, for events: class Event(object): pass # The mother event in case you need to share class ImportantEvent(Event): pass class IgnorableEvent(Event): pass class UsefulEvent(Event): pass you could change the guts of your Talk method from: ... > evt, listener = i > if evt == event: > listener(*args) To: ... criterion, listener = i if issubclass(event, criterion): listener(*args) Or (for the data-attached form): criterion, listener = i if isinstance(event, criterion): listener(*args) ... From drew at gremlinhosting.com Thu Nov 25 14:31:27 2004 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 25 Nov 2004 19:31:27 +0000 Subject: Does anyone know of a Python WebDAV library? Message-ID: <1101411087.30632.17.camel@odin> All, I've been trying to find a generic WebDAV library (possibly with the extra versioning extensions) in Python for a project I'm developing with mod_python. Ideally, I'm looking for one which which wraps around the XML and lets you instantiate classes for each request, like: req = PropFindRequest(myRequestText) resp = PropFindResponse(files) I've found two possibilities so far: http://comlounge.net/webdav/ - DAVServer and http://sandbox.xerox.com/webdav/ - Python WebDAV Server Neither of these projects provides the sort of interface that I'm looking for, and neither seems to be currently maintained. I'd rather not roll my own library if I can avoid it - can anyone point me in the direction of some existing work or (preferably) a current project? I will buy the owner of the winning response a drink should he/she ever come to London... Many thanks. Andrew -- Andrew James From Scott.Daniels at Acm.Org Wed Nov 10 16:25:31 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 10 Nov 2004 13:25:31 -0800 Subject: Combine two dictionaries into a list of 3-tuples In-Reply-To: References: Message-ID: <41929a86@nntp0.pdx.net> Nickolay Kolev wrote: > My attempts so far: > ... [(t, c, l) for t, c in one.items() for (t, l) in two.items()] Simply forget about items for two. [(key, val1, two[key]) for key, val1 in one.items() if key in two] --Scott David Daniels Scott.Daniels at Acm.Org From imbosol at aerojockey.com Thu Nov 11 19:41:21 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 11 Nov 2004 16:41:21 -0800 Subject: Summary: strong/weak typing and pointers References: <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> <10p1ud2juqlkb7c@corp.supernews.com> <60dfb6f6.0411101037.5cd6a17d@posting.google.com> <10p52ccen1ql956@corp.supernews.com> <60dfb6f6.0411102119.2091c0d@posting.google.com> <10p7h4rphhpg64c@corp.supernews.com> Message-ID: <60dfb6f6.0411111641.52902410@posting.google.com> Jeff Shannon wrote in message news:<10p7h4rphhpg64c at corp.supernews.com>... > >If you paid attention > >in your study of grammar, [...] > > Please don't assume that someone who disagrees with you is either > uneducated or stupid. It's rather insulting and wholly inappropriate. Testy? What, do you expect me to automatically give you credit for having paid attention to some decades-ago schooling unrelated to you field of work, even though I've never met or spoken to you? Anyways, although you've claimed "rigid" is very specific in meaning, based on some dictionary entries, I really don't see any arguments that tried to refute my claim that "rigid" could be easily taken to mean inability to reinterpret bits, or less easily to mean static typing. Conversely, I also didn't see any good examples of how "solid" could easily mean something else. (I thought the idea that it could refer to data hiding quite a stretch, although not totally off the wall. Nevertheless, I would say "rigid" is vastly more applicable to interpreting bits than "solid" is to data hiding.) I would like to see your ideas and thoughts about how applicable "solid" and "rigid" are specifically to typing. I've already stated my thoughts about this. What objections to you have those points? -- CARL BANKS From steven.bethard at gmail.com Wed Nov 10 11:49:27 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 10 Nov 2004 09:49:27 -0700 Subject: Packing list elements into tuples In-Reply-To: References: Message-ID: On Wed, 10 Nov 2004 19:00:52 +0800, Deepak Sarda wrote: > > > >>> l = [1,2,3,4,5,6] > > >>> zip(*(iter(l),)*3) > > [(1, 2, 3), (4, 5, 6)] > > >>> l = [1,2,3,4,5,6,7,8,9] > > >>> zip(*(iter(l),)*3) > > [(1, 2, 3), (4, 5, 6), (7, 8, 9)] > > Can someone explain how this works?! > [snip] > > So zip() basically gets zip(iter(l), iter(l), iter(l)) , right? Close, but note that zip(iter(l), iter(l), iter(l)) creates three iterators to the list l, while zip(*(iter(l),)*3) uses the same iterator at each position in the tuple. >>> l = [1,2,3,4,5,6] >>> zip(iter(l), iter(l), iter(l)) [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6)] >>> itr = iter(l) >>> zip(itr, itr, itr) [(1, 2, 3), (4, 5, 6)] Here's basically what zip ends up doing when you give it 3 names bound to the same iterator: >>> itr = iter(l) >>> tuple1 = (itr.next(), itr.next(), itr.next()) >>> tuple1 (1, 2, 3) >>> tuple2 = (itr.next(), itr.next(), itr.next()) >>> tuple2 (4, 5, 6) >>> result = [tuple1, tuple2] >>> result [(1, 2, 3), (4, 5, 6)] Note that when they're not the same iterator, zip does something like: >>> itr1, itr2, itr3 = iter(l), iter(l), iter(l) >>> tuple1 = (itr1.next(), itr2.next(), itr3.next()) >>> tuple1 (1, 1, 1) >>> tuple2 = (itr1.next(), itr2.next(), itr3.next()) >>> tuple2 (2, 2, 2) ... So you just get 3 copies of the elements at each index in your list. Hope that helped! Steve -- You can wordify anything if you just verb it. - Bucky Katt, Get Fuzzy From beliavsky at 127.0.0.1 Wed Nov 3 15:11:08 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 3 Nov 2004 14:11:08 -0600 Subject: Problems using numarray References: Message-ID: <41893b5c$1_1@127.0.0.1> Sonium wrote: >Hi, I am new to numarray and I'm going to use it in a nummerical >computation of planet and probe orbits. There for I created a body >class, representing an gravity affected mass (like a planet or a probe). >Now I have different bodys each with it's own position, velocity and >mass that pull each other together by gravity. Based on the previous >position and velocity I'm now calculating the positions and velocity for > the next timeframe and so on... So I get a quite high amout of data >because i have to store (number-of-bodys)*(number-of-timeframe) objects. > >Now, how can I use a numaray to store the body objects? I read the docu, >but didn't figure out how to solve my problem. In C++ I just created a >multidimensilnal array like data = new body[objects*timeframes] and I'm >looking for something synonymous with numarray. I asked a similar question regarding Numeric a few months ago, with subject "Numeric array of objects" -- see http://groups.google.com/groups?hl=en&lr=&c2coff=1&selm=3064b51d.0403031508.53498c6f%40posting.google.com for the thread. Probably the syntax is the same for Numeric and Numarray, but I have not checked. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From donn at drizzle.com Thu Nov 11 01:54:20 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 11 Nov 2004 06:54:20 -0000 Subject: Problem flushing stderr in embedded python References: <1100065836.697971@yasure> Message-ID: <1100156058.567069@yasure> Quoth "Farshid Lashkari" : ... | I've tried calling fflush on stderr, but that doesn't work either. OK, this would seem to mean that your sys.stderr has been replaced with something else. I guess I don't know for sure what you can count on in Windows, but I would have to expect that fflush on stderr really does work - that is, it flushes stderr's buffer. | I've encountered another weird problem also. If my python code causes an | error and I don't flush stderr, then I get a runtime error when my app | exits. It also prints out: | | Exception exceptions.NameError: "global name 'y' is not defined" in 'garbage | collection' ignored | Fatal Python error: unexpected exception during garbage collection. | | Does this give anybody a clue as to what's happening? Doesn't do anything for me, but you may find out what that is when you locate the code for the faux stderr you're (not) flushing. I would be more worried about this 'y' thing in principle, though, because it sounds like a problem in the C (or whatever) to Python interface that could have other unpleasant consequences. Donn Cave, donn at drizzle.com From someone at microsoft.com Sat Nov 20 19:25:03 2004 From: someone at microsoft.com (Jive) Date: Sun, 21 Nov 2004 00:25:03 GMT Subject: Python and generic programming References: <1gm17og.ctwoqv17vkctxN%aleaxit@yahoo.com><419EEEAA.D3C1046F@yahoo.com> Message-ID: I take it the ampersand is a neologism in 2.4? Jive jdadson at yahoo dott com "Ian Bicking" wrote in message news:mailman.6643.1100939117.5135.python-list at python.org... > Jive Dadson wrote: > > If you have, for example, several data-types for matrices, how do you > > write code that will automatically find the right routine for quickly > > multiplying a vector by a diagonal matrix represented as a vector, and > > automatically call the right code for multiplying by a sparse matrix > > represented by some sparse coding, etc? > > I haven't been following this thread, but Phillip Eby's recent > implementation of generic functions should be mentioned if it hasn't > been already: > > http://dirtsimple.org/2004/11/generic-functions-have-landed.html > > It might look something like this: > > @dispatch.on('m1', 'm2') > def matrix_mul(m1, m2): > "Multiply two matrices" > > @matrix_mul.when(VectorMatrix, SparseMatrix) > def matrix_mul_sparse(m1, m2): > "Special implementation" > > > -- > Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From godoy at ieee.org Thu Nov 25 07:13:28 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 25 Nov 2004 10:13:28 -0200 Subject: Python 2.4 and Visual C++ Express References: <9APod.4998157$ic1.468025@news.easynews.com> <30ji62F31ppn0U1@uni-berlin.de> Message-ID: Tim Peters writes: > 2.4 based on MSVC 6. There's no policy against that, but Pythons ^^^^^^^ > don't grow on trees. ^^^^^^^^^^^^^^^^^^^ Sorry, but I couldn't resist the joke :-) : http://www.whozoo.org/Intro98/jennglaz/jennglaz21.htm Be seeing you, -- Godoy. From boumenotspamyou at hotmail.com Thu Nov 18 11:21:09 2004 From: boumenotspamyou at hotmail.com (Christopher Boumenot) Date: Thu, 18 Nov 2004 11:21:09 -0500 Subject: PIL for Python 2.4? In-Reply-To: References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Thu, 18 Nov 2004 14:17:50 +0100, rumours say that Gerhard Haering > might have written: > > >>>Has anyone built PIL (1.1.4 or 1.1.5) for Python 2.4? If yes, >>>please let me know, [...] >> >>I haven't. But it would have been useful if you had mentioned which >>platform ;-) Windows? > > > Oh, yes, Windows... On Linux I built it myself. I just don't have > access to a MS compiler on Windows. > > Sorry for not being clear. You can download Microsoft's C/C++ compiler for free. (It's command line only, but good enough.) http://msdn.microsoft.com/visualc/vctoolkit2003/ Chris From misterbike at hotmail.com Sat Nov 13 14:50:54 2004 From: misterbike at hotmail.com (Craig D) Date: 13 Nov 2004 11:50:54 -0800 Subject: utility for install in zipped distutils packages Message-ID: <638038a2.0411131150.5e2a6926@posting.google.com> I got really tired of unpacking a distutils package, installing then cleaning up. So I wrote distinstall.py - it reads a zip file, unpacks it, installs the bits and cleans up. I've only used it on windows and Linux and for pure Python packages. Windows: distinstall.py Photronics.zip Linux: python distinstall.py Photronics.zip Hopefully somebody else will find it useful. #======================== distinstall.py ===================== #!/usr/bin/env python '''Install a zipped up distutils package''' import zipfile import sys, os, os.path def usage(): print "distinstall.py pack.zip: Install a zipped distutil python package" print "One arg: name of the zip package" print "THIS PROGRAM ONLY WORKS WITH ZIPPED PURE PYTHON PACKAGES!" sys.exit(1) def nuke(top): # Delete everything reachable from the directory named in 'top'. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(top) def explodeZipFile(zippedPackageFileName): if not zipfile.is_zipfile(zippedPackageFileName): print '"%s" is not a zip file!' % zippedPackageFileName usage() zip = zipfile.ZipFile(zippedPackageFileName,'r') if not filter(lambda n:"setup.py" in n, zip.namelist()): print "setup.py isn't in the zip file! Not a distutil package?" usage() tmp = os.getenv('TMP') or os.getenv('TMPDIR') if (not tmp) and os.path.isdir('/tmp'): tmp = '/tmp' if not tmp: print 'Can\'t find the tmp directory!' sys.exit(1) path,fileName = os.path.split(zippedPackageFileName) tmpDir = os.path.join(tmp,os.path.splitext(fileName)[0]) print "unzip %s to %s" % (zippedPackageFileName,tmpDir) for z in zip.namelist(): # print z data = zip.read(z) try: os.makedirs(os.path.join(tmp,os.path.split(z)[0]),0777) except: pass f = file(os.path.join(tmp,z),'w') #?? what's up with wb? f.writelines(data.split('\r')) # this really sucks f.close() zip.close() setup = os.path.join(tmpDir,"setup.py") return tmpDir,setup if len(sys.argv) < 2: usage() cwd = os.getcwd() zippedPackageFileName = sys.argv[1] tmpDir,setup = explodeZipFile(zippedPackageFileName) print "====================Install=================" os.chdir(tmpDir) install = "%s setup.py install --force" % sys.executable print install os.system(install) os.chdir(cwd) print "\nClean up %s" % tmpDir nuke(tmpDir) # this will clean up the build directory #======================== distinstall.py ===================== From maney at pobox.com Mon Nov 8 15:11:32 2004 From: maney at pobox.com (Martin Maney) Date: Mon, 8 Nov 2004 20:11:32 +0000 (UTC) Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> Message-ID: Greg Ewing wrote: > solid typing -- sharp boundaries between types, few > automatic coercions > fluid typing -- lots of automatic coercions > (Don't ask me what "gaseous typing" might mean...) Surely that would be typing by context, no? -- Among the greater ironies of the computer age is the fact that information is cheap and accessible, and so it is no longer very valuable. What is valuable is what one does with it. And human imagination cannot be mechanized. -- the New York Times From adam at 757.org Sun Nov 7 14:57:25 2004 From: adam at 757.org (Adam C.) Date: Sun, 07 Nov 2004 14:57:25 -0500 Subject: recover data from html form In-Reply-To: References: Message-ID: Peter Hansen wrote: > Armand Federico - INFO wrote: > >> How can i recover data from an html module? >> I have a form that send 3 or 4 text field >> >> I wanna to recover this data, to analyse, and process, and insert in >> MySQL >> >> (mod_python, Mysql4, Apache1.3) > > > The question is unclear. Are you looking for suggestions on > the process called "web scraping"? (search the web before > responding, if that term is unfamiliar to you, please) I think he's looking for the REQUEST object that mod_python passes in containing the GET/POST elements from his text fields. Check out: http://www.modpython.org/live/current/doc-html/tut-pub.html for a quick introduction to using the request object with an HTML form. -- Adam From bounces at foo.org Mon Nov 22 20:04:38 2004 From: bounces at foo.org (Dan) Date: Tue, 23 Nov 2004 01:04:38 GMT Subject: Identifying exceptions that can be raised In-Reply-To: References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: Cameron Laird wrote: > I'm sympathetic. It bothers me no end when working > with C and Java that documenters are as relaxed as > I've found them to be in failing to document error > conditions. Then there was the DEC C library, in which free() returned an error code on failure--and was so documented, but which was prototyped to return void as required by the standard. But I'll stop looking for the tool that finds all the exceptions that a function can raise. :-) /Dan -- dedded att verizon dott net From gumuz at NO_looze_SPAM.net Tue Nov 30 07:18:22 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Tue, 30 Nov 2004 13:18:22 +0100 Subject: Python Huffman encoding References: <41a525c6$0$76502$b83b6cc0@news.wanadoo.nl> Message-ID: <41ac64f3$0$16481$4d4ebb8e@news.nl.uu.net> Wow Paul! thanks a lot for your comments! I learned a lot already only by reading them, I will implement them and see what the speed gains are. Keep an eye on my blog, I will post an update on it soon! thanks, guyon ps. love this group "Paul McGuire" wrote in message > http://gumuz.looze.net/wordpress/index.php/archives/2004/11/25/huffman-encoding/ > Great first step at some self-learning with a non-trivial test program. > Here are some performance speedups that will help you out. From ed-no at spam-eepatents.com Wed Nov 24 14:16:56 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Wed, 24 Nov 2004 11:16:56 -0800 Subject: GCJ equivalent for Python? Message-ID: I have been programming Python for a year or so and like everything about it except for the difficulty of distributing programs to someone who doesn't have the 10MB+ interpreter package downloaded installed. I'm a frequent user of pdftk, a Java-based PDF-manipulation program that runs natively (no JVM required) because it is compiled with gcj. It's plenty fast and you really never know that it was written in Java unless you try to build it. So, the question naturally arises, why isn't there something like the gcj compiler for Python? Ed Suominen Registered Patent Agent Open-Source Software Author (yes, both...) Web Site: http://www.eepatents.com From jhefferon at smcvt.edu Mon Nov 22 19:45:40 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 22 Nov 2004 16:45:40 -0800 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: <545cb8c2.0411221645.442bb88a@posting.google.com> Peter Hansen wrote .. > The usual approach is to have a caller catch exceptions > *which it is capable of dealing with appropriately*, and > ignore others. In some cases it's necessary to have a > "generic" exception handler, such as at the top level of > a thread, to catch and log all exceptions, but that's > relatively rare. I wonder if perhaps you don't write different kinds of programs than I do. For instance, I have a cgi program. One routine will get an id from a httpd parameter, use it to reach into a database and fetch some xml, and then pull information out of the xml for display. That I can tell, there are about 100 exceptions that could be raised (the xml parser is vague about what it could raise, and although the dB is a bit better, it is not always clear what an exception means or under what condidtions it could be raised). I'm left with the feeling that for any amount of testing that I do (and I've found cgi hard to automatically test), there is always another exception lurking out there. I have a great deal of difficulty achieving the feeling that I am consistently returning a sensible error screen to the user. I've tried Java, and found it a slog, but for some programs knowing which exceptions could be raised would be a comfort. > All that said, you do sometimes find yourself pondering > what exceptions a given function might raise and which > you *do* want to handle properly. It's not always clear, > and unfortunately short of examining the source or hoping > that the author wrote decent documentation, you're out > of luck. I second that. Jim From someone at microsoft.com Sat Nov 27 22:48:42 2004 From: someone at microsoft.com (Jive) Date: Sun, 28 Nov 2004 03:48:42 GMT Subject: futue feature division not found (embedded) References: <41a925d5.1197560430@news.oz.net> Message-ID: "Bengt Richter" wrote in message news:41a925d5.1197560430 at news.oz.net... > On Sat, 27 Nov 2004 22:51:24 GMT, "Jive" wrote: > > >I've got a program with Python 2.3 embedded. When I try to run a script > >containing "from __future__ import division", I get an exception: > > > > File "main2.py", line 3 > > from __future__ import divison > >SyntaxError: future feature divison is not defined > ^^ s/divison/division/ ;-) > > > >Anyone know how to fix that? BTW, when I run the program with > >CO_FUTURE_DIVISION set in PyCompilerFlags, division works the new way, as it > ^^^ > >should. > > > > > HTH. On to the next bug ;-) What's HTH? It does fail though. Here's the message when I type it right: File "main2.py", line 3, in ? from __future__ import division ImportError: No module named __future__ I didn't misspell __future__ did I? From michael at stroeder.com Thu Nov 11 16:29:50 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 11 Nov 2004 22:29:50 +0100 Subject: ANN: python-ldap-2.0.5 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.5 2004-11-11 Changes since 2.0.4: Some small improvements for SASL: The noisy output during SASL bind is avoided now. Interaction with output on stderr can be enabled by the calling application by explicitly defining SASL flags. Removed obsolete directory Win32/. Lib/: * Make sure that ldap.sasl.sasl.cb_value_dict is a dictionary even when the caller passes in None to argument cb_value_dict * Added new key-word arg sasl_flags to method LDAPObject.sasl_interactive_bind_s() Modules/: * l_ldap_sasl_interactive_bind_s(): New key-word arg sasl_flags passed to ldap_sasl_interactive_bind_s() From jfouhy at paradise.net.nz Sun Nov 7 23:02:36 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 7 Nov 2004 20:02:36 -0800 Subject: Floating point -> string conversions Message-ID: Can someone explain these differences? >>> from math import pi >>> pi 3.1415926535897931 >>> type(pi) >>> repr(pi) '3.1415926535897931' >>> str(pi) '3.14159265359' >>> '%f' % pi '3.141593' >>> '%.16f' % pi '3.1415926535897931' Why do the string and default floating point representations get rounded? (and is this documented anywhere?) -- John. From ukunapul at hotmail.com Tue Nov 2 02:30:17 2004 From: ukunapul at hotmail.com (Uday) Date: 1 Nov 2004 23:30:17 -0800 Subject: Newbie question Message-ID: <783d0f8c.0411012330.4172d1d4@posting.google.com> Hi, I would like to know how can I create and assign variables by de-referencing the values in other variable in Python. I can illustrate what I mean by an example of perl $a = "task_id"; $i = "1"; $c = $a."_".$i; $$c = 2; print "$task_id_1\n"; # Gives the answer as 2 My problem is that I need to dynamically generate a unique variable within a for loop in Python. The name of the variable should be appended by the index of the loop. In the above example if $i were an array index, then as we traverse through the array, a unique variable is defined. Is there any way to do it in Python?? I am not in python.users mailing list, please reply to me directly. Thanks, Uday From tim.peters at gmail.com Sat Nov 6 01:47:04 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 6 Nov 2004 01:47:04 -0500 Subject: CGIs and file exclusion In-Reply-To: <4edc17eb.0411052049.7df47379@posting.google.com> References: <2uvedvF2g1pv3U1@uni-berlin.de> <6f402501.0411050228.aea8068@posting.google.com> <4edc17eb.0411052049.7df47379@posting.google.com> Message-ID: <1f7befae04110522476d98e20f@mail.gmail.com> [Michele Simionato] > ... > Maybe Diez B. Roggisch is right and a real database server is the simplest > solution. However my first attempt with ZEO didn't worked either: That's OK, nobody's first attempt with any database server works <0.6 wink>. > $ cat zeoclient.py > import ZODB, ZEO > from ZEO.ClientStorage import ClientStorage > > def openzeo(host, port): > db = ZODB.DB(ClientStorage((host, port))) > conn = db.open() > return db, conn, conn.root() > > def store(): > # I have a ZEO instance running on port 9999 > print "Opening the db ..." > db, conn, root = openzeo("localhost", 9999) > print "Storing something ..." > root["somekey"] = "somedata" It's important to note that store() always changes at least the root object. > get_transaction().commit() > print "Closing the db ..." > conn.close(); db.close() > > if __name__ == "__main__": > store() > > $ echo Makefile > default: > python zeoclient.py& > python zeoclient.py > > $ make > python zeoclient.py& > python zeoclient.py > Opening the db ... > Opening the db ... > > Storing something ... > Storing something ... > Closing the db ... > Traceback (most recent call last): > File "zeoclient.py", line 20, in ? > store() > File "zeoclient.py", line 15, in store > get_transaction().commit() > File "/usr/share/partecs/zope/lib/python/ZODB/Transaction.py", line > 247, in commit > ~/pt/python/zopexplore $ > ~/pt/python/zopexplore $ vote(self) > File "/usr/share/partecs/zope/lib/python/ZODB/Connection.py", line > 699, in tpc_vote > s = vote(transaction) > File "/opt/zope/lib/python/ZEO/ClientStorage.py", line 841, in > tpc_vote > return self._check_serials() > File "/opt/zope/lib/python/ZEO/ClientStorage.py", line 825, in > _check_serials > raise s > ZODB.POSException.ConflictError: database conflict error (oid > 0000000000000000, serial was 035900d31b7fedaa, now 035900d2f6cd8799) > > (it works with a single process instead). Yes, that's predictable too . > Maybe I misunderstood how ZEO is intended to be used, as usual it is > difficult to found the relevant documentation :-( Maybe I should ask > on another list ... zodb-dev at zope.org is the best place for ZODB/ZEO questions independent of Zope use. Note that you must subscribe to a zope.org list in order to post to it (that's a Draconian but very effective anti-spam policy). In the case above, ZEO isn't actually relevant. You'd see the same thing if you had a single process with two threads, each using a "direct" ZODB connection to the same database. ZODB doesn't do object-level locking. It relies on "optimistic concurrency control" (a googlable phrase) instead, which is especially appropriate for high-read low-write applications like most Zope deployments. In effect, that means it won't stop you from trying to do something insane, but does stop you from *completing* it. What you got above is a "write conflict error", and is normal behavior. What happens: - Process A loads revision n of some particular object O. - Process B loads the same revision n of O. - Process A modifies O, creating revision n+1. - Process A commits its change to O. Revsion n+1 is then current. - Process B modifies O, creating revision n+2. - Process B *tries* to commit its change to O. The implementation of commit() investigates, and effectively says "Hmm. Process B started with revision n of O, but revision n+1 is currently committed. That means B didn't *start* with the currently committed revision of O, so B has no idea what might have happened in revision n+1 -- B may be trying to commit an insane change as a result. Can't let that happen, so I'll raise ConflictError". That line of argument makes a lot more sense if more than one object is involved, but maybe it's enough to hint at the possible problems. Anyway, since your store() method always picks on the root object, you're going to get ConflictErrors frequently. It's bad application design for a ZODB/ZEO app to have a "hot spot" like that. In real life, all ZEO apps, and all multithreaded ZODB apps, always do their work inside try/except structures. When a conflict error occurs, the except clause catches it, and generally tries the transaction again. In your code above, that isn't going to work well, because there's a single object that's modified by every transaction -- it will be rare for a commit() attempt not to give up with a conflict error. Perhaps paradoxically, it can be easier to get a real ZEO app working well than one's first overly simple attempts -- ZODB effectively *wants* you to scribble all over the database. From bokr at oz.net Mon Nov 22 09:51:13 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 22 Nov 2004 14:51:13 GMT Subject: unicode question References: <419fc9b9$0$198$9b622d9e@news.freenet.de> <419ff7cd_3@newspeer2.tds.net> <41A061E1.8050203@v.loewis.de> <41a0ab62$0$151$9b622d9e@news.freenet.de> Message-ID: <41a1d80d.718896828@news.oz.net> On Mon, 22 Nov 2004 08:04:08 GMT, "wolfgang haefelinger" wrote: >Hi Martin, > >if print is implemented like this then I begin to understand the problem. > >Neverthelss, I regard > > print y.__str__() ## works > print y ## fails?? > >as a very inconsistent behaviour. > >Somehow I have the feeling that Python should give up the distinction >between unicode and str and just have a str type which is internally >unicode. > > >Anyway, thanks for answering >Wolfgang. > >""Martin v. L?wis"" wrote in message >news:41a0ab62$0$151$9b622d9e at news.freenet.de... >> wolfgang haefelinger wrote: >>> I was actually thinking that >>> >>> print x >>> >>> is just kind of shortcur for writing (simplifying bit): >>> >>> import sys >>> if not (isinstance(x,str) or isinstance(x,unicode)) and x.__str__ : >>> x = x.__str__() >>> sys.stdout.write(x) >> >> This is too simplifying. For the context of this discussion, >> it is rather >> >> import sys >> if isinstance(x, unicode) and sys.stdout.encoding: >> x = x.encode(sys.stdout.encoding) >> x = str(x) >> sys.stdout.write(x) >> >> (this, of course, is still quite simplicated. It ignores tp_print, >> and it ignores softspaces). >> >>> Or in words: if x is not a string type but has method __str__ then >>> >>> print x >>> >>> behaves like >>> >>> print x.__str__() >> >> No. There are many types for which this is not true; in this specific >> case, it isn't true for Unicode objects. >> >>> Is this a bug?? >> >> No. You are just misunderstanding it. >> >> Regards, >> Martin > It's an old issue, and ISTM there is either a problem or it needs to be better explained. My bet is on a problem ;-) ISTM the key is that a plain str type is a byte sequence but can be interpreted as a byte-stream-encoded character sequence, and there are some seemingly schizophrenic situations. E.g., start with a sequence of numbers, obviously just produced by a polynomial formula having nothing to do with characters: >>> numbers = [(lambda x: (-499*x**4 +4634*x**3 -13973*x**2 +13918*x +1824)/24)(x) for x in xrange(5)] >>> numbers [76, 246, 119, 105, 115] Now if we convert those to str type characters with chr() and join them: >>> s = ''.join(map(chr, numbers)) Then we have a sequence of bytes which could have had any numerical value in range(256). No character encoding is assumed. Yet. If we now assume, say, a latin-1 encoding, we can decode the bytes into unicode: >>> u = s.decode('latin-1') >>> type(u) Now if we print that, sys.stdout.encoding should come into play: >>> print u L?wis :-) And we are ok, because we were explicit the whole way. But if we don't decode s explicitly, it seems the system makes an assumption: >>> print s L?wis That is (if it survived) the 'cp437' character for byte '\xf6'. IOW, print seems to assume that a plain str is encoded ready for output in sys.stdout.encoding in a kind of reinterpret_cast of the str, or else a decode('cp437').encode('cp437') optimized away. >>> sys.stdout.encoding 'cp437' >>> sys.getdefaultencoding() 'ascii' If it were assuming s was encoded as ascii, it should really do s.decode('ascii').encode('cp437') to get it printed, but for plain str literals it does not seem to do that. I.e., >>> s.decode('ascii') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 1: ordinal not in range(128 doesn't work, so it can't be doing that. It seems to print s as s.decode('cp437').encode('cp437') >>> s.decode('cp437') u'L\xf7wis' but that is a wrong decoding, (though the system can't be expected to know). >>> print s.decode('cp437').encode('cp437') L?wis >>> print s.decode('latin-1').encode('cp437') L?wis What other decoding should be attempted, lacking an indication? sys.getdefaultencoding() might be reasonable, but it seems to be locked into 'ascii' (I don't know how to set it) >>> sys.getdefaultencoding = lambda: 'latin-1' >>> sys.getdefaultencoding() 'latin-1' >>> unicode('L\xf6wis') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 1: ordinal not in range(128 So, bottom line, as Wolfgang effectively asked by his example, why does print try to coerce the __str__ return value to ascii on the way to the ouput encoder, when there is encoding info in the unicode object that it is happy to defer reencoding of for sys.stdout.encoding? >>> s 'L\xf6wis' >>> u u'L\xf6wis' >>> print s L?wis >>> print u L?wis >>> class Y: ... def __str__(self): return self.c ... >>> y = Y() >>> y.c = s >>> print y L?wis >>> y.c = u >>> print y Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in r ange(128) >>> print u L?wis Maybe the output of __str__ should be ok as a type basestring subclass for print, so y.c = u print y above has the same result as print u It seems to be trying to do u.encode('ascii').decode('ascii').encode('cp437') instead of directly u.encode('cp437') when __str__ is involved. >>> print u'%s' % y L?wis works, and >>> print '%s' % u L?wis works, and >>> print y.__str__() L?wis and >>> print y.c L?wis works, >>> y.c u'L\xf6wis' but >>> print '%s'%y Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in r ange(128) and never mind print, >>> '%s' % u u'L\xf6wis' >>> '%s' % y.__str__() u'L\xf6wis' >>> '%s' % y Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in r ange(128) I guess its that str.__mod__(self, other) can deal with a unicode other and get promoted, but it must do str(other) instead of other.__str__(), or it would be able to promote the result in the latter case too... This seems like a possible change that could smooth things a bit, especially if print a,b,c was then effectively the same as print ('%s'%a),('%s'%b),('%s'%c) with encoding promotion. Regards, Bengt Richter From aleaxit at yahoo.com Tue Nov 16 06:00:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 16 Nov 2004 12:00:56 +0100 Subject: Zope 3.0, and why I won't use it References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> <1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com> Message-ID: <1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> Josiah Carlson wrote: > > but the point is whether, if and when 'optional static typing' _syntax_ > > gets it, it will have this semantics or that of inserting a lot of > > typechecks... people can do typecheks or adaptation now, and neither > > will go away -- but which, if either, should syntax facilitate? That, > > as I see it, is key. > > I guess it all depends. > "In the face of ambiguity, refuse the temptation to guess." > "Explicit is better than implicit." > > With the requisite zens quoted, I'd say that there should be an explicit > way to do both, because guessing which one (but not both) is necessarily > the wrong thing to do. Since the actual need for type-checking is extremely rare, I contend it should not _at all_ be a candidate for a syntax to facilitate it. Since the actual need for adaptation is much wider, I contend it's the one obvious choice for the "nice syntax" if any. > With that said, type-based dispatch, checking and adaptation are > provided by decorators, which are explicit. They are not a syntax > per-se, but they will get the job done in the mean time (if placing type > checking and adaptations in the function body is not sufficient). Type checking is ugly, so it's quite fitting that it be implemented in ugly ways -- by boilerplate or user-coded splats. Adaptation is beautiful, and beautiful is better than ugly (see, I can quote the zen of Python too...), so it should have nice syntax ( 'as' ). Type-based dispatch is a little bit of a mess to implement with decorators, IMHO. Consider the hypothetical code...: class A(object): @ dispatch(int) def foo(x): ... @ dispatch(float) def foo(x): ... class B(object): @ dispatch(int) def foo(x): ... @ dispatch(str) def foo(x): ... Sure, dispatch can be a H**2OF which returns a dispatching-foo and stashes somewhere a (say) foo__int, foo__float or whatever, but the problem is, _WHAT_ 'somewhere'. dispatch isn't told what class body it's being called from, so it can't easily stash stuff in the obvious place, the class dictionary being built. Attributes of the dispatching-foo don't seem good, because of the problem of getting at the right previously-returned dispatching-foo object on successive calls of dispatch from within the same class body (but not from separate class bodies). Maybe some peek-into-the-stack black magic or custom metaclass can help, but it does seem a little bit of a mess, unless I'm overlooking something obvious. If the implementation is hard to explain, it's a bad idea... Alex From jarppe_remove_this_ at gmail.com Fri Nov 5 08:28:16 2004 From: jarppe_remove_this_ at gmail.com (Jarppe) Date: Fri, 05 Nov 2004 13:28:16 GMT Subject: Calling python interpreter from a thread created in C In-Reply-To: References: Message-ID: Hi, Greg Chapman wrote: > First, you need to ensure that Python is ready for threading. From the > application's main thread, call PyEval_InitThreads (if this has already been > called, it simply returns. But if this is the first call, it assumes it is > being called on the application's main thread, so you don't want to call this on > your callback thread). That's it!!! I didn't realize that and I just keep getting SIGSEGV no matter what I did. I added call to PyEval_InitThreads() and it started to work immediately! Thanks!!! > Then, in your thread's callback, call PyGILState_Ensure before accessing any > part of the Python API. When you're done working with python, call > PyGILState_Release. See the documentation and example here: > > http://www.python.org/dev/doc/devel/api/threads.html > > (Note that before the example of using PyGILState_Ensure, > the text refers to > needing an interpreter state. This text is left over > from versions before > PyGILState was introduced. Just do what the example shows > and you shouldn't have a problem.) Oh, that's interesting! I used PyEval_AcquireThread() and PyEval_ReleaseThread(). Now I changed to PyGILState_Ensure()/PyGILState_Release(), and now the code looks much simpler. And it works :) Thanks a lot!!! -- -jarppe If you have the right attitude, interesting problems will find you. -- Eric Steven Raymond From belred1 at yahoo.com Tue Nov 16 20:13:31 2004 From: belred1 at yahoo.com (Bryan) Date: Wed, 17 Nov 2004 01:13:31 GMT Subject: adaptation In-Reply-To: References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm><1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com><1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com><1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> Message-ID: <%Axmd.95367$HA.60678@attbi_s01> Terry Reedy wrote: >>example? > > > The example used in the Zope3 programmer tutorial: > > You have database of (USA) Buddy objects, each with firstname, lastname, > streetaddress, zipcode, and email fields. You want to use them in a > context that requires the (redundant) city and state fields. So you write > a zip to city/state lookup function and then an ExpandedBuddy adapter that > gets the zip from the adapted Buddy, calls city_state(zip), and packages > the result together as needed in the usage context. > > Terry J. Reedy > > > thanks carlos, alex, terry... the part i was missing was that adapt() retrieves a registered customized adapter from a registry. so, i see that this would completely decouple code which wants objects of protocol Y from code that created objects with different protocols X[n]. this seems to be the basic adapter pattern, but with the added feature of the registry lookup. i'm sure there are some other dynamic benifits you get by using python. i'll read the links the links that were posted and catch up... thanks, bryan From gashton at cmedltd.com Mon Nov 1 16:34:53 2004 From: gashton at cmedltd.com (Graham Ashton) Date: Mon, 01 Nov 2004 21:34:53 +0000 Subject: Flushing stdout Message-ID: Hi. I'm having trouble flushing sys.stdout. I've written a small example to illustrate my problem (see below). In short, I expect it to ping "received hello", sleep for 5 seconds and then print "received world". Instead I get nothing for 5 seconds and then both statements pop out at once. As you'll no doubt gather from the example, the problem I'm really trying to solve is sending message back from one process to another via a pipe. Changing the buffering option in the os.pipe() call doesn't have any effect either. Any thoughts? Thanks. P.S. I've not found -u and PYTHONUNBUFFERED to help me. P.P.S. I'm running 2.3.3 on Linux, libc 2.2.5-11.5. ---cut--- #!/usr/bin/env python import os, sys, time if len(sys.argv) > 1: sys.stdout.write("hello\n") sys.stdout.flush() time.sleep(5) sys.stdout.write("world\n") else: command = "python %s foo" % os.path.basename(sys.argv[0]) for line in os.popen(command, "r", 1): print "received", line, From jbzsmith at lycos.com Sat Nov 27 14:02:52 2004 From: jbzsmith at lycos.com (Jim Smith) Date: Sat, 27 Nov 2004 12:02:52 -0700 Subject: [web_framework] Basic Question regarding web framework In-Reply-To: References: Message-ID: Francis Lavoie wrote: > > I have some knowledge with PHP and JSP. > > Secondly, I would like to receive any advice on which webframe is best. > Each of the frameworks uses a different approach and has different strengths and weaknesses. It depends on which one fits you brain the best. The evaluation process can take a fair amount of time. > Is webware is a good choice? - Webware - Works well, but requires an application server that communicates with the web server. This is difficult in many hosting situations. A few that I like that work in most hosting environments are: - Quixote - A programmer's approach. You write a program that has subroutines that create the web pages. This one either fits your brain or it doesn't. If you view your site as a program this is good choice. http://www.mems-exchange.org/software/quixote/ - jonpy - A better CGI. It provides an object oriented interface for writing CGI programs. I like it for its simplicity. http://jonpy.sourceforge.net/ - Spyce - Python Server Pages. Web pages with embedded python. The ability to embed Python chunks including proper indentation is very nice. http://spyce.sourceforge.net/ All of these work well, it just depends your style. If you are looking for something close to PHP then I think Spyce is your best choice. Good luck, Jim From steven.bethard at gmail.com Fri Nov 19 20:00:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 20 Nov 2004 01:00:52 GMT Subject: Pythonic list to bitflag mapping In-Reply-To: <76c29906.0411191647.4b135e06@posting.google.com> References: <76c29906.0411191647.4b135e06@posting.google.com> Message-ID: Ramon Felciano wrote: > I have a list of integers that I'd like to convert to a bitflag or 1D > matrix format: > > a = [3,4,6] > b = [0,0,0,1,1,0,1,0,0,0] # a 1 for each position in the a list [snip] > [1 if x in a else 0 for x in range(10)] How about: >>> a = [3,4,6] >>> [int(x in a) for x in range(10)] [0, 0, 0, 1, 1, 0, 1, 0, 0, 0] The idea here is to treat the bool 'x in a' as an int, making use of the fact that int(True) == 1 and int(False) == 0. Steve From changli_to at hotmail.com Wed Nov 24 22:39:14 2004 From: changli_to at hotmail.com (Chang LI) Date: 24 Nov 2004 19:39:14 -0800 Subject: Use Python library from C++ Message-ID: <89cc6e1f.0411241939.61a19596@posting.google.com> I want to use the Python Libray from my C++ program. The Python Libray is no GUI. How can I mix C++ and Python? One way is to run PY library as an independent process. Another way is to start PY as a C++ thread. The third way is to run Python engine as part of the C++. Which way is better? No intention to access all the Python's code but only access APIs of a module. From hans at zephyrfalcon.org Fri Nov 5 18:33:10 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 05 Nov 2004 18:33:10 -0500 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: <418C0DB6.1040007@zephyrfalcon.org> John Machin wrote: > Or is this a joke/troll?? I can't believe the "unimelb.edu.au"; surely > a forgery. Is it just me, or is the climate in c.l.py getting less friendly to newbies? In any case, http://www.zoology.unimelb.edu.au/staff/nicholas.htm mentions Maurice Ling as an honor student. -- Hans Nowak http://zephyrfalcon.org/ From austin at maxtronic.com.tw Thu Nov 11 08:08:41 2004 From: austin at maxtronic.com.tw (Austin) Date: Thu, 11 Nov 2004 21:08:41 +0800 Subject: socket.error:(13,'Permission deied') Message-ID: <4193644c@news.seeder.net> ........................ data = .... self.broadcast_ip = 255.255.255.255 UDPSock.sendto(data,(self.broadcast_ip,36)) ......................... These codes run on Windows without errors and warnings. But i excute that on Fedora Core 2, it shows the error "socket.error:(13,'Permission deied')" i try to disable the firewall and become a root but it doesn't work, either. Does anyone have any suggestions ? From asid at sympatico.ca Thu Nov 11 08:59:31 2004 From: asid at sympatico.ca (Alex Sidorenko) Date: Thu, 11 Nov 2004 08:59:31 -0500 Subject: socket.error:(13,'Permission deied') References: <4193644c@news.seeder.net> Message-ID: <7fKkd.29659$Z7.928089@news20.bellglobal.com> Austin wrote: > ........................ > data = .... > self.broadcast_ip = 255.255.255.255 > > UDPSock.sendto(data,(self.broadcast_ip,36)) > ......................... > > > These codes run on Windows without errors and warnings. > But i excute that on Fedora Core 2, it shows the error > "socket.error:(13,'Permission deied')" > i try to disable the firewall and become a root but it doesn't work, > either. > > Does anyone have any suggestions ? Broadcasting is a privileged operation on Unixes, you need to set SO_BROADCAST flag. See manpage socket(7). Hope this helps, Alex From mark.asbach at post.rwth-aachen.de Mon Nov 22 18:25:59 2004 From: mark.asbach at post.rwth-aachen.de (Mark Asbach) Date: Tue, 23 Nov 2004 00:25:59 +0100 Subject: Wrapping a C library in Python References: Message-ID: <1gnogzb.1rj5ma5sd0l6aN%mark.asbach@post.rwth-aachen.de> Hi Craig, > Just out of interest, do you know if SWIG can be used to generate an > extension module to provide interfaces to the API of an application that > embeds a Python interpreter? Why not? We do that for the next generation of an open source finite-element-toolkit driven by an embedded Python interpreter. And it was really nice to see how easy it is to retro-fit new SWIG wrapped code to already existing hand written wrappers and externally developed Python wrappers (vtk). So in fact we were able to dramatically reduce the time spent for writing wrappers and adaptor code just by using SWIG. What we needed wouldn't have been possible with Boost.Python and it would also mean a longer compile time. Mark From 3d_4533212 at katamail.it Wed Nov 24 04:32:25 2004 From: 3d_4533212 at katamail.it (3d) Date: Wed, 24 Nov 2004 10:32:25 +0100 Subject: Vtk Message-ID: Hi, you have a information on the Vtk and its installation to use it with python on windows? thanks men -- questo articolo e` stato inviato via web dal servizio gratuito http://www.newsland.it/news segnala gli abusi ad abuse at newsland.it From pekka.niiranen at wlanmail.com Sat Nov 6 16:58:26 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sat, 06 Nov 2004 23:58:26 +0200 Subject: Shortcut needed: avoiding temporary variables with regular expressions Message-ID: <418d498f$0$12683$39db0f71@news.song.fi> Hi there, I am using regular expressions like this: matcher = re.compile(r'(.*)\s(.*)', re.UNICODE) tmp = matcher.search(mystring) if tmp: myvariable = tmp.group(1) The idea is that group(1) is accessed only if it was found from 'mystring'. Is there a way to avoid the usage of 'tmp' -variable? Sure, I could try: matcher = re.compile(r'(.*)\s(.*)', re.UNICODE) if matcher.search(mystring): myvariable = matcher.search(mystring).group(1) but then I am searching 'mystring' twice. -pekka- From rff_rff at remove-yahoo.it Sat Nov 6 04:56:02 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Sat, 06 Nov 2004 09:56:02 GMT Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <878y9gbkh7.fsf@pop-server.bigpond.net.au> Message-ID: Harald Massa ha scritto: > Israel Raj T wrote in news:878y9gbkh7.fsf at pop- > server.bigpond.net.au: > > >>On the updated version at http://shootout.alioth.debian.org/craps.php, >>Python beats at least two java implementations. > > > Very interesting link, great ressource!!! > > What really is disturbing: within the test "hash access" perl2 comes out > first compared with java. > > A know that Python dictionaries are the most heavily used datastructure > (because it is allways used within Python itself), and from looking at the > sourcecode there is the line "with help from Raymund Hettinger"; so I am > very sure it is probably THE optimal coding. > > So... string processing, regular expression, blablabla no problem; but why > second to perl2 in Hash-access ??? maybe because perl has been polished for more years :) Anyway, 3 things worth noting about the shootou - you won't *ever* write heapsort and things like that in python, obviously it is slow, and obviously you have'em builtin. - there are some tricks like using numarray for matrix calculations - the ranking system is named CRAP(s). From http Sun Nov 7 13:53:49 2004 From: http (Paul Rubin) Date: 07 Nov 2004 10:53:49 -0800 Subject: remove assert statement (Was: Re: PEP new assert idiom) References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> <7xy8hep325.fsf@ruckus.brouhaha.com> <10osqs5al7tii49@news.supernews.com> Message-ID: <7xhdo1pk1u.fsf@ruckus.brouhaha.com> "John Roth" writes: > I see assert as a statement of an invariant: each and every time > I come here this *must* be true. Yes, that was the intention of the assert statement. However, there's a very great temptation to use it for a somewhat different purpose, namely checking data validity. When there's a great temptation to misuse some feature to do X when it's really intended for Y, that's a sign that it's time to add an equally convenient feature intended for doing X. > For me, an assert failing is a programing error in the caller, not > in the method with the assert! Trying to catch an assert is a misuse > of what the statement provides. There's a slight non-sequitur there. Every large system contains programming errors, and assert statements are a good way to detect the errors. If an assert fails and isn't caught, the system crashes. Crashing a running system on detection of the slightest programming error is not always an acceptable thing to do. Sometimes you have to log the error and try to recover from it, disable the feature where the error happened until someone can figure out what went wrong, or whatever; but not crash. So you need to be able to catch assert failures. From steve at holdenweb.com Thu Nov 18 03:13:37 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Nov 2004 03:13:37 -0500 Subject: SQL Server stored prcedures with output parameters In-Reply-To: References: Message-ID: Steve Holden wrote: > > Hmmm, following up, added another test to adodbapi to retrieve a value > from a table into an output parameter it works, so this puts the > suspicion on to the stored procedure. Since this was written by the > client I'll take a look at it later (when I'm back in the office) and > see what the problem might be. > > happily-talking-away-to-myself-ly y'rs - steve However, the stored procedure below appears to consistently return zero for the link_id when called with: columnist_id, url, title, description, link_id = \ curs.callproc("sp_InsertArticle", (columnist_id, url, title, description, 0)) so maybe there really *is* something wrong. Or, hopefully, I'm just making a simple mistake in the calls? Whatever value is used as the fifth (output) parameter seems to get returned, despite the apparent change in the stored procedure. Create PROCEDURE dbo.sp_InsertArticle ( @columnist_id int, @url varchar(255), @title varchar(99), @description text, @link_id int OUTPUT ) AS BEGIN INSERT INTO link (columnist_id,url,title,description) VALUES (@columnist_id, at url, at title, at description) SELECT @link_id = @@IDENTITY END GO not-quite-so-happi-ly y'rs - steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From dnovatchev at yahoo.com Thu Nov 4 05:58:39 2004 From: dnovatchev at yahoo.com (Dimitre Novatchev) Date: Thu, 4 Nov 2004 21:58:39 +1100 Subject: Python AST as XML References: <1e015c2a.0410272209.3e831f94@posting.google.com> Message-ID: <2uugb2F2emt2rU1@uni-berlin.de> "Oleg Paraschenko" wrote in message news:1e015c2a.0410272209.3e831f94 at posting.google.com... > Hello, > > maybe of some interest: > > http://pysch.sourceforge.net/ast.html This is definitely of interest. An AST as any tree is a perfect fit for XSLT processing. Many people overlook the fact that XSLT operates on generic trees, which do not have to necessarily originate from an XML document. My personal experience in implementing graph-processing algorithms in XSLT (e.g. Eulerisation of a graph -- the chinese postman and the N.Y street sweeper algorithms) shows that XSLT is efficient programming language for such problems -- similarly it will be efficient in rewriting and optimization. Do keep the good work, Oleg! Cheers, Dimitre. > > [quote] > XML can be considered as an external representation of in-memory > tree-like structures, and XML-related standards - as methods of > processing such data. Some types of applications may benefit > from this approach. One of the examples are compilers with > theirs parse trees. > > The Pysch distribution contains an example of representing Python > parse trees (abstract syntax trees, AST) as XML and applying an > XSLT transformation to these trees. > > At the moment the whole code should be considered as a toy, > not as a production version. Anyway, it works. > > ... > [/quote] > > -- > Oleg From pinard at iro.umontreal.ca Tue Nov 30 17:12:12 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 30 Nov 2004 17:12:12 -0500 Subject: Closing files In-Reply-To: <41ac4e7a$0$25785$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <1gnz2kq.1jnqpi01tkznh0N%news+0409@henrikholm.com> <41ac4e7a$0$25785$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <20041130221212.GA16019@alcyon.progiciels-bpi.ca> > Daniel Dittmar wrote: > >- that suggest a different solution; like declarations on local > >variables that say "call destructor when object goes out of scope" I did not follow all of this thread (that precise subject reoccurs once in a while, with some regularity), but I merely would like to point out that objects never go "out of scope". Only variables do, and variables hold references to objects. When the last reference to an object disappears, only then the destructor is called. With Python (that particular Python that some call C-Python), this is guaranteed. [Nick Coghlan] > You may be interested in PEP 310 (reliable acquisition/release pairs): > http://www.python.org/peps/pep-0310.html Such a PEP might be useful for Jython or other Python-like languages. Yet with Python, the real thing, the effect of the PEP is easily achieved by relying on the timely finalisation of objects. For example, in Pymacs, the `let' and other various `save-' constructs of Emacs Lisp are simulated through Let() objects, used like in this example: let = Let().push_excursion() if True : ... user code ... del let Here, the `if' sole-purpose is to indent the "with" block, and so, to make the whole construct more legible. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From circulus at seznam.cz Thu Nov 4 14:06:30 2004 From: circulus at seznam.cz (Pavel Starek) Date: 4 Nov 2004 11:06:30 -0800 Subject: Python module for Mitsubishi PLC FX series - exist ? Message-ID: <2d5d81ff.0411041106.2371c5b5@posting.google.com> Hi all, For first, excuse me poor english, i am a czech citizen. I have question. Exist somewhere a python module for working with a Mitsubishi PLC FX series + cooperation with (famous) pyserial module ? Thanks for answers, Pavel Starek From behnel_ml at dvs1.informatik.tu-darmstadt.de Mon Nov 8 07:12:18 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Mon, 08 Nov 2004 13:12:18 +0100 Subject: How come wxPython isn't in the standard library? In-Reply-To: References: <1099858070.544710.146320@z14g2000cwz.googlegroups.com> <1099858260.250679.61490@f14g2000cwb.googlegroups.com> Message-ID: James Stroud schrieb: > What am I missing here? Lets look at it from an END USER's perspective. I come > from a situation where I was sys-admin to where I am the 0 privelige user. I > wanted to install a python module. So I called in the sys-admin. He tried to > add it with RPM. This rpm depended on that rpm and that rpm depended on a > chicken which depended on an egg which, expectedly, depended on a > chicken--you can guess where this is going. I guess your sys-admin just forgot to install apt-for-rpm first. Stefan From ch.pingel at web.de Fri Nov 19 05:17:11 2004 From: ch.pingel at web.de (Christoph Pingel) Date: Fri, 19 Nov 2004 11:17:11 +0100 Subject: regex-strategy for finding *similar* words? In-Reply-To: References: <1100774319.18258.249.camel@bucket.localnet> Message-ID: >There >are faster algorithms available than the dynamic-programming one -- >google "Heikki Hyyro". These allow you to preprocess your input word >and then compare with multiple dictionary candidates in O(kn) instead >of O(kmn) time where the input word has length m, and you compare with >k dictionary words each of average length n. John, thanks for the rich input! I found the Hyyro/Navarro algorithm, and this looks interesting. First I will give python's own difflib.SequenceMatcher class a try - the project here doesn't necessarily need the fastest algorithm, coding time is an issue however. I found that a match ratio slightly above 0.85 captures most of my misspelling cases without producing errors. best, Christoph From someone at microsoft.com Tue Nov 23 18:08:42 2004 From: someone at microsoft.com (Jive) Date: Tue, 23 Nov 2004 23:08:42 GMT Subject: A lock that times out but doesn't poll References: Message-ID: <_pPod.3495362$yk.537691@news.easynews.com> Ironic, isn't it? The whole idea of a condition variable is to avoid sleeping and polling. The polling soaks up CPU cycles, and the sleeping introduces latency that might not be acceptable for a given application. I presented two versions of sleepless timed condition variables in this NG a year or two ago. They hooted me down like an English kuneegut. One version used an alarm clock thread. From a very quick glance at your code, I presume that's what you've done. The other used a C coded timed lock, something that's not in standard Python. Why, I wonder? I can't imagine there are many platforms where you can't implement such a thing. I showed a C extension for MS Windows. I made my Python module a drop-in replacement for the current threading module, BTW. I am uncomfortable with the existing package not only because it uses polling, ("the evil from which we flee"), but also because it's so convoluted. Reading it, I have a hard time proving to myself that it's correct. If the package I posted is still on the net somewhere, take a look at it and see just how simple it can be. Now they will taunt me a second time. From djc at object-craft.com.au Tue Nov 2 20:20:40 2004 From: djc at object-craft.com.au (Dave Cole) Date: Wed, 03 Nov 2004 12:20:40 +1100 Subject: Line buffering pipes In-Reply-To: References: Message-ID: Shaun Jackman wrote: > I'm reading from a tcpdump pipe. I want to receive one line from the > pipe as soon as its available from tcpdump. Something is buffering the > pipe though, so I am receiving nothing, then multiple lines in a big > batch. I thought this was the inherent buffering of next(), but it > affects readline too. > > For example, > tcpdump = os.popen( 'sudo tcpdump', 'r') > both > while True: print tcpdump.next(), > and > while True: print tcpdump.readline(), > buffer mutiple lines before printing. My understanding is that the libc library linked to tcpdump queries the file it has as standard output and discovers a pipe. It then decides to buffer output for efficiency. So what you need to do is make sure that the tcpdump standard output is not a pipe. Check out the pty module. It will connect a psuedo tty as the tcpdump standard output. This will prevent the libc from buffering. - Dave -- http://www.object-craft.com.au From greg at cosc.canterbury.ac.nz Tue Nov 2 21:51:14 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 03 Nov 2004 15:51:14 +1300 Subject: strong/weak typing and pointers In-Reply-To: References: <2upctrF2dhnfeU1@uni-berlin.de> Message-ID: <2uqvd6F2dn4seU1@uni-berlin.de> Diez B. Roggisch wrote: > I'm no native speaker, so I maybe confused the meaning of permanent. In > german, permanent not only means that things are enduring, but also that > things are done on regular bases: "He permanently changed his cloth." We would say "regularly", "frequently", "habitually", or something like that. In English, "permanently" means "once and for all". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From len-1 at telus.net Thu Nov 25 12:57:44 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Thu, 25 Nov 2004 17:57:44 GMT Subject: Microsoft Patents 'IsNot' References: <30ijkhF31dg9sU1@uni-berlin.de> Message-ID: <3byxq0a1.fsf@telus.net> Paul Robson writes: > On Wed, 24 Nov 2004 18:04:03 +0000, Lenard Lindstrom wrote: > > > Greg Ewing writes: > > > >> Lenard Lindstrom wrote: > >> > So Delphi is definitely not BASIC-derived. It is BASIC-like in that various > >> > basic dialects, including QBasic, came to support the structured programming > >> > that Pascal was designed from the beginning to teach. > >> > >> So it would be more accurate to say that those Basic > >> dialects are, in those respects, Pascal-like... > >> > > By saying Delphi is BASIC-like I just mean that many languages have come > > to resemble each, having adopted many of the same features. But it was > > definitely Basic that did most of the adopting. So yes, more precisely, > > Basic has become more Pascal-like. I was just giving the patent applicants > > a minor benefit of a doubt. > > I believe the author of .NET is the bloke that designed Turbo Pascal, so > it's hardly surprising :) Is this Andreas Heiljberg which you mentioned in an earlier posting to this thread? http://groups.google.com/groups?q=g:thl3163358907d&dq=&hl=en&lr=&selm=pan.2004.11.23.07.09.08.229463%40autismuk.muralichucks.freeserve.co.uk Lenard Lindstrom From donn at u.washington.edu Wed Nov 17 15:31:34 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 17 Nov 2004 12:31:34 -0800 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) References: <30001hF2ptnqcU1@uni-berlin.de> Message-ID: In article , Dave Brueck wrote: > Greg Ewing wrote: > > Jeremy Bowers wrote: > > > >> Generally, returning a tuple is either a sign that your return value > >> should be wrapped up in a class, or the function is doing too much. > > > > > > While I suspect you may be largely right, I > > find myself wondering why this should be so. > > *Is* it largely right? I don't think so. As you said, there doesn't seem to be > anything "wrong" with passing multiple pieces of data _into_ a function, so why > should we assume that complex data passing should be so one way? What's up with keyword arguments, then? I don't think you can argue that on one hand keyword arguments are a valuable feature, but plain by-order tuples are a totally satisfactory interface on the other hand. > One of my biggest pet peeves about programming in C, for example, is that you > are often forced to wrap stuff up into a structure just to pass data back and > forth - you create the structure, populate it, send it, and then pull out the > data. > > In many, many cases this is nothing more than poor-man's tuple unpacking, and > you end up with lots of extra work and lots of one-off structures. Also > annoying > is the use of "out" parameters, which is again basically manual tuple > unpacking. Take stat(), which for those who haven't used it reports a number of characteristics of a file. It's not the ideal example, because it's big (10 items) and it's already "fixed" (has attributes like a class instance.) But its worst problem has nothing to do with the size, or whether or not the items can be referred to by name. As long as they can be referred to by position, we're stuck with the exact same items on all platforms, in all situations, for the rest of eternity. Whether some of them might not really be supported on some platforms, or it omits some useful values on others. It's not very flexible. C stat(2) doesn't have this problem. I don't know if I'd go along with "largely right", but it could fall somewhere between "some truth in it" and "completely whacked." Donn Cave, donn at u.washington.edu From carribeiro at gmail.com Mon Nov 15 10:56:46 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 15 Nov 2004 13:56:46 -0200 Subject: Authoritative documentation on packages, import & ihooks Message-ID: <864d3709041115075629d15045@mail.gmail.com> I am looking for information on packages & import hooks, including simple examples on how to implement a simple import hook. Quick googling turns out some documents, such as: -- PEP 302: http://www.python.org/peps/pep-0302.html -- What's new on Python 2.3: http://www.python.org/doc/2.3.4/whatsnew/section-pep302.html -- Import SIG: http://www.python.org/sigs/import-sig/ -- PyDoc for the ihooks module: http://pydoc.org/2.3/ihooks.html However, after reading them, I ended up more confused than before. There are lots of references to the ihooks standard module, but there is no documentation about it on the standard Python docs. The "Modules That Needs Docs" Wiki entry (http://www.python.org/moin/ModulesThatNeedDocs) lists ihooks and imputils, but noone has volunteered to do it yet (worse, not even a bug report was filled; this is something that I'm going to do). Packages are also not documented (there is still a reference to an essay from 1.5 days on the Python 2.3 docs). It's a messy state of affairs. For what I could see, the import system went over several iterations and patches since the 1.5 release (when packages were added). It's now hard to understand what is the preferred hooking mechanism as far as Python 2.4 (and future versions) are concerned. For this reason, I would like to know if there is any document which may be considered "authoritative" for the import system (besides ihooks.py and import.c). If *all* that exists is the source code, well, I guess I'll have to read it. But anyway... pointers to simple examples also are helpful. Thanks in advance. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From mwm at mired.org Tue Nov 16 15:58:17 2004 From: mwm at mired.org (Mike Meyer) Date: Tue, 16 Nov 2004 14:58:17 -0600 Subject: Announce: csv_xs.py References: Message-ID: jarrodhroberson at yahoo.com (Y2KYZFR1) writes: > > Can you explain what you liked about Perl's csv_xz package and/or didn't > > like about Python's csv module that motivated you to write your own class? > > > > Thx, > > > > Skip > > I'm a native perl speaker, but at my last work i had to learn python, to > edit some zope thinks (quite difficult). > > Now i wanna learn python for me and i often work with csv files with perl > but now i wanna develop some python programs for csv file working. > In this task i would extend the csv module for my needs but there i get any > errors, so it was easier for me to develop a class which is like the perl > one. > > hope it is ok > Chris If I interpret this correctly as "get many errors", then you're throwing away one of the benefits Python has over Perl. Perl silently does something implicit with errors in your data. Python requires that they be dealt with explicitly. It may be that Perl does the right thing for you. But in many cases, Perl *doesn't* do the right thing. Python lets you decide how to deal with them, and makes that explicit. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ialbert at mailblocks.com Tue Nov 30 10:17:47 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 30 Nov 2004 10:17:47 -0500 Subject: module imports and memory usage In-Reply-To: References: Message-ID: Brad Tilley wrote: > Also, is there a way to load and unload modules as they are needed. I > have some scripts that sleep for extended periods during a while loop > and I need to be as memory friendly as possible. I can post a detailed > script that currently uses ~ 10MB of memory if anyone is interested. I believe that the rule of thumb for Python, C, Java and probably most other portable languages is that freed memory cannot be released back to the operating system. The best you can expect (usually true) is that allocating the same amount later will not increase the memory footprint. So the only way to write memory efficient programs might be to: 1. either not load all the data 2. run the data intensive routines as a separate process that terminates and exists Istvan. From peter at engcorp.com Thu Nov 18 12:18:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Nov 2004 12:18:02 -0500 Subject: PyChecker "self is argument in staticmethod" In-Reply-To: <9e5ea2c4.0411180909.35db39d5@posting.google.com> References: <9e5ea2c4.0411180909.35db39d5@posting.google.com> Message-ID: Olaf Meding wrote: > What does the below PyChecker warning mean? > > More importantly, is there a way to suppress it? > > PyChecker warning: > ..\src\phaseid\integration.py:21: self is argument in staticmethod > > My best guess is that the warning is related to PyChecker not > supporting C++ extensions. Sounds like a pretty wild guess to me. ;-) c:\>c:\a\python23\python.exe c:\a\python23\Lib\site-packages\pychecker\checker.py test.py Processing test... Warnings... test.py:2: self is argument in staticmethod c:\>type test.py class A: def func(self, blah): pass func = staticmethod(func) Does your code look anything like the above? The warning message is very explicit about what is wrong here... a staticmethod should not really have a "self" parameter. -Peter From NOmanlio_perilloSPAM at libero.it Wed Nov 10 17:37:50 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 10 Nov 2004 22:37:50 GMT Subject: ConfigParser References: <35t4p0lou2lmcigaj2ic1fv9b253d5nq6k@4ax.com> Message-ID: On Wed, 10 Nov 2004 21:09:39 +0100, Ivo Woltring wrote: >On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo > wrote: > >>Regards. >> >>Since sections in CongiParser files are delimited by [ and ], why >>there is not an escape (and unescape) function for escaping >>&, [, and ] characters to &, [ and ] ? >> >> >> >> >>Thanks Manlio Perillo > >another discovery: > >the get() DOES translate [ etc back to '[' etc, so it seameth >to me that the whole question is mute ;-)) > What version are you using? In Python 2.3.3 get does not handles [ (or I did not understand what you are saying). Thanks and regards Manlio Perillo From cme at lampcoders.net Wed Nov 10 13:27:26 2004 From: cme at lampcoders.net (Christian Meissner) Date: Wed, 10 Nov 2004 19:27:26 +0100 Subject: Announce: csv_xs.py Message-ID: Hi Folk, i had developed my own csv class which is inspired by perls csv_xs module. All interrested people can find the class on http://www.linux-scene.de/files/python/ Hope it helps, you'll be pleased to extend the class Chris From pdmurray at ntlworld.com Thu Nov 11 16:52:40 2004 From: pdmurray at ntlworld.com (Peter Murray) Date: Thu, 11 Nov 2004 21:52:40 -0000 Subject: Sorting email addresses by domain Message-ID: <20041111215248.LFTO6712.aamta04-winn.mailhost.ntl.com@Bender> I did send a thank you but it doesn't seem to have shown up, so thank you all for your help! The different ways of tackling this problem have really helped. Some of the ideas were similar to the way I tried, but a lot simpler and yes, more elegant. One thing this did show me was how the list.sort() method works. In the O'Reilly Learning Python book there is only one example of actually passing in a function and for me it didn't really explain how it works. But if I understand it correctly now, you give the sort() method a function that will act on two values and return a -1, 0 or 1, and because the function you give it may play around with the items, the actually list that sort() processes stays the same. So you give the sort method a function *object*, is that right? There is no () on the end of the function so it isn't a call. The sort() method calls this function with the list members. I think I have it! Thanks again all. Pete. From steven.bethard at gmail.com Fri Nov 5 11:22:48 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 5 Nov 2004 16:22:48 +0000 (UTC) Subject: deref in a string into an operand References: Message-ID: John Doe yahoo.com> writes: > > So using a builtin object like 'x' ... > > x = 5 > attr = '__mul__' > > print x.__getattribute__( attr )( 5 ) > 25 > > My program will store the operand as '__mul__' instead of '*', along with > a health bit of comment. You also might consider just storing the operator. methods in an appropriate dictionary: >>> import operator >>> operator_map = {'+':operator.add, '-':operator.sub} >>> operator_map['+'](1, 2.0) 3.0 This allows you to call the add function whatever you want. Steve From rkern at ucsd.edu Tue Nov 9 17:33:19 2004 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 09 Nov 2004 14:33:19 -0800 Subject: ANN: IPython 0.6.4 is out. In-Reply-To: References: Message-ID: Fernando Perez wrote: > Thanks! That is indeed my intention, so I'll probably follow your advice. But > will this mean that unsuspecting souls using CVS will get HEAD automatically? > If that's the case, I'll add a nice warning about HEAD becoming _really_ > unstable for a while, so I don't burn anyone. So far HEAD has been the place > for users to get cutting-edge bugfixes, so at least I should warn them that > this may change in the future. You could also leave CVS HEAD as it is and hop on the SVN bandwagon for the new version. Come on! You know you want to! -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From phleum_nospam at chello.se Sun Nov 21 13:38:27 2004 From: phleum_nospam at chello.se (Carl) Date: Sun, 21 Nov 2004 19:38:27 +0100 Subject: How can I interrupt os.system(cmd)? Message-ID: Dear friends, I have written a small Python program that executes "cmd" via os.system(cmd). My problem is that "cmd" runs on forever. More specifically, I want to run "cmd" for one hour on a regular day-to-day basis by using crontab as a scheduler. What options do I have to control execution of external programs from Python? Carl From mwm at mired.org Thu Nov 4 22:13:31 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 04 Nov 2004 21:13:31 -0600 Subject: Summary: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <2uqvd6F2dn4seU1@uni-berlin.de> Message-ID: Steven Bethard writes: > JCM myway.com> writes: >> >> > Definition 1 is the definition most commonly used in Programming >> > Languages literature.... However, for >> > all intents and purposes, it is only applicable to statically typed >> > languages; no one on the list could come up with a dyamically typed >> > language that allowed bit-reinterpretation. >> >> Assembly language. The types of values are implied by what >> instructions you use. > > I'm sure some people would argue that assembly language is untyped (not > statically or dynamically typed) and that the operations are defined on bits, > but this is definitely the best example I've seen. Thanks! The previously mentioned BCPL has the exact same property. For that matter, early versions of C used to allow it to a large degree. I've actually compiled programs written as "char *main = { ... }". To me, a dynamically typed language is one where objects - rather than variables - have a type attached. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ptmcg at austin.rr._bogus_.com Sun Nov 28 02:30:19 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 28 Nov 2004 07:30:19 GMT Subject: UML and OO design tool with Python support Message-ID: I just found out that my favorite UML modeling tool, Enterprise Architect, has just released a new version, *with* Python code support. You can download EA at http://www.sparxsystems.com.au. It is not free, but I think it is very reasonably priced for the features it provides (under $200 gives you good UML graphical modeling, including sequence and class diagrams, with code reverse engineering and round-tripping, vs. $000's for comparable Rational environment). Well, as it turns out, the Python support is still a bit buggy but I have already gotten good mileage from this tool in other applications, most notably reverse engineering C++ and C# code, so the Python additions are icing on the cake. But it is certainly another reassuring note, to see the inclusion of Python support into this commercial software development tool. I've already started to forward bug reports for some of the Python import errors. Perhaps if they get more feedback from other Python users, it will help reinforce their opinion of Pythonistas as a valuable target market segment. -- Paul Note: I am *not* an employee or in any way connected with the supplier of this code, other than as a satistifed customer. Note2: the Python support is not an obvious product feature. It requires installation of a separate (free) add-in, downloaded from the Sparxsystems web site. The add-in must be separately "add-in"ed to each project, too, instead of just being a globally installed plug-in. My first couple of attempts failed at completely reverse engineering my pyparsing module, although I did get a nice first-pass class inheritance diagram for PIL. We take what we can get... From sridharinfinity at gmail.com Sun Nov 21 10:34:55 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 21 Nov 2004 07:34:55 -0800 Subject: Gnome version of Idle? In-Reply-To: <992f396f.0411202018.1edbc6d0@posting.google.com> References: <992f396f.0411202018.1edbc6d0@posting.google.com> Message-ID: <1101051295.435416.307320@c13g2000cwb.googlegroups.com> If you ask me, aliased fonts are better for coding. Gtk+ layer could be added to Idle as an *optional* UI layer, so that idle could be distributed with python without any fear of dependencies (tkinter is enough for platforms like windows, ...) May be you could contribute code to the idle guys :) From deepak.sarda at gmail.com Mon Nov 8 00:23:10 2004 From: deepak.sarda at gmail.com (Deepak Sarda) Date: Mon, 8 Nov 2004 13:23:10 +0800 Subject: checking a thread has started In-Reply-To: <418da3e0$1_4@omega.dimensional.com> References: <418d3323$1_2@omega.dimensional.com> <418da3e0$1_4@omega.dimensional.com> Message-ID: Hi Michael. Thanks for the detailed response.. On 6 Nov 2004 21:26:08 -0700, Michael Fuhr wrote: > You can examine os.environ['GATEWAY_INTERFACE'] to see how your > script is run: the value should be "CGI/1.1" if you're running > via CGI and "Python-CGI/1.1" if you're under mod_python. This > environment variable probably won't be set if you run the script > from the command line, so use has_key() or trap KeyError to avoid > exceptions. > It give 'CGI/1.1' which means no mod_python > What do you mean "runs as a local user"? CGI programs usually run > as whatever user the web server runs as, although it's possible to > have them run as the script's owner (e.g., by setting up suEXEC). > Yes, it's using the suEXEC mechanism. The script is in my home folder so it get's executed as my uid/gid. > > That doesn't make sense given the description of StartServers. > Besides, as I recall, Apache 1.3.27, which you said you were using, > doesn't even use threads -- each instance of the web server is run > in a separate process. Have you tested your hypothesis by altering > the value of StartServers and checking whether your script behaves > differently? I couldn't check this yet as the sys admin is not available. but something related is there in the mail below. > > The program _always_ successfully creates and completes execution of > > exactly seven new threads leaving the remaining eight requested > > threads in no man's land! > > How are you determining which threads are starting and which aren't? Just seeing if the run() is called - with a print. > > > So there must be some relation between apache and the script. Also, as > > I said earlier, when run through a shell as the same user - the script > > works perfectly fine. > > Something's going on but we lack sufficent evidence to say what. > We haven't seen your code yet -- could you post the smallest possible > script that demonstrates the problem? > > The following script always works for threads less than 8. Increase it beyond that and it almost always fails. I say almost always because sometimes it manages to run. But it fails almost 98% of the time (unscientific observation!). The key thing is the os.system() call. Without that, everything works fine. Also - if I start the threads just after creating them - then the success rate become 98% (again - guess). #!/usr/bin/python2.2 import sys, os, threading class Worker(threading.Thread): def __init__(self, index): self._index = index threading.Thread.__init__(self) print "Made object", self._index sys.stdout.flush() def run(self): print "Ran thread with index", self._index sys.stdout.flush() os.system("date") sys.stdout.flush() Worker.count += 1 if __name__ == '__main__': sys.stderr = sys.stdout print "Content-type: text/plain\n" sys.stdout.flush() Worker.count = 0 tlist = [] for i in range(10): t = Worker(i) #t.start() tlist.append(t) for t in tlist: t.start() for t in tlist: t.join() print "Count:", Worker.count I'll experiment with the other suggestions offered and get back soon. -- Online: http://www.antrix.net/journal/ From kartick_vaddadi at yahoo.com Thu Nov 18 23:41:28 2004 From: kartick_vaddadi at yahoo.com (kartik) Date: 18 Nov 2004 20:41:28 -0800 Subject: don't NaN & infinities hide FP errors References: <940ee3e8.0411170130.31d247@posting.google.com> <419bbb08$0$531$a1866201@visi.com> Message-ID: <940ee3e8.0411182041.74321118@posting.google.com> Grant Edwards wrote in message news:<419bbb08$0$531$a1866201 at visi.com>... > On 2004-11-18, Jeremy Bowers wrote: > Let's say you've got a bunch of process control modules. Each > of them takes a set of input values and produces a set of > outputs. > > Now let's say one of the inputs fails (no valid value is > available). You can just shut down the whole refinery, you've > got to try to keep going as best you can. The easiest way to > do that is to feed a NaN in on the invalid input, and let it > propogate through the network of modules. The outputs that > don't depend on the invalid input remain valid. The outputs > that do depend on the invalid input are NaNs. > > At the output end of things you don't have to do all sorts of > logic to figure out which outputs are valid and which ones > aren't -- all you have to do is decide what to do when each > output is a NaN. I understand. But I wasn't saying NaN should be removed, only that arithmetic operations shouldn't produce it; you will still be free to explicitly set a variable to NaN if you don't have valid input. Besides, Python seems to raise exceptions instead of generating NaNs or infinities, at least on my machine (Linux, GCC 3.3.2, Python 2.3.3). Doesn't that support my view? From jeff at ccvcorp.com Fri Nov 19 16:48:20 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 19 Nov 2004 13:48:20 -0800 Subject: Microsoft Patents 'IsNot' In-Reply-To: <3073pnF2rf1v9U1@uni-berlin.de> References: <16798.16559.745209.751967@montanaro.dyndns.org> <3073pnF2rf1v9U1@uni-berlin.de> Message-ID: <10psqa2c5o4vr19@corp.supernews.com> Peter Maas wrote: > Isnot is semantically equivalent to the inequality operator which is > some hundred years old. I doubt that this can be an approved patent, > even under the liberal patent US laws. Maybe it's not a technically *valid* patent, but that doesn't mean it can't be approved. The US patent system has become appallingly lazy about checking for things like prior art and obviousness. (After all, we're talking about the system that approved a patent on "one-click purchasing"....) The sad thing about this is that these patents can be challenged in courts... but only if you can afford the legal budget necessary. And big corporations can afford to defend these patents, regardless of their legal viability, well enough to prevent all but the most determined (and well-heeled) challengers from actually getting a judgement on the actual merits of the case. Jeff Shannon Technician/Programmer Credit International From cjw at sympatico.ca Tue Nov 16 07:19:57 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 16 Nov 2004 07:19:57 -0500 Subject: Social Commentary on Open Source Message-ID: <4199F06D.3060503@sympatico.ca> These papers from a recent Paris workshop on FLOSS might be of interest to some c.l.p folk. http://www.firstmonday.org/issues/issue9_11/index.html Colin W. From onurb at xiludom.gro Tue Nov 2 18:27:07 2004 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 03 Nov 2004 00:27:07 +0100 Subject: general class functions In-Reply-To: <4186f23d$1_3@newspeer2.tds.net> References: <4186f23d$1_3@newspeer2.tds.net> Message-ID: <418815ca$0$9247$636a15ce@news.free.fr> Kent Johnson a ?crit : > syd wrote: > >> In my project, I've got dozens of similar classes with hundreds of >> description variables in each. In my illustrative example below, I >> have a Library class that contains a list of Nation classes. In one >> case, I might want a Library class with only Nations of with the >> continent variable "Europe", and so I'll do something like >> library.getContinent('Europe') which will return a Library() instance >> with only European nations. Similarly, I could also want a Library() >> instance with only 'small' size nations. >> >> My question follows: is there a way I can make a general function for >> getting a subclass with my specific criteria? For instance, can I >> pass in an equivalence test or something like that? I have hundreds >> of variables like "nation", "continent", and so forth, and do want to >> write a separate "get______" function for each. > > > You can use getattr to read the Nation attributes by name. Add this > method to Library: > def getMatches(self,attribute, value): > library=Library() > for nation in self.list: > if getattr(nation, attribute) == value: > library.add(nation) > return library > > Now you can call > print library.getMatches('continent', 'Europe').getNameList() > print library.getMatches('continent', 'Europe').getMatches('size', > 'small').getNameList() You could make it even more simple - and avoid creating useless instances of Library and Nation - with keyword arguments: class Library: [...] def getAll(self, **kwargs): library=Library() for nation in self.list: keep = True for attribute, value in kwargs.items(): if not getattr(nation, attribute) == value: keep = false break if keep : library.add(nation) return library print library.getAll(continent='Europe').getNameList() print library.getAll(continent='Europe', size='small').getNameList() This is and 'and' search, you could also have an 'or' search method: def getAny(self, **kwargs): library=Library() for nation in self.list: for attribute, value in kwargs.items(): if getattr(nation, attribute) == value: library.add(nation) break return library print library.getAny(continent='Europe', size='small').getNameList() and then a more generic search: def getMatches(self, op, **kwargs): fun = {'or': self.getAny, 'and' : self.getAll}.get(op) return fun(**kwargs): print library.getMatches('and', continent='Europe', size='small').getNameList() print library.getMatches('or', continent='Europe', size='small').getNameList() Bruno From austin at maxtronic.com.tw Tue Nov 2 01:13:21 2004 From: austin at maxtronic.com.tw (Austin) Date: Tue, 2 Nov 2004 14:13:21 +0800 Subject: wxPython frame Message-ID: <41872581$1@news.seeder.net> In tkinter, the dialogs has the function grab_set(). That means disable other windows while it's open. Is there any function like that in wxPython. I want to use it on my frame. For example, a.py is main frame. There is a button "config" to open b.py(config frame). If the function exists in wxPython, i could put that in b.py when b.py is open and we couldn't click a.py. Or any other ways to avoid click a.py when b.py is open. Thanks a lot. From bowman at montana.com Sun Nov 21 11:52:05 2004 From: bowman at montana.com (bowman) Date: Sun, 21 Nov 2004 09:52:05 -0700 Subject: Detecting memory leaks References: Message-ID: <30bv7bF2v8js0U1@uni-berlin.de> Jive wrote: > The short form of the question is, how can I trace memory usage > (preferably from C) with an eye toward finding out if I'm leaking memory? Have you looked at efence or dmalloc? I don't know if either could be ported to your RTOS. efence depends on the hardware and both make assumptions on the memory allocation schemes. From Scott.Daniels at Acm.Org Tue Nov 30 14:29:07 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Nov 2004 11:29:07 -0800 Subject: documentation for PyArg_ParseTupleAndKeywords In-Reply-To: <8Q1rd.490968$D%.41813@attbi_s51> References: <8Q1rd.490968$D%.41813@attbi_s51> Message-ID: <41acdc96$1@nntp0.pdx.net> Steven Bethard wrote: > Thanks for the pointers. What's the "doco gadget" you're talking about? I conclude from this question that you are not using a Windows python. I suspect, therefore, the answer is Gilda Ratner's ".... Never mind." --Scott David Daniels Scott.Daniels at Acm.Org From gergina at abv.bg Mon Nov 22 14:52:06 2004 From: gergina at abv.bg (Nickolay) Date: 22 Nov 2004 11:52:06 -0800 Subject: if need small python executable Message-ID: <77969915.0411221152.6f293b6f@posting.google.com> it's easy to create small executable from python code, when using assembler compilers. I ask you if need it? From peter at engcorp.com Thu Nov 11 22:26:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Nov 2004 22:26:13 -0500 Subject: Iterating over PDF documents In-Reply-To: References: Message-ID: Peter Maas wrote: > I'm trying to edit a PDF document line-wise. This is more difficult > than I thought, because PDF uses a mixture of all line terminators It should also be pretty difficult because PDFs are binary, not text... (They might contain a whole lot of stuff that looks like text, but there are binary sections mixed into many of them, and I believe the header at least is binary. The sample files I'm looking at definitely are, in any case. Your solution could not be general.) -Peter From jerry at jerrysievers.com Wed Nov 24 08:30:19 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 24 Nov 2004 08:30:19 -0500 Subject: Transfer data from webpage form to database References: <41a36ab7$0$23056$ba624c82@nntp05.dk.telia.net> <41a38f13$0$23068$ba624c82@nntp05.dk.telia.net> <41a3ccf2$0$29450$ba624c82@nntp06.dk.telia.net> <41a3d863$0$29440$ba624c82@nntp06.dk.telia.net> <41a3de0b$0$29437$ba624c82@nntp06.dk.telia.net> <1101268631.7318.11.camel@flmrroach.okmaybe.com> Message-ID: Mark Roach writes: > On Wed, 2004-11-24 at 02:16 +0100, Pete..... wrote: > > That syntax doesn't look right. I think you were closer with your > previous attempt. This is slightly more correct > > cur.execute('''INSERT INTO persons (name, surname, username, password) > VALUES('%s','%s', '%s', '%s')''' % (form[name].value, > form[surname].value, form[username].value, form[password].value)) > > (Note the single quotes around the %s) > > The real problem with this code is that you are letting the user of your > website inject whatever SQL they want directly into your command. I am > not sure if this works for pypgsql, but with psycopg the safe way to do > this is If you are using pygresql the execute() method allows an optional dict as arg2 and if provided, will be quoted according to data types and the LHS string integrated with the dict as if by the % operator. cur.execute('query') cur.execute('query with hand quoted args %s' % (foo)) cur.execute('query with args quoted by API %(name1)s, %(name2)d',dict) String types will get wrapped in single quotes and have embedded single quotes escaped, the most common use but other types such as datetime will get special treatment as well. I agree with you. Any up to date API should have this capability which can always be overridded in an extreme case. Bye -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From ian at kirbyfooty.com Wed Nov 17 18:36:43 2004 From: ian at kirbyfooty.com (Ian Cook) Date: 17 Nov 2004 15:36:43 -0800 Subject: ZipFile - How to update an existing zip file Message-ID: <8cf64c3d.0411171536.76f16538@posting.google.com> Hi, I'm new to python so please excuse me if this is a 'dumb' question. I want to use the ZipFile module to UPDATE, rather than append, or create a new zip file. Does anyone know how this can be done? This is a snippet of the code I have now.. try: zf = zipfile.ZipFile(zfname,mode='a') except: zf = zipfile.ZipFile(zfname,mode='w') for name in cutflist: fp = os.path.join(root,name) print "adding ",fp,"...", compresstype = zipfile.ZIP_DEFLATED if zipfile.is_zipfile(fp): compresstype = zipfile.ZIP_STORED zf.write(fp,compress_type=compresstype) print 'done.' Thanks in advance. Ian Cook (Freeware author of Kirby Alarm And Task Scheduler) http://www.kirbyfooty.com/ From davecook at nowhere.net Mon Nov 22 14:53:17 2004 From: davecook at nowhere.net (Dave Cook) Date: Mon, 22 Nov 2004 19:53:17 GMT Subject: Help for newbie References: <419f06a8$0$32335$636a15ce@news.free.fr> <41a10093$0$4569$626a14ce@news.free.fr> Message-ID: On 2004-11-21, Leuk wrote: > Thanks very much for your information > But I would like to know how I'll write and retreive my objets when my > system will be written in Java. At what time or how I'll switch to Python. Are you planning on using Jython? http://www.jython.org In that case, you might want to find a Java solution that you can use with Jython. I've used hibernate + hsql from Jython, but that may be overkill for your application. Dave Cook From uche at ogbuji.net Tue Nov 23 09:34:23 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 23 Nov 2004 06:34:23 -0800 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: Peter Hansen wrote in message news:... > Roy Smith wrote: > > Computer Science is not an experimental science. > > Again, you've said nothing that in any way justifies this statement. > > I'm not saying CS _is_ an experimental science, but I think > I would say that your implied statement that one should *never* > do this is fundamentally flawed. > > Ultimately, however, this is a silly argument, because neither > you nor I write code solely in the manner I described, nor > in the manner you appear to be recommending (i.e. going exclusively > based on the documentation), so I'm not even sure why you > wrote... Personally, I shared Mr. Smith's reaction to your posting. I've seen a lot of claims of the magical fairy dust of test-first programming (an idea whose basic soundness I agree with), but the idea that such prophetic pre-testing is a sounder way of learning an API properly than reading the documentation tops them all. I believe now your claims that you didn't mean anything so radical, but you can hardly blame Mr. Smith from reading what you wrote, originally and coming to the natural conclusion from comprehension of your prose. The reason why he wrote is to make it clear to anyone else who respects you as an intelligent commentator on Python programming (this was a thread started by a noob question, after all) that in reality that reading the documentation should generally be the first step in comprehending code. I think he achieved this aim by pointing out that the very example you trumpeted proved the overriding value of documentation. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com A hands-on introduction to ISO Schematron - http://www-106.ibm.com/developerworks/edu/x-dw-xschematron-i.html Schematron abstract patterns - http://www.ibm.com/developerworks/xml/library/x-stron.html Wrestling HTML (using Python) - http://www.xml.com/pub/a/2004/09/08/pyxml.html XML's growing pains - http://www.adtmag.com/article.asp?id=10196 XMLOpen and more XML Hacks - http://www.ibm.com/developerworks/xml/library/x-think27.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ From sam at three60.com Wed Nov 3 08:12:34 2004 From: sam at three60.com (Sam) Date: 3 Nov 2004 05:12:34 -0800 Subject: Should I learn Python? References: <624a388a.0411021328.5ac41f4c@posting.google.com> <418807d0$0$19691$626a14ce@news.free.fr> Message-ID: <624a388a.0411030512.3cf84547@posting.google.com> So you're saying, in order to write smart, clean, well structured, readable code, and have fun doing so, I'm going to have to drop PHP and use Python? I'm not really interested in finding a replacement for PHP, it works just fine for me. I apologize for not phrasing my questions clearly, I wasn't looking for critisisms of PHP or why I shouldn't use it. What i'm really after, is given that I use PHP to develop sites currently, what types of situations would/could i use Python in web development? Is there a point when learning Python, that I'll say to myself "why use php?". Thanks From agriff at tin.it Mon Nov 1 03:52:28 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 01 Nov 2004 08:52:28 GMT Subject: "number-in-base" ``oneliner'' References: <1gmfz0k.a3xefz1xzms61N%aleaxit@yahoo.com> Message-ID: On Mon, 01 Nov 2004 07:21:09 GMT, Andrea Griffini wrote: >This is a bit shorter ... > >roman = lambda x: "".join(["".join(map(lambda c: "IVXLCDM"[ord(c) - >ord("A")+2*N], "/A/AA/AAA/AB/B/BA/BAA/BAAA/AC".split("/")[x//10**N % >10])) for N in (3, 2, 1, 0)]) No idea why I initially thougt about using ASCII codes... this is simpler and shorter... roman = lambda x: "".join(["".join(map(lambda c: "IVXLCDM"[int(c) +2*N],"/0/00/000/01/1/10/100/1000/02".split("/")[x//10**N % 10])) for N in (3, 2, 1, 0)]) Andrea From peter at engcorp.com Wed Nov 3 13:50:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Nov 2004 13:50:20 -0500 Subject: threads and exception in wxPython In-Reply-To: References: <6_qdnQZOZ_YYZRXcRVn-sw@powergate.ca> Message-ID: Nick Craig-Wood wrote: > Peter Hansen wrote: > >> >>> t = T() >> >>> t >> >> >>> asyncexc = ctypes.pythonapi.PyThreadState_SetAsyncExc >> >>> exc = ctypes.py_object(ValueError) >> >>> asyncexc(t.id, exc) >> 1 >> >>> thread terminated! >> >> >>> t >> > > > On a related subject, I'm trying to forcibly terminate a thread thats > already running. I don't see any means of doing this in the docs. > Sending it an exception would be ideal. Is the above the only way of > doing this? This isn't just a related subject, this is exactly what I was trying to do above. I have a test case here which is failing, however, because the exception is *not* being delivered asynchronously for some reason, but appears in the thread only when the thread is already terminating itself. I'm still experimenting, but I will probably post the failing test case shortly for others to play with. Nick, if you want to learn more, read the threads from this google search: http://groups.google.ca/groups?q=PyThreadState_SetAsyncExc Then you'll know as much as anyone about this... -Peter From tjreedy at udel.edu Tue Nov 9 13:56:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Nov 2004 13:56:05 -0500 Subject: should i start looking for a new list? References: <20041109101248.F1B661C001B2@mwinf0101.wanadoo.fr> Message-ID: "Jelle Feringa // EZCT / Paris" wrote in message news:20041109101248.F1B661C001B2 at mwinf0101.wanadoo.fr... I've been posting some of my most burning (newbie) questions to this list, and most of them have been unanswered. Should I be posting these questions at a different list, since their technical level is quite low? Am I looking for answers in the right place? ------------------ Some suggestions: 1) there is a tutor list available via www.python.org. 2) make sure your subject lines are as informative or intriguing as this one. I tend to skip over subject line that start with 'Newbie ...'. 3) post plain ascii text without markup rather than rtf/html 4) use spaces rather than tabs when you post code Here is what the code quoted by Stroud looks like in Outlook Express. > i = 0 > for x in hour: > skyName = skiesok[i] > print skyName > number = str(skyName[3:-4]) > oconv, oo, oe = win32pipe.popen3('oconv -i no_sky.oct'\ > +' sky'+number+'.sky'+' > '+'tmpOct'+number+'.oct') If you did not give continuation lines an extra indentation in your original (not required by the syntax rules, but often helpful for reading), consider doing so. Terry J. Reedy From Scott.Daniels at Acm.Org Thu Nov 18 13:43:17 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Nov 2004 10:43:17 -0800 Subject: PIL for Python 2.4? In-Reply-To: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> References: <6r6pp018glonqu2kqeau5ru9nhfj9fpchv@4ax.com> Message-ID: <419d002e$1@nntp0.pdx.net> Christos TZOTZIOY Georgiou wrote: > Has anyone built PIL (1.1.4 or 1.1.5) for Python 2.4? If yes, please > let me know, since I can't test a couple of my apps using PIL with 2.4 . > You can even reply by email (yes, I dare use true email in newsgroup > postings, but then, I'm postmaster and welcome spam :) > > TIA [... windows ... replies from others on using the MS VC 7.1 ...] Note that if you install MinGW, distutils can build acceptable files with it. Since I believe I remember the PIL stuff is set up to build with distutils, you should be able to get it going that way as well. --Scott David Daniels Scott.Daniels at Acm.Org From NOmanlio_perilloSPAM at libero.it Wed Nov 10 17:32:42 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 10 Nov 2004 22:32:42 GMT Subject: ConfigParser References: <2rs4p01b9uugvd6huie5g3oebbe8n2ueo3@4ax.com> Message-ID: <2q55p0t4g6rbhog25bm3hed2evqto7e26s@4ax.com> On Wed, 10 Nov 2004 21:04:55 +0100, Ivo Woltring wrote: >On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo > wrote: > >>Regards. >> >>Since sections in CongiParser files are delimited by [ and ], why >>there is not an escape (and unescape) function for escaping >>&, [, and ] characters to &, [ and ] ? >> >> >> >> >>Thanks Manlio Perillo > >By the way I did some testing because i have a similar thing going on >right now. I found out that > >[section] >option = [Ivo Woltring] > >is valid and does not have to be translated to >[section] >option = [Ivo Woltring] > Yes, I have discovered this too. But my problem is with section names. Thanks and regards Manlio Perillo From jbperez808 at wahoo.com Mon Nov 1 07:32:32 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Mon, 01 Nov 2004 20:32:32 +0800 Subject: What is Python's answer to Perl 6? In-Reply-To: References: <2uh4j7F2a86uqU1@uni-berlin.de> Message-ID: <2umo5dF2cmvkqU1@uni-berlin.de> A.M. Kuchling wrote: >>Is Python taking a similar step (-> Python 3) some time in the near future? > > > The list of features for Python 3000 is described in PEP 3000, > appropriately enough: > > http://www.python.org/peps/pep-3000.html > > Most of the suggested changes remove redundancy, such as removing > now-unneeded built-in functions and language features. Which I heartily concur with as being what should be one of the primary goals... TIMTOWTDI and ad hoc feature development are exactly what makes Perl source code so unwieldy and inelegant. From peter at designtheory.org Mon Nov 22 13:59:55 2004 From: peter at designtheory.org (Peter Dobcsanyi) Date: 22 Nov 2004 18:59:55 GMT Subject: ANN: pydesign 0.5 Message-ID: PYDESIGN version 0.5 has been released. It is available from: http://designtheory.org/software/pydesign/ What is it? ----------- PYDESIGN is a collection of Python modules and applications to provide a computational framework for working with combinatorial and statistical designs. For more details, see the online documentation and the release notes at the above URL. -- , Peter Dobcsanyi From danu_milis at yahoo.com Wed Nov 3 18:46:16 2004 From: danu_milis at yahoo.com (danu kusmana) Date: Wed, 3 Nov 2004 15:46:16 -0800 (PST) Subject: Python for PDAs/Mobile phones? In-Reply-To: Message-ID: <20041103234616.22411.qmail@web60605.mail.yahoo.com> check out these sites: http://www.mobilewhack.com/programming/python/python_on_nokia_screenshots.html http://www.monkeyhouse.eclipse.co.uk/mobile/python.htm danu --- Andre Meyer wrote: > Hi Pythoneers > > Some time ago there was an annoucement* of Python > being implemented for > Nokia phones. Is that project still alive? > > What are the options for running Python on mobile > phones or PDAs? > > Thanks for your help > Andre > > > * http://www.mobileburn.com/news.jsp?Id=732 > > http://www.theregister.co.uk/2004/01/21/nokia_prefers_python_to_perl/ > > http://arki.uiah.fi/Documents/2004_06_11_pyth-20040521T215043 > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From atterdan at yahoo.com Fri Nov 5 05:13:03 2004 From: atterdan at yahoo.com (John Doe) Date: Fri, 05 Nov 2004 10:13:03 GMT Subject: deref in a string into an operand References: Message-ID: Foolish me; I examined the __builtin__ and found __getattribute__, along with '__mul__' '__add__', '__sub__' and '__div__'. So using a builtin object like 'x' ... x = 5 attr = '__mul__' print x.__getattribute__( attr )( 5 ) 25 My program will store the operand as '__mul__' instead of '*', along with a health bit of comment. Dan. Closed. On Fri, 05 Nov 2004 08:01:59 +0000, John Doe wrote: > I've got the action '+' stored as the variable 'plus', > that is plus='+' > > Now I want to use the variable plus in an equation: > 5 plus 7, just line 5 + 7 > > How do I do that? > > Dan From loic.mahe at free.fr Fri Nov 19 11:19:54 2004 From: loic.mahe at free.fr (Lo?c Mah?) Date: 19 Nov 2004 08:19:54 -0800 Subject: wxPython: how to update a panel content/layout according to a variable content Message-ID: <27a5ac50.0411190819.3ad36f15@posting.google.com> Hello I have a problem to update the content of a wx.Panel already displayed after changing a variable, used to define the wx.Panel content. I have the following elements in my code: DataList: is a list containing some data CustomPanel: is a derived class of wx.Panel, it contains one sizer which contains a smaller panel for each element of the DataList list After having displayed CustomPanel on the screen, the elements in DataList change (after a user action like clicking on button) I would like to refresh the CustomPanel to take into account the changes of the DataList list Is there a kind of Refresh/Update function which could update the CustomPanel so that evry sizers and panles contained by this CustomPanel are redrawn according to the current value of DataList ? or do you have to write your own update/refresh method for Panel and Windows objects ? and are you obliged to detroy the CustomPanel object and re-create a new one? I would appreciate any hint/reference to do this, and also a code sample if possible. Thanks. Lo?c From jcarlson at uci.edu Wed Nov 17 13:29:47 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 17 Nov 2004 10:29:47 -0800 Subject: eval syntax problem In-Reply-To: References: <86pt2c3lgx.fsf@mut.mteege.de> Message-ID: <20041117102513.F995.JCARLSON@uci.edu> Erik Max Francis wrote: > > Matthias Teege wrote: > > > what is wrong with > > > > eval('print %s %s %s' % ('%s', '%', 'foo')) > > print is a statement, not an expression, and eval only handles > expressions. Use exec instead. What the hell are you talking about? Don't use either eval or exec, both are remote holes waiting to happen. Furthermore... >>> print %s % foo File "", line 1 print %s % foo ^ SyntaxError: invalid syntax > > fmt='%.2f' > > a=1 > > b="fmt %" % a That is also incorrect syntax. Seemingly you want to be doing the equivalent of... b = '%.2f'%a Which will just create a string representation of a float to 2 decimal places of precision. If you want to do rounding on the object, use round... b = round(a, 2) - Josiah From jonathon.blake at gmail.com Tue Nov 2 17:54:24 2004 From: jonathon.blake at gmail.com (Jonathon Blake) Date: Tue, 2 Nov 2004 14:54:24 -0800 Subject: Python needs a CPyAN In-Reply-To: References: Message-ID: Stephen wrote: > Python's lack of a CPAN-like facility, CPAN is useful, _if_ you know the name of the file you want. When you don't know the name of the file, it isn't that useful. I'll grant that something like CPAN would mean that Anaconda, PyAstro and the like wouldn't disappear from the Python World. xan jonathon From news-and-lists at the-me.de Fri Nov 12 05:28:33 2004 From: news-and-lists at the-me.de (Axel Bock) Date: Fri, 12 Nov 2004 11:28:33 +0100 Subject: re.compile.match() results in unicode strings - why? In-Reply-To: <419388f2$2_2@newspeer2.tds.net> References: <2vh2mlF2lbkrdU1@uni-berlin.de> <419388f2$2_2@newspeer2.tds.net> Message-ID: <2vjhjcF2kgeidU1@uni-berlin.de> Kent Johnson wrote: > Apparently if the input strings are unicode then the groups will be as > well: > [...] > Are you sure that exp is not a unicode string? hm. pretty much - i read the lines from a text file which contains only normal text. a sample line looks like that: 6. call_noparam 1000 runs 149453,1 ms 149,4531 ms/call no surprise here, i think ... . Actually I also wrote the program which produces that file, and I really didn't use unicode then. opening the file with a text editor also does not show unicode, and I can't believe that windows does actually manage the unicode stuff transparently to text editors. and also I have never heard of file-attached codepage information, those would be the only things i could imagine as a reason. but interesting though, thanks! ciao, axel. From peter at engcorp.com Sun Nov 7 22:46:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Nov 2004 22:46:20 -0500 Subject: Python OS In-Reply-To: References: Message-ID: Jeremy Jones wrote: > Peter Hansen wrote: >> You _cannot_ use Python for a time-critical interrupt, even >> when you allow for pure C or assembly code as the bridge >> (since Python _cannot_ be used natively for interrupts, of >> course), because -- as noted above! -- the interrupt must >> execute in a few hundred CPU cycles. > > I'm really not trying to contradict nor stir things up. But the OP > wanted to know if it were possible to prototype an OS and in a > follow-up, referred to a virtual OS. Maybe I mis-read the OP, but it > seems that he is not concerned with creating a _real_ OS (one that talks > directly to the machine), it seems that he is concerned with building > all the components that make up an OS for the purpose of....well.....he > didn't really state that.....or maybe I missed it. Richard's post, to which I was replying, didn't include the proper attributions for his quoted material, so I don't at this point know who actually wrote what. There was someone who said you could do interrupts in Python (the argument being that this was so "because you can do them in C", which is non-sensical given that they are different languages with different capabilities), and then someone else wrote about "time-critical code" of "a few hundred CPU cycles", and then Richard's reply in effect justified the original argument again (at least, that was my interpretation. I don't know if he meant to do that. I suspect not, given his rebuttal.) Note that I have *no idea* who the OP was in this thread, nor what questions he asked or what claims he was making. Sorry, I didn't read it in that detail. I just saw the message to which I replied, with the unattributed stuff just as I quoted it, and reacted purely to it. Probably a bad idea, but I stand by what I said. If, as you suggest, the OP just wants a prototype, then I say wonderful, use Python. Just don't waste time writing real interrupts in Python, and certainly don't try to make the prototype work in an environment where 100 CPU cycles is important... > So, asking in total ignorance, and deferring to someone with obviously > more experience that I have (like you, Peter), would it be possible to > create an OS-like application that runs in a Python interpreter that > does OS-like things (i.e. scheduler, interrupt handling, etc.) and talks > to a hardware-like interface? If we're talking about a virtual OS, > (again, I'm asking in ignorance) would anything really be totally time > critical? Especially if the point were learning how an OS works? Sure, everything you describe would be straightforward and work wonderfully with Python. > I totally agree with you...sort of. I totally agree with your technical > assessment. However, I'm reading the OP a different way. I didn't read the OP, just Richard. Unless he was the OP, in which case I'm confused about various comments that have been made, but not concerned enough to go back and try to figure the whole thing out. *Your* comments appear right on the mark, as far as I can see. ;-) >> Of course, if you will allow both assembly/C code here and >> there as a bridge, *and* you are willing to accept an operating >> system that is arbitrarily slower at certain time-critical >> operations (such as responding to mouse activities) than we >> are used to now, then certainly Python can be used for such things... >> > OK - so here's my answer. It should be possible, but it will be slower, > which seems to be acceptable for what he meant when mentioning > prototyping and a virtual OS. But here's another question. Would it be > possible, if I've interpreted him correctly, to write the whole thing in > Python without directly calling C code or assembly? Nope. Python has no ability to interface to something that is defined only at the assembly level (interrupt routines) without using assembly. (I don't even mention C here, as it requires special non-standard C extensions to support these things, in effect doing a quick escape to assembly.) I'll add an additional note: there's a qualitative difference between being fast enough to respond to hardware interrupts at the 100-CPU cycle sort of level of performance, and at a speed 100 times slower. It's not a matter of just having a slower overall system, which might be fine for a prototype or a simulation. In fact *it simply won't work*. That's because if hardware interrupts aren't answered fast enough, in most non-trivial cases _information will be lost_, and that means the system is broken. That's the definition of a "hard realtime system", by the way, and an unfortunate reason that Python in its current form (i.e. assuming its bytecode interpreted rather than compiled to some kind of native code) cannot ever be used at the lowest levels of an OS. The argument should really be about *how little* assembly and/or C you can get away with, and perhaps here is where Mel Wilson should step in with some of his thoughts on the matter, as I've heard him discuss some ideas in this area. ;-) -Peter From Michael.J.Fromberger at Clothing.Dartmouth.EDU Thu Nov 11 17:04:21 2004 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Thu, 11 Nov 2004 17:04:21 -0500 Subject: Identifying bundles in MacOS X Message-ID: Greetings, The following question pertains to a problem I am solving in Python 2.4b2 on a MacOS 10 (Panther) system with an HFS+ filesystem. Given the pathname of a directory in my filesystem, I would like a graceful way to determine whether or not that directory represents a "bundle", in the sense that, when you double-click on the directory's icon in the Finder, it is launched rather than "opened" for viewing. Applications behave this way by default, but so do various other file types (e.g., the "rtfd" files created by TextEdit, and the data files for certain applications such as Quicken). So, what I want is the following: A function I can call which will, given a pathname, return True if the corresponding directory has that property, and False otherwise. So far, I'm stumped. Can anyone help? Here are the things I've tried so far: I found the Carbon.File module, and tried what I thought was the obvious thing: from Carbon import File fss = File.FSSpec(dir_path) info = fss.FSpGetFInfo() This, unfortunately, does not seem to work for directories; an OSError is raised (-43, File Not Found). I investigated on Apple's developer site, and it seems this is the expected behaviour. So, no fault of Python there. Next, I tried the following: from Carbon import Files fsr = File.FSRef(dir_path) cat_info = fsr.FSGetCatalogInfo(Files.kFSCatInfoFinderInfo) This works, but now I have no idea how to determine the answer to my question. The value of cat_info is a tuple consisting of: - a File.FSCatalogInfo object - a Unicode string (the name of the directory) - a File.FSSpec object - a File.FSRef object According to [1], the FSCatalogInfo structure has finderInfo and extFinderInfo fields, which ought to contain what I'm after (I think), but these do not appear to be exposed by the FSCatalogInfo class in the Carbon.File library, even if I specify I want the Finder info and extended Finder info when I call FSGetCatalogInfo(). All right, so now my questions for those of you who know better than I do, are these: 1. Am I looking in the right place for this information? 2. If not, is there a preferred method for determining whether a given directory represents a "bundle" in the MacOS sense? I would be most grateful for any helpful advice you might be able to lend me regarding this puzzle. Thanks, -M P.S.- I was disconcerted to discover that the Python documentation does not seem to list the Carbon.File module. The macfs module is listed, but it is deprecated, so I would prefer not to use it in new code. References: [1] Carbon API documentation, "FSCatalogInfo" http://shorl.com/biginegastuni -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From peter at engcorp.com Thu Nov 25 16:37:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 25 Nov 2004 16:37:27 -0500 Subject: dictionary initialization In-Reply-To: References: Message-ID: Weiguang Shi wrote: > In article , Dan Perl wrote: >>That would not be justified in python. The type of b[1] is >>undetermined until initialization and I don't see why it should be >>an int by default. > > In my example, it was b[1]+=1. "+=1" should at least tell Python two > things: this is an add operation and one of the operands is an > integer. Why would it tell Python that? >>> b = {1: 2.5} >>> b[1] += 1 >>> b {1: 3.5} So at this point, it can clearly be either an integer or a float. Doubtless it could also be an object which overloads the += operator with integer arguments, though what it might actually do is anyone's guess. -Peter From ianb at colorstudy.com Fri Nov 5 12:05:07 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 05 Nov 2004 11:05:07 -0600 Subject: why python is slower than java? In-Reply-To: <418b166f$1@news.unimelb.edu.au> References: <418b166f$1@news.unimelb.edu.au> Message-ID: <418BB2C3.1000108@colorstudy.com> Maurice LING wrote: > This may be a dumb thing to ask, but besides the penalty for dynamic > typing, is there any other real reasons that Python is slower than Java? Python is generally late-bound, which means much more happens at runtime compared to Java. For instance, consider accessing an attribute, "self.x". In Java you know what the class is shaped like, exactly. Usually this turns into some bytecode like "access the variable of self, at offset 3". I don't know any of the details, but that's the general gist. Similarly, there's many other optimizations where you can know at compile time exactly what functions are called, how variables are stored, etc. Using that information, you can do optimizations like inline code. In the same places in Python, you are typically doing one (or several!) hashtable lookups based on the variable or attribute name. But even in Java there are limits. Because of interfaces and subclasses you can know the shape of self/this, but you can't know the exact shape of the objects around you (C++ is more aggressive in this respect, and often can determine the exact shape; but in the process it's dangerous to put together different pieces of compiled code when they don't know about each other, which is why binary interfaces there are fragile). Anyway, Java does a lot of the same stuff as Python when the exact type is determined at runtime (which is frequently). This is where JIT comes in, doing the optimizations at runtime; it is still limited, as it cannot guarantee the type of the objects in the system, but must check them each time before using the optimized path. And, actually, Python can do the same sort of things with psyco. It's still harder in Python, and the end result not as effective, but it's one among many tools. If Java wasn't doing any optimizations, I don't think it would be significantly faster than Python. Also note that Python assimilates external (C, Fortan, etc) libraries much better than Java seems to. In an entire system, Python can easily be faster because Java includes many slow libraries (slow compared to equivalent libraries available in Python). E.g., Swing is much slower than wxPython. Anyway, that's my take. I'm no authority, as I've never seriously used Java, and haven't done any tests, nor spent anytime looking at the bytecodes, etc. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From danb_83 at yahoo.com Sat Nov 20 08:32:54 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Nov 2004 05:32:54 -0800 Subject: don't NaN & infinities hide FP errors References: <940ee3e8.0411170130.31d247@posting.google.com> <419bbb08$0$531$a1866201@visi.com> <940ee3e8.0411182041.74321118@posting.google.com> Message-ID: kartick_vaddadi at yahoo.com (kartik) wrote in message news:<940ee3e8.0411182041.74321118 at posting.google.com>... > Grant Edwards wrote in message news:<419bbb08$0$531$a1866201 at visi.com>... > > On 2004-11-18, Jeremy Bowers wrote: > > Let's say you've got a bunch of process control modules. Each > > of them takes a set of input values and produces a set of > > outputs. > > > > Now let's say one of the inputs fails (no valid value is > > available). You can just shut down the whole refinery, you've > > got to try to keep going as best you can. The easiest way to > > do that is to feed a NaN in on the invalid input, and let it > > propogate through the network of modules. The outputs that > > don't depend on the invalid input remain valid. The outputs > > that do depend on the invalid input are NaNs. > > > > At the output end of things you don't have to do all sorts of > > logic to figure out which outputs are valid and which ones > > aren't -- all you have to do is decide what to do when each > > output is a NaN. > > I understand. But I wasn't saying NaN should be removed, only that > arithmetic operations shouldn't produce it; you will still be free to > explicitly set a variable to NaN if you don't have valid input. > > Besides, Python seems to raise exceptions instead of generating NaNs > or infinities, at least on my machine (Linux, GCC 3.3.2, Python > 2.3.3). Doesn't that support my view? Python's inconsistent about OverflowErrors: Python 2.3.4 (#2, Nov 13 2004, 18:58:41) [GCC 3.3.5 (Debian 1:3.3.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1e1000 inf >>> 10. ** 1000 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') Python 2.1.1 (#1, Aug 25 2001, 04:19:08) [GCC 3.0.1] on sunos5 Type "copyright", "credits" or "license" for more information. >>> 1e1000 Infinity >>> 10. ** 1000 Infinity From ialbert at mailblocks.com Sun Nov 21 10:14:32 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Sun, 21 Nov 2004 10:14:32 -0500 Subject: Small Database Needed In-Reply-To: References: Message-ID: Kevin McBrearty wrote: > I'm looking at implementing DB in my program for > analysis of CAD (STL Files). This database will > require the basic functionality. PySQLite to the rescue: http://pysqlite.sourceforge.net/manual.html Istvan. From tim.golden at viacom-outdoor.co.uk Tue Nov 2 03:46:20 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 2 Nov 2004 08:46:20 -0000 Subject: problem querying WMI in a background thread Message-ID: [dr_burrito at yahoo.com] | I'm using Tim Golden's WMI implementation | (http://tgolden.sc.sabren.com/python/wmi.html) version 0.6 along with | pywin32 build 202. I'm able to successfully query WMI in the main | thread but not in a separate thread. | | Here's a little snippet of sample code that fails for me: [... snip example ...] Well, I'm going to be mildly unhelpful, and say that I don't strictly understand why your code doesn't work. The thing which usually bites when using WMI and threads is the CoInitialize trap, but it usually comes out as an explicit "Must call CoInitialize" exception rather than as a random COM error. At the end of the day, the plumbing in WMI is just COM/DCOM so most things comes down to issues of COM and threading. But, to me more helpful, the example below does work, so maybe you can work backwards from it. import pythoncom import wmi import threading class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () c = wmi.WMI () while 1: for process in c.Win32_Process (): print process.ProcessId, process.Name if __name__ == '__main__': print 'In Main Thread' c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name Info ().start () TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From steven.bethard at gmail.com Mon Nov 22 02:27:36 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 Nov 2004 07:27:36 GMT Subject: generic object implementation In-Reply-To: <41a17599.693692997@news.oz.net> References: <8W9od.373195$wV.310530@attbi_s54> <41a17599.693692997@news.oz.net> Message-ID: Bengt Richter wrote: > > UIAM 'bunch' already has a related meaning from c.l.py past (approx the first > three lines of your class), so how about 'gob' ? ;-) Yeah, the intent is basically to provide that 3-liner. Could be that's all that should be in the class... It wouldn't cover all my use cases, but I'd certainly be happier with that than nothing. > I dunno, begins to look more like a dict with getattr access substituted for __getitem__ > than a primitive generic object... Yeah, the idea is to provide getattr access instead of __getitem__ -- that's basically what the original 3-liner does too. For my uses, I don't think I'd ever want any of __len__, __iter__, __contains__, items, keys, values, etc. but I wasn't the only one who seemed interested in the idea... The pyparsing code in particular might benefit from something like the frommapping method (and I know I could use it to convert XML DOM into nested objects)... > >>> class dbunch(dict): > ... def __metaclass__(name, bases, cdict): > ... cdict.update(dict.__dict__) > ... cdict['__getattr__'] = cdict['__getitem__'] > ... cdict['__setattr__'] = cdict['__setitem__'] > ... cdict['__delattr__'] = cdict['__delitem__'] > ... def raiseunsub(*ignore): raise TypeError, 'unsubscriptable object' > ... cdict['__getitem__'] = raiseunsub > ... cdict['__setitem__'] = raiseunsub > ... cdict['__delitem__'] = raiseunsub > ... return type(name, bases, cdict) > ... Interesting approach here. I hadn't thought of going this way. While I hadn't planned on supporting the whole mapping interface, this would certainly be an easy way to do so. I'll probably wait for a little more feedback to see what the others who were interested want to use these for... If people have good use cases for keys, items, etc. this is probably the right answer... > It the hope for a lean representation for small numbers > of items? Not exactly sure what you mean by lean... All the use cases I have for it only care about 'obj.x' type access, and don't really use any of the other container type methods. So in my case, __init__, __eq__, __repr__, update and frommapping do pretty much everything I want... If this is true for everyone else's use cases, I'd rather not "pollute" the class with a bunch of dict methods... But I'm certainly willing to be persuaded that other methods are also essential. Steve From tjreedy at udel.edu Tue Nov 9 21:20:20 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Nov 2004 21:20:20 -0500 Subject: Problems with user input References: Message-ID: "Florian Wilhelm" wrote in message news:pan.2004.11.09.22.54.37.120023 at web.de... > I want to read exactly one char from stdin, there should > be no need to hit enter. Your problem is that terminal input, as seen from C, is usually, by default, in buffered line mode. This allows the user to edit entries, at least by back-spacing, before hitting enter. How to switch to character mode or grab the raw keyboard input is OS specific. > Input: (y/N) y > Your input: y > > Why does the whitespace char appear in front of "Your input..."? Because the print statement puts spaces between items so you don't have to. If the convenience of print does not do what you want, take control by using sys.stdout.write(), which writes *exactly* what you tell it to. Terry J. Reedy From james at frontlogic.com Wed Nov 10 16:43:31 2004 From: james at frontlogic.com (James Sapara) Date: Wed, 10 Nov 2004 21:43:31 GMT Subject: Python for Reverse Engineering In-Reply-To: <41927B47.6000904@gmail.com> References: <418c50ad$1_3@omega.dimensional.com> <418C54E9.2000409@vt.edu> <41927B47.6000904@gmail.com> Message-ID: <41928B82.5040804@frontlogic.com> Here's some statistical data from the set of keys I posted. I didn't do any pattern matching, but I think this shows that the keys are fairly random in composition. I have also included stats for a much larger set of keys. I noticed in the set of 100 that I didn't get any keys in the fourth deviation, so I wanted to make sure such keys do exist. If you can think of any other stats from the ord values of character I could do that as well. Since I know the algo I also know that the sets of 5 are only for readability. Pattern matching based on Number/Alpha would probably show that over a large set of keys it matchs the ratio of numbers to alpha's used in the keys. You could do binary comparisons of the N,A's and try to find common patterns. Min/Max ord values ('0', 48) ('Z', 90) Min Sum/Max Sum/Average Sum 1200 2250 1725 Average value of byte 69 Number of Keys 100 Average sum of keys 1745 Range of Key Sums 1564 to 1894 STD range -3 to 3 Squard Root of Key Sums 79.1896457878 Min/Max ord values ('0', 48) ('Z', 90) Min Sum/Max Sum/Average Sum 1200 2250 1725 Average value of byte 69 Number of Keys 10000 Average sum of keys 1753 Range of Key Sums 1460 to 1977 STD range -4 to 4 Squard Root of Key Sums 75.0266619276 James ****** wrote: > I'm not a cryptanalysis guy, is there any value in doing this to the > strings, uploading this data to a DB and then searching for patterns: > > ;5V6XBTV6N65H7J3WWTWQ6H74B;5V6XB;TV6N6;5H7J3;WWTWQ;6H74B;NANAAAANANNANANAAAAANANNA;NANAA;AANAN;NANAN;AAAAA;NANNA;[53, > 86, 54, 88, 66, 84, 86, 54, 78, 54, 53, 72, 55, 74, 51, 87, 87, 84, > 87, 81, 54, 72, 55, 52, 66];[53, 86, 54, 88, 66];[84, 86, 54, 78, > 54];[53, 72, 55, 74, 51];[87, 87, 84, 87, 81];[54, 72, 55, 52, > 66];1733;347;356;305;426;299 > ;CBPPCLTJ5X1S8ZS5LVBZYRFVW;CBPPC;LTJ5X;1S8ZS;5LVBZ;YRFVW;AAAAAAAANANANAANAAAAAAAAA;AAAAA;AAANA;NANAA;NAAAA;AAAAA;[67, > 66, 80, 80, 67, 76, 84, 74, 53, 88, 49, 83, 56, 90, 83, 53, 76, 86, > 66, 90, 89, 82, 70, 86, 87];[67, 66, 80, 80, 67];[76, 84, 74, 53, > 88];[49, 83, 56, 90, 83];[53, 76, 86, 66, 90];[89, 82, 70, 86, > 87];1881;360;375;361;371;414 > ;QJCT6VXYLT2S9QZSQ02GMJD9S;QJCT6;VXYLT;2S9QZ;SQ02G;MJD9S;AAAANAAAAANANAAAANAAAANA;AAAAN;AAAAA;NANAA;AANAA;AANA;[81, > 74, 67, 84, 54, 86, 88, 89, 76, 84, 50, 83, 57, 81, 90, 83, 81, 79, > 50, 71, 77, 74, 68, 57, 83];[81, 74, 67, 84, 54];[86, 88, 89, 76, > 84];[50, 83, 57, 81, 90];[83, 81, 79, 50, 71];[77, 74, 68, 57, > 83];1867;360;423;361;364;359 > > -- ----------------------------------------------------------------------- James Sapara Software Architect Front Logic Inc. Tel: 306.653.2725 x14 Suite 300, Scotia Center Toll Free: 1.800.521.4510 111 Second Ave South Fax: 306.653.0972 Saskatoon, SK S7K 1K6 Canada http://www.frontlogic.com james at frontlogic.com Find out what TYPENGO(tm) N300 Search Technology can do for your company: http://www.frontlogic.com/interactive/hosts/typengo/index.html ----------------------------------------------------------------------- From steve at holdenweb.com Mon Nov 22 09:29:20 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Nov 2004 09:29:20 -0500 Subject: Trouble with psyco In-Reply-To: References: Message-ID: Dick Moores wrote: > psyco is acting a bit psycho for me. > > Please see my spinForWeb.py at > > When psyco is in use, entering an integer somewhere between 2000 and > 2500 causes my computer to freeze. Not really freeze but the program > doesn't finish, and I have to quit with a ^Q. > > psyco is really impressive, but I'm disappointed that I can't > demonstrate (to friends) counting with it to numbers above 2 billion. > > If I remark out the "psyco.bind(spin)" line, there's no problem no > matter what integer I enter. Can someone explain what the problem with > psyco is? > > Windows XP, Python 2.3.4 > > Thanks, > > Dick Moores > rdm at rcblue.com > > > $ python -c "print 2**31" 2147483648 [Please note this is all theory, as I'm not a psyco user] You are hitting the limit of your platform's integers. After that Python (and, presumably, psyco) starts using longs, which will be considerably slower. In plain Python you probably notice the difference much less, because there is less difference between integer ops and long ops when no optimization is applied. I presume that psyco (stealing a phrase from Tim Peters) "optimizes the snot" out of the integer operations, and the transition to longs then becomes much more noticeable. The alternatives are to use a platform with 64-bit integers or stop trying to deal with large integers. I should thank you for the post, as the statement above about my not being a psyco user is no longer true. To test the theory I actually installed psyco, and verified that your figure of 2000 isn't accurate - an input of 2100 could be processed by the psyco-optimized version in 9.834 seconds on my machine. An input of 2200 took longer than I cared to wait, which I regard as strong evidence that it's crossing the integer/long boundary that's biting you. Given that without psyco it took me almost 41 seconds to process an input of 100, I think you should be grateful for what you've got ;-) regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From esj at harvee.org Tue Nov 30 12:35:01 2004 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 30 Nov 2004 12:35:01 -0500 Subject: asynchat and threading In-Reply-To: <20041129220200.17481.475573126.divmod.quotient.11687@ohm> References: <41AB8F0A.7050502@harvee.org> <20041129220200.17481.475573126.divmod.quotient.11687@ohm> Message-ID: <41ACAF45.1050202@harvee.org> Jp Calderone wrote: > > > Why not use apt-get? well, I am recommending using apt-get but within entirely different and separate namespace for modules. But on second thought,, it might not be necessary to separate the namespace. If you just need to add the repository for Python modules to the apt-get configuration files, it might just work. hmmm. the trick would be making modules that were multiplatform/distribution aware. ---eric From apardon at forel.vub.ac.be Mon Nov 15 06:44:31 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Nov 2004 11:44:31 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: Op 2004-11-15, Peter Hansen schreef : > Antoon Pardon wrote: >> AFAIU the Queue module doesn't block on a full/empty queue when >> a timeout is specified but goes in a loop sleeping and periodically >> checking whether place/items are available. With signals that >> can be sent to a thread the queue could just set an alarm and >> then block as if no timeout value was set and either unblock >> when place/items are available or get signalled when the timeout >> period is over. > > I'm fairly sure that the Queue uses an internal Event > (or REvent?) to signal when space or a new item is > available, so I believe your description (and possibly > conclusion) above is wrong. There should be no > "periodical check", as that would imply polling. Check > the source if you're interested. I did check the source, I just didn't study it carefully and got my understanding mostly from the comments. But anyway here is the relevant part and IMO we have a polling loop here. class Queue: ... def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ if block: if timeout is None: # blocking, w/o timeout, i.e. forever self.esema.acquire() elif timeout >= 0: # waiting max. 'timeout' seconds. # this code snipped is from threading.py: _Event.wait(): # Balancing act: We can't afford a pure busy loop, so # we # have to sleep; but if we sleep the whole timeout time, # we'll be unresponsive. The scheme here sleeps very # little at first, longer as time goes on, but never # longer # than 20 times per second (or the timeout time # remaining). delay = 0.0005 # 500 us -> initial delay of 1 ms endtime = _time() + timeout while 1: if self.esema.acquire(0): break remaining = endtime - _time() if remaining <= 0: #time is over and no element arrived raise Empty delay = min(delay * 2, remaining, .05) _sleep(delay) #reduce CPU usage by using a sleep -- Antoon Pardon From mlh at furu.idi.ntnu.no Fri Nov 19 16:44:56 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 19 Nov 2004 21:44:56 +0000 (UTC) Subject: Recursive regexps? Message-ID: Hi! I've been looking at ways of dealing with nested structures in regexps (becuase I figured that would be faster than the Python parsing code I've currently got) and came across a few interesting things... First there is this, mentioning the (?) and (?<-DEPTH>) constructs of the .NET regexp matcher: http://www.rassoc.com/gregr/weblog/archive.aspx?post=590 Then there was some documentation on PCRE, mentioning (among other things) The (?R) construct, which (as far as I can tell) matches the pattern recursively): http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=pcrepattern It seems that this functionality was introduced in Perl 5.6. Is this (or something similar) something that would be realistic to get in the re module? I know I would find it very useful... -- Magnus Lie Hetland Fallen flower I see / Returning to its branch http://hetland.org Ah! a butterfly. [Arakida Moritake] From tchur at optushome.com.au Fri Nov 19 19:36:58 2004 From: tchur at optushome.com.au (Tim Churches) Date: 20 Nov 2004 11:36:58 +1100 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: <16798.16559.745209.751967@montanaro.dyndns.org> <419E6C13.1040508@v.loewis.de> Message-ID: <1100911018.1301.19.camel@emilio> On Sat, 2004-11-20 at 10:51, Mike Meyer wrote: > "Martin v. L?wis" writes: > > > Neal D. Becker wrote: > >> Doesn't Python (along with probably every other language ever invented) > >> display prior art here? > > > > Wrt. claim 1, yes. Actually, C is prior art here: you have two > > expressions representing pointers, and you have a system where > > you can determine that the pointers refer to different memory > > locations. > > LISP has had NEQ for about 40 years. > > Can they actually get away with patenting the spelling of the > keywords in a language? It is worth remembering that US patents are only valid in the US. Although a US patent application like this establishes a priority date, if Microsoft (or anyone else) wants patent protection in other countries, then they still need to pursue separate applications in each of those countries. Here in Australia, the test for novelty has been tightened for patents applications filed after Jan 2002. Previously the prior art needed to be described in a single document (or single public "performance of an act"). Now elements of prior art published in separate published documents but which is clearly related (in the view of a skilled person) are also acceptable. Thus prior art comprising any published description of the BASIC programming language, and the prior art comprising a published description of "is not" in just about any other programming language should be sufficient to torpedo the application. Previously it may have required prior art of someone describing in a published work the concept of "is not" specifically in the context of BASIC. Of course, if and when Microsoft files an application for this in Australia, it may be necessary for someone to lodge an objection pointing out the above, if the Australian patent office examiners don't reject the application at its preliminary examination. Oh, IANAL. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 From db3l at fitlinxx.com Tue Nov 16 12:51:00 2004 From: db3l at fitlinxx.com (David Bolen) Date: 16 Nov 2004 12:51:00 -0500 Subject: Redirecting system output quietly References: Message-ID: hugonz at hotmail.com (Hugo Gonz?lez) writes: > There's an even easier way to do this. You can use the "commands" > module: > > http://www.python.org/doc/current/lib/module-commands.html > > This is easier and faster than using popen, and will allow you to get > exit status (os.popen* won't let you) Well, since the commands module is just a simple wrapper around the os.popen() call, it's hard to see it giving you anything you can't get with the call itself :-) You can certainly get the exit status from os.popen - it is returned as the result of the close() operation. (Under Windows, for the higher order popen* calls, you get the exit status from the close() on the final of the multiple handles you close, while under Unix I think you need to explicitly do a wait() on the returned handle). One thing to be aware of with commands (although this shouldn't be a problem for the OP in this case), is that it is Unix only, and won't work properly under Windows. -- David From benji at benjiyork.com Sat Nov 6 10:46:34 2004 From: benji at benjiyork.com (Benji York) Date: Sat, 06 Nov 2004 09:46:34 -0600 Subject: Python OS In-Reply-To: References: Message-ID: <418CF1DA.2000001@benjiyork.com> Diez B. Roggisch wrote: > And it backs my assertions: Definitely. I missed that part. I wonder if someone were to start a similar project today if they would be able to use Pyrex (which generates C) to do large parts of the OS. Perhaps when I retire . -- Benji York benji at benjiyork.com From ukunapul at hotmail.com Tue Nov 2 02:35:37 2004 From: ukunapul at hotmail.com (Uday) Date: 1 Nov 2004 23:35:37 -0800 Subject: Newbie Question Message-ID: <783d0f8c.0411012335.196183ce@posting.google.com> Hi, I would like to know how can I create and assign variables by de-referencing the values in other variable in Python. I can illustrate what I mean by an example of perl $a = "task_id"; $i = "1"; $c = $a."_".$i; $$c = 2; print "$task_id_1\n"; # Gives the answer as 2 My problem is that I need to dynamically generate a unique variable within a for loop in Python. The name of the variable should be appended by the index of the loop. In the above example if $i were an array index, then as we traverse through the array, a unique variable is defined. Is there any way to do it in Python?? I am not in python.users mailing list, please reply to me directly. Thanks, Uday From technique at oceanicsky.com Tue Nov 30 06:06:45 2004 From: technique at oceanicsky.com (David Siedband) Date: Tue, 30 Nov 2004 03:06:45 -0800 Subject: recombination variations Message-ID: The problem I'm solving is to take a sequence like 'ATSGS' and make all the DNA sequences it represents. The A, T, and G are fine but the S represents C or G. I want to take this input: [ [ 'A' ] , [ 'T' ] , [ 'C' , 'G' ], [ 'G' ] , [ 'C' , 'G' ] ] and make the list: [ 'ATCGC' , 'ATCGG' , 'ATGGC' , 'ATGGG' ] The code below is what I have so far: 'alphabet' is a dictionary that designates the set oif base pairs that each letter represents (for example for S above it gives C and G). I call these ambiguous base pairs because they could be more then one. Thus the function name 'unambiguate'. It makes a list of sequences with only A T C and Gs and none of the ambiguous base pair designations. The function 'unambiguate_bp' takes a sequence and a base pair in it and returns a set of sequences with that base pair replaced by each of it's unambiguous possibilities. The function unambiguate_seq takes a sequence and runs unambiguate_bp on each base pair in the sequence. Each time it does a base pair it replaces the set of things it's working on with the output from the unambiguate_bp. It's a bit confusing. I'd like it to be clearer. Is there a better way to do this? -- David Siedband generation-xml.com def unambiguate_bp(seq, bp): seq_set = [] for i in alphabet[seq[bp]]: seq_set.append(seq[:bp]+i+seq[bp+1:]) return seq_set def unambiguate_seq(seq): result = [seq] for i in range(len(seq)): result_tmp=[] for j in result: result_tmp = result_tmp + unambiguate_bp(j,i) result = result_tmp return result alphabet = { 'A' : ['A'], 'T' : ['T'], 'C' : ['C'], 'G' : ['G'], 'W' : ['A','T'], 'M' : ['A','C'], 'R' : ['A','G'], 'Y' : ['T','C'], 'K' : ['T','G'], 'S' : ['C','G'], 'H' : ['A','T','C'], 'D' : ['A','T','G'], 'V': ['A','G','C'], 'B' : ['C','T','G'], 'N' : ['A','T','C','G'] } From anhtt at hotmail.com Fri Nov 19 09:51:17 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 19 Nov 2004 06:51:17 -0800 Subject: SPARK v.s. PLY References: Message-ID: Anyone has used ANTLR? Daniel Dittmar wrote in message news:... > Tran Tuan Anh wrote: > > I am searching for a suitable parsing tool to parse C++ for a research > > project. > > Actually I am parsing SystemC, it is a C++ lib with some macros, hence > > I need to modify the grammar a little bit to handle some new keywords. > > OpenC++ (http://opencxx.sourceforge.net/) is not written in Python, but > it knows probably more about C++ than any simple parser generator. > > Daniel From nehalmistry at gmx.net Tue Nov 16 00:57:36 2004 From: nehalmistry at gmx.net (Nehal) Date: Mon, 15 Nov 2004 21:57:36 -0800 Subject: cgi.FieldStorage() is slow Message-ID: <20041115215736.00007a5c@nehal> i wanted to created a simple CGI script for uploading files to my http server, and decided to use python for it. it seems to work fine except for one issue: there is a lot of CPU overhead. after profiling, it seems like: self.read_lines_to_outerboundary() which is called from cgi.FieldStorage() is the reason why it's so slow. when uploading small files, you won't notice a difference, but if you upload files larger than 2 megs, you can notice it. this happens on both win2k and freebsd is there some other way to process CGI, excluding doing it all manually? will this code be improved in the future? -- thx, Nehal From exarkun at divmod.com Sun Nov 7 12:38:46 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Sun, 07 Nov 2004 17:38:46 GMT Subject: determine IP In-Reply-To: <3ADD583A-30DE-11D9-A056-003065B11E84@leafe.com> Message-ID: <20041107173846.14104.1093455745.divmod.quotient.1272@ohm> On Sun, 7 Nov 2004 11:58:21 -0500, Ed Leafe wrote: >On Nov 7, 2004, at 11:53 AM, exarkun at divmod.com wrote: > > > The above code will _always_ return the local IP address, regardless > > of NAT configuration. For example, running on my desktop: > > > >>>> import socket > >>>> s = socket.socket() > >>>> s.connect(('google.com', 80)) > >>>> print s.getsockname() > > ('192.168.42.4', 40044) > >>>> > >>>> > > Not OMM: > > >>> import socket > >>> s = socket.socket() > >>> s.connect(('google.com', 80)) > >>> s.getsockname() > ('66.66.222.137', 55096) > >>> > > The local IP address is in the 192.168 subnet. It sounds like you are running this code on the machine performing the NAT'ing. It's "local" address can easily be argued to be either of those two addresses, since it sits on two networks. The behavior I referred to was for any of the other machines on the NAT'd network. Jp From reinhold-birkenfeld-nospam at wolke7.net Mon Nov 22 12:45:56 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 22 Nov 2004 18:45:56 +0100 Subject: Text widget - insert line In-Reply-To: References: <41a21527$0$8170$8fcfb975@news.wanadoo.fr> Message-ID: <30emukF2u6uf7U2@uni-berlin.de> beps wrote: > Eric Brunel ha scritto: >> I'm not sure I understand the question... Do you have some code generating > the >> first, and you want it to generate the second? If my guess is correct, can > you >> show us the code? It will surely only be a matter of inserting a 'n' at the > end >> of each line, then do a textWidget.insert(END, ...), but I'm just guessing > here... > > Here there's my code: > def show_customers(self, customers) : > ## data is a list > for data in customers: > dato = operator.concat(str(data), '/n') ^^ You have to use \n, not /n. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From aleaxit at yahoo.com Mon Nov 15 17:33:07 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 15 Nov 2004 23:33:07 +0100 Subject: Zope 3.0, and why I won't use it References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> Message-ID: <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> Jim Fulton wrote: > > Guido has repeatedly stated that a future version of Python will include static type support. The Zope project has driven numerous past changes to Python. What's funny about this? > > For the record, I'm against static typing for Python, although, > if Guido decides he wants it, I have an open mind. :) Glad to hear that. As for me, I'd love it if function arguments, only, could bear an 'as' clause (making 'as' a keyword is long overdue): def x(y as foo, z as bar): translating into: def x(y, z): y = adapt(y, foo) z = adapt(z, bar): where builtin 'adapt' does protocol adaptation. On the other hand, if the semantics of those 'as' clauses were something like: def x(y, z): if type(y) is not foo: raise TypeError, 'y must be foo' if type(z) is not bar: raise TypeError, 'z must be bar' then that's the day I move to Ruby, or any other language that remained halfway sensible (if any). In other words, if the 'as' clause (or whatever absurd syntax ends up being adopted in its place -- judging on recent performance, probably a two-arguments version of splat, or a nice << to complement the just as nice 'print>>bah,humbug' syntax -- good thing I don't really care about syntax sugar;-) ends up being a way to ease *type-checking*, then, well, I'll evaluate that as being on a par with easing alcohol abuse. What the syntax supports, people will do more of, and we already know that type-checking, like alcohol abuse, is a _very_ popular although self-destructive practice. Protocol adaptation is the polar opposite from type checking. I'd see syntax that supports adaptation as being on a par with easing things that are good for you, as well as pleasant, and yet are not widely practiced -- yoga, aerobics, many other forms of exercise, healthy nutrition -- the language gently encouraging you to do the right thing. Alex From steve at holdenweb.com Mon Nov 22 08:00:17 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Nov 2004 08:00:17 -0500 Subject: Python with Apache 2.0 In-Reply-To: References: <89cc6e1f.0411190632.2976b3e1@posting.google.com> <306sikF2sueanU1@uni-berlin.de> Message-ID: Graham Dumpleton wrote: > Steve Holden wrote in message news:... > >>Damjan wrote: >> >> >>>>Does python support threads safely along with Apache 2.0 in web >>>>applications. >>> >>> >>>Are you talking about mod_python? >>>If so, then yes. But note that Apache threads entering the python >>>interpreter (via mod_python) will be serialized on the GIL. >>> >>> >> >>This is true, but it doesn't tell the whoel story: mod_python has taken >>care to make it possible to configure multiple interpreters - on a >>per-directory basis if necessary. Obviously they all share the pure >>code, but if I undestand correctly each has its own data space, and >>hence its own GIL. > > > There is actually a possible bug in PythonInterpPerDirectory directive > which applies even if threading isn't being used. Specifically, mod_python > doesn't calculate the interpreter name correctly and although access to a > directory by name and something in it should logically resolve to the > same interpreter name it doesn't. More information can be found at: > > http://www.modpython.org/pipermail/mod_python/2004-November/016788.html > > Overall, I am not sure that PythonInterpPerDirectory is a good idea, but > then it probably was created to workaround the short comings of the > module importing system in mod_python which makes it impossible in > mod_python.publisher to have an index.py file in separate directories > within the context of the one interpreter. It wouldn't take much effort to > fix this limitation in the module importing system, but there doesn't seem > to be much interest in doing so. Thank a lot for the additional information. I agree that the namespace confusion is less than ideal in mod_python. regards STeve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From boisgera at isia.cma.fr Thu Nov 25 09:35:23 2004 From: boisgera at isia.cma.fr (Sebastien Boisgerault) Date: 25 Nov 2004 06:35:23 -0800 Subject: Operator Overloading References: Message-ID: Peter Maas wrote in message news:... > Sebastien Boisgerault schrieb: > > I wonder if the following quotation from the Python Reference Manual > > (release 2.3.3) about operator overloading is true : > > > > "For example, if a class defines a method named __getitem__(), and x > > is an instance of this class, then x[i] is equivalent to > > x.__getitem__(i)" > [...] > >>>>from Numeric import * > >>>>a = array([0.5]) > >>>>a[0] > > > > 0.5 > > > > but > > > > > >>>>a.__getitem__(0) > > > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: __getitem__ > > The quotation above is true. Short form: > > IF __getitem__ in dict THEN [] works. Not exactly the same assertion: replace "__getitem__ in dict" by "__getitem__ in the class dict" and more importantly "[] works" by "[] and __getitem__" are *equivalent*. Here, "__getitem__" does belongs to type(a).__dict__, so "[]" and "__getitem__" should work exactly the same according to the reference, but they don't. > [...] > but this is not what the Python Reference Manual says. Im not a > Numeric expert but AFAIK Numeric arrays are basically C arrays > having [] intrinsically so there's no need no deliver it via > __getitem__. I would buy your argument if I couldn't find the "__getitem__" method. But it does exist ! Except that it is hidden is the class __dict__ and apparently cannot be recovered from the instance.__getitem__ call ... Thanks for your help, SB From steven.bethard at gmail.com Thu Nov 11 14:28:42 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 11 Nov 2004 19:28:42 +0000 (UTC) Subject: typed variables (WAS re.compile.match() results ...) References: <2vh2mlF2lbkrdU1@uni-berlin.de> <41938e20$1@nntp0.pdx.net> <6GOkd.971$ry5.380@fe51.usenetserver.com> Message-ID: Stefan Seefeld sympatico.ca> writes: > > Steven Bethard wrote: > > > I think perhaps Axel Bock was getting a little pedantic here. Sorry, I misread the quoting. s/Axel Bock/Scott David Daniels. Sorry! > > Python does not have typed variables; any "variable" in Python can hold an > > object of any type. Hence examples like: > > I don't see this as a contradiction (but then, may be we'd need to > define what 'variable' means, the reference or the referee). I only > meant to point out that there is a distinction between strong/weak > and static/dynamic typing, and thus, that Axel's question was perfectly > valid. Yeah, that's why I said the responder was being pedantic. The question is, of course, a valid one. I think the phrasing could have been a little confusing though -- if you thought that the OP believed that "variables" in Python could be of type str (meaning that they were statically typed), then you would interpret his question as "how does a str-typed variable get converted into a unicode-typed variable?" instead of the real question, "why does m.groups() return unicode objects?" Again, the question was valid -- I just thought it would be helpful to explain what Scott David Daniels meant when he said "Python does not have typed variables", and perhaps give a more standard wording for these kind of descriptions in Python. Steve From TheDolphin at ivonet.nl Tue Nov 9 14:07:07 2004 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Tue, 9 Nov 2004 20:07:07 +0100 Subject: HTML to Text renderer References: <3A81C87DC164034AA4E2DDFE11D258E324510E@exchange.hqamor.amorhq.net> Message-ID: <41911561$0$765$3a628fcd@reader10.nntp.hccnet.nl> "Marc Christiansen" wrote in message news:l5i562-hih.ln1 at halut.solar-empire.de... > Ian Bicking wrote: > > Robert Brewer wrote: > >> To clarify: you don't want the HTML tags merely stripped; you want to > >> replace e.g. br with a line break and p with, say, two line breaks? > > > > Right. And word wrapping too. Some other tags would also be > > interesting:
,
, 
,
,  , and something > > to control alignment (e.g.,

). > > Have a look at htmllib.HTMLParser and formatter in the standard Python > lib (but also look at the source of htmllib). Maybe they provide what > you need. > > HTH > Marc look at this code: ===CUT BELOW=== from sgmllib import SGMLParser class html2txt(SGMLParser): """html2txt() """ def reset(self): """reset() --> initialize the parser""" SGMLParser.reset(self) self.pieces = [] def handle_data(self, text): """handle_data(text) --> appends the pieces to self.pieces handles all normal data not between brackets "<>" """ self.pieces.append(text) def handle_entityref(self, ref): """called for each entity reference, e.g. for "©", ref will be "copy" Reconstruct the original entity reference. """ if ref=='amp': self.pieces.append("&") def output(self): """Return processed HTML as a single string""" return " ".join(self.pieces) if __name__=="__main__": html="""

just a piece of html

""" parser = html2txt() parser.reset() parser.feed(html) parser.close() print parser.output() === END CUT === The html2txt class is of course extendable and changeble. For me it was important to convert html to text but the behavior of the class can be adjusted to change tags to do other stuff... hope it helps Ivo. From skysoe at jpcomputers.com.sg Fri Nov 19 03:52:17 2004 From: skysoe at jpcomputers.com.sg (Sky Soe) Date: Fri, 19 Nov 2004 16:52:17 +0800 Subject: Pls Help Me Message-ID: Hello Everybody, I've a big problem when I installed MySQLdb1.1.2 on python2.3.4 running on Linux 9.0. And there is an error shows that " Cannot Import MySQLdb''. Another problem is that it shows me the fatal error that cannot run Python interpreter because of "Version Mismatch". I would like to know all these things urgently. Thank u. Regards, Sky Soe From elbertlev at hotmail.com Wed Nov 24 15:19:10 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 24 Nov 2004 12:19:10 -0800 Subject: asynchat and threading References: Message-ID: <9418be08.0411241219.43437101@posting.google.com> Rob! Sure it was suggested you may go with twisted. But with minimal modifications of asyncore you can add a hook. There are 2 ways to do this: 1. Use small timeout 2. Use a "control socket" Timeout: from asyncore import * def loop(timeout=30.0, use_poll=0, map=None, after_pool = None): if map is None: map = socket_map if use_poll: if hasattr(select, 'poll'): poll_fun = poll3 else: poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map) if (after_pool): after_pool(map) after_pool - is a function called when you exit poll_fun. You can do whatever you want in this function. If you call loop with timeout 0.3 - for all practical reasons your GUI will react OK. If there are a few sockets (I think 1 in your case), the overhead will be negligible on any reasonable computer. The second approach is more effective, but more complex too. You add a socket (as channel 0) and when something happens (f.e. user presses enter), you write a byte (or any command you want). Write into this control socket has to be made atomic to be thread save. The reason I do not use twisted for client applications is the size of distribution file. I do not assume python is installed on client PC. I use distutils with py2exe option. If I use twisted the size is 10mb+. With asyncore - 2-3 mb. Hope this helps. From tdelaney at avaya.com Tue Nov 16 23:12:33 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 17 Nov 2004 15:12:33 +1100 Subject: Rounding curiosity Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A90BE@au3010avexu1.global.avaya.com> PyBo wrote: > What's wrong with this picture? > >>>> x = 500000000.0 >>>> y = x / (1024 * 1024) >>>> y > 476.837158203125 >>>> z = round(y, 2) >>>> z > 476.83999999999997 > > I have tried this and get the same result using different CPU's and > operating systems. Obviously, '476.83999999999997' is not rounded to > two decimal places. > > Or am I doing something wrong? You just have a fundamental misunderstanding of floating-point arithmetic. http://www.python.org/doc/faq/general.html#why-are-floating-point-calcul ations-so-inaccurate Tim Delaney From caleb1 at telkomsa.net Thu Nov 11 22:18:14 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 11 Nov 2004 22:18:14 -0500 Subject: Concise idiom to initialize dictionaries References: Message-ID: Peter, respect :) For interest sake, how would such a thing look with new-style classes? My (likely misinformed) impression is that __getattr__ for example, doesn't behave in quite the same way? thx Caleb On Tue, 09 Nov 2004 20:12:15 +0100, Peter Otten <__peter__ at web.de> wrote: > > Here is a bunch of dictionaries that spring into existence by what is > believed to be magic :-) > >>>> class AllDicts: > ... def __getattr__(self, name): > ... d = {} > ... setattr(self, name, d) > ... return d > .. def __repr__(self): > ... items = self.__dict__.items() > ... items.sort() > ... return "\n".join(map("%s -> %r".__mod__, items)) > ... >>>> ad = AllDicts() >>>> ad.a[1] = 99 >>>> ad.b[2] = 42 >>>> ad.b[3] = 11 >>>> ad > a -> {1: 99} > b -> {2: 42, 3: 11} > > Peter > From jerf at jerf.org Thu Nov 18 05:56:45 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 18 Nov 2004 05:56:45 -0500 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) References: <30001hF2ptnqcU1@uni-berlin.de> <419bbf2a.319309032@news.oz.net> Message-ID: On Thu, 18 Nov 2004 05:51:00 -0500, Jeremy Bowers wrote: > * math-type code where the tuple really is the class, as you suggest By the way, Bengt, just to be explicit, except for this particular "you" the parent message is addressed generally. From imbosol at aerojockey.com Thu Nov 18 00:14:19 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 17 Nov 2004 21:14:19 -0800 Subject: arrays References: Message-ID: <60dfb6f6.0411172114.44d514ac@posting.google.com> codedivine at gmail.com (Rahul Garg) wrote in message news:... > Hi. > Is there someway i can get something similar to multi-dimensional > arrays in python.I dont want to use Numarray. > rahul It seems (from other posts) as if you're looking for a way to get simple multidimensional array behavior in Python, while making convenient to access it in C, without using numarray or Numeric. Probably the simplest way to accomplish this without numarray is to use a class to wrap a list. Override __getitem__ and __setitem__ to get the effect of multidimensional access. Because the data is stored in a single list, rather than a list of lists, it is convenient to access it from C. A minimal example follows. class MinimalMultiArray: def __init__(self,rows,cols): self.rows = rows self.cols = cols self.data = [0.0] * self.rows * self.cols def __getitem__(self,(row,column)): return self.data[row*self.cols + column] def __setitem__(self,(row,column),value): self.data[row*self.cols + column] = value Notice that Python can unwrap tuples right into function arguments, so if you reference array[1,2], in __getitem__, row will be set to one and column to two. Any improvements left as an exercise. Here's a suggestion: check whether row and column arguments are slice objects, and return a list or a smaller multidimensional array if so. -- CARL BANKS From syd.diamond at gmail.com Wed Nov 3 21:57:18 2004 From: syd.diamond at gmail.com (syd) Date: 3 Nov 2004 18:57:18 -0800 Subject: two new wrinkles to the general class! In-Reply-To: References: Message-ID: <1099537038.677930.245340@c13g2000cwb.googlegroups.com> Recap: For a general "container" type class, I wanted to grab another instance of this class based upon attributes of the items contained within. Eg, for an illustrative library of nations, I want to be able to do operations like library.get_continent('Europe').get_size('medium'). A good sol'n: Use __getattr__ to intercept the "get_continent" on-the-fly and split it into "get_" (the function I want) and "continent" (the attribute I want to select for). By using the built-in getattr(), I can grab the value of this attribute in each component object in my library. Thus, each "get_foo" does not need to be hard coded. Some things I learned: subclass object -- ie, "class Library(object):" -- for post python-2.2 for a variety of reasons including better agreement with upcoming versions. Also, __getattr__ intercepts *after* looking in __dict__, and __getattribute__ (when you've subclassed object) intercepts *before*. First off, thanks to everyone for helping me to this point! Looking forward, I've got two other related issues: >>1) Because I've got many "container" type classes, the best route would obviously seem be to subclass each to a general "container". Ie, class Library_A(Container): ... class Library_B(Container): ... The problem: in the current setup, a library_a.get_continent('Europe') would pass back an instance of Container and *not* Library_A. The obvious implication is that any attributes/method specific to Library_A are gone. (In the code at the bottom, we'd lose the "defineNation" method). My (bad?) remedy: when you create library_a, give it a "blankSelf" attribute that it can deepcopy before you pass it back. Within the __getattr__: def get(value): container=copy.deepcopy(self.blankSelf) if self.isNotEmpty()==True: for item in self.list: if getattr(item,attribute)==value: container.add(item) return container This hard-code / deepcopy does not seem ideal! >>2) I've got a bunch of "get_foo" type things where "foo" is not an attribute of the component class but rather a method. In our illustrative example, we could imagine a "get_nameLongerThanFourLetters" where we add the component nation class when "nation.is_nameLongerThanFourLetters()==True". Above, we use getattr() to grab the attribute on-the-fly. Can we grab a method on-the-fly, too? Ie, when we see "get_foo", use the "is_foo" criteria from the class below. I hope this makes sense. In response to Andrea's comments, I'll state the obvious: I'm fairly new to the intricacies of Python class structures :). I'm a student (non CS), and my year or so of Python experience before this project has been "functional" (alternatively: quick hacks). But I love the language! And I want to learn! Thanks again, everyone. Appendix: Here's the code for the illustrative example... #!/usr/bin/python import copy class Container(object): def __init__(self,list=None,blankSelf=None): self.list=list self.blankSelf=blankSelf def __getattr__(self,name): def get(value): container=copy.deepcopy(self.blankSelf) if self.isNotEmpty()==True: for item in self.list: if getattr(item,attribute)==value: container.add(item) return container def getMethodAndAttribute(): if name.startswith('get_'): return 'get',name[4:] else: return '','' method,attribute=getMethodAndAttribute() if method=='get': return get else: raise AttributeError,name def add(self,item): try: self.list.append(item) except: self.list=[item] def count(self): if type(self.list)==type([]): return len(self.list) else: return 0 def getNameList(self): outList=[] for nation in self.list: outList.append(nation.name) return outList def isNotEmpty(self): if self.count()>0: return True else: return False class Library(Container): def __init__(self): pass def defineNation(self,name,continent,size): nation=Library.Nation() nation.name=name nation.continent=continent nation.size=size self.add(nation) class Nation: def __init__(self,name=None,continent=None,size=None): self.name=name # eg, Spain self.continent=continent # eg, Europe self.size=size # eg, medium library=Library() library.blankSelf=Library() library.defineNation('Spain','Europe','medium') library.defineNation('USA','NorthAmerica','large') library.defineNation('Luxembourg','Europe','small') library.defineNation('Portugal','Europe','medium') print library.getNameList() print library.get_continent('Europe').getNameList() From bill.mill at gmail.com Sat Nov 13 12:30:31 2004 From: bill.mill at gmail.com (Bill Mill) Date: 13 Nov 2004 09:30:31 -0800 Subject: numarray + cPickle problem In-Reply-To: <1100366822.119444.157780@z14g2000cwz.googlegroups.com> References: <1100326589.669597.252570@f14g2000cwb.googlegroups.com> <1100366822.119444.157780@z14g2000cwz.googlegroups.com> Message-ID: <1100367031.042556.162860@z14g2000cwz.googlegroups.com> Ok, sorry for sending another message to the list so soon, but I think I've figured out the problem. On Windows, if you want to use one of the binary pickle settings, you *need* to open your output file in binary mode. Perhaps this should be mentioned in the cPickle documentation? Peace Bill Mill bill.mill at gmail.com From ncoghlan at email.com Tue Nov 30 08:01:17 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Tue, 30 Nov 2004 23:01:17 +1000 Subject: Python code and C code in the same module? In-Reply-To: References: <%uVqd.112242$V41.104378@attbi_s52> Message-ID: <41ac6f1c$0$25782$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Fredrik Lundh wrote: > if you insist on doing it the other way around, This paragraph should actually continue ". . .you clearly have too much free time" };> Cheers, Nick. From helten0007 at yahoo.com Tue Nov 23 11:52:58 2004 From: helten0007 at yahoo.com (Pete.....) Date: Tue, 23 Nov 2004 17:52:58 +0100 Subject: Transfer data from webpage form to database Message-ID: <41a36ab7$0$23056$ba624c82@nntp05.dk.telia.net> Hi all. I have made a webpage where there is a webform where people can fill in their personel information: The code is below: I want to transfer the data to a postgreSQL database ( I have allready made the database with the neccesary tables, and I know how to connect to it ) but I really have no idea how I can transfer the data from the webform to the database. If any can help me I will be more than pleased... thanks for your help... Adminperson

Insert Person


Name:

Surname:

Username:

Password:

Adresse:

Zipcode:

City:

Phone:

Mail:

What is your profession?

Student Teacher Teacher Assistent

From ramen at lackingtalent.com Fri Nov 5 17:43:25 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 05 Nov 2004 22:43:25 -0000 Subject: strong/weak typing and pointers References: <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> <10ol7sqdr84k619@corp.supernews.com> Message-ID: In article , Diez B. Roggisch wrote: > Steven Bethard wrote: > >> Michael Hobbs hobbshouse.org> writes: >>> >>> One word: union >>> >> >> Interestingly, unions can be well-defined even in a strongly-typed >> language, e.g. OCaml: >> >> # type int_or_list = Int of int | List of int list;; >> type int_or_list = Int of int | List of int list >> # Int 1;; >> - : int_or_list = Int 1 >> # List [1; 2];; >> - : int_or_list = List [1; 2] > > Unions in functional languages are also known as direct sums of types (as > opposed to products, which form tuples). And trying to access a union that > holds an int as list will yield an error - runtime, most probably. So there > is no way of reinterpreting an int as list, which still satisfies the > paragdigms of a strong typed language. Just FYI: In OCaml, the error will be at compile time, and the compiler will warn you if you do not deal with all possible cases for a given union type. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From deetsNOSPAM at web.de Thu Nov 4 09:39:44 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 04 Nov 2004 15:39:44 +0100 Subject: seg fault References: Message-ID: Ajay wrote: > hi! > > i have some code with a gui that does some processing in another thread, > say t2. > when t2 needs to display something on the gui, it generates an event > (which i have binded earlier). the code runs fine on windows but segfaults > on linux. > the point where it segfaults is when it generates the event. > > any ideas why? Lots of gui-toolkits don't like to be manipulated outside the thread their main eventloop is running. I don't know this for sure for tk, but your problem looks like it's the case here. So I suggest you communicate your event to the main thread using a queue, and insert the event in tk's event loop somehow. For that you could use after-calls that periodically check for pending events. -- Regards, Diez B. Roggisch From wgshi at namao.cs.ualberta.ca Thu Nov 25 14:27:46 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Thu, 25 Nov 2004 19:27:46 +0000 (UTC) Subject: dictionary initialization References: Message-ID: Hi, In article , Caleb Hattingh wrote: > ... >Dict entries accessed with 'string' keys, Not necessarily. And doesn't make a difference in my question. > ... > >Which feature specifically do you want justification for? Have it your way: string-indexed dictionaries. >>> a={} >>> a['1']+=1 Traceback (most recent call last): File "", line 1, in ? KeyError: '1' a['1'] when it referenced, is detected non-existent but not automatically initialized so that it exists before adding 1 to its value. Weiguang From valkyrie at cuhk.edu.hk Tue Nov 16 09:14:33 2004 From: valkyrie at cuhk.edu.hk (Valkyrie) Date: Tue, 16 Nov 2004 22:14:33 +0800 Subject: HTMLParser problem In-Reply-To: References: <1100610863.75889@eng-ser4> Message-ID: <1100614470.532201@eng-ser4> Thank you. That means there is no way to deal with it using simple python built-in functions? Richard Brodie wrote: > "Valkyrie" wrote in message news:1100610863.75889 at eng-ser4... > > >> >> >>HTMLParser.HTMLParseError: unknown declaration: 'if !IE', at line 4, column 1 >> >>May I ask why such error is raised? > > > HTMLParser isn't very forgiving of bad HTML; you feed it syntactically invalid HTML, > it tends to give you errors. That includes Microsoft only extensions like Unless you know you have known valid sources it may be best to use one of > the forgiving parsers: Beautiful Soup, UTidylib, libxml etc.. (see many past discussions). > Uche's article: http://www.xml.com/pub/a/2004/09/08/pyxml.html may be of interest. > > From mwm at mired.org Wed Nov 17 21:12:31 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 17 Nov 2004 20:12:31 -0600 Subject: Enumerating Classes in Modules References: Message-ID: Rob Snyder writes: > Greetings - > The idea is basically to support "plug-ins" for an application I'm building. > I want the end user to be able to sub-class an example plug in class, then > throw the implementation in a given directory, where I'll find it > automatically when I need it. webcheck supports plugin modules. You might want to give it a look. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin at v.loewis.de Sun Nov 14 04:34:55 2004 From: martin at v.loewis.de (=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Nov 2004 10:34:55 +0100 Subject: .pyc files... In-Reply-To: References: Message-ID: <419726bf$0$521$9b622d9e@news.freenet.de> Eddie Parker wrote: > b) Would this go against some sort of coding convention/design decision? > i.e., "Bylaw 3, subsection 42 of the Python 'Code' states: No config options > should be specified to the running interpreter, from within any .py file"? See http://www.python.org/peps/pep-0304.html Regards, Martin From someone at microsoft.com Mon Nov 29 14:15:42 2004 From: someone at microsoft.com (Jive) Date: Mon, 29 Nov 2004 19:15:42 GMT Subject: A lock that times out but doesn't poll References: Message-ID: "Peter Hansen" wrote in message news:coe5l8$6l1$1 at utornnr1pp.grouptelecom.net... > Jive wrote: > > Oh, there will be no bugs. > > ?? What kind of a statement is that? Humorous? Imagine Carl Spackler in Caddy Shack saying, "Oh, there will be no money." > Seriously, why are you so confident about that? Even if > the code were trivial, we're talking *threads* here... > Two reasons: 1) I just know I can do it. Argue with *that* logic! B) Writing bug-free code is quite possible when the job is well-defined and "from scratch." It's when you have to modify a mess that it gets tricky. I think a lot of programmers would be capable of writing bug-free code if they just knew it was possible and believed they could do it. My programmers submit very few bugs. I've made some bugs in my day, but the odds are with me on this one. But enough about me... Read any good books lately? From mwm at mired.org Mon Nov 15 14:33:46 2004 From: mwm at mired.org (Mike Meyer) Date: Mon, 15 Nov 2004 13:33:46 -0600 Subject: .pyc files... References: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> <2mqfp0tuuutj01njq2400trfhd4vtbv81m@4ax.com> Message-ID: Christos "TZOTZIOY" Georgiou writes: > So, "...these are the GNU versions..." could be wrong or misleading, I > agree (but I believe it's not); I think that "...the traditional Unix > ones..." is correct though. Which leaves open the question of what "traditional Unix" is. Being a BSD user since 3.0 or thereabouts, that's what I think of as traditional Unix. And I'm pretty sure CSRG added the 0 options to find and xargs. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeff at ccvcorp.com Tue Nov 9 15:50:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 09 Nov 2004 12:50:46 -0800 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> Message-ID: <10p2b7nc5efcse3@corp.supernews.com> Dave Cook wrote: >wxpython runs on top of gtk on Linux, but I don't know if they use the gtk >treeview as a "peer" or work around it and implement their own tree widget. > > Given that the express goal of wxWidgets is to use native widgets wherever possible (a goal which results in some cross-platform inconsistencies, but is largely responsible for its "better" (i.e. native) look and usually-better speed), I'd think it very likely that it does use the GTK treeview. Jeff Shannon Technician/Programmer Credit International From caleb1 at telkomsa.net Thu Nov 11 22:48:33 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 11 Nov 2004 22:48:33 -0500 Subject: Concise idiom to initialize dictionaries References: Message-ID: Steve, Not only did you answer my silly question, but also the question I actually wanted to ask ...__getattribute__ is what I was thinking of. thats cool :) thx Caleb On Thu, 11 Nov 2004 20:30:18 +0000 (UTC), Steven Bethard wrote: > Caleb Hattingh telkomsa.net> writes: >> >> For interest sake, how would such a thing look with new-style classes? >> My >> (likely misinformed) impression is that __getattr__ for example, doesn't >> behave in quite the same way? > > Just the same[1] =) > >>>> class AllDicts(object): > ... def __getattr__(self, name): > ... d = {} > ... setattr(self, name, d) > ... return d > ... def __repr__(self): > ... items = self.__dict__.items() > ... items.sort() > ... return '\n'.join(['%s -> %r' % item for item in items]) > ... >>>> ad = AllDicts() >>>> ad.a[1] = 99 >>>> ad.b[2] = 42 >>>> ad.b[3] = 11 >>>> ad > a -> {1: 99} > b -> {2: 42, 3: 11} >>>> > > I believe that __getattr__ works just the same (but to check for > yourself, see > http://docs.python.org/ref/attribute-access.html). I think what you're > thinking > of is __getattribute__ which new-style classes offer *in addition* to > __getattr__. While __getattr__ is called only if an attribute is not > found, > __getattribute__ is called unconditionally for every attribute access. > > Steve > > [1] modulo my preference for list comprehensions/generator expressions > instead > of map > From apardon at forel.vub.ac.be Fri Nov 26 04:21:04 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Nov 2004 09:21:04 GMT Subject: A lock that times out but doesn't poll References: Message-ID: Op 2004-11-25, Jive schreef : > Okay, I've got a comment: How about some comments? Maybe it's just me, but > I find the code a little hard to comprehend. The basic algorithm is that you have a list of simple locks that is treated mostly like a queue. A tread that aquires the Tlock, first allocates a new lock that is appened to the list and aquired, then the next to last lock is aquired too. A thread that releases the lock, releases the first lock and deletes it from the table and then release the new first lock. A thread that specifies a timeout on the release, starts a timer thread. This timer thread will look if the lock is in the table and if so releases it and removes it from the table. It also marks the lock is broken. > What's up with this? > > Exception in thread Thread-456: > Traceback (most recent call last): > File "C:\Python23\lib\threading.py", line 436, in __bootstrap > self.run() > File "C:\Python23\lib\threading.py", line 544, in run > self.function(*self.args, **self.kwargs) > File "C:\Python23\Scripts\foo.py", line 29, in break_lock > sc.pl.release() > error: release unlocked lock > > That crops up occasionally. There are two solutions for that. 1) Just remove line 29, it is not needed but I entered it for "estetical" concerns. 2) Use semaphores in the table. That means changing the Lock to a Semaphore on lines 11 and 38. > It's been a while, but as I recall, the tricky bit in implementing timed > locks with an alarm clock thread is seeing to it that threads that don't > time out waiting on a timed lock do not leave zombie alarm clock threads > running. If you are not careful, they could proliferate and eat up system > resources. What do you mean with a Zombie? The clock thread will remain for as long as the timeout, which may be longer then needed but then they disappear, so there won't be any real zombies. But I expect some of the python comunity are laughing at me now, because I have discoverd that the Timer class is implemented by a Condition variable that is waited upon with a timeout. And this timeout is implemented by a polling loop. -- Antoon Pardon From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Nov 1 05:06:24 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 01 Nov 2004 11:06:24 +0100 Subject: "number-in-base" ``oneliner'' In-Reply-To: References: <1gmfz0k.a3xefz1xzms61N%aleaxit@yahoo.com> Message-ID: <41860aa0$0$78738$e4fe514c@news.xs4all.nl> Andrea Griffini wrote: > roman = lambda x: "".join(["".join(map(lambda c: "IVXLCDM"[int(c) > +2*N],"/0/00/000/01/1/10/100/1000/02".split("/")[x//10**N % 10])) > for N in (3, 2, 1, 0)]) This rocks!! I'm still trying to understand how it works though :) --Irmen From steven.bethard at gmail.com Tue Nov 2 17:34:06 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 22:34:06 +0000 (UTC) Subject: strong/weak typing and pointers References: <4187aafe$1@nntp0.pdx.net> <41880188$0$14993$626a14ce@news.free.fr> Message-ID: Christophe Cavalaria free.fr> writes: > > If by ML you thing of OCaml you should try again. OCaml isn't type safe > because of a few modules of the standard library. The marshaling module > comes to mind. Using it you can "typecast" a pointer to an integer as a > pointer to a string and segfault in the process because the unmarshal > function trusts the caller to cast the result in the good type. Thanks, I knew I'd read something like that somewhere. Totally surprised me too 'cause I figured that, of all people, ML folks would be the most afraid of a module like this. =) Steve From philippecmartin at sbcglobal.net Wed Nov 24 12:57:38 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 24 Nov 2004 11:57:38 -0600 Subject: tkinter shell problem Message-ID: <200411241157.38212.philippecmartin@sbcglobal.net> Hi, I have the following problem: I wrote a tkinter shell which on a key return event first evals the input buffer (in a try: except:) and then, in case of except, execs the input buffer. I have the problem if the exec fails: If I trap it, I do not get the stack dump that I which I would show. ex: % import dontexist Traceback (most recent call last): File "", line 1, in -toplevel- import dontexist ImportError: No module named dontexist If I don"t trap it, then my clean up code which is after the exec obviously does not get called (i.e, clear my input buffer, save the history, print a prompt .......) Yet Idle manages - any clue ? Regards, Philippe From riko.wichmann at remove-this.desy.de Tue Nov 23 07:37:10 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Tue, 23 Nov 2004 13:37:10 +0100 Subject: seg fault when doing shelve.open Message-ID: Dear all, I have Pyhthon 2.3.4 compiled from sources installed. I would like to create a data base which is accessed by a key using the shelve module. However, if I try to open a (non-exixting) file I get a segmantation fault: >>> import shelve >>> d = shelve.open("MyDB") Segmentation fault Stepping through the module which pdb tells me where is crahes: > /usr/local/lib/python2.3/bsddb/__init__.py(248)_checkflag()->5 -> return flags | db.DB_THREAD (Pdb) s > /usr/local/lib/python2.3/bsddb/__init__.py(185)hashopen() -> d = db.DB() (Pdb) s Segmentation fault However, that doesn't tell me anything. Do i need to compile python with a special configure flag so that shelve'ing works properly? does it use some installed db package which might be broken? Any hint would be greatly appreciated. Thanks and Cheers, Riko From news5 at bennymo.ch Tue Nov 16 15:14:43 2004 From: news5 at bennymo.ch (Benny Mohr) Date: Tue, 16 Nov 2004 21:14:43 +0100 Subject: get function arguments In-Reply-To: References: Message-ID: Thanks a lot, that's what I'm looking for Benny Steven Bethard wrote: > Benny Mohr bennymo.ch> writes: > >>How can I get the list of argumens of this function? > > > Is this what you mean? > > >>>>def myFunc(a,b,c='default'): > > ... pass > ... > >>>>myFunc.func_code.co_varnames > > ('a', 'b', 'c') > > I don't know where (if?) the func_code attributes are documented, but you should > be able to figure them out with a little object introspection (e.g. dir or an > editor like PythonWin that does some code completion). > > Steve > From cappy2112 at gmail.com Mon Nov 1 19:55:29 2004 From: cappy2112 at gmail.com (Tony C) Date: 1 Nov 2004 16:55:29 -0800 Subject: Linksys Router & Python References: Message-ID: <8249c4ac.0411011655.5ebd6f1a@posting.google.com> BRad Here's a one-liner way of getting your IP address, but you'd need a shell account on a webserver to get it. I made a python CGI script, and had it print the IP address of the client as HTML. import os print os.environ["REMOTE_ADDR"] I don't show the code to to format the output as HTML, but that's rpretty straightforward. However, this would still require you to have your computer on while you're away, which isn't your goal. But at least you don't have to login to your router to get the info. You can accomplish the same thing by running a python script to www.myipaddress.com, and scraping the screen. These are just another ways of getting your IP address. I copied this from a post on CLP, so I can't take credit for it. Brad Tilley wrote in message news:... > Probably a stupid question, but here goes: > > Is there any way to get a scaled down version of Python onto a Linksys > Wireless router? Are there any projects out there that are doing this? > I've googled around a bit, but didn't find much. I want to keep the > router's software as it is, but I also would like to have some scripting > abilities on it as well (like email the router's IP addy every x hours), > etc. > > I have scripts that run on my computers that do this sort of thing. > > def url_open(): > """ Function that gets and returns the IP addy > of my Linksys BEFW11S4 Wireless DSL router.""" > import urllib, re > ip = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') > f = urllib.urlopen("http://user:passwd at 192.168.1.1/RouterStatus.htm") > data = f.read() > f.close() > routerip = ip.findall(data) > print routerip[0] > return routerip[0] > > But, when I leave town for vacation, I don't like leaving a computer > running. If I could get the interpreter embedded in the device itself, > then that would solve the problem. > > This is probably a shot in the dark, but I thought I'd ask. > > Thanks, > Brad From steven.bethard at gmail.com Tue Nov 2 18:38:45 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 2 Nov 2004 23:38:45 +0000 (UTC) Subject: [OT] Re: general class functions References: <4186f23d$1_3@newspeer2.tds.net> <418815ca$0$9247$636a15ce@news.free.fr> Message-ID: bruno modulix xiludom.gro> writes: > > class Library: > [...] > def getAll(self, **kwargs): > library=Library() > for nation in self.list: > keep = True > for attribute, value in kwargs.items(): > if not getattr(nation, attribute) == value: > keep = false > break > if keep : > library.add(nation) > return library I haven't been watching this thread, but I saw a pattern here that Python allows a much easier solution to. The code: keep = True for item in lst: if test(item): keep = False break if keep: ... can generally be rewritten as: for item in lst: if test(item): break else: For example: >>> def loop1(lst, test): ... keep = True ... for item in lst: ... if test(item): ... keep = False ... break ... if keep: ... print "reached if" ... >>> def loop2(lst, test): ... for item in lst: ... if test(item): ... break ... else: ... print "reached if" ... >>> loop1(range(10), lambda x: x == 5) >>> loop1(range(10), lambda x: x == 11) reached if >>> loop2(range(10), lambda x: x == 5) >>> loop2(range(10), lambda x: x == 11) reached if Always good to take advantage of a language construct when you can. =) Steve From ncoghlan at email.com Fri Nov 26 08:56:47 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Fri, 26 Nov 2004 23:56:47 +1000 Subject: PEP263 + exec statement In-Reply-To: References: Message-ID: <41a7361d$0$25779$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Carlos Ribeiro wrote: > Does anyone have more information on this? I have tried Google in > vain. It seems that exec is not that popular (which is a good sign, > IMHO), and that nobody else had this problem before. Does compile() work? (i.e. "bytecode = compile(code_str); exec bytecode" instead of "exec code_str"). PEP 263 states explicitly that feeding a unicode string to compile() should respect the encoding. It's silence on the question of exec fails to inspire confidence. . . If compile() does work even though exec doesn't, it would explain why exec has never been fixed :) Cheers, Nick. From sxanth at ceid.upatras.gr Fri Nov 5 23:17:02 2004 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Fri, 05 Nov 2004 20:17:02 -0800 Subject: Wrapping or converting Perl module? In-Reply-To: References: <200411030759.15909.hancock@anansispaceworks.com> Message-ID: <418C503E.9020800@ceid.upatras.gr> Terry Hancock wrote: > 1) Wrap a perl module the way you would a C module > (does this ever make sense to do?) > I don't know if it helps but do you know the "pyperl" module. It's rather interesting. BTW, I hope pyperl becomes a standard python module. All in all. Perl is great for Practical Extraction and Report. Stelios From carribeiro at gmail.com Mon Nov 22 05:31:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 22 Nov 2004 08:31:17 -0200 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: <16798.16559.745209.751967@montanaro.dyndns.org> <16798.19563.729805.103774@montanaro.dyndns.org> Message-ID: <864d37090411220231582b7426@mail.gmail.com> On Mon, 22 Nov 2004 11:22:20 +0100, Fredrik Lundh wrote: > Skip Montanaro wrote: > > >> My guess is Microsoft hopes to discourage Visual Basic knock-offs. Claim > > >> 2 clearly seems to restrict the scope to BASIC. > > > > Neal> Doesn't Python (along with probably every other language ever > > Neal> invented) display prior art here? > > > > Sure, but maybe there is no such prior art in the BASIC arena. > > IIRC, the "inventor" mentioned on his weblog that he didn't come up with the idea > himself; it was suggested by customers. In other words, the solution clearly wasn't > obvious to the "inventor" himself, since he didn't invent it. And if it's not obvious, > it can be patented, right? As chewbacca would say, if it doesn't make sense, you > must patent! Patenting something that was suggested by customers is asking for trouble. What if the customer who suggested the feature sues Microsoft? Or worse -- if it turns out that the suggestion came after seeing 'prior art' elsewhere? (Of course, the patent itself doesn't cover the idea, but also the implementation, which is why Microsoft could get away with it. But it does not invalidate the above points, because the customer could possibly have suggested enough of the implementation to Microsoft). (btw, do I automatically assign to Microsoft the property of any idea that I eventually communicate to them? I'm curious). > I need coffee. Me too (but not of the java variety, please) :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From deetsNOSPAM at web.de Thu Nov 18 11:39:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 18 Nov 2004 17:39:12 +0100 Subject: Need function to test if EFFECTIVE UID has read-access to a file. References: <9b96ed1.0411170915.2b88da0e@posting.google.com> <9b96ed1.0411180820.21447337@posting.google.com> Message-ID: > Ow, is that the only way? =( Because as I see it, open() is a > relatively costly function compared to something like os.access(), and > since I'll be calling the function thousands of times in a row it'd be > really cool if there was something similar to os.access(). But if > there isn't I guess that'll have to do ... I didn't measure it, but I bet open internally uses the same function os.access uses - so in case of failure, you won't have lost much, if anything at all. Now for the positive case: if you actually want to _do_ something with that file, you might needed an open anyway? -- Regards, Diez B. Roggisch From jcarlson at uci.edu Mon Nov 15 22:44:06 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 15 Nov 2004 19:44:06 -0800 Subject: determining the number of output arguments In-Reply-To: <1gnbg4k.13z20mj1w1o0ysN%aleaxit@yahoo.com> References: <1gnbg4k.13z20mj1w1o0ysN%aleaxit@yahoo.com> Message-ID: <20041115175212.F945.JCARLSON@uci.edu> aleaxit at yahoo.com (Alex Martelli) wrote: > > Fernando Perez wrote: > > > > Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's > > > recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd > > > edition (which I'm supposed to be working on right now -- deadline > > > closing in, help, help!-). > > > > Well, I feel pretty good now: I didn't see Jp's mention of this, and just > > guessed it should be doable with those three tools. I just looked it up, and > > it seems it's exactly what I had in mind :) Cute hack, but I tend to agree > > with Scott Daniels' comment that this kind of cleverness tends to promote > > rather unreadable code. Maybe I just haven't seen a good use for it, but I > > think I'd rather stick with more explicit mechanisms than this. > > Yeah, but "once and only once" is a great principle of programming. Any > time you have to say something _TWICE_ there's something wrong going on. > > So, > > a, b, c, d = lotsa[:4] > > _should_ properly give the impression of a code smell, if your "once and > only once" sense is finely tuned. What's the business of that ':4' on > the RHS? Showing the compiler that you can count correctly?! You're > having to tell twice that you're getting four items into separate > variables, once by listing exactly four variables on the LHS, and > another time by that ':4' on the RHS. IMHO, that's just as bogus as > struct.unpack's limitation of not having any way to indicate explicitly > 'and all the rest of the bytes goes here', and for similar reasons. The slicing on the right is not so much to show the compiler that you know how to count, it is to show the runtime that you are looking for a specified slice of lotsa. How would you like the following two cases to be handled by your desired Python, and how would that make more sense than what is done now? a,b,c = [1,2,3,4] a,b,c = [1,2] > I think it would be better to have a way to say 'and all the rest'. > Lacking that, some automated way to count how many items are being > unpacked on the LHS is probably second-best. Is it worth a keyword, or would a sys.getframe()/bytecode hack be sufficient? In the latter case, I'm sure you could come up with such a mechanism, and when done, maybe you want to offer it up as a recipe in the cookbook *wink*. > Another case where a specific number of items is requested, which is not > (syntactically speaking) a multiple assignment, is assignment to an > _extended_ slice of, e.g., a list (only; assignment to a slice with a > stride of 1 is happy with getting whatever number of items are coming). > I don't particularly LIKE writing: > L[x:y:z] = len(L[x:y:z]) * [foo] I much prefer... for i in xrange(x, y, z): L[i] = foo But then again, I don't much like extended list slicing (I generally only use the L[:y], L[x:] and L[x:y] versions). - Josiah From Scott.Daniels at Acm.Org Tue Nov 9 22:47:46 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 09 Nov 2004 19:47:46 -0800 Subject: Determining combination of bits In-Reply-To: <54k0p0pt8jsekrchcic6ob3v0p3uq6do6o@4ax.com> References: <8KQjd.121796$hj.4674@fed1read07> <418ff674$1@nntp0.pdx.net> <41901545$1@nntp0.pdx.net> <54k0p0pt8jsekrchcic6ob3v0p3uq6do6o@4ax.com> Message-ID: <4191a26c$1@nntp0.pdx.net> Dennis Lee Bieber wrote: > On Mon, 08 Nov 2004 15:33:01 -0800, Scott David Daniels > declaimed the following in comp.lang.python: >>(OCA) and increment (INA)". Note that a ones complement turns all of >>the least significant zeros to ones, and the least significant one to >>a zero. When you increment that the carry propagates back to the 0 for > Ones complement turns ALL 0 bits to 1, and ALL 1 bits to 0. Right. In particular, all of the lowest order zeroes turn to 1s, the one directly before them turns to zero. Those bits are the only bits where I care what the value is, all others are simply inverted (and it doesn't matter what values they have). > 00000000 > 1C 11111111 ones complement has a "negative zero" > +1 00000000 twos complement "overflows" back to single zero Correct, and this isoloates the least significant one bit for this value as well (inasmuch as it doesn't exist). --Scott David Daniels Scott.Daniels at Acm.Org From peter at somewhere.com Mon Nov 29 04:35:00 2004 From: peter at somewhere.com (Peter Maas) Date: Mon, 29 Nov 2004 10:35:00 +0100 Subject: Building web graphics with Python In-Reply-To: References: Message-ID: Steven Feil schrieb: > I am wondering if there is a light weight Python library for producing > web graphics on-the-fly. There is a C-language library called gd that > can be used in a CGI program to produce gif images. The Library can > be used to produce graphics images that are dynamically generated. I > was wondering if there is something similar for Python. You can create a Python wrapper for gd with SWIG or Pyrex. PIL (Python Imging Library) and Piddle are native Python solutions. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From tjreedy at udel.edu Tue Nov 16 18:06:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Nov 2004 18:06:06 -0500 Subject: adaptation (was: Zope 3.0, and why I won't use it) References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm><1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com><1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com><1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> Message-ID: >example? The example used in the Zope3 programmer tutorial: You have database of (USA) Buddy objects, each with firstname, lastname, streetaddress, zipcode, and email fields. You want to use them in a context that requires the (redundant) city and state fields. So you write a zip to city/state lookup function and then an ExpandedBuddy adapter that gets the zip from the adapted Buddy, calls city_state(zip), and packages the result together as needed in the usage context. Terry J. Reedy From donn at u.washington.edu Tue Nov 23 13:13:09 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 23 Nov 2004 10:13:09 -0800 Subject: Is there a consensus on how to check a polymorphic instance? References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> Message-ID: In article , "Dan Perl" wrote: > "Steven Bethard" wrote in message > news:lkCod.88653$5K2.13406 at attbi_s03... > > The big question, I guess, is what do you want to happen if a user did not > > inherit from your base class, but still provides all the appropriate > > functionality? In a dynamically-typed language like Python the answer is > > usually that the user's class should still be considered valid, though of > > course there are exceptions to this rule. > > I have a question here, as we are discussing now protocol interfaces vs. > inheritance. Is using a class that implements a protocol without inheriting > from a base class still "polymorphism"? There are probably many definitions > for polymorphism and probably all those definitions can be interpreted in > such a way that they accept also protocols. But what I would like to hear > is what is the general opinion of people who use python. I am biased > because I come from a C++ and Java background and I am still used to a > certain practical meaning for "polymorphism". But it's beginning to dawn on > me that it is only a bias and polymorphism does apply also to python > protocol interfaces. Is that generally accepted? Not only are there many definitions of polymorphism, there are several kinds of polymorphism, each with many definitions. You could spend some time with a web search engine and get lots of reading material on this, and I think you would find that a good deal of it is coming from a point of view that kind of tends to ignore object oriented programming altogether. Check it out. If you want to stay with the more immediately relevant OOP thinking on this, search for polymorphism and smalltalk. Note that C++ and Java need two mechanisms in support of something approximating parametric polymorphism. The subtype polymorphism I think you're thinking of is the classic OO device, but it doesn't support really generic functions and types. The template system has been bolted onto these languages (I gather Java has one now) for this purpose. With these two mechanisms, they more or less support parametric polymorphism, in a statically typed, compiled language. Python is not statically typed, of course, so where the literature about parametric polymorphism focuses on types you have to decide for yourself how important that is in principle. In the end it of course doesn't really matter what you call it. Donn Cave, donn at u.washington.edu From jdhunter at ace.bsd.uchicago.edu Sun Nov 14 13:43:10 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 14 Nov 2004 12:43:10 -0600 Subject: Tkinter and Graphics In-Reply-To: <10pf6ersh138jbe@corp.supernews.com> (Andrew's message of "Sun, 14 Nov 2004 21:46:27 -0800") References: <10pf6ersh138jbe@corp.supernews.com> Message-ID: >>>>> "Andrew" == Andrew writes: Andrew> Hi I was wondering if there is anyway in Tkinter to create Andrew> GUIs using Graphics, like windows media player or other Andrew> tools like that Andrew> basically so the interface wouldn't be your standard Andrew> interface Andrew> any ideas, links to tutorials, or examples Andrew> is appreciated This sounds like enthought's enable toolkit, which is still under development. Basically, they use the antigrain graphics library to develop their own GUI widgets, which can then be embedded in a tk graphic's canvas, at gtk drawing area, a wx panel, etc. Though enable doesn't support all of these GUIs currently, I believe, it can in principle. http://svn.enthought.com/svn/enthought I've often wished for something like this in developing matplotlib, because a lot of work goes into supporting multiple GUIs, and it would be nice to have a core set of widgets that port across GUIs. Another approach is anygui, which I've been meaning to look into... JDH From fuzzyman at gmail.com Fri Nov 5 05:28:55 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 5 Nov 2004 02:28:55 -0800 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> Message-ID: <6f402501.0411050228.aea8068@posting.google.com> "darkhorse" wrote in message news:<2uvedvF2g1pv3U1 at uni-berlin.de>... > Hi all, > > While doing a quite big "set of programs" for a university subject I've > found myself in the middle of a problem someone surely has had before, so > I'm looking for some help. > > At one point, I call a python cgi that pickle.load's a file, adds or deletes > a registry and dumps the result again in the file. > I'm worried that the cgi could be called simultaneously from two or more > different computers, thus most probably corrupting the files. I don't think > I can use a mutex as it's two different instances of the program and not > different threads, so I was thinking about locking the files between > programs, but I really don't know how to do that. It's not a problem if > there's no portable way of doing this, it's only going to be run on a linux > based computer. > Another solution I would accept is that the second called cgi detects that > other instance is running and displays a message saying to try again later. > Yes, not quite professional, but it'd do the job, after all this is just a > little detail I want to settle for a quite picky professor and not a "real > life" thing. > I think that's all the background you need, if someone can answer with > references on what should I look for or even better example code that would > be simply great. > Many thanks in advance. > DH A simple solution that doesn't scale well is to create a file when the access starts. You can check if the file exists and pause until the other process deletes it - with a timeout in case the file gets keft there due to an error. Obviously not an industrial strength solution, but it does work... import time import os def sleep(thelockfile, sleepcycle=0.01, MAXCOUNT=200): """Sleep until the lockfile has been removed or a certain number of cycles have gone. Defaults to a max 2 second delay. """ counter = 0 while os.path.exists(thelockfile): time.sleep(sleepcycle) counter += 1 if counter > MAXCOUNT: break def createlock(thelockfile): """Creates a lockfile from the path supplied.""" open(thelockfile, 'w').close() def releaselock(thelockfile): """Deletes the lockfile.""" if os.path.isfile(thelockfile): os.remove(thelockfile) The sleep function waits until the specified file dissapears - or it times out. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From stan at saticed.me.uk Tue Nov 2 12:40:25 2004 From: stan at saticed.me.uk (stan at saticed.me.uk) Date: 2 Nov 2004 17:40:25 GMT Subject: function object and copies of variables Message-ID: <20041102174025.GA26478@marge.cehill.co.uk> can a function object store values so this 3 liner can print 0 1 instead of 1 1? f = [] for i in [0, 1]: f.append(lambda: i) for j in f: print j() TIA From skip at pobox.com Sun Nov 14 10:09:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 14 Nov 2004 09:09:21 -0600 Subject: .pyc files... In-Reply-To: <41976617_1@newspeer2.tds.net> References: <419726bf$0$521$9b622d9e@news.freenet.de> <41976617_1@newspeer2.tds.net> Message-ID: <16791.29985.807526.318735@montanaro.dyndns.org> Kent> But PEP 304 seems to be abandoned, if I read the record correctly. Kent> It has an incomplete patch that is almost two years old and no Kent> activity since then. PEP 320 (Python 2.4 Release Schedule) says I guess "abandoned" is the appropriate term. There were problems raised with how this would work on Windows and I lost interest. (The current scheme works pretty well for me. I wrote PEP 304 more for pedantic reasons and to address other peoples' concerns.) It shouldn't be hard to resurrect if there are some folks with Windows experience willing to help solve those problems. Kent> The biggest stumbling block seems to be the lack of a patch for Kent> Windows, though the *nix is also incomplete. Ideally, the patch, when complete, should just be a single patch. Skip From saynotodevilspam at yahoo.com Sun Nov 28 22:04:24 2004 From: saynotodevilspam at yahoo.com (Yet Another Mike) Date: Mon, 29 Nov 2004 03:04:24 GMT Subject: graphics References: Message-ID: You'll need wxPython. Once you get that, look in the samples for pySketch. This is a very straightforward program that helped me learn a lot about GUI with wxPython. Pretty easy to do. Once you get a hang for the basics, then you might be interested in wxGlade, an interactive GUI designer. wxGlade is more advanced than you need for your request. From jcarlson at uci.edu Mon Nov 1 17:38:25 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 01 Nov 2004 15:38:25 -0700 Subject: Why is heapify linear? In-Reply-To: <4186cb77$1@nntp0.pdx.net> References: <4186cb77$1@nntp0.pdx.net> Message-ID: <20041101153502.0C5F.JCARLSON@uci.edu> Scott David Daniels wrote: > > I am sorry, but in the Python 2.4 description of "heapify", I find the > description of "Transform list x into a heap, in-place, in linear time," > unbelievable. I understand the hand-wave that makes dictionary building > linear (though I have a hard time with even that). Could somebody tell > me what twist of logic makes "heapify" linear, except in the sense that > linear is coming to mean "very fast?" It has to do with the amount of work done by doing the heapify operation from the bottom up. Using ugly ascii-art math, we get the following work for heapifying from the bottom up: log(n) i*n SUM ---- i=1 2**i That sum is known to converge to 2n from below (there is a simple picture that I can present that will prove it to you, if desired). 2n is O(n). Hence linear. - Josiah From sholden at flexal.cs.usyd.edu.au Wed Nov 10 20:34:04 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 11 Nov 2004 01:34:04 GMT Subject: distutils and Debian References: <4192AD69.5040707@sympatico.ca> Message-ID: On Wed, 10 Nov 2004 20:03:51 -0500, Istvan Albert wrote: > Sam Holden wrote: > > >>>Should this be reported as a Debian bug? > >> No. > > I would say yes ... there is no logic in crippling > a standard python distribution. What else is missing? If it's anything like perl then lots of things. But they are easily installed via their seperate packages. The documentation being the big obvious thing. Tkinter being another. The logic might be to make small installs possible. If all of "standard python" was put in one package then debian couldn't use python for writing things which might be wanted on small systems. It might also make sense to split "pure python" and "binary" packages up since the "pure python" packages might be sharable across architecures, but I don't think that is done. "no logic" seems a bit extreme. Cost exceeding the benefit might be true, but of the top of my head there's two vaguely "logical" reasons. -- Sam Holden From alanmk at hotmail.com Thu Nov 18 10:45:52 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 18 Nov 2004 15:45:52 +0000 Subject: SPARK v.s. PLY In-Reply-To: References: Message-ID: [Tran Tuan Anh] > I am searching for a suitable parsing tool to parse C++ for a research > project. and > If you know the parsing stuff well, could you briefly tell me the > pros. and cons. of those packages? (or some others you find good too) You might find Martin von Loewis paper "Towards a Standard Parser Generator" useful. It discusses the pros and cons of multiple python parser frameworks, in the concrete context of implementing xpath expression parsing. It discusses SPARK, but not PLY. http://www.python.org/sigs/parser-sig/towards-standard.html regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ian at kirbyfooty.com Wed Nov 24 19:01:21 2004 From: ian at kirbyfooty.com (Ian Cook) Date: 24 Nov 2004 16:01:21 -0800 Subject: Newbie requires help me on how to use the ZipFile module please. Message-ID: <8cf64c3d.0411241601.feca1f7@posting.google.com> Hi, Can someone PLEASE shed some light on using the ZipFile module correctly. I'm new to python so please excuse me if this is a 'dumb' question. If I use mode='a' then what happens is the zip file just gets bigger and bigger as the SAME file is appended to the zipfile. If I use mode='w' then what happens is the zip file is erased before adding files to it. Therefore I lose the files that were in the original file zipfile. What I want is to use the ZipFile module to UPDATE an existing zip file, rather than append, or create a new zip file. The zip file then contains my original files and any updated files. Does anyone know how this can be done with the Zipfile module? This is a snippet of the code I have now.. try: zf = zipfile.ZipFile(zfname,mode='a') except: zf = zipfile.ZipFile(zfname,mode='w') for name in cutflist: fp = os.path.join(root,name) print "adding ",fp,"...", compresstype = zipfile.ZIP_DEFLATED if zipfile.is_zipfile(fp): compresstype = zipfile.ZIP_STORED zf.write(fp,compress_type=compresstype) print 'done.' Thanks in advance. Ian Cook (Freeware author of Kirby Alarm And Task Scheduler) http://www.kirbyfooty.com/ From mauriceling at acm.org Tue Nov 9 16:29:05 2004 From: mauriceling at acm.org (Maurice Ling) Date: Wed, 10 Nov 2004 08:29:05 +1100 Subject: possible to pass python objects into java without jython? In-Reply-To: <4190BFE0.5080507@bellsouth.net> References: <4190A2DE.6040505@acm.org> <4190BFE0.5080507@bellsouth.net> Message-ID: <419136A1.8030601@acm.org> Jeremy Jones wrote: > Maurice Ling wrote: > >> Hi, >> >> I have read that this had been asked before but there's no >> satisfactory replies then. >> >> I have a module (pA) written in python, which originally is called by >> another python module (pB), and passes a python object (pO) to pB. >> Now I require pA to be called in a java class (jC) and pass pO into >> jC. As pA uses non-python modules, I am not able to use Jython on this. >> >> Are there any way out in this? >> >> Thanks in advance. >> >> Maurice > > How about: > > * XMLRPC > * SOAP > * a messaging queue of some sort (pA or pB - I'm a little unclear > on which is the starting point - could put pO in a message queue > and jC could pick it up) > * serialize the Python object to disk in an intermediate format > (say, XML) and have the Java process pick it up > * CORBA > > Without more details, and some clarification, that's the best I can > do. Are you sure you meant to say pA is called by pB, or is it the > other way around? If pA is being called, it really can't pass pO to > pB, unless you've got a callback setup. > > > Jeremy Jones Say this scenario... pA.py contains imports (something non-pure python) def A(n): ...(does something)... returns pO pB.py comtains import pA def B(n): (does something) x = pA.A(n) (does more things) How can I get Java to call pA.A function and then receives the object it returns? I am considering SOAP or CORBA, but just wondering if there is any other ways without resorting to network or socket programming, since all modules are on the same machine? Thanks Maurice -------------- next part -------------- A non-text attachment was scrubbed... Name: mauriceling.vcf Type: text/x-vcard Size: 347 bytes Desc: not available URL: From skip at pobox.com Tue Nov 30 13:49:50 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Nov 2004 12:49:50 -0600 Subject: comment out more than 1 line at once? In-Reply-To: <41ACBAD6.60704@q-voz.com> References: <41ACBAD6.60704@q-voz.com> Message-ID: <16812.49358.844099.146116@montanaro.dyndns.org> >> if False: >> >> (indented) block of code here is commented out >> I've no idea how efficient it is compared to triple-quoted strings or >> line by line comments. Gustavo> Actually, it's infinitly [sp?] more defficient (contrary of Gustavo> efficient?) than triple-quoted strings or line-by-line Gustavo> comments, because those two never make it to execution stage, Gustavo> because they're dropped by the compiler. :-) If you use 'if 0:' the 2.4 byte code compiler also deletes it: >>> import dis >>> def f(a): ... if False: ... return a ... return a+1 ... >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (False) 3 JUMP_IF_FALSE 8 (to 14) 6 POP_TOP 3 7 LOAD_FAST 0 (a) 10 RETURN_VALUE 11 JUMP_FORWARD 1 (to 15) >> 14 POP_TOP 4 >> 15 LOAD_FAST 0 (a) 18 LOAD_CONST 1 (1) 21 BINARY_ADD 22 RETURN_VALUE >>> def g(a): ... if 0: ... return a ... return a+1 ... >>> dis.dis(g) 4 0 LOAD_FAST 0 (a) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 RETURN_VALUE The 'if False:' case isn't optimized because you can (today, anyway) redefine or override False. Skip From pythongnome at hotmail.com Tue Nov 23 08:03:28 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 23 Nov 2004 13:03:28 GMT Subject: instant messenging In-Reply-To: References: <2004112108293216807%craig@yumaca> Message-ID: JanC wrote: > Lucas Raab schreef: > > >>Ah, could you possibly have a zip file?? I looked on your site and >>downloaded the BZ2 file, but I'm not sure how to extract it. I have >>Cygwin for another application, but I don't know how to get the files >>out the BZ2. So either a ZIP file or instructions on extracting files in >> BZ2 files would be greatly appreciated. > > > I think Cygwin has bzip2 & tar to extract files from .bz2 archives? > > If you prefer a GUI application, try 7-Zip: > > (version 3.13, don't use 4.x yet) > > It does have both of those, but I;m not sure how to get them to act in concert with each other. From steven.bethard at gmail.com Thu Nov 4 12:39:45 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 17:39:45 +0000 (UTC) Subject: Summary: strong/weak typing and pointers References: <20041104172742.23443.474029896.divmod.quotient.1435@ohm> Message-ID: divmod.com> writes: > > Python 2.3 (#3, Jan 26 2004, 21:50:33) > [GCC 2.95.3 20010315 (release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import intrinsics, become > >>> class phpstr(str): > ... def __setitem__(self, index, value): > ... become.memwrite(id(self) + 20 + index, str(value)[0]) > ... > >>> oldstr = intrinsics.replace(str, phpstr) > >>> foo = 'abc' > >>> foo[0] = 65 > >>> foo > '6bc' Oooh! So dirty! ;) I've never used the intrinsics module (and Googled, but apparently didn't search for the right thing), but does this do a global replace? E.g. if my module imports some module that calls intrinsics.replace(str, phpstr), are all the uses of str in my module then replaced with phpstr's? Steve From pierre.barbier at cirad.fr Fri Nov 5 08:22:29 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 05 Nov 2004 14:22:29 +0100 Subject: sys.stdout .>_<. In-Reply-To: References: Message-ID: <418b7e2f$0$30017$626a14ce@news.free.fr> It's not possible ! stdout is usually a pipe ... and you cannot go back in a pipe ... Try with any pipe you should have the same result. The only way toi achieve this is to assume an ANSI terminal and to use ANSI codes to go back ("\r" to go at the beginning of the line "^h" to go back one char) Leon a ?crit : > import os,sys > a = os.fdopen(sys.stdout.fileno(),"w") > b = os.fdopen(sys.stdout.fileno(),"w") > a.write("test1 ") > b.write("test2 ") > > stdout result is > > test1 test2 > > but use general file object such as... > > a = open("test.txt","w") > b = open("test.txt","w") > a.write("test1") > b.write("test2") > > the "test.txt" file content is > > test2 > > how to do this result to sys.stdout > > From ianb at colorstudy.com Wed Nov 24 15:33:37 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 24 Nov 2004 14:33:37 -0600 Subject: teaching OO In-Reply-To: References: Message-ID: <41A4F021.7080700@colorstudy.com> Gabriel Zachmann wrote: > Another question is: can you teach effectively the inner workings, if you > teach only a dynamic language? To a degree, maybe not. But I don't think that's the place to start -- to me the foundation of CS is abstract algorithmic thought, not a CPU; math, not electronics. Again, that's not a perspective everyone agrees with, some feel it's best to start with assembler. But then, if you are writing assembler, there's a good chance now that you'd be writing MIX or some other fake assembler for a fake CPU. I can imagine approaching that from Python -- code an assembler and virtual CPU in Python, and start programming it. To the degree that the virtual CPU looks like real CPUs, you learn about processors. The assembler teaches the beginning of compiler design. The next level up -- C, where you are dealing with pointers and memory management -- probably isn't feasible from Python. In assembler you are only writing trivial programs, so it's not a big deal that it's slow; you can't realistically implement either C or an efficient runtime environment in Python; even if you could, the task would be too large. But that's okay, C still has an important role in a CS education. I'm less certain about C++ -- it's neither low level nor high level. And since Java or C# will almost inevitably be taught at some point, most of C++'s features and complications are not novel, again making C seem more reasonable. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From onurb at xiludom.gro Wed Nov 24 20:16:07 2004 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 25 Nov 2004 02:16:07 +0100 Subject: Global surprise In-Reply-To: References: Message-ID: <41a5305e$0$18593$636a15ce@news.free.fr> Nick a ?crit : > Hello, > > It must be simple but it seems I misunderstand scopes in Python... :( > > Could someone out there please explain to me why this is printed? > 2 {0: 1, 1: 1} > instead of > 2 {} > > Thanks. > N. > > ---- test.py ---- > > g = 0 > di = {} > > def test(): > global g > di[g] = 1 > g += 1 > > test() > test() > > print g, di > > Because di is a global variable, modified by the test() function (which is a Bad Thing(tm) BTW). Try this : g = 0 di = {} def test(): global g di = {g : 1} g += 1 Here you create a local di variable, and bind a new dict to it, so it doesnt look for another di variable in the enclosing (here the global) scope. Keep in mind that modifying the state of an object (your code) is not the same thing as binding an object to a variable (my code). HTH Bruno From deetsNOSPAM at web.de Thu Nov 4 07:53:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 04 Nov 2004 13:53:49 +0100 Subject: question for sys.stdout References: <4189ec52$0$6282$626a14ce@news.free.fr> Message-ID: > how to replace sys.stdout to file-like object ? sys.stdout = open("/this/is/so/simple", "w") -- Regards, Diez B. Roggisch From export at hope.cz Mon Nov 29 13:29:56 2004 From: export at hope.cz (Lad) Date: 29 Nov 2004 10:29:56 -0800 Subject: Question on sorting Message-ID: <81a41dd.0411291029.4cff137d@posting.google.com> Hi, I have a file of records of 4 fields each. Each field is separated by a semicolon. That is Filed1;Ffield2;Field3;Field4 But there may be also empty records such as ;;;; (only semicolons). For sorting I used ################# lines = file('Config.txt').readlines()# a file I want to sort lines.sort() ff=open('ConfigSorted.txt','w')# sorted file ff.writelines(lines) ff.close() ############### It was sorted but empty records were first. I need them to be last(at the end of the file). How can I do that? Thanks for help Lad From bj_666 at gmx.net Mon Nov 29 16:47:30 2004 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 29 Nov 2004 22:47:30 +0100 Subject: The use of : References: <89cc6e1f.0411251858.40b6bbc7@posting.google.com> <89cc6e1f.0411260953.4b6b98e7@posting.google.com> <41aa1abb$0$25542$636a15ce@news.free.fr> Message-ID: In <41aa1abb$0$25542$636a15ce at news.free.fr>, bruno modulix wrote: > > In fact, from a purely technical POV, the ':' could have been omitted > from the Python syntax, since indentation does the whole job of defining > blocks. It's only here for readability AFAIK. > The ':' serves as a very good hint to "python aware" text editors to automagically indent the next line after hitting return. Ciao, Marc 'BlackJack' Rintsch From carribeiro at gmail.com Fri Nov 26 06:25:54 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 26 Nov 2004 09:25:54 -0200 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: Message-ID: <864d3709041126032529c9ce0b@mail.gmail.com> On Thu, 25 Nov 2004 20:11:47 -0800, Tim Roberts wrote: > > > Carlos Ribeiro wrote: > > > >I think that Delphi is *so* underated when it comes to language & > >framework design... Delphi suffered from a couple of problems; first, > >it was Pascal's child, and not C; also, because it was a proprietary > >project, owned by a single company. > > > >For some reason, being a Pascal descendant was regarded as a big "no" > >by a huge part of the industry, not to mention academia, that was at > >that time fascinated with the prospect of C++. I wonder what could > >have happened if Delphi (maybe with another name -- P++ anyone?) was > >widely adopted instead of C++ for big projects... > > You are absolutely correct. I have never understood the industry prejudice > against Delphi. The code is just as efficient as the typical C compiler. > GUI design in the IDE has always been easier in Delphi than in Visual > Studio. VCL is easier to understand than MFC Not to mention that Delphi is way 'saner' (sic?) than either VB and VC++ when it comes to weird features & behavior. But it also strikes to me that a lot of Delphi folks are now Python converts. It seems that, in a sense, Delphi managed to be a step in the right direction; in a time where everyone was jumping in the C++ bloat wagon, Delphi was clearly a much better choice in terms of language & environment design. Of course, now Delphi is nearly dead, but we have Python :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fiedzia at fiedzia.prv.pl Wed Nov 24 13:08:09 2004 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Wed, 24 Nov 2004 19:08:09 +0100 Subject: Is there any tools to create User Interface (Dialogs...) for wxPython visually? References: <41a4adf0$0$17787$626a14ce@news.free.fr> Message-ID: <20041124180809.9E7.0.NOFFLE@fiedzia.homeip.net> App wrote: > I am looking for something like VB6.0 IDE to design visually UI et > application but using Python. > > Thank you for your help. All popular gui toolkits have such utility (wxWidgets, gtk, qt). ie. look at glade (gtk gui builder): http://glade.gnome.org/ -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl Give your children these two things. One is roots, the other, wings. From lashkariNO at SPAMworldviz.com Thu Nov 11 13:51:03 2004 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Thu, 11 Nov 2004 18:51:03 GMT Subject: Problem flushing stderr in embedded python References: <1100065836.697971@yasure> <1100156058.567069@yasure> Message-ID: Well I've somewhat solved my problem. First off, the 'y' problem was just an error I purposely created in order to trigger an exception. My application uses a bunch of calls to PyObject_Call to run python code. After each of these calls I added: if(PyErr_Occurred()) PyErr_Print(); This will force the errors to be printed to stderr, and now calling the flush method on the stderr object works. I still don't understand why running the string "sys.stderr.flush()" is different. Maybe it forces any current errors to be printed and then flushes them too. My app doesn't replace the python stderr object either. Anyways, thanks to everybody for your help and suggestions. -Farshid "Donn Cave" wrote in message news:1100156058.567069 at yasure... > Quoth "Farshid Lashkari" : > ... > | I've tried calling fflush on stderr, but that doesn't work either. > > OK, this would seem to mean that your sys.stderr has been replaced > with something else. I guess I don't know for sure what you can > count on in Windows, but I would have to expect that fflush on stderr > really does work - that is, it flushes stderr's buffer. > > | I've encountered another weird problem also. If my python code causes an > | error and I don't flush stderr, then I get a runtime error when my app > | exits. It also prints out: > | > | Exception exceptions.NameError: "global name 'y' is not defined" in 'garbage > | collection' ignored > | Fatal Python error: unexpected exception during garbage collection. > | > | Does this give anybody a clue as to what's happening? > > Doesn't do anything for me, but you may find out what that is when you > locate the code for the faux stderr you're (not) flushing. I would be > more worried about this 'y' thing in principle, though, because it sounds > like a problem in the C (or whatever) to Python interface that could have > other unpleasant consequences. > > Donn Cave, donn at drizzle.com From zanesdad at bellsouth.net Wed Nov 10 14:20:13 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 10 Nov 2004 14:20:13 -0500 Subject: get element text in DOM? In-Reply-To: <419269BE.6040903@bellsouth.net> References: <1100113869.1638.9.camel@swdb> <419269BE.6040903@bellsouth.net> Message-ID: <419269ED.6020009@bellsouth.net> Sorry - my send finger got a little trigger happy. Let's try again. Jeremy Jones wrote: > Juliano Freitas wrote: > >>How can i get the text between the tags?? >> >> >> >>>>>xml = """ texto """ >>>>>from xml.dom import minidom >>>>>document = minidom.parseString(xml) >>>>>document >>>>> >>>>> >> >> >> >>>>>minidom.getElementsByTagName('teste') >>>>> >>>>> >> >> >> >>>>>element = document.getElementsByTagName('teste') >>>>>element >>>>> >>>>> >>[] >> >> >>>>>element[0].nodeType >>>>> >>>>> >>1 >> >>Juliano Freitas >> >> >> >> > How about something like this: > > > In [24]: from xml.dom import minidom In [25]: x = """ texto """ In [26]: document = minidom.parseString(x) In [27]: print document.documentElement.getElementsByTagName('teste')[0].childNodes[0].data -------------- next part -------------- An HTML attachment was scrubbed... URL: From rkern at ucsd.edu Thu Nov 25 00:35:24 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 24 Nov 2004 21:35:24 -0800 Subject: Use Python library from C++ In-Reply-To: <89cc6e1f.0411241939.61a19596@posting.google.com> References: <89cc6e1f.0411241939.61a19596@posting.google.com> Message-ID: Chang LI wrote: > I want to use the Python Libray from my C++ program. > The Python Libray is no GUI. How can I mix C++ and > Python? > > One way is to run PY library as an independent process. > Another way is to start PY as a C++ thread. > The third way is to run Python engine as part of the C++. > Which way is better? > > No intention to access all the Python's code but only > access APIs of a module. Try Elmer. http://elmer.sf.net -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Wed Nov 24 14:44:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 24 Nov 2004 19:44:52 GMT Subject: Python's annoyance. In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Wed, 24 Nov 2004 19:03:26 GMT, Steven Bethard wrote: > >>While I'm not a fan of the decorator syntax or the $syntax in >>string.Template, you're not forced to use either of these: > > You may not be forced to write them [snip] > it is likely that you will be forced to *read* them. [snip] > the argument "If you don't like that feature, don't use it" is > relatively meritless. Well, it's certainly true that reading code is often a more important concern, but I'm not sure I agree that the issue's as black and white as you seem to want to draw it. If 90% of people don't use the features, then I only have to read them 10% of the time. So the more people I convince not to use the feature, the less code that gets written with the feature, and the easier my reading gets. ;) Of course, I still have to be able to read both syntactic variants, but I don't have to read them *all the time*. If I have to look up an unfamiliar variant occasionally, I don't see this as any worse than having to look up a library module's functions occasionally[1]. Steve [1] Since string.Template *is* a library module, I don't see looking up what the $-syntax means as being any worse than, say, reading the re module docs again (which I have to do pretty much every time I decide to use regexps). From fake at not-real.bogus Wed Nov 10 18:08:08 2004 From: fake at not-real.bogus (Matt Garman) Date: Wed, 10 Nov 2004 23:08:08 GMT Subject: saving curses screen state (putwin() and getwin() again) References: Message-ID: On Wed, 10 Nov 2004 13:04:09 -0600, Mike Meyer wrote: > > This works as described the *first* time, but subsequent calls to > > getwin() return the window that was saved with the first call to > > putwin(). I.e., it's as though only the first call to putwin() has > > any effect. > > Yes. Show us some code, please. There are any number of bugs that > could cause this behavior, and it'd be easier to narrow things > down if we knew what you were actually doing. I was hoping that the error was well-known or obvious and that wouldn't be necessary. Anyway, I posted some code that exhibits this behavior on my website, http://www.raw-sewage.net/ Specifically, download the following files (and save in a common directory): http://raw-sewage.net/newwin.py http://raw-sewage.net/curseschooser.py http://raw-sewage.net/cursescolors.py Then run the script "newwin.py". You are initially presented with an option menu; the selection is controlled by either the up and down arrow keys or 'j' and 'k'. Example run to duplicate buggy behavior: 1. Run newwin.py, arrow down to option '3', press enter 2. The screen will redraw; press 'q' to go back to the menu 3. The screen should appear in the state you left it when you pressed enter from the option menu (i.e. choice 3 selected) 4. Now choose option 5, press enter 5. The alternate screen appears, press 'q' to quit it 6. Now, the screen will re-draw as it did in step (3) above, i.e. choice 3 is highlighted, *not* choice 5 where you left off 7. But, if you use the up/down arrow keys, you'll realize that the option menu thinks it left off on choice 5 (even though it's not highlighted). The behavior is consistent on my Linux box, running the following version of Python: Python 2.3.4 (#1, Oct 17 2004, 14:17:06) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Thanks again! Matt -- Matt Garman email at: http://raw-sewage.net/index.php?file=email From ville at spammers.com Wed Nov 24 13:12:50 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Nov 2004 20:12:50 +0200 Subject: teaching OO References: Message-ID: >>>>> "Gabriel" == Gabriel Zachmann writes: Gabriel> My question now is: do you think I should switch over to Gabriel> Python completely (next time), and dump all the Gabriel> interesting issues involved in C++'s virtual classes, Gabriel> overloading, and templates? (In Python, all of that would Gabriel> just disappear ... ;-) ) I don't think virtual classes (as in inheriting from base classes "virtually" to avoid a certain multiple inheritance problems) is all that important in this single inheritance favouring world. The concept of overloading is easy, you can go one step further by introducing generic functions / multimethods through one of the modules floating around the net. -- Ville Vainio http://tinyurl.com/2prnb From bokr at oz.net Sat Nov 27 18:59:08 2004 From: bokr at oz.net (Bengt Richter) Date: Sat, 27 Nov 2004 23:59:08 GMT Subject: Subclassing complex with computed arguments References: Message-ID: <41a90c3c.1191007398@news.oz.net> On 25 Nov 2004 14:30:18 -0800, pcolsen at comcast.net (Peter Olsen) wrote: >I want to define a class "point" as a subclass of complex. > >When I create an instance > >sample = point() > >I want "sample" to "be" a complex number, but with its real and >imaginary parts computed in point()'s __init__ function with their >values based on the arglist. I want to compute with point instances >as though they were native complex numbers, but I want to be able to >define some new methods and over-ride some of complex's existing ones. > >This is probably very simple, but it hasn't been simple to me. > >Please feel free to flame me with RTFM as long as you also tell me >where in TFM to R. > >If you respond, please send a copy directly to me. I seldom have >access to this group. (My primary network isn't connected to the >internet.) > Well, let us know how it goes, and maybe tell the curious what your application is ;-). BTW, as others have explained, the initialization of values is done via complex.__new__, not via __init__. You can override that too, but I just let it be inherited to do its normal thing. The following is a way to automate wrapping complex so as to return point instances from the various operations. Not tested beyond what you see, and it won't be a speed demon, but might be something to explore your concept with. If you want to add special methods, you can do it like __repr__ and __coerce__ in the example, or you could add them after. Or you could use a proper metaclass instead of doing it the function way. Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class point(complex): ... """complex wrapper subclass point""" ... def __metaclass__(cname, cbases, cdict): ... P = type(cname, cbases, cdict) ... def mkm(name, func): ... def m(*args): return P(func(*args)) ... m.__name__ = name ... return m ... for name, func in complex.__dict__.items(): ... if callable(func) and name not in ['__coerce__', ... '__doc__', '__float__', '__getattribute__', '__getnewargs__', ... '__hash__', '__int__', '__long__', '__new__', '__repr__', ... '__str__', 'imag', 'real']: ... setattr(P, name, mkm(name, func)) ... def __coerce__(self, other): return self, P(other) ... P.__coerce__ = __coerce__ ... def __repr__(self): return ''% complex.__repr__(self) ... P.__repr__ = __repr__ ... return P ... >>> p = point(3, 4) >>> p >>> p+1 >>> p-1 >>> 1-p >>> 1+p >>> p*p >>> p*p.conjugate() >>> abs(p) >>> print p, type(p), repr(p) (3+4j) >>> p.imag 4.0 >>> p.real 3.0 You can explore further, and fix the bugs ;-) I don't know what __getnewargs__ does, so I left it alone to be inherited. Regards, Bengt Richter From peter at engcorp.com Thu Nov 4 10:02:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Nov 2004 10:02:01 -0500 Subject: yet another recipe on string interpolation In-Reply-To: <4edc17eb.0411032219.659c1824@posting.google.com> References: <4edc17eb.0411032219.659c1824@posting.google.com> Message-ID: Michele Simionato wrote: > I was playing with string.Template in Python 2.4 and I came out with the > following recipe: > > def merge(*dictionaries): > """Merge from right (i.e. the rightmost dictionary has the precedence).""" > Do you have any comments? Suggestions for improvements? My only comment is about *your* comment, above. I would have called the behaviour described "merge from left". Maybe best just to cut out that part of the comment, and leave it as "merge where rightmost dictionary has precedence". Cute recipe though. :-) -Peter From loritsch at gmail.com Fri Nov 19 11:23:57 2004 From: loritsch at gmail.com (Michael Loritsch) Date: 19 Nov 2004 08:23:57 -0800 Subject: Wrapping a C library in Python References: Message-ID: Roy Smith wrote in message news:... > I've got a C library with about 50 calls in it that I want to wrap in > Python. I know I could use some tool like SWIG, but that will give me a > too-literal translation; I want to make some modifications along the way > to make the interface more Pythonic. > > For example, all of these functions return an error code (typically just > errno passed along, but not always). They all accept as one of their > arguments a pointer to someplace to store their result. I want to > change all that to returning the result directly and throwing exceptions. > > I also want to mutate some of the return types. A common way these > functions return a set of values is a pair of arrays of strings, forming > key-value pairs. In Python, it would make sense to return this as a > dictionary. > > I know what I'm describing is kind of vague, but are there tools around > which might help automate (at least in part) this translation process? While SWIG is a strong tool for wrapping C code into many different langauges, there are definitely better tools out there for producing python modules from C code. I recommend both boost::python (http://www.boost.org/libs/python/doc/index.html) and ctypes (http://starship.python.net/crew/theller/ctypes/), but for very different reasons. If wrapped code speed and production of a binary is a goal in creating your python extensions, use boost::python. The price you pay for creating an fast binary python extension is coding your translation from python in C/C++ in C/C++ (I suppose you could get around this by creating a boost::python module, and then wrapping it with a python module to do the type translation). And in boost::python, C++ to python exception translation is supported. If speed of development is your main goal, then I'd use ctypes. ctypes will dynamically load the library in python code. At the python code level, you should then do the translation to python types. No C/C++ coding required. Hope this helps! Michael Loritsch From mwm at mired.org Thu Nov 4 23:00:15 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 04 Nov 2004 22:00:15 -0600 Subject: pep 336: Make None Callable References: <2-GdneEPltMGJBTcRVn-3g@comcast.com> Message-ID: The Eternal Squire writes: >> It would be more sensible to promote the addition to builtins of a >> predefined null function -- one somewhat equivalent to 0, [], and {}. > > I'd like to see it standardized, and I'd like to see it intuitively > obvious. That's why None appears to me to be such an obvious > candidate. How about nop? The real problem with allowing None to act as a function is that it turns exceptions into very obscure bugs. Actually, this argument applies to allowing one to do anything with None. So I'm against it, even in Python-3000. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rune.hansen at scanmine.com Fri Nov 12 05:07:34 2004 From: rune.hansen at scanmine.com (roderik) Date: Fri, 12 Nov 2004 11:07:34 +0100 Subject: idle on mac os 10.3.5 In-Reply-To: References: Message-ID: baza wrote: > Is there a version of Idle that works under Mac Panther? > > B Simple answer, yes. You'll need to get MacPython2.3 for panther from http://homepages.cwi.nl/~jack/macpython/download.html Install it and launch /Applications/MacPython-2.3/PackageManager. Install tkinter. You may, or may not - can't remember, have to install TclTkAqua-8.4.7 from http://tcltkaqua.sourceforge.net/ regards /rune From neil.benn at gmail.com Sun Nov 7 12:57:12 2004 From: neil.benn at gmail.com (Neil Benn) Date: Sun, 7 Nov 2004 17:57:12 +0000 Subject: remove assert statement (Was: Re: PEP new assert idiom) In-Reply-To: <20041107130209.GA3318@nl.linux.org> References: <7xr7n62t0v.fsf@ruckus.brouhaha.com> <7xy8hep325.fsf@ruckus.brouhaha.com> <20041107130209.GA3318@nl.linux.org> Message-ID: Hello, While I get what you are talking about - I think you are missing the point of an assert function. If you document an assert (which you should do) you are saying :- if you give me something which follows these rules, then I will do this - thankyouverymuch. In both Java and Eiffel, you have the option to compile the code without the assert checking in - giving you a tight debug stuation and a looser and faster run-time situation (as long as your code is tested and robust). However Eiffel's require and ensure are Assert statements on steroids!! A classic text on this is by Bertrand Meyer - the inventor of Eiffel. Although Eiffel's philosophy is very different than python's it's a classic text. Here's a link to a short article about it : http://archive.eiffel.com/doc/manuals/technology/contract/ Cheers, Neil On Sun, 7 Nov 2004 14:02:09 +0100, Gerrit wrote: > Paul Rubin wrote: > > "Raymond Hettinger" writes: > > > Why do you need a statement for this? > > > IMO, a plain function will do the trick: > > > > I do write such functions sometimes, but using a statement is more > > natural. That's why the assert statement exists, for example. > > I think 'assert' being a statement is on Guido's regrets list. exec and > print are on his regrets list: both should have been a function. I > think the same holds for assert, although I'm not sure. > > > statement is very great, and I find myself doing it all the time > > thinking I'll clean it up later. So I think having a statement for > > runtime checking would be in the correct spirit. > > In my opinion, assert is almost useless. It can sometimes be useful for > debugging purposes, but beyond that, it isn't. The exception raised by > 'assert' is always AssertionError. That is a major disadvantage, because > it's not specific. If a method I'm calling would raise an AssertionError > is some cases, and I want to catch it, I'm catching too much. Creating a > new exception-class and raising that one is better because of this. > > I don't see the use of a statement like > "assert isinstance(message, basestring)". It's by far the most common > use of assert: some assertions about the types of the arguments. This is > at best redundant. In the case of warnings.py, it's followed by > re.compile(message, ...). Removing the assertion in this example would result > in three differences: > - The error raised would be TypeError, not AssertionError. Therefore > it's more specific and thus easier to catch. > - The error would me raised by the re module, not warnings module > - The error would be "first argument must be string or compiled > pattern" instead of "message must be a string". Therefore, the > assertion makes it impossible to pass a compiled pattern instead > of a string. > > Duck typing eliminates the use of assert. > > In my opinion, assert should be deprecated and then removed in Py3K: > assertions are redundant, unspecific, and conflict with the philosophy > of duck typing and EAFP. > > What do others think of this? > > Gerrit. > > -- > Weather in Twenthe, Netherlands 07/11 13:25: > 12.0?C wind 3.6 m/s N (57 m above NAP) > -- > In the councils of government, we must guard against the acquisition of > unwarranted influence, whether sought or unsought, by the > military-industrial complex. The potential for the disastrous rise of > misplaced power exists and will persist. > -Dwight David Eisenhower, January 17, 1961 > -- > http://mail.python.org/mailman/listinfo/python-list > From mwm at mired.org Sun Nov 7 12:53:28 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 07 Nov 2004 11:53:28 -0600 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: Maurice LING writes: >>>>it is comparing versions that are YEARS out of date and use! >>> >>> Are the codebase of Python 1.5.2 and Java 1.1 totally replaced and >>> deprecated? >> For new development, yes, Python 1.5.2 has been totally replaced. >> There >> are legacy applications running in Python 1.5.2 that aren't worth the >> trouble to upgrade. >> >>> Lisp compiler is the 1st compiler to be created (according to the >>> Red-Dragon book, I think) and almost all others are created by >>> bootstrapping to LISP compiler. >> That's just silly. It is true that LISP was one of the pioneers of >> the >> compiled languages, but other compilers were not written in LISP. Almost >> without exception, compilers were all written in assembly language until >> Pascal came around. > > I'm wrong again. I suppose what I am trying to suggest is that design > decisions made in the last may have a longer effect than what we > consciously think. At least this is the impression I get while reading > James Gosling's argument that Java should be object-oriented from day > 1 (and not added onto the language, like in C++) in The Java > Programming Environment: A white paper. The design decisions about the syntax and grammar of the languages may have a longer effect (thought it's not clear how much of Java can be blamed on CPL). The design decisions about the implementation tend to vanish every time the language is implemented, and to vanish over time as an implementation evolves. I'd be surprised if all the 1.5.2 code has vanished from the complete python distribution. On the other hand, the core compiler and VM may well have been completely replaced since then. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From someone at microsoft.com Sat Nov 27 18:21:19 2004 From: someone at microsoft.com (Jive) Date: Sat, 27 Nov 2004 23:21:19 GMT Subject: A lock that times out but doesn't poll References: Message-ID: "Antoon Pardon" wrote in message news:slrncqdtc0.61m.apardon at rcpc42.vub.ac.be... > > What do you mean with a Zombie? The clock thread will remain for as long > as the timeout, which may be longer then needed but then they disappear, > so there won't be any real zombies. Whether you call them zombies or not, they can multiply like crazy and fll up system memory. From siona at chiark.greenend.org.uk Tue Nov 9 11:34:04 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Nov 2004 16:34:04 +0000 (GMT) Subject: sockets: How to know when your data is sent References: <4190e27f$0$95596$a1866201@visi.com> Message-ID: Grant Edwards wrote: >On 2004-11-09, Marc Ederis wrote: >> When I use the send function, it will >> happily send a buffer of a megabyte and more in one shot. But >> of course, the data is still in the network buffer... >> [ ... ] The >> problem is, how can I know when it's done? >Under Linux, there is no way to tell. IIRC, there's no way to >tell under BSD either. I actually wrote some kernel mode code >once upon a time to provide an ioctl() that I could call from >user space to find out when the data I had written to a socket >was actually sent. I may well be missing the point of the problem here, but wouldn't just turning TCP_NODELAY on guarantee that send() won't return until the last ACK has returned? And if you're not using TCP: >The way to tell that data has been sent is to use an >application-level protocol that acknowleges the data transferr. applies in spades if you care about reliability. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From andrea.valle at unito.it Tue Nov 2 18:27:05 2004 From: andrea.valle at unito.it (andrea valle) Date: Wed, 3 Nov 2004 00:27:05 +0100 Subject: pickling a dict In-Reply-To: <20041102083027.F7CC.JCARLSON@uci.edu> References: <783d0f8c.0411012330.4172d1d4@posting.google.com> <20041102083027.F7CC.JCARLSON@uci.edu> Message-ID: I was saving on a file three dicts, for a total of ca. 950 keys (that is: 24 kb). In order to reopen the file, first I read the three lines and used on each eval(item). This rude approach worked: but it took me some minutes to load the data. So I used pickle (and also cPickle) supposing it should be much more efficient. But it takes exactly the same. Is it normal? When I manipulate the loaded data ad draw the on screen the updated result, everything is very fast. This are my two methods bound to a tk view: def save(self, event): # first approach ## self.file = file("/Graph/default.gra", "w") ## self.file.write(str(self.model.verticesDict)+"\n") ## self.file.write(str(self.model.edgesDict)+"\n") ## self.file.write(str(self.model.trajectoryDict)+"\n") ## self.file.close() self.file= file("/Graph/pickle.gra", "w") pickle.dump(self.model.verticesDict, self.file) pickle.dump(self.model.edgesDict, self.file) pickle.dump(self.model.trajectoryDict, self.file) self.file.close() def open(self, event): # first approach ## self.file = file("/Graph/default.gra", "r") ## verticesDict = eval(self.file.next()) ## edgesDict = eval(self.file.next()) ## trajectoryDict = eval(self.file.next()) self.file = file("/Graph/pickle.gra", "r") verticesDict = pickle.load(self.file) edgesDict = pickle.load(self.file) trajectoryDict = pickle.load(self.file) self.model.setVerticesDict(verticesDict) self.model.setEdgesDict(edgesDict) self.model.setTrajectoryDict(trajectoryDict) Am I using pickle in a bad way? Or am I making some other mistake? Thanks -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From danperl at rogers.com Tue Nov 2 14:52:18 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 2 Nov 2004 14:52:18 -0500 Subject: general class functions References: Message-ID: "syd" wrote in message news:a76ba315.0411021009.46b06459 at posting.google.com... > Many many thanks, Andrea and Kent! > > To keep changes to calls in my current code to a minimum, I'm hoping I > can encode Andrea's "on-the-fly" get function. I added Andrea's > __getattr__ to my Library() class, populated the class with a few > nations, and tried: > >>>> library.get_continent('Europe') This line creates and returns an instance of Library. I assume that you imported foo in a python session and then you executed that line. That results in a call to Library.__repr__( ), which is not defined. First of all, I recommend you change class Library to subclass from object. That's just good practice in general and in this case it will give you a default __repr__( ) method. But that's probably not what you want. What you probably want is to still use a line like: print library.getContinent('Europe').getNameList() Otherwise, library.get_continent('Europe') is going to print something like: <__main__.Library object at 0x00A9F430> Dan > Traceback (most recent call last): > File "", line 1, in ? > File "foo.py", line 16, in __getattr__ > return self.__dict__[name] > KeyError: '__repr__' > > I then commented out lines 15 and 16... > #else: > #return self.__dict__[name] > > ... and re-ran. > >>>> library.get_continent('Europe') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'NoneType' object is not callable > > I tweaked a bit, but I could not get to the bottom of this problem. I > see the logic here (and it's brilliant I should add, Andrea), but I'm > not sure what is wrong. > > Ideas? From aleaxit at yahoo.com Sat Nov 6 16:25:58 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 Nov 2004 22:25:58 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> <418C7DCB.60502@acm.org> <62kv52-npq.ln1@home.rogerbinns.com> Message-ID: <1gmun13.6rynz217b0hm1N%aleaxit@yahoo.com> Roger Binns wrote: > Alex Martelli wrote: > > while ((c = in.read()) != -1) > > out.write(c); > > Incidentally, that Java code copies one character at a time. Yep, I noticed -- pretty silly, but if that's how the Java designers decided the read method should behave by default, who am I to argue? Just an example I grabbed off the net, first google hit for (if I recall correctly) java file reading that had the source of a complete example. > > outputFile.write(inputFile.read()) > > The Python code is reading the entire string into memory and > then writing it. Right, _Python_'s default. > The interpretter overhead vs system calls could be measured > by having the language involved in every byte transferred as > in the Java example, or negligibly as in the Python example. The claim posted to this newsgroup, without any support nor examples being given, was that Python's I/O was far slower than Java's in _disk-intensive_ operations. I'm still waiting to see any small, verifiable examples of that posted on this thead. Apparently, at least in default operations on both sides, based on calls to read without parameters, that is definitely not the case - no doubt, as you say, that's because of the different ways those defaults are tuned, making Python much faster. Great, then let those who claim Java's I/O is much faster in disk intensive operation post suitable examples, and we'll see. > Whenever anyone has an agenda, you can make all sorts of silly > claims. IMHO the best thing to do is to lead by examples. I posted examples -- probably not "leading" ones, just one grabbed off the net using Java's defaults, and one using Python's defaults. I'm not the one making any claims regarding I/O performance of _properly tuned_ disk-intensive programs -- what I would like to see would be some such examples posted by those who DO make such claims. Shouldn't the burden of proof lay on the side making positive assertions, by ordinary rules?! > For years many people claimed Perl was line noise, hard to > maintain etc. I never really saw much response, since the > Perl people were too busy writing real world code and helping > deliver part of the web revolution. (And selling zillions of > books for O'Reilly :-) Surely more than we have sold so far with Python, yes - Tim O'Reilly has published data about that. Which is why I'm striving to _worsen_ the quality of Python's free docs until they match Perl's, against heathens who (can you imagine that!) are instead trying to *improve* them further (thus no doubt hurting book sales). > I couldn't find any Python success stories on python.org itself, > but if you dig you can find the stories for the Python Business > Forum as well as Pythonology. Lots of digging, yes, considering that if you google for python success stories those pbf and pythonology hits are just at the top (other similar links, such as those to O'Reilly's booklets covering the same material and their PDF forms, make up the rest of the top-ten pages). > There are however remarkably few where you can go grab the > source code and see how it is all put together. In fact I > couldn't find a single one, but didn't do an exhaustive > search from python.org. Without straying from the top google hit, you can find that some of the listed success stories are open-source, such as mayavi -- they're admittedly a minority of the "success stories" listed on these sites. > Perhaps it is also worth linking to the projects done in > Python on SourceForge and elsewhere? > > http://sf.net/softwaremap/trove_list.php?form_cat=178 If the message you're keen to send is "Python is great for open-source", yes. If you're focusing on "Python is great for your _business_" (as the python *business* forum does, for example), then emphasizing open-source projects can reasonably be considered secondary to emphasizing projects that make or save money for the businesses which developed them. If you're looking for highly visible open-source projects using Python, I'd think that bittorrent, chandler, zope and plone, mayavi, all the scipy.org site, twisted, schooltool, ubuntu, and the like, should keep you in reading materials for a while. Not sure how many of these projects are specifically on sourceforge, but I believe some minority probably is. Alex From peter at engcorp.com Wed Nov 3 09:18:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Nov 2004 09:18:14 -0500 Subject: threads and exception in wxPython In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2004-11-02, Zunbeltz Izaola schreef : > Yes they can. Unfortunately in order to protect us from ourselves > the powers that be, decided to only allow this to people who know C > and have access to a C compilor. > > int PyThreadState_SetAsyncExc( long id, PyObject *exc) There was a comment by someone that perhaps ctypes would allow calling this directly. I don't know whether that's possible, but if it is it's probably a fairly simple operation. I've used ctypes in a fairly limited fashion, so I suspect it would take me a while to figure it out, but this much works anyway: >>> import ctypes >>> py = ctypes.dll.python23 >>> py.PyThreadState_SetAsyncExc Presumably the "id" above is a non-issue, but I think you need to do something more complex to get a PyObject reference to an exception in ctypes... not yet in my repertoire. A quick test gave this when trying the brainless approach, with t being a thread and exc a KeyboardInterrupt instance. >>> py.PyThreadState_SetAsyncExc(id(t), byref(exc)) Traceback (most recent call last): File "", line 1, in ? TypeError: expected CData instance Anyone? Anyone? Bueller? -Peter From wgshi at namao.cs.ualberta.ca Thu Nov 25 16:22:22 2004 From: wgshi at namao.cs.ualberta.ca (Weiguang Shi) Date: Thu, 25 Nov 2004 21:22:22 +0000 (UTC) Subject: dictionary initialization References: Message-ID: Hi, In article , Caleb Hattingh wrote: > ... > *** > # You *must* use a={}, just start as below > '>>> a={} Yeah I know. I can live with that. > '>>> a['1']=0 > '>>> a['1']+=1 Right here. You have to say a['1'] = 0 before you can say a['1'] +=1 Python does not do the former for you. That's what I'm asking justifications for. Regards, Weiguang From R.Brodie at rl.ac.uk Tue Nov 16 08:45:15 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 16 Nov 2004 13:45:15 -0000 Subject: HTMLParser problem References: <1100610863.75889@eng-ser4> Message-ID: "Valkyrie" wrote in message news:1100610863.75889 at eng-ser4... > > > HTMLParser.HTMLParseError: unknown declaration: 'if !IE', at line 4, column 1 > > May I ask why such error is raised? HTMLParser isn't very forgiving of bad HTML; you feed it syntactically invalid HTML, it tends to give you errors. That includes Microsoft only extensions like Message-ID: <4edc17eb.0411042031.65b84885@posting.google.com> Peter Hansen wrote in message news:... > My only comment is about *your* comment, above. I would > have called the behaviour described "merge from left". > Maybe best just to cut out that part of the comment, and > leave it as "merge where rightmost dictionary has precedence". Ok. > Cute recipe though. :-) Thanks ;-) I was asking for comments about the performance of this approach and/or design choices: for instance, in the case an explicit dictionary is passed, it could make sense to use it for interpolation, without merging it with the locals and globals. I could add a default argument to set this behavior, but I am not sure if this is worthwhile ... Michele Simionato From caleb1 at telkomsa.net Fri Nov 26 20:46:47 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Fri, 26 Nov 2004 20:46:47 -0500 Subject: Delphi underrated, IDE clues for Python References: Message-ID: I have been using Delphi 6 at work for several years now (python where I can squeeze it in!). As a programming environment, Delphi is *awesome*. Sure, it's statically typed. Sure, it's proprietry. Sure, it is Windows-based. BUT as an IDE, the Delphi environment is amazing. What I want in a Python IDE is the Delphi ide, but with python as the language. The *code-insight*, code/class completion, integrated debugging, integrated help, and *incredibly* fast GUI design is a killer combination. We actually use Delphi mostly for numerical stuff (chemical reactor modelling), and find its runtime speed is pretty good. The other amazing thing is that Delphi exhibits the fastest compilation I have seen in a native optimising compiler. Working with it is almost like working in an interpreter. So why is my wish to use Python if I think Delphi is so great? Because Python is dynamic and compact while still easy to read (although decorators have curbed my enthusiasm a little). Python is just a better language. ObjectPascal syntax is very verbose (compared to Python). The Delphi IDE minimizes this issue to great extent with several code-completion mechanisms, but I tried to use FPC several days ago (without Lazarus), and couldn't type up a simple unit without referring the docs - After having used Delphi for 5 years! I was 80% productive in Python after reading the tutorial *once* (but probably not with the most optimal code). STILL...Having a Delphi-like IDE for Python would make me giddy. I know there are several ever-improving options out there already...I guess I am waiting to see which one floats to the surface. I also tend to want to use Tk because it is the 'standard' while the more exciting work seems to be with the other toolkits, wx, GTK, etc. I am keen to see what becomes of Tk3000 though. Thanks Caleb On Thu, 25 Nov 2004 20:11:47 -0800, Tim Roberts wrote: > Carlos Ribeiro wrote: >> >> I think that Delphi is *so* underated when it comes to language & >> framework design... Delphi suffered from a couple of problems; first, >> it was Pascal's child, and not C; also, because it was a proprietary >> project, owned by a single company. >> >> For some reason, being a Pascal descendant was regarded as a big "no" >> by a huge part of the industry, not to mention academia, that was at >> that time fascinated with the prospect of C++. I wonder what could >> have happened if Delphi (maybe with another name -- P++ anyone?) was >> widely adopted instead of C++ for big projects... > > You are absolutely correct. I have never understood the industry > prejudice > against Delphi. The code is just as efficient as the typical C compiler. > GUI design in the IDE has always been easier in Delphi than in Visual > Studio. VCL is easier to understand than MFC From jgrahn-nntq at algonet.se Sun Nov 14 02:40:11 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 14 Nov 2004 07:40:11 GMT Subject: Advice needed References: <1100361297.413616.17890@f14g2000cwb.googlegroups.com> <58494099.0411131402.57e9aec5@posting.google.com> Message-ID: On 13 Nov 2004 14:02:08 -0800, Chad Crabtree wrote: > "Alberto" wrote in message news:<1100361297.413616.17890 at f14g2000cwb.googlegroups.com>... >> I was trying to understand the reasons why I should learn Python. More >> like a pros/cons about this language. Currently, I use C, C/C++, Java, >> Perl, Visual VB and was looking to see the usefulness of Python. Any >> suggestions? > > Well if you have all those languages then I don't think there's any > real reason to spend the time learning python. Except if a cooler > object system, minimialistic syntax, and a groovy community are > important to you then perhaps you should learn python. IMHO there are always reasons to learn new languages, especially if they are as simple as Python. Could be hard though if all the OP's work is closely tied to the languages on the list above (Java seems especially good at building a whole Java-only world around it). Some openings I see: - There's no language with dynamic typing on his list (except maybe C++ templates and advanced Perl, if the OP is into that). - There's no language that's easily embedded as an internal scripting language in the OP's list. - If the OP doesn't really know Perl all that well, Python is a better fit for most perlish things. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From pastor.gabriel at wanadoo.fr Tue Nov 16 07:33:43 2004 From: pastor.gabriel at wanadoo.fr (Gabriel PASTOR) Date: Tue, 16 Nov 2004 13:33:43 +0100 (CET) Subject: xmlrpclib - error marshalling new-style classes Message-ID: <24053689.1100608423575.JavaMail.www@wwinf0602> I'm trying to send object using xmlrpclib, but it seems that classes inheriting from object cannot be marshalled. Here is an example: -------- server.py -------- import xmlrpclib, SimpleXMLRPCServer class MyObject(object): def __init__(self,name): self._name=name def getMyObject(name): obj = MyObject(name) return obj if __name__ == "__main__": server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888)) print 'server running on port 8888' server.register_function(getMyObject) server.handle_request() ---- client.py ------ import xmlrpclib, SimpleXMLRPCServer server = xmlrpclib.ServerProxy("http://localhost:8888") obj = server.getMyObject('john') print obj I get the following error xmlrpclib.Fault: objects"> And if the class MyObject doesn't inherit from object then the program runs correctly. I have this problem using python 2.3 and the problem is exacltly the same with python 2.4 beta1 Am I doing something wrong or is it a bug in xmlrpclib ? Regards, gp From jfouhy at paradise.net.nz Thu Nov 18 20:46:31 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 18 Nov 2004 17:46:31 -0800 Subject: Floating point -> string conversions References: Message-ID: Steve Holden wrote in message news:... > The fact that %s coerces things makes us expect more of other format > tokens, but what would you expect %d to do with 2147483648.5? I'd expect it to give me "2147483648", since that would be consistent with its other behaviour :-) (eg: eval('"%d" % 1.5') == '1') I guess what annoys me is that python encourages you to not worry about the difference between ints and longs (which is great) (unless you're doing high performance computing), but then something like this can cause code to stop working just because you've passed a border which is almost invisible. (of course, this means that one solution which I would be happy with is for python to reject any non-integer/long arguments to "%d" :-) ) -- John. From steve at holdenweb.com Tue Nov 16 12:04:24 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Nov 2004 12:04:24 -0500 Subject: cgi.FieldStorage() is slow In-Reply-To: <20041116085406.00001ef4@nehal> References: <20041116085406.00001ef4@nehal> Message-ID: <419A3318.4080004@holdenweb.com> Nehal wrote: > On Tue, 16 Nov 2004 07:40:17 -0500 > Steve Holden wrote: > > >>The cgi module is a confusing mess of code munged, over the >>years, by many hands. It would take a brave programmer to plunge >>in and do what's necessary. >> >>not-brave-enough-ly y'rs - steve > > if i were to do it, could i rewrite the functions in the cgi > module?, or would i need to keep the same functions for backward > compatibility? > -- Nehal > > Well, code breakage is regarded as pretty bad, so you would need to retain the same interfaces that the module supports now. Of course you could implement them completely differently, as long as they worked the same, and you could add new interfaces as well. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From bokr at oz.net Fri Nov 5 03:14:00 2004 From: bokr at oz.net (Bengt Richter) Date: Fri, 05 Nov 2004 08:14:00 GMT Subject: Has anyone released a Python "mock filesystem" for automated testing? References: Message-ID: <418b257b.1662187619@news.oz.net> On Thu, 04 Nov 2004 21:31:04 -0500, Peter Hansen wrote: >The term "mock filesystem" refers to code allowing unit >or acceptance tests to create, read and write, and manipulate >in other ways "virtual" files, without any actual disk >access. Everything is held in memory and therefore fast, >without risk of damaging real files, and with none of the >messiness of leftover files after testing. > >Googling the archives and the web suggests that only I and >Remy Blank have done much along these lines. I don't see >any sign that anyone has actually released such a beast >yet, however. > >My own past work in this area was always proprietary, and >as "you can't take it with you" I've been starting over >on a new project and have the basics working. If nobody >can point me to a more complete implementation, I'll be >happy to continue to work on mine and release it in the >near future. > >For now, in case anyone is interested, I have support >for basic open, read/write, __iter__, close, "r" and "w" >modes, a couple of the most basic exceptions, and a >tiny handful of lesser things. All well supported by >their own unit tests, of course, to ensure quality. >Stripped class/def lines shown below, as that may be >an easier way for you to picture what this is about: > >class MockFile(object): > def __init__(self, fs, path, data='', mode=''): > def _getContents(self): > def read(self): > def write(self, data): > def close(self): > def __iter__(self): > > >class FileSystem(object): > '''Acts like a real file system to support testing.''' > def __init__(self, mocktime=False): > def _createFile(self, path, data): > def _getFile(self, path): > def open(self, path, mode='r'): > >Thanks for any pointers to more advanced stuff. > In a recent post, I suggested a way to virtualize selected files or glob-pattern sets of files specified by string. The idea was/is to make open and/or file check whether the path it's being passed has been registered in a hook registry of substitute classes or factory functions to be called instead of the normal file builtin functionality, so that the returned object is an instance of _your_ registered custom class. "Registering" might be as simple API-wise as sys.filehook['filename.ext'] = MockFile (to use your example ;-) *args, **kw would be passed to Mockfile and the resulting instance would be passed back to the caller of file, so e.g. file('filename.ext', 'rb').read() would have the effect of Mockfile('filename.ext', rb').read() Of course there are a bunch of other file things that might have to be supplied if you wanted to virtualize using low level os.open & friends. Re a whole file system virtualization, I tried to float that one time long ago, but got no enthusiasm, even though I only wanted to introduce a virtual branch of the root. If you do do something with a VFS, IMO it should be mountable and require mounting. Maybe unix-style mapping of the file tree like msys does for windows would allow mounting in a platform-independent way, referring to c:\some\path\ as /c/some/path/ and so forth. Not sure about virtualizing fstab... I guess you could do os.filehook['fstab'] = Something to feed something special to the mount. With a mount command you could also specify text file cooking or not, etc. Just stirring the pot, but I think it would open up some different testing possibilities ;-) If the hook really hooks well, I would think you could write sys.filehook['foo'] = __import__('StringIO').StringIO("print 'hi from dummy foo.py'\n") import foo and expect a greeting (the first time)(untested ;-) I guess it depends on where i/o funnels back to common layer interfaces. Regards, Bengt Richter From elbertlev at hotmail.com Sat Nov 27 09:59:55 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 27 Nov 2004 06:59:55 -0800 Subject: 1 file, multiple threads References: <41a7000c$0$16489$4d4ebb8e@news.nl.uu.net> Message-ID: <9418be08.0411270659.9b163ad@posting.google.com> "Guyon Mor?e" wrote in message news:<41a7000c$0$16489$4d4ebb8e at news.nl.uu.net>... > If I have multiple threads reading from the same file, would that be a > problem? > > if yes, how would I solve it? > > Let's say I want to take it a step further and start writing to 1 file form > multiple threads, how would I solve that? > > > thanx, > > Guyon The sort answer: yes you will. The long: how it will hurt you, depends on OS, the sequence of operations and the kind of operations. If you read "next line" (or something like this) or read data from random positions, using lock/unlock around seek/read, will solve the problem (and maybe defeat the multithreading gain). Anyway writes may be not seen by readers. Remember, that for each file OS has one read position and one write position. For writing from multiple threads you also needs lock/unlock guard. You really would be better off if you use Queues in all threads From jeff at ccvcorp.com Thu Nov 11 15:02:19 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 11 Nov 2004 12:02:19 -0800 Subject: Summary: strong/weak typing and pointers In-Reply-To: <60dfb6f6.0411102119.2091c0d@posting.google.com> References: <2uqvd6F2dn4seU1@uni-berlin.de> <60dfb6f6.0411050715.601f381f@posting.google.com> <2v82u3F2dhtcpU1@uni-berlin.de> <10p1ud2juqlkb7c@corp.supernews.com> <60dfb6f6.0411101037.5cd6a17d@posting.google.com> <10p52ccen1ql956@corp.supernews.com> <60dfb6f6.0411102119.2091c0d@posting.google.com> Message-ID: <10p7h4rphhpg64c@corp.supernews.com> Carl Banks wrote: >Jeff Shannon wrote in message news:<10p52ccen1ql956 at corp.supernews.com>... > > >>On the other hand, I personally think that "rigid/fluid" make a better >>metaphor specifically *because* they are not tied so much to physical >>properties >> >> > >Just to nitpick: something with a vague meaning really isn't a >metaphor so much as a literal description in a different sense of the >word. > > From www.m-w.com, "metaphor" is: *1* *:* a figure of speech in which a word or phrase literally denoting one kind of object or idea is used in place of another to suggest a likeness or analogy between them (as in /drowning in money/); /broadly/ *:* figurative language -- compare SIMILE Please note that the use of the phrase "rigid guidelines" is indeed figurative language. One is figuratively likening the strict adherence to a set of rules to the physical property of inflexibility. I also disagree with your assertion that rigid has a vague meaning. It has a *very* specific meaning, and that meaning is "lacking flexibility" (again from www.m-w.com -- "*1 a* *:* deficient in or devoid of flexibility"). And for the record, "solid" has more alternative definitions in said dictionary than "rigid" does. >If you don't like how the word solid is tied to material properties, >then it seems to me that your real problem with it is that you just >don't like metaphors. Personally, to me, it doesn't matter too much. >I am equally comfortable with either metaphorical or literal >descriptions. > > On the contrary, I'm quite comfortable with metaphor. However, I completely disagree with your assertion that "rigid rules" is not a metaphorical usage of the word "rigid". It is an entirely standard and commonplace usage, yes, but that does not make it non-metaphorical. Everyday language can be (and often is) figurative, too. >If you paid attention >in your study of grammar, [...] > Please don't assume that someone who disagrees with you is either uneducated or stupid. It's rather insulting and wholly inappropriate. >OTOH, solid has a specific (literal) meaning that is very analogous to >its proposed use (hence its suitability as a metaphor). Thus it >qualifies as a name much better than rigid does. > > On the other hand, I could posit that "solid typing" could be seen as implying that objects are opaque black boxes, and thus that it's related more to data-hiding than to lack of type coercions. I'm not convinced that the physical property of solidity is a more compelling metaphor, and is less prone to alternative interpretations, than the physical property of rigidity. Indeed, after looking at the dictionary definitions of both words, I find the case for "solid" to be even *more* vague. The first given definition of "rigid" as "lacking flexibility" leads one immediately to the idea that is being discussed here. "Solid", on the other hand, has a first definition of "being without an internal cavity" -- how does *that* relate to types? And your attempts to simply repeat your assertions while insulting me don't make your argument any more convincing. Jeff Shannon Technician/Programmer Credit International From jerry at jerrysievers.com Sat Nov 27 11:33:55 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 27 Nov 2004 11:33:55 -0500 Subject: Replacing words from strings except 'and' / 'or' / 'and not' References: <41A5EFA9.5030907@arcor.de> Message-ID: Alexandre Cecchi writes: > > Hi there, > > > > Background of this question is: > > I want to convert all words except 'and' / 'or' / 'and not' from > > a string into '**'. > > Hello, > > def do(s): > L = [] > for x in s.split(): > if x in ('or','and'): > L.append(x) > elif x == 'not' and L and L[-1] == 'and': > L.append('not') > else: > L.append("'*%s*'" % x) > return ' '.join(L) > > I think that it is more readable, maybe not faster, elegant I don't know =) > print 'Yeahh it was my first post on the list.' > > bye. Might as well throw in a recursive approach, eh? excludedWords = {'foo': 1, 'bar': 1} def fixEmUp(list, result = []): x = list.pop(0) result.append('*' * int(x not in excludedWords) + x) if not list: return result return fixEmUp(list, result) Takes a list of words and returns the same list with the words not in excludedWords with the * prepended. (Original poster's professor is going to ask for this eventually... :-) A very easy way might be to use REs with negative look-ahead on the excluded words. Peace -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From exarkun at divmod.com Sun Nov 28 15:08:35 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 28 Nov 2004 20:08:35 GMT Subject: The use of : In-Reply-To: Message-ID: <20041128200835.17481.1655588139.divmod.quotient.9851@ohm> On Sun, 28 Nov 2004 19:17:52 GMT, gabriele renzi wrote: >Reinhold Birkenfeld ha scritto: > > > Without the ':', single-line suites are impossible. If you allow only > > multi-line suites, you're right. > > > > are they really? > if > and the likes would invho parse just fine if (a) (b) (c) Hmmm. Sure, you could parse that, but you'd have to make a wild, wild guess about what it means. Jp From jcarlson at uci.edu Thu Nov 25 12:52:05 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 25 Nov 2004 09:52:05 -0800 Subject: network programming without goto In-Reply-To: <20041125145353.89046.qmail@web41503.mail.yahoo.com> References: <20041125145353.89046.qmail@web41503.mail.yahoo.com> Message-ID: <20041125092843.FA17.JCARLSON@uci.edu> kent sin wrote: > > Please help: > > I was really blocked here. without goto I really do > not known how to do it. > > The problem is to use PyZ3950 to consult a lists of > hosts and for each of them to search for a list of > targets. Since the network is undetermined, there were > always some exceptions: I would like to allow it to > retry for 3 times. Moreover, during the query process, > the conn will timeout (set by the remote server). > Reconnect is preferred before fail the current search, > but the reconnect may fail even if the first try is > succeed. The trick with getting it to do what you want it to do is to understand what you want it to do. Being that I can't understand what you want it to do, the following is just an interpretation of what I think you want it to do. If you want it to do something different, then be clearer with what you want it to do and ask again. Note that depending on the semantics of your connection, this could probably be made more efficient. queries = [buildquery(t) for t in targets] for host in hostlist: tries_remaining = 3 #tunable parameter for q in queries: for i in xrange(tries_remaining+1): if i == tries_remaining: break try: conn = zoom.Connecton(host.ip, host.port) r = conn.search(q) conn.close() break except: continue #handle result r break tries_remaining -= i if tries_remaining == 0: break - Josiah From russblau at hotmail.com Tue Nov 9 16:45:06 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 9 Nov 2004 16:45:06 -0500 Subject: Packing list elements into tuples References: Message-ID: <2vcs36F2ju6jkU1@uni-berlin.de> "Nickolay Kolev" wrote in message news:cmrcqq$rv4$1 at f1node01.rhrz.uni-bonn.de... > Hi all, > > I have a list whose length is a multiple of 3. I want to get a list of > tuples each of which has 3 consecutive elements from the original list, > thus packing the list into smaller packets. Like this: > > l = [1,2,3,4,5,6,7,8,9] > > tups = [(1,2,3), (4,5,6), (7,8,9)] How's this? : >>> alist [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> tups = [tuple(alist[i:i+3]) for i in xrange(0, len(alist), 3)] >>> tups [(1, 2, 3), (4, 5, 6), (7, 8, 9)] > > if i can dictionaries it would be even better: > > > l = [1,2,3,4,5,6] > > tups = [ > {'first':1,'second':2,'third':3}, > {'first':4,'second':5,'third':6} > ] Well, now that you've been introduced to the concept of list indexes and list comprehensions, I think that extending it to dictionaries is fairly simple. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From ialbert at mailblocks.com Tue Nov 9 11:40:44 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 09 Nov 2004 11:40:44 -0500 Subject: possible to pass python objects into java without jython? In-Reply-To: References: Message-ID: Maurice Ling wrote: > Are there any way out in this? No. From peter at somewhere.com Wed Nov 17 05:27:48 2004 From: peter at somewhere.com (Peter Maas) Date: Wed, 17 Nov 2004 11:27:48 +0100 Subject: don't NaN & infinities hide FP errors In-Reply-To: <940ee3e8.0411170130.31d247@posting.google.com> References: <940ee3e8.0411170130.31d247@posting.google.com> Message-ID: kartik schrieb: > Since Python floats are implemented using C doubles, assuming IEEE 754 > compliance, certain operations should result in NaN or infinity. Don't > such special values hide errors? Would we want our variables to be in > such states? I feel it would be better if a floating point division by > zero (or other actions that produce NaNs or infinities) throws an > exception, just like an integer divide by zero. > > Am I right? Just try it. 1./0. raises a ZeroDivisionError, math.log(0) raises a math range error, and math.log(-1) yields nan. If you want math.log(-1) raise an error, too, you must write your own log() that tests for nan and raises a NaN error or write a trace function that looks for nan returned by math.log() (see sys.settrace()). -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From skip at pobox.com Thu Nov 25 10:27:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 25 Nov 2004 09:27:27 -0600 Subject: Replacing words from strings except 'and' / 'or' / 'and not' In-Reply-To: <41A5EFA9.5030907@arcor.de> References: <41A5EFA9.5030907@arcor.de> Message-ID: <16805.63967.731507.509398@montanaro.dyndns.org> Nico> Example: Nico> I have the following string: Nico> "test and testing and not perl or testit or example" Nico> I want to convert this string to: Nico> '*test*' and '*testing*' and not '*perl*' or '*testit*' or '*example*' Nico> Any idea, how to do this? Here's my shot at it: def decorate(s): words = s.split() # make "and not" a 'word' for i in range(len(words)-1,-1,-1): if words[i] == 'and' and words[i+1] == 'not': words[i:i+2] = ["and not"] special = ('and', 'and not', 'or') for word in words: if word in special: yield word else: yield "*%s*" % word s = "test and testing and not perl or testit or example" print " ".join(decorate(s)) Hoping I didn't just do your homework, I wish you a Happy Thanksgiving... Skip From sylvain.thenault at nospam.logilab.fr Thu Nov 4 08:21:55 2004 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Thu, 04 Nov 2004 14:21:55 +0100 Subject: ANN: New configuration module released References: <2e37dc1.0411030650.ff44840@posting.google.com> Message-ID: On Thu, 04 Nov 2004 11:00:32 +0000, Vinay Sajip wrote: > Sylvain Thenault wrote: >> the "configuration" module in logilab's common library is doing this (make >> a bridge between optparse and ConfigParser). You give a kind of >> configuration schema to a configuration object and then it can be >> initialized from a configuration file and/or command line. Environment >> variable are not considered yet, but I don't think it would be hard to add >> this feature. The main problem is the lack of documentation, but if there >> is some interest I can post an usage example. > > I'm interested to see how your bridging works. well, the basic idea is a class providing a (simple) unified api to register options and to read them from different sources, those methods taking care of optparse / ConfigParser particularities A basic example showing main functionalities : ---- begin example >>> import sys >>> from logilab.common.configuration import Configuration >>> >>> options = [('dothis', {'type':'yn', 'default': True, 'metavar': ''}), ... ('value', {'type': 'string', 'metavar': ''}), ... ('multiple', {'type': 'csv', 'default': ('yop',), ... 'metavar': '', ... 'help': 'you can also document the option'}), ... ('number', {'type': 'int', 'default':2, 'metavar':''}), ... ] >>> config = Configuration(options=options, name='My config') >>> print config['dothis'] True >>> print config['value'] None >>> print config['multiple'] ('yop',) >>> print config['number'] 2 >>> >>> config.help() usage: [options] options: -h, --help show this help message and exit My config: --dothis= --value= --multiple= you can also document the option --number= >>> >>> f = open('myconfig.ini', 'w') >>> f.write('''[MY CONFIG] ... number = 3 ... dothis = no ... multiple = 1,2,3 ... ''') >>> f.close() >>> config.load_file_configuration('myconfig.ini') >>> print config['dothis'] 0 >>> print config['value'] None >>> print config['multiple'] ['1', '2', '3'] >>> print config['number'] 3 >>> >>> sys.argv = ['mon prog', '--value', 'bacon', '--multiple', '4,5,6', 'nonoptionargument'] >>> print config.load_command_line_configuration() ['nonoptionargument'] >>> print config['value'] bacon >>> >>> config.generate_config() [MY CONFIG] dothis=no value='bacon' # you can also document the option multiple=4,5,6 number=3 ---- end example > Using the config module I released, access to environment variables is > very easy. Here's how: > > 1. Add the line > > os : `os` > > to your configuration (say, test.cfg). I think the idea was to ask in the configuration file to specify a value should be taken from an environment variable, but to get a value from an environment variable and / or from the configuration file. > 2. Access it like this: > >>>> from config import Config >>>> cfg = Config(file('test.cfg')) >>>> cfg.os.environ['OS'] > 'Windows_NT' > > The point, of course, is that you can refer to environment variables > from elsewhere in your configuration, e.g. > > temp_path: `os.environ['TEMP']` > work_file_prefix: $temp_path + `os.sep` I've one problem with this approach (other that the person writing the configuration file has to know python to benefit from your module). Is there something preventing things like : work_file_prefix: `os.remove('/etc/password')` -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From grante at visi.com Tue Nov 30 11:44:16 2004 From: grante at visi.com (Grant Edwards) Date: 30 Nov 2004 16:44:16 GMT Subject: pyserial with binary data References: <23ae7099.0411260218.7ff9119c@posting.google.com> Message-ID: <41aca360$0$85028$a1866201@visi.com> On 2004-11-26, alastair wrote: > When I send the data on windows everything is ok - on Linux I get the > following traceback: > > Traceback (most recent call last): > ... > File "/home/pythonCode/loader.py", line 155, > in serialWrite > ser.write(buffer) > File "/usr/lib/python2.3/site-packages/serial/serialposix.py", line > 288, in write > n = os.write(self.fd, d) > OSError: [Errno 11] Resource temporarily unavailable A patch that fixes this is available from the pyserial SF site. > Can anyone offer any pointers as to why this should happen ? It happens because the serial device driver returns -11. The Regular serial (16x50) driver doesn't do this and will buffer up to 4K, then block. For reasons known only to their authors, some serial drivers don't behave like that. If you try to write more than they can immediately send to the HW (a dozen or two bytes in the case I ran across with a Prolific USB->serial widget), they take as much as they can send and return immediately. If you then try to write more data, you get a return of -11. > I first thought that it might be because I was using binary > data, but the same happens when I tried a large ASCII data > file. Any ideas for a workaround appreciated :) Here's the bug: http://sourceforge.net/tracker/index.php?func=detail&aid=1043420&group_id=46487&atid=446302 Here's the patch: http://sourceforge.net/tracker/index.php?func=detail&aid=1043436&group_id=46487&atid=446304 -- Grant Edwards grante Yow! TATTOOED MIDGETS at are using ALFREDO in their visi.com SALAMI FACTORY! From imbosol at aerojockey.com Fri Nov 12 20:32:21 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 12 Nov 2004 17:32:21 -0800 Subject: permuting letters and fairy tales References: <67lld8kr76.fsf@aster.homelinux.net> Message-ID: <60dfb6f6.0411121732.2e0ac82c@posting.google.com> Johannes Nix wrote in message news:<67lld8kr76.fsf at aster.homelinux.net>... > yesterday I met a cute person Obviously this wouldn't have happened if you were using Perl. > (after my dance class) who told me about an > interesting experiment regarding cognition. People were told to read a > typed text; However, in every word in the text, only the first and the > last letter were in the right place. The other letters had their > positions changed in an arbitrary manner. The surprising result, I was > told, was that people can read this mixed-up text fairly well. I never entirely bought this, although I've never gone to the empirical extreme you did. If you look at the oft-cited example (see http://www.snopes.com/language/apocryph/cambridge.asp ), you will see that the intetior letters are not even close to being in random order. For the most part, letters near the front of the word remain near the front, and letters towards the back remain near the back. My thought is that, the brain doesn't read the word as a whole as they claim, but neither does it pay too much attention to the _exact_ ordering. So you could scramble the letters a little, and it will still be recognizable; but scramble them a lot, and you will have trouble. I suspect that a fairy tale wouldn't be too hard even with random ordering, though, since fairy tales don't use a lot of big words. > Because I am a somewhat sceptical guy, at times, and because I thought > that I deserved some play, I decided to code the rule above in a > scriptlet. The resulting 23 lines are below, and the outcome is quite > interesting, not only from the point of view of librarians ;-) : > > -------------------------------------------------- > #!/usr/bin/python > import sys > import locale > import string > import re > import Numeric > import RandomArray > > locale.setlocale(locale.LC_CTYPE, '') > wordsep = re.compile('([^%s])' % string.letters) > > for line in sys.stdin.xreadlines(): > for word in wordsep.split(line): > if word and word[0] in string.letters: > word = string.lower(word) > wlen = len(word) > if wlen > 3: > wa = Numeric.array(word) > perm = RandomArray.permutation(wlen-2) > wa[1:wlen-1] = Numeric.take(wa[1:wlen-1],perm) > word = wa.tostring() > sys.stdout.write('%s' % word) > > -------------------------------------------------- > > > For the Uninitiated, Numeric is a package which deals with array data; > arrays are mutable sequences and Numeric.take() can reorder items in > them; RandomArray.permutation() delivers the randomized reordering we > need. > > Now I have two innocent questions: > > - Is it possible to make it a bit more concise ;-))) ? Yes, but I'd say you're already at the point where more conciseness causes an unacceptable hit in the readability. I suspect you also thought this. > - Can it coerced to run a little bit faster ? > (on my oldish, 300 MHz-AMD K6 , run time looks like this > for a famous, 2663-word-long fairy tale from the Grimm's brothers: > > nix at aster:~> time v > > real 0m6.970s > user 0m3.634s > sys 0m0.120s Well, the thing about Numeric and numarray is that it's not designed to scale down well. If performance is your concern, you are probably better off using regular Python lists if your operations act on small arrays, as they do in this case. It doesn't surprise me that Steven Bethard found that ordinary Python ran faster. However, maybe we can use numarray to a greater advantage. The best way to use numarray is to operate on as much data as possible, which in this case is the whole text file. The question is: can we use operations on the whole text file to do this job? Well, we probably can't scramble the letters of individual words by operating on the whole text file at once. But could we find the word boundaries that way? The answer is yes. Have a look at my snippet to see how: ----------------------- import numarray as na from numarray import random_array as ra def interior_scramble(text): # First, build a length 256 table indicating if this is a real # letter. It's a boolean-valued array. ltable = na.array([ chr(c).isalpha() for c in range(256) ]) # Turn the above text into a numarray array We add a space # before and after the text, to make it possible to see the # boundaries on the first and last words atext = na.fromstring(" %s " % text, na.UInt8) # Now, calculate a mask. This uses the binary values of the # text string to index into the ltable, so that whereever a # letter appears in the text, a one appears in the mask. amask = ltable[atext] # Here's the magic: to find the word boundaries, we xor two # slices that are offset by one. Learning to use slicing in # this way is one of the greatest ways to channel the power of # numarray. # In the mask array, a start boundary will be a zero followed # by a one. An end will be a one followed by a zero. # Therefore, if you xor adjacent entries in the mask array, # the result will be nonzero whereever there's a boundary. # So, let's xor two one-off slices (which has the effect of # xoring adjacent entries) of the mask to get the word # boundaries. pat = amask[:-1] ^ amask[1:] # pat will be nonzero wherever there's a word boundary. Let's # use numarray.nonzero to get the indices of the word # boundaries. The word boundaries will be # start,end,start,end,... so we can reshape the array so that # each row is a start,end pair. words = na.reshape(na.nonzero(pat)[0],(-1,2)) # Because of how the resulting array aligns, we have to add 2 # to each start value to get the index where the scrambling # begins. words[:] += [2,0] # We got the word boundaries. Now, loop through them and # scramble. Because the whole file is a numarray, we don't # need to convert each word to a numarray and back # individually. That also saves some time. for start,end in words: n = end-start if n < 2: continue perm = ra.permutation(end-start) atext[start:end] = atext[start:end][perm] # It's scrambled. Convert the applicable slice back to a # string. return atext[1:-1].tostring() ----------------- I'm not sure if this is faster than your method or the pure-Python method; I didn't check (I worked too hard writing it :). But, generally speaking, whenever you can operate on your whole data set using numarray at once, doing so will be a big time savings. -- CARL BANKS From f.geiger at vol.at Fri Nov 5 02:25:32 2004 From: f.geiger at vol.at (F. GEIGER) Date: Fri, 5 Nov 2004 08:25:32 +0100 Subject: Script Generation, help! References: Message-ID: A sketch of a solution could be (untested): yourText = "%s=(%d)" % (yourString, yourNumber) try: f = open(yourFileName, "wt") f.write(yourText + "\n") f.close() except IOError, e: print "There's a problem writing to file %s: %s" % (yourFileName, e) Creating strings and numbers and putting that and the write into a loop is yours ;-) Kind regards Franz GEIGER "digital_ant2" schrieb im Newsbeitrag news:mailman.5952.1099638388.5135.python-list at python.org... > > I'm new to python, so I'll be at detailed as I can be. > > I need to generate a script where each line is like this: > > Spam=(x) > Spam=(y) > Spam=(z) > > each entry being on their own line, Spam is a string of text and > x,y,and z are random numbers, I also need it to be exported to a text > file with a specified extension.... being completely NEW to python I > push in the right direction would be really helpfull! > > Thanks, > Pat > > > > From mwm at mired.org Wed Nov 3 02:10:21 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 03 Nov 2004 01:10:21 -0600 Subject: Python needs a CPyAN References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> <41880b1a$0$19736$626a14ce@news.free.fr> <87vfcnr76l.fsf@sinken.local.csis.hku.hk> Message-ID: Isaac To writes: >>>>>> "Gerhard" == Gerhard Haering writes: > > Gerhard> Well, could have happened with a Debian [*] or *BSD, > Gerhard> etc. update as well, right? > > Yes, userss of systems with proper package management shouldn't want > to install anything from CPAN. On the other hand, there are many > people who are stuck with a braindead distribution or even OS that > doesn't have proper package management, or whose packages are severely > limited. Actually, what people on systems with proper package management want is packages that pull stuff from CPAN and install them as packages. Doing this right is hard, because CPAN makes assumptions about where things are liable to be installed. For Python, what we want are packages that use distutils to install them as packages. Doing this right is trivial, because distutils gets all the relevant information from the environment. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Nov 29 15:12:24 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Mon, 29 Nov 2004 21:12:24 +0100 Subject: how to drop all thread ?? References: Message-ID: <41ab8c1d$0$8667$8fcfb975@news.wanadoo.fr> Hi ! The best method, it is the suicide (of the threads). From finite.automaton at gmail.com Fri Nov 5 18:55:29 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 5 Nov 2004 15:55:29 -0800 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> Message-ID: <4b39d922.0411051555.24f31663@posting.google.com> Yes, wxPython is typically quicker than swing. It's not fair to use this in a generic Python-vs-Java speed shootout, though, since wxPython is just a wrapper around wxWidgets' C++ code; you're really comparing C++ vs. Java here. It does highlight the fact that it's easy to write C extensions for Python, though. AFAIK the major two reasons for Python's relative slowness are that it's interpreted and dynamically typed. There's almost always a convenience-for-speed trade-off, and Python is certainly more convenient than Java :P Israel Raj T wrote in message news:<87d5ysbkq9.fsf at pop-server.bigpond.net.au>... > Maurice LING writes: > > > This may be a dumb thing to ask, but besides the penalty for dynamic > > typing, is there any other real reasons that Python is slower than > > Java? > > Do you have any data to support this ? > On Windows XP, Windows NT and Linux (Gentoo ), I have consistently > found python apps using wxpython to be far faster to load > and to be far more responsive than Java apps. From vze4rx4y at verizon.net Sat Nov 6 23:11:16 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 07 Nov 2004 04:11:16 GMT Subject: yet another recipe on string interpolation References: <4edc17eb.0411032219.659c1824@posting.google.com> Message-ID: "Michele Simionato": > I was playing with string.Template in Python 2.4 and I came out with the > following recipe: > > import sys > from string import Template > > def merge(*dictionaries): > """Merge from right (i.e. the rightmost dictionary has the precedence).""" > merg = {} > for d in dictionaries: > merg.update(d) > return merg > > def interp(s, dic = None): > if dic is None: dic = {} > caller = sys._getframe(1) > return Template(s) % merge(caller.f_globals, caller.f_locals, dic) The ASPN chainmap() recipe is an alternative to merge(). It spares the initial effort of combining all the dictionaries. Instead, it does the lookups only when a specific key is needed. In your example, it is likely that most of globals will never be looked-up by the template, so the just-in-time approach will save time and space. Also, chainmap() is a bit more general and will work with any object defining __getitem__. The interp() part of the recipe is nice. Raymond Hettinger http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268 : --------- chainmap() --------- import UserDict class Chainmap(UserDict.DictMixin): """Combine multiple mappings for sequential lookup. For example, to emulate Python's normal lookup sequence: import __builtin__ pylookup = Chainmap(locals(), globals(), vars(__builtin__)) """ def __init__(self, *maps): self._maps = maps def __getitem__(self, key): for mapping in self._maps: try: return mapping[key] except KeyError: pass raise KeyError(key) Raymond Hettinger From foo at bar.com Wed Nov 10 08:28:22 2004 From: foo at bar.com (Steve Menard) Date: Wed, 10 Nov 2004 08:28:22 -0500 Subject: property for class objects In-Reply-To: <4191edee.85006843@news.oz.net> References: <4191edee.85006843@news.oz.net> Message-ID: Bengt Richter wrote: > On Tue, 09 Nov 2004 23:08:44 -0500, Steve Menard wrote: > > >>Jp Calderone wrote: >> >>>On Tue, 09 Nov 2004 21:54:50 -0500, Steve Menard wrote: >>> >>> >>>>As par of JPype, I find that I have to brifge Java static members into >>>>class attributes. >>>> >>>>I am using a metaclass to dynamically create a Python class for every >>>>Java type encountered. Instance variables were handled by adding a >>>>property(get, set) to the class's dictionary. >>>> >>>>Now static members are giving me a headache. I cannot use "property" for >>>>them, because properties are for instances only. >>>> >>>>What I am currently doing is adding a __getattr__ and a __setattr__ >>>>methods to the metaclass, which is called when a class attribute is >>>>requested but not found in the class' dict. >>>> >>>>This works fine exact it does not walk the inheritance tree to find >>>>static members defined in base classes. I am currently adding up all the >>>>names in every class. This "works", however it is misleading when you do >>>>a dir() of the class. >>>> > [ SNIP previous idea] > > Sometimes a custom descriptor can get you there. You can pass stuff to its > constructor to hang on its self, which is accessible separately from the self > of an instance or the latter's class. So there is room for customizing various > descriptor instances using one class (not a metaclass). If you only need read > access, this is easy. If you want a r/w property you may have to go to a metaclass > solution unless you are willing to use cvar.x = val or cvar[something] = var or > cvar.method(var) etc. -- i.e. return the descriptor self and have __setitem__ etc > as methods of the descriptor. You can hang something temporarily on self for use > in the subsequent method call, though I have the feeling there's some pitfall in > some uses of that. Anyway, here's a minimal descriptor (property is build on > the descriptor mechanisms, and you probably know all this, so I don't know why > I'm posting this ;-) IIRC, if you don't have a __set__ method, an attribute > assignment to an instance can shadow the descriptor, but not if you have __set__. > Of course, an attribute assignment to the class is no different than the original > class var assignment unless you have a descriptor/property in the metaclass to intercept it. > > >>> class Desc(object): > ... def __get__(self, inst, cls=None): > ... if inst is None: print 'accessed via class attribute' > ... else: accessed > ... > >>> class Desc(object): > ... def __get__(self, inst, cls=None): > ... if inst is None: print '%r accessed via class attribute' %cls > ... else: print '%r accessed via instance attribute' %inst > ... > >>> class Foo(object): > ... cvar = Desc() > ... > >>> foo = Foo() > >>> foo.cvar > <__main__.Foo object at 0x009B61B0> accessed via instance attribute > >>> Foo.cvar > accessed via class attribute > > Regards, > Bengt Richter I wasnt aware of those descriptors (I am just now delving in the "meta" side of things), and it looks promising. So thanks for taking the time to tlel me about it :) Static variables are not just constants however, and the __set__ has to work as normal. I did a quick test and it seems by mistake you can even erase the descriptor with a new value .. not good. At least I can use this for the constant static values (which probably comprises the bulk) and use the __setattr__ to prevent overwriting them. Steve Still looking for a more complete solution howeber From len-1 at telus.net Mon Nov 22 18:53:37 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Mon, 22 Nov 2004 23:53:37 GMT Subject: Microsoft Patents 'IsNot' References: Message-ID: Skip Montanaro writes: > My guess is Microsoft hopes to discourage Visual Basic knock-offs. Claim 2 > clearly seems to restrict the scope to BASIC. > No, Claim-2 refers to a "BASIC-derived programming language". Description 42 claims "BORLAND DELPHI" is such a "BASIC-like or BASIC-derived language". Now I have not used Delphi but understand it is a kind of Pascal. It looks like Microsoft is casting a wide net indeed. Is it wide enough to ensnare Python? We all know Python is not Basic, though it fills a similar niche. But let me indulge my paranoia for a moment. Could the Python Software Foundation weather a lawsuit from a large company, even if the lawsuit was unfounded? A small change like removing 'is not' from the language would still be a significant inconvenience. And hey, maybe IronPython would remain unaffected, making it more backward compatible than CPython. But enough with being the conspiracy guy. Actually I believe Microsoft is just trying to keep Visual Basic distinct from potential competitors. Lenard Lindstrom From exarkun at divmod.com Wed Nov 24 14:25:44 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 24 Nov 2004 19:25:44 GMT Subject: Python's annoyance. In-Reply-To: <_V4pd.386875$wV.330416@attbi_s54> Message-ID: <20041124192544.17481.818437030.divmod.quotient.3890@ohm> On Wed, 24 Nov 2004 19:03:26 GMT, Steven Bethard wrote: >caroundw5h wrote: > > Serioulsy, one of python's main selling points is its elegant syntax, > > non perl like, non C like. If it can't live up to it. I guess i might > > as well use perl or ruby or server side javascript. > > While I'm not a fan of the decorator syntax or the $syntax in > string.Template, you're not forced to use either of these: You may not be forced to write them (on the other hand, you may well be forced to - by your employer, by the coding standard of a project you contribute to, etc). More importantly though, their availability in the language means that someone will use them, and then it is likely that you will be forced to *read* them. This is a greater slight: consider the relative frequencies of code being written and code being read. This is not to say either that I am opposed to or in favor of either of the specific features mentioned by the original poster, only to point out that the argument "If you don't like that feature, don't use it" is relatively meritless. Jp From db3l at fitlinxx.com Wed Nov 17 17:05:39 2004 From: db3l at fitlinxx.com (David Bolen) Date: 17 Nov 2004 17:05:39 -0500 Subject: thread, threading; how to kill a thread? References: Message-ID: Ian Bicking writes: > (...) > Even if it messes things up and I have to restart the process at the > soonest possible time to clean up the problems, it would be nice to be > able to exit the process. (...) I'm not positive, but os._exit() may at least let you get the process exited regardless of any thread states. -- David From fumanchu at amor.org Fri Nov 19 18:55:28 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Nov 2004 15:55:28 -0800 Subject: instances v. threads Message-ID: <3A81C87DC164034AA4E2DDFE11D258E324525E@exchange.hqamor.amorhq.net> Brad Tilley wrote: > I've just started using classes in Python for some projects > at work and > have a few questions about them. I understand that once a class is > defined that I can create many instances of it like this: > > class xyz: > def one(): > pass > def two (): > pass > def three(): > pass > > a = xyz() > b = xyz() > c = xyz() > > a.one() > b.one() > c.one() > c.two() > c.three() > > How does asynchronous/threaded programming differ from OO programming > and classes? C is not OO and has no classes, but one can > write threaded > programs in C, right? Perhaps I'm totally off on this... can some > explain how these concepts differ? Exactly how is an 'instance' > different from a 'thread'? A thread is a "thread of execution". An object instance is a chunk of data on the heap. Any instance is available to any thread, if the thread can obtain a reference to that instance. Robert Brewer MIS Amor Ministries fumanchu at amor.org From igouy at yahoo.com Sat Nov 27 17:15:17 2004 From: igouy at yahoo.com (Isaac Gouy) Date: 27 Nov 2004 14:15:17 -0800 Subject: scripting languages vs statically compiled ones References: <7z7jpaez0y.fsf@pc-032.diku.dk> Message-ID: torbenm at diku.dk (Torben ?gidius Mogensen) wrote in message > You could use the "The Great Computer Language Shootout" at > http://shootout.alioth.debian.org/craps.php . It may give the > impression that you can't trust the numbers it gives, but I believe > this is mainly because it is more honest than the majority of other > language comparisons. Thank you! That's very kind - some folk seem to assume it's because the authors are plain stupid ;-) However, the websites been rearranged over the last month, so it would be better to start from one of the main pages: http://shootout.alioth.debian.org/ http://shootout.alioth.debian.org/great/ http://shootout.alioth.debian.org/sandbox/ > The main problem with this test is that the benchmark programs are fairly > small, so the results may not be representative of large programs. We'd quite like to include larger programs - but would people volunteer their time to write larger programs in all those languages? From thorsten at thorstenkampe.de Sun Nov 14 09:32:03 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 14 Nov 2004 15:32:03 +0100 Subject: simple recursion help References: <1gm4uqv.nmgjbj1vt0spjN%aleaxit@yahoo.com> <8ef9bea6.0410231916.450f67d@posting.google.com> Message-ID: * Hung Jung Lu (2004-10-24 04:16 +0100) > Steven Bethard wrote: >> Does anyone know what this operation is called? It's not permutations or >> combinations as I understand them since permutations and combinations do >> not allow repetition. I assume there was already a solution for this >> somewhere, but I didn't know what term to google for. > --------------------------------------------------- > aleaxit at yahoo.com (Alex Martelli) wrote: >> There's been a recent thread where the OP called them 'permutations', >> somebody commented they're 'variations'. In that thread you'll find a >> bazillion solutions, recursive and non, with or without itertools, &c. > --------------------------------------------------- > > (1) "Variation" is the same as "permutation". It's matter of > semantics. Some people use the notation V(n, k), some people use the > notation P(n, k). For people that use the term "variation", the term > "permutation" is reserved for the special case V(n, n). Neither name > is right for the original question. Well in fact it's a variation with repetition of the length 3 (or the cartesian product "['a', 'b', 'c'] ** 3"). With the cvp[1] utility you could generate that like: >>> l = ['a', 'b', 'c'] >>> util.cvp(l, 3, '#vr') # make sure it doesn't grow too big 27 >>> util.cvp(l, 3, 'vr') [['a', 'a', 'a'], ['a', 'a', 'b'], ['a', 'a', 'c'], ['a', 'b', 'a'], ['a', 'b', 'b'], ['a', 'b', 'c'], ['a', 'c', 'a'], ['a', 'c', 'b'], ['a', 'c', 'c'], ['b', 'a', 'a'], ['b', 'a', 'b'], ['b', 'a', 'c'], ['b', 'b', 'a'], ['b', 'b', 'b'], ['b', 'b', 'c'], ['b', 'c', 'a'], ['b', 'c', 'b'], ['b', 'c', 'c'], ['c', 'a', 'a'], ['c', 'a', 'b'], ['c', 'a', 'c'], ['c', 'b', 'a'], ['c', 'b', 'b'], ['c', 'b', 'c'], ['c', 'c', 'a'], ['c', 'c', 'b'], ['c', 'c', 'c']] Or like that: >>> util.cartes(util.cartes(l, l), l, 'triple') Thorsten [1] cvp = "combinations, variations and permutations" http://www.thorstenkampe.de/python/util.py From arso_AT_libero_DOT_it at non.ce Tue Nov 9 17:25:34 2004 From: arso_AT_libero_DOT_it at non.ce (Arso - Italy) Date: Tue, 09 Nov 2004 22:25:34 GMT Subject: Eric3 and mod_python debugging (reply from Detlev) In-Reply-To: References: Message-ID: <41915297.5020605@non.ce> Detlev Offenbach wrote: > Am Dienstag, 9. November 2004 00:13 schrieben Sie: > > >> Arso - Gentoo wrote: >> >> >>> Detlev Offenbach wrote: >>> >>> >>>> Am Montag, 8. November 2004 20:32 schrieben Sie: >>>> >>>> >>>>> Hi >>>>> >>>>> excuse me, i will try to use eric3 to debug interactly python scripts >>>>> running on apache with mod_python. >>>>> In the Eric documentation I have find only how to patch python.py, but >>>>> not how to activate the debug function. >>>>> Where I can find this information ? >>>>> >>>>> A lot of thanks. >>>>> >>>> >>>> In the mod_python manual. >>>> >>>> Detlev >>>> >>> >>> Thanks >>> when I have activate in apache configuration for a specific virtual host >>> PythonDebug on >>> PythonEnablePdb on >>> >>> I get the below error. >>> Are there other activity or setting to do for using eric debugger ? >>> Other lot of thanks. >>> >>> Mod_python error: "PythonAccessHandler draco.dracohandler" >>> >>> Traceback (most recent call last): >>> >>> File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line >>> 298, in HandlerDispatch >>> result = pdb.runcall(object, req) >>> >>> File >>> "/usr/lib/python2.3/site-packages/eric3/Debugger/eric3dbgstub.py", >>> line 60, in runcall >>> return debugger.run_call(__scriptname, func, *args) >>> >>> AttributeError: 'NoneType' object has no attribute 'run_call' >>> >> >> Hi >> I have try also with your example, modpython_dbg custumizing the path >> with the absolute value in the >> initDebugger method. >> The hello message apper but the debugger is not fired even there are >> some breakpoints active for the modpython_dbg itself. >> What is wrong ? >> >> For execution with draco i have inserted the call to >> apache.initDebugger(mpreq.filename) in the handler method of >> dracohandler but I get the above error. >> What is wrong ? >> >> If there are some document that describe the step for use the debug >> write to me where are there. >> >> Thanks. >> > > > There is a little document in erics Documentation directory (mod_python.html). This gives instruction on how I got it working. > > Detlev > > Excuse me. My mistake, I have activate *PythonEnablePdb on* only for the virtual domain managed with draco and not for that used for modpython_dbg. Now modpython_dbg.py is running with debug. The features of eric are VERY interesting. Either for the debugging features either for the editor, syntax highlight autocompletion ecc. For information: The python options *PythonDebug on* and *PythonEnablePdb on* are set directly into apache.conf in the directive "Directory" for the virtual-domain managed by mod_python. Sometimes after the end of the execution and after the popup form informing of the exit status of the script, eric terminate. It is normal ? In the debug option "Automatic reset after client exit" isn't activated. This message will be post in comp.lang.python too. Regards and a lot of thanks. -- ====================================================== Arso - Italy Gentoo 2004-02 Stage 1 Armada e500 ====================================================== From rogerb at rogerbinns.com Sun Nov 7 20:04:39 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 7 Nov 2004 17:04:39 -0800 Subject: checking a thread has started References: Message-ID: <8qt262-pfm.ln1@home.rogerbinns.com> [Please do not email and reply via news as well.] > So with this arrangement, would I be running into import lock > problems? Unlikely. Google for 'python "import lock"' if you would like to learn more. Roger From paul at subsignal.org Tue Nov 16 19:17:47 2004 From: paul at subsignal.org (paul koelle) Date: Wed, 17 Nov 2004 01:17:47 +0100 Subject: nonblocking read() In-Reply-To: References: Message-ID: <2vvjkoF2re95sU1@uni-berlin.de> Peter Ammon wrote: > Are there better approaches? Thanks, What is wrong with: fp = open('foo', 'r') while 1: line = fp.readline() if not line: time.sleep(0.3) continue process(line) ?? Paul From carribeiro at gmail.com Mon Nov 15 08:27:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 15 Nov 2004 11:27:47 -0200 Subject: Zope 3.0, and why I won't use it In-Reply-To: References: Message-ID: <864d3709041115052737faa705@mail.gmail.com> On Sun, 14 Nov 2004 19:41:13 -0500, Steve Holden wrote: > You managed to get it to run? I found the whole load opaque beyond > belief, and removed it after an hour's examination. >From time to time, I download Zope, try it a little bit, and uninstall it. Perhaps I am too dumb for it (which may be the case) :-( ... but I somehow feel that there is a problem, for I am not alone in this feeling. For me, Zope lacks Python's inherent clarity; it seems that it requires a 'mental mode' of its own. Many things are not obvious, in the way they normally are when I am working with Python. This places a lot of burden on the documentation, which - as said elsewhere - is confusing. It's a shame. (The best image that I can cast is of a rough gem. A good gem cutter can see the finished gem through layers of dirty, and locate the correct planes to cut. For others, even knowing that the gem is inside there is not enough, for they can't see it until finished. For me Zope looks like an still unfinished gem, and even if I know that there is a beautiful gem inside, I can't just see it there.) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From miles_f at yahoo.com Tue Nov 9 18:20:29 2004 From: miles_f at yahoo.com (Miles Fender) Date: Tue, 09 Nov 2004 15:20:29 -0800 Subject: Stripping HTML with RE In-Reply-To: <76d8b714.0411091506.581637c0@posting.google.com> References: <76d8b714.0411091506.581637c0@posting.google.com> Message-ID: Steveo wrote: > I am currently stripping HTML from a string with the following code. > (I know it's not the best way to strip HTML but bear with me) > [...] Instead of using REs, you might consider the StrippingParser from the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52281 It allows you to specify explicitly which tags you want to leave intact, so you'll be able to change your mind later without futzing about with a complex RE... Miles From ncoghlan at email.com Sat Nov 20 12:12:54 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sun, 21 Nov 2004 03:12:54 +1000 Subject: Is Python/C api thread safety enough? In-Reply-To: References: Message-ID: <419f7b16$0$25777$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Casper wrote: > Can sombody tell me is this possible? Thanks first. If you're going to call the Python C/API, you need to be holding the GIL. So you either can't release it, or the long-running function has to use PyGILState_Ensure when it needs to call the Python C/API. Cheers, Nick. From peter at engcorp.com Sun Nov 28 12:31:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 28 Nov 2004 12:31:49 -0500 Subject: Timer hangs when quitting app In-Reply-To: References: Message-ID: Gitte Wange wrote: > I'm trying to create an application that needs a Timer() to do various > checks. > My class has a self.timer = Timer(900, self.sendDNSRequest) > The timer itself works fine but whenever I try to exit the application, it > simply hangs and I have to kill the proces using `kill pid` > > I have tried uncommenting the timer stuff, and then the app works as > expected. > > Is there anything I need to do to kill the timer? > I have tried to create a __del__(self) function in my app. It gets called > when I leave out the timer, but with the timer enabled, it never gets > called. A Timer is a subclass of threading.Thread, which means you can do "self.timer.setDaemon(True)" on it *before* you start it, and it will not hang the app when it is trying to exit. See notes in the threading module's Thread.setDaemon docs for background. -Peter From mickey at travelexpert2004.biz Sun Nov 28 09:43:55 2004 From: mickey at travelexpert2004.biz (mickey) Date: Sun, 28 Nov 04 14:43:55 GMT Subject: Trip to Disney Message-ID: <04112814435516792@newshost.allthenewsgroups.com> GET YOUR TRIP TRIPS TO DESNEY TRIPS TO HAWAII http://travelexpert2004.us http://travelexpert2004.biz http://gotraveling85.us From bdesth.quelquechose at free.quelquepart.fr Fri Nov 12 09:38:44 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Nov 2004 15:38:44 +0100 Subject: Plone and mod_python In-Reply-To: References: <7l1ld.13845$3_.7287@ns2.gip.net> Message-ID: <4194cab6$0$27786$626a14ce@news.free.fr> Thorsten Kampe wrote: > mod_perl enables Apache without Zope to execute Python scripts (CGI). > s/mod_perl/mod_python/ !-) From theller at python.net Mon Nov 8 11:35:02 2004 From: theller at python.net (Thomas Heller) Date: Mon, 08 Nov 2004 17:35:02 +0100 Subject: generic way to access C++ libs? References: <1gmxizh.3rip5na92f0nN%aleaxit@yahoo.com> <1gmxn7d.19o8q51jt2gu5N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Jacek Generowicz wrote: > ... >> > > > Is there any generic way to use C++ libraries from within Python. >> > > >> > > > Without doing anything else (such as recompiling the library or >> > > > generating wrappers). >> > > >> > > Bit of a tall order, don't you think? >> > >> > Well, ctypes does that for C libraries (as long as they're >> > DLL/so/dynlib/...), it's not immediately obvious that using C++ >> > libraries is an order of magnitude harder (though probably true). >> >> Maybe not _immediately_ obvious, but obvious after a few minutes >> thought :-) > > To somebody with a good grasp of the current state of C++ technology, > maybe. Somebody who might just like to using existing dynlib/&c which > happen to be oriented to C++ rather than C might quite reasonably not > find the distinction obvious, IMHO. > > Indeed, I suspect ctypes could be extended to do some of the requested > task, if one focused on a single, specific C++ compiler. I guess that MSVC uses the same binary layout for C++ objects as for COM objects, so it should be possible. I don't know if the name mangling rules are documented somewhere. But I have no idea how inline definitions of member functions (I'm not sure that's the correct term - I mean code defined in the header files) should be converted to Python code. Thomas From littlejohn.75 at noos.fr Mon Nov 22 11:35:48 2004 From: littlejohn.75 at noos.fr (F. Petitjean) Date: 22 Nov 2004 16:35:48 GMT Subject: for(each) element aliasing References: <2844q0l5ccahj6poumolghrcm2u2boo9ka@4ax.com> Message-ID: <41a21564$0$10222$626a14ce@news.free.fr> On Mon, 22 Nov 2004 17:21:26 +0100, Matija Papec wrote: > > I know how to alter the list via list indicies but I would like to know if > there is posibility to write in Python something like: > > my @arr = 1..3; > for my $element (@arr) { > $element *= 2; > } > print "@arr\n"; For instance : arr = 1, 2, 3 # range(1, 4) arr = [ element*2 for element in arr ] print arr # [2, 4, 6] it is a list for element in arr: print element, # note the comma print # useful if not in interactive mode only Read the documentation about "list comprehension" > > and get the result > ------- > 2 4 6 > > From rune.hansen at scanmine.com Mon Nov 8 02:52:13 2004 From: rune.hansen at scanmine.com (roderik) Date: Mon, 08 Nov 2004 08:52:13 +0100 Subject: mod_python, multiple calls to PythonAuthenHandler In-Reply-To: References: Message-ID: I've posted this question on the mod_python mailing list but didn't get much response, so I thought I'd post it here. It seems to me that for each path element in a URI a mod_python handler will be invoked. This applies to PythonAuthenHandler, PythonHeaderParserHandler and so on. Since I'm making a database request in my PythonAuthenHandler, this quickly becomes a problem. Example: http://lucene.moonspawn.scanmine.com/ => AuthenHandler::authenhandler called: 1 index got called once http://lucene.moonspawn.scanmine.com/SearchHandler.py/search => AuthenHandler::authenhandler called: 1 AuthenHandler::authenhandler called: 2 /search got called once http://lucene.moonspawn.scanmine.com/search.html => (using mod_rewrite) AuthenHandler::authenhandler called: 1 AuthenHandler::authenhandler called: 2 AuthenHandler::authenhandler called: 3 /search got called once I get the same behavior on three separate installations So, either I've got a miss-configuration which results in multiple calls to handlers or.., this is expected behavior, and there is a technique to avoid this or..., this is expected and, for reasons that escapes me, desired behavior. I'd greatly appreciate any help and suggestion regards /rune From steve at holdenweb.com Mon Nov 8 07:42:02 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 08 Nov 2004 07:42:02 -0500 Subject: sh: test: argument expected In-Reply-To: References: Message-ID: <8WJjd.13318$931.3055@lakeread01> Iv?n Cabria wrote: > Hi, > > I have run the script using "python scriptname.py" and the error does > not go away. I got the same error: > > sh: test: argument expected > > > I have checked again that the first line of the python script is > #!/usr/bin/env python > > There are no blank lines or empty spaces before > #!/usr/bin/env python > > > I also did "grep loginname /etc/passwd" to confirm I was using bash, and the > line I got ended with > > :/usr/bin/bash > That's as may be, but I can't escape the conclusion that your script is involving the shell somehow - maybe the GetPotentialEnergy() method calls os.system() or some other piece of functionality. About all I can say is that the error message you are seeing is definitely NOT from the Python interpreter. Try putting a print statement of some kinf as the second loine of your script and make sure that Python is actually running that script. If it is, you'll need to find out where it's calling shell functionality. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From merman at snafu.de Mon Nov 8 11:13:52 2004 From: merman at snafu.de (T. Kaufmann) Date: Mon, 08 Nov 2004 17:13:52 +0100 Subject: MySQLdb installation Message-ID: <418f99db$0$175$9b622d9e@news.freenet.de> Hi, RDBMS MySQL works fine on my machine. I want to install MySQL-python 1.0.0 under Red Hat 9.0. >>> platform.platform() 'Linux-2.4.20-8-i686-with-redhat-9-Shrike' There are some problems. If I call python setup.py build there are lots of errors: _mysql.c:41:19: mysql.h: File not found What can I do? How can I fix it? o-o Thomas From rkern at ucsd.edu Sat Nov 13 23:19:33 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 13 Nov 2004 20:19:33 -0800 Subject: map, LC, genexp In-Reply-To: References: Message-ID: Bryan wrote: > i thought that LC and genexp were supposed to be faster than map. i > also thought i read somewhere in this group that the slowest looping > mechanism in 2.4 is 20% faster than the fastest looping mechanism in > 2.3. if i'm wrong about this, remembered wrong or did something wrong, > please let me know. here are some timeit tests i did on my machine. > notice that map is faster in both python versions and that LC24/LC23 is > only a 5.5% speed improvement. > > python 2.3 > > timeit "for i in map(str, xrange(100)): pass" > 10000 loops, best of 3: 118 usec per loop map still beats list comprehensions and generator expressions when the function is builtin. Try again with a Python function that gets "inlined" in the LC and genexp: E.g. def neg(x): return -x map(neg, xrange(100)) [-x for x in xrange(100)] (-x for x in xrange(100)) I believe (though I haven't tested this specific example) that is the case for which they are faster than map. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From anhtt at hotmail.com Thu Nov 18 09:48:33 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 18 Nov 2004 06:48:33 -0800 Subject: SPARK v.s. PLY Message-ID: Hi all, I am searching for a suitable parsing tool to parse C++ for a research project. Actually I am parsing SystemC, it is a C++ lib with some macros, hence I need to modify the grammar a little bit to handle some new keywords. I need to construct the Control Flow Graph and play around with it a bit. So far, I have found SPARK and PLY that seem to be suitable to my task. Other packages are either not so well established or not so well tested and documented. (Please correct me if I am wrong). If you know the parsing stuff well, could you briefly tell me the pros. and cons. of those packages? (or some others you find good too) Thanks a lot! Tuan-Anh From xnews2 at fredp.lautre.net Wed Nov 17 07:55:43 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 17 Nov 2004 12:55:43 GMT Subject: Zope 3.0, and why I won't use it References: <41985663$0$272$edfadb0f@dread12.news.tele.dk> <4198cc5f$0$258$edfadb0f@dread12.news.tele.dk> <4198e036$0$289$edfadb0f@dread12.news.tele.dk> Message-ID: Tim Peters said : >> If only the lower part of that page had figured in a prominent >> WINDOWS_INSTALL_README.TXT or some such in the Windows >> installer, there'd been much less bitchin' here :-) > > Ah, but where would you put this file? In a *tarball* distribution, > it's easy: you stick README_FILES_WITH_SCREAMING_NAMES in the root of > the distribution, and then they're easy to find. > > But this is a Windows *installer*, and every file it installs is > "hiding" under some subdirectory of your pre-existing Windows Python > installation. Where could the X3 Windows installer put > WINDOWS_INSTALL_README.TXT where a new user is likely to find it? Yes, good point. I was sort of speaking for myself because I had actually browsed through the newly created directories under site-packages looking for some such, and would have found it there. So it would work for people used to installing Python packages (like most of those who've posted in this thread), but it's clearly not a bulletproof "end-user" solution. -- YAFAP : http://www.multimania.com/fredp/ From bokr at oz.net Tue Nov 23 20:09:58 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 24 Nov 2004 01:09:58 GMT Subject: int(float(sys.maxint)) buglet ? Message-ID: <41a3d612.849461871@news.oz.net> Peculiar boundary cases: >>> 2.0**31-1.0 2147483647.0 >>> int(2147483647.0) 2147483647L >>> int(2147483647L ) 2147483647 >>> >>> -2.0**31 -2147483648.0 >>> int(-2147483648.0) -2147483648L >>> int(-2147483648L ) -2147483648 some kind of one-off error? I.e., just inside extremes works: >>> [int(x) for x in (-2.0**31, -2.0**31+1.0, 2.0**31-2.0, 2.0**31-1.0)] [-2147483648L, -2147483647, 2147483646, 2147483647L] But those longs at the extremes can be converted successfully, so int(int(x)) works ;-/ >>> [int(int(x)) for x in (-2.0**31, -2.0**31+1.0, 2.0**31-2.0, 2.0**31-1.0)] [-2147483648, -2147483647, 2147483646, 2147483647] ISTM this is a buglet, or at least a wartlet for a 32-bit system ;-) Almost forgot: Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 but same thing on 2.3.2: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> [int(x) for x in (-2.0**31, -2.0**31+1.0, 2.0**31-2.0, 2.0**31-1.0)] [-2147483648L, -2147483647, 2147483646, 2147483647L] >>> [int(int(x)) for x in (-2.0**31, -2.0**31+1.0, 2.0**31-2.0, 2.0**31-1.0)] [-2147483648, -2147483647, 2147483646, 2147483647] Hm, ... except for the thought that CPUs with 64-bit integers might truncate maxint when converting to float, I might say maybe these reprs should be tested for equality in the system tests? >>> import sys >>> repr(int(float(sys.maxint))), repr(sys.maxint) ('2147483647L', '2147483647') >>> repr(int(float(-sys.maxint-1))), repr(-sys.maxint-1) ('-2147483648L', '-2147483648') or maybe at least check for equality of these?: >>> type(int(float(sys.maxint))), type(sys.maxint) (, ) >>> type(int(float(-sys.maxint-1))), type(-sys.maxint-1) (, ) Regards, Bengt Richter From maxm at mxm.dk Wed Nov 17 15:33:36 2004 From: maxm at mxm.dk (Max M) Date: Wed, 17 Nov 2004 21:33:36 +0100 Subject: imaplib ... understanding the result from a fetch of RFC822s In-Reply-To: <419bb3a7$0$259$edfadb0f@dread12.news.tele.dk> References: <419bb3a7$0$259$edfadb0f@dread12.news.tele.dk> Message-ID: <419bb54a$0$304$edfadb0f@dread12.news.tele.dk> Max M wrote: > I guess that I can iterate it like: > > for ((envelopeStart, msg), envelopeEnd) in range(0, len(messages), 2): > # do stuff I guess not. I really meant: for i in range(0, len(results), 2): ((envelopeStart, msg), envelopeEnd) = (results[0], results[1]) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From jcarlson at uci.edu Fri Nov 5 03:30:21 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 05 Nov 2004 00:30:21 -0800 Subject: dijkstra algorithm by object oriented In-Reply-To: <1gmrpqw.1omlhxkz9r7yN%aleaxit@yahoo.com> References: <1gmrpqw.1omlhxkz9r7yN%aleaxit@yahoo.com> Message-ID: <20041105002753.F82D.JCARLSON@uci.edu> aleaxit at yahoo.com (Alex Martelli) wrote: > > Josiah Carlson wrote: > > > "Ricardo Batista" wrote: > > > > > > But i need it for a homework. > > > > We try not to do homework here. > > Well, Ricardo's trying not to do homework there either, so there seems > to be the basis for mutual understanding... Tee hee. Yeah, if I was told (for an assignment) object-orient this thing, I'd probably go all out. Nodes, edges, graph. - Josiah From deetsNOSPAM at web.de Wed Nov 10 06:28:17 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 10 Nov 2004 12:28:17 +0100 Subject: html parsing? Or just simple regex'ing? References: Message-ID: Forget about the last part - I just read Jp Calderone's reply after writing mine - interesting. I've never heard of "chunked" encoding before. -- Regards, Diez B. Roggisch From jonasgalvez at gmail.com Tue Nov 16 01:13:52 2004 From: jonasgalvez at gmail.com (Jonas Galvez) Date: Tue, 16 Nov 2004 04:13:52 -0200 Subject: cgi.FieldStorage() is slow In-Reply-To: <20041115215736.00007a5c@nehal> References: <20041115215736.00007a5c@nehal> Message-ID: <7c60b605041115221364adb6fa@mail.gmail.com> Nehal wrote: > after profiling, it seems like: > self.read_lines_to_outerboundary() > which is called from > cgi.FieldStorage() > is the reason why it's so slow. > > when uploading small files, you won't notice a difference, but if > you upload files larger than 2 megs, you can notice it. Well, you could use sys.stdin.read() and retrieve POST data in a customized manner (bytes per cycle). But I doubt it would help. \\ jonas galvez // jonasgalvez.com From aleaxit at yahoo.com Sun Nov 14 12:57:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 14 Nov 2004 18:57:26 +0100 Subject: .pyc files... References: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> <2vp91pF2obee4U1@uni-berlin.de> Message-ID: <1gn98lj.1obb1shw8nfr9N%aleaxit@yahoo.com> Reinhold Birkenfeld wrote: > >> alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" > > or with backticks: rm -rf `find . -name '*.pyc'` > > Beware of spaces in filenames! Yeah, but it's pretty unlikely, though not impossible, to have a .pyc file, specifically, with spaces in the name; that module would be somewhat hard to use from Python in normal ways. Alex From jeff at ccvcorp.com Wed Nov 10 16:46:23 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 10 Nov 2004 13:46:23 -0800 Subject: How to communicate to device In-Reply-To: References: Message-ID: <10p52ru90lemn2e@corp.supernews.com> kamarudin samsudin wrote: >Hi all, > >Im new to linux and very very new to python. But i have to write a >program to communicate with a devide. The device will send a data >after i send something to it. > > This depends on the device and how it's intended to communicate with the computer. Is it a serial port link, an ethernet connection, or some other connection mechanism? Is there a device driver for it in /dev? What sort of communication protocol does it use? Without knowing some of these specifics, we will have a hard time helping you, and the more specific you are, the better the help that you're likely to get. (Obviously, as a newbie, you may not know *how* to answer some specifics, but give us what you *do* know and we'll try to help you find any more details that are needed.) You may also benefit by reading ESR's essay "How To Ask Smart Questions" ( http://www.catb.org/~esr/faqs/smart-questions.html ). Jeff Shannon Technician/Programmer Credit International From davidf at sjsoft.com Thu Nov 25 03:23:46 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 25 Nov 2004 10:23:46 +0200 Subject: Python Huffman encoding In-Reply-To: <41a525c6$0$76502$b83b6cc0@news.wanadoo.nl> References: <41a525c6$0$76502$b83b6cc0@news.wanadoo.nl> Message-ID: "@ dot wrote: > Hi all, I have written a Python huffman Encoding Module, for my own > amusement. I thought it might be educational/entertaining for other > people, so I've put it on my website and wrote about it a little. > > http://gumuz.looze.net/wordpress/index.php/archives/2004/11/25/huffman-encoding/ > > > Your comments are highly appreciated! > Looks cool. Now if only I had seen this before I implemented my own huffman decoding for JPEG ... I wonder if your module could be used instead ... From aleaxit at yahoo.com Wed Nov 17 02:34:40 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 17 Nov 2004 08:34:40 +0100 Subject: why python? References: Message-ID: <1gndypu.1e28rl1cgo8nsN%aleaxit@yahoo.com> 99%SugarFree wrote: > Hi,there > I've just known about Python language recently for a research project. > I'm just wondering what kind of applications out there using Python?? Hard to think of any kind of app where Python is NOT being used. Googling for python success stories will show off a few notable cases (those where developers could be troubled to write things up and their management gave release etc etc). > Where can I find more information about the philosophical, technical and > design features of Python?? O'Reilly's "Safari" http://search.safaribooksonline.com/ offers two free weeks -- join and read the first few chapters of "Python in a Nutshell" and other Python books it stores, it should give an idea well within the two free weeks. > For those of you who used Python, have you used Prolog or ML??What do u > think of these 3 language comparing to each other when you are coding? I've played with them both but not used them in production. For Prolog, I was part of the scientific audit team for a project at IBM Research in the '80s -- being one of the few comfortable with Prolog without being heart and soul into it, and also familiar with IBM 370 machine architecture and assembly language (which said research project was meant to deal with) made me sort of a natural candidate for that audit. At the time I was impressed by how good prolog was when you were doing what it was MEANT for, and how bad it suddenly became as soon as you strayed and started piling up cuts &c to simulate imperative coding. I decided I would never have prolog as the ONLY language for a project, to avoid the latter half. But then, I've always liked multilanguage approaches to large programming projects -- "one language to rule them all" always struck me as silly, from PL/I onwards. Functional programming is quite a different story. Though I've never used it in anger, I _am_ quite convinced that if you can put together a team of people with PhD in maths or CS for all the development and maintenance you can probably get more done with it than with languages that let you take shortcuts by modifying data. Whether S/ML, O'CAML, Haskell, Erlang, or other languages yet, best embody that ideal, I can't claim to know. In the real world, I believe putting and keeping together a team of people who are math whizzes IS gonna be a problem. Python has little to do with Prolog, and not all that much more to do with FP languages: it took from the latter quite a few ideas and gadgets, but merged them into its very own style. You do find yourself making new objects (e.g. by list comprehension) rather than modidying old ones, and generating functions on the fly (e.g. by closures), much more often than with most imperative languages -- but modifying objects is also quite common (more than even in multi-paradigm O'CAML), emphasis is on iteration and against recursion (strong iteration protocol, generators, etc, vs no tail recursion optimization, for example). What's very surprising is that the various paradigms and ideas merge pretty seamlessly and elegantly (much more so than in O'CAML, I think, to give another example of a multi-paradigm language, albeit with a FP basis at the core). Strong but highly dynamic (runtime) typing (versus strictly compile time typing common in FP languages, excepting maybe Erlang), strong statement/expression distinction, and the various design philosophies illustrated in the "Zen of Python" which was already quoted on this thread, merge quite well to yield high productivity, in Python. Alex From jcarlson at uci.edu Fri Nov 26 00:54:49 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 25 Nov 2004 21:54:49 -0800 Subject: Few things In-Reply-To: <20041125204315.FA26.JCARLSON@uci.edu> References: <5c882bb5.0411251641.6177ee9d@posting.google.com> <20041125204315.FA26.JCARLSON@uci.edu> Message-ID: <20041125215400.FA29.JCARLSON@uci.edu> Josiah Carlson wrote: > theory) end up repeatedly (logn) time selecting the 'kth' smallest > element (varying k's), where sorting would actually run slightly faster. That should have read: theory) end up repeatedly (logn times) selecting the... - Josiah From jcarlson at uci.edu Tue Nov 16 20:50:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 16 Nov 2004 17:50:43 -0800 Subject: Zope 3.0, and why I won't use it In-Reply-To: <419A4E64.6050005@colorstudy.com> References: <20041116085317.F96A.JCARLSON@uci.edu> <419A4E64.6050005@colorstudy.com> Message-ID: <20041116174139.F982.JCARLSON@uci.edu> Ian Bicking wrote: > > Josiah Carlson wrote: > >>Since the actual need for type-checking is extremely rare, I contend it > >>should not _at all_ be a candidate for a syntax to facilitate it. Since > >>the actual need for adaptation is much wider, I contend it's the one > >>obvious choice for the "nice syntax" if any. > > > > > > Sounds reasonable, but there will be a group of people who will beg and > > plead for type checking, because they want "static type checking on > > function call and return". > > Yes, but they've been begging for it for years. They seem insistant > that this Python Thing will never catch on without these important features. And they can keep insisting. It hasn't stopped it from catching on yet *wink*. > Anyway, a much more general and useful feature would be contracts. > Which is just to say, a formal place to put constraints on input and > output for a function. Contracts could include type checking -- > sometimes quite validly -- but not necessarily. There's no type that > can indicate "only valid username strings" or "only integers contrained > by some global variable". Certainly not, but an arbitrary 'argument validator' decorator is just minutes away from someone implementing it (and likely has more than a few times already). > > @ multi_dispatch_to_methods > > class A(object): > > dispatch = dispatch_factory() > > > > @ dispatch(int) > > def foo(x): ... > > > > @ dispatch(float) > > def foo(x): ... > > > > > > It may have a couple warts, but it is implementable today. > > Phillip Eby just did this, in like the last week. It's very cool: > > http://peak.telecommunity.com/DevCenter/VisitorRevisited > http://www.eby-sarna.com/pipermail/peak/2004-November/001916.html > > It looks similar to what you were thinking: > > class A(object): > @dispatch.on('x') > def foo(x): > """This is a dummy function, for documentation purposes""" > > @foo.when(int) > def foo(x): ... > > @foo.when(float) > def foo(x): ... > > Of course, you can use interfaces in addition to types, and you can also > use arbitrary expressions (e.g., @foo.when("x % 2") and @foo.when("not x > % 2") to dispatch odd and even numbers separately). There goes Phillip Eby going off and doing something reasonable again. - Josiah From jfabiani at yolo.com Sun Nov 28 09:54:00 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sun, 28 Nov 2004 14:54:00 GMT Subject: Psycopg2 mirror availability References: Message-ID: Andrew James wrote: > All, > I'd like to be able to use psycopg2's new features for my development > work with postgresql, but unfortunately the init.d site seems to be > broken and I can't get to the repository there. > > Does anyone know: > a) Why init.d is down, and when it might be back up > b) Where I might be able to find a psycopg2 mirror, and > c) Whether there's a Gentoo ebuild available? > > Any help would be much appreciated, > > Regards, > Andrew > > I don't think there is a mirror. I also can confirm that the site appears to be down. John From just at xs4all.nl Thu Nov 11 08:26:03 2004 From: just at xs4all.nl (Just) Date: Thu, 11 Nov 2004 14:26:03 +0100 Subject: Iterating over PDF documents References: Message-ID: In article , Peter Maas wrote: > Just schrieb: > > try this: > > > > for line in open(path, "U"): # universal newline mode > > Thanks, Just, I tried this but the edited PDF was damaged. That's probably because PDF can also contain arbitrary binary data, which would indeed break if all occurances of \r\n and \r were replaced by \n... Just From mauriceling at acm.org Sun Nov 7 01:21:45 2004 From: mauriceling at acm.org (Maurice LING) Date: Sun, 07 Nov 2004 17:21:45 +1100 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> Message-ID: <418DBEF9.7070207@acm.org> > What??? If you are referring to the original IBM PC, which did ship with > 64k base memory, that was 1980, not 1960. You could certainly order one > with more than 64kB. > > In the late 1960s, IBM was worrying about the System/360. It had a lot > more than 64kB of base memory. > I was thinking about the part whereby a program is allocated 64k memory and other allocations are heap allocations which needs pointers. I vaguely recall Turbo Pascal manual mentioned that you cannot statically allocate more than 64k of variable memory, which is why pointers are needed to circumvent it. And there is something called extended memory manager (EMM386.com or something) in DOS 5 that is needed to address up to 640kB of memory or something... DISCLAIMER: before I am flamed again, I wish to say that these are from vague memories of more than a decade ago. I may be COMPLETELTY WRONG. I was then still an early teens trying to get my games running...... > >>>it is comparing versions that are YEARS out of date and use! >> >>Are the codebase of Python 1.5.2 and Java 1.1 totally replaced and >>deprecated? > > > For new development, yes, Python 1.5.2 has been totally replaced. There > are legacy applications running in Python 1.5.2 that aren't worth the > trouble to upgrade. > > >>Lisp compiler is the 1st compiler to be created (according to the >>Red-Dragon book, I think) and almost all others are created by >>bootstrapping to LISP compiler. > > > That's just silly. It is true that LISP was one of the pioneers of the > compiled languages, but other compilers were not written in LISP. Almost > without exception, compilers were all written in assembly language until > Pascal came around. I'm wrong again. I suppose what I am trying to suggest is that design decisions made in the last may have a longer effect than what we consciously think. At least this is the impression I get while reading James Gosling's argument that Java should be object-oriented from day 1 (and not added onto the language, like in C++) in The Java Programming Environment: A white paper. maurice From dieringe at zedat.fu-berlin.de Mon Nov 22 09:28:54 2004 From: dieringe at zedat.fu-berlin.de (Martin Dieringer) Date: Mon, 22 Nov 2004 15:28:54 +0100 Subject: split large file by string/regex References: Message-ID: <7m9972-0c6.ln1@pc.dieringer.dyndns.org> Jason Rennie writes: > On Mon, Nov 22, 2004 at 09:38:55AM +0100, Martin Dieringer wrote: >> I am trying to split a file by a fixed string. >> The file is too large to just read it into a string and split this. >> I could probably use a lexer but there maybe anything more simple? > > If the pattern is contained within a single line, do something like this: Hmm it's binary data, I can't tell how long lines would be. OTOH a line would certainly contain the pattern as it has no \n in it... and the lines probably wouldn't be too large for memory... m. From ian.rmthispart at excess.org Thu Nov 4 23:17:07 2004 From: ian.rmthispart at excess.org (Ian Ward) Date: Thu, 04 Nov 2004 23:17:07 -0500 Subject: urwid with multi-byte encoded and bidirectional text? Message-ID: <418AFEC3.8020806@excess.org> I hope to add support for multi-byte encoded and bidirectional text to my curses-based UI library: http://excess.org/urwid/ I would like to support whatever encoding the user likes. Are there functions for: - querying the preferred encoding - splitting encoded strings into characters based on an encoding - determining the direction (L to R, R to L) of each character - determining the number of columns used by each character when written to the terminal I currently use a "line translation" structure to store instructions for mapping a text string to a two-dimensional "canvas". Its current, simple, format is described here: http://excess.org/urwid/reference.html#Text-get_line_translation The line translation structures describe the result of word-wrapping/clipping and justification applied to the source text. A *new* line translation format would have to support characters that are N bytes in the string and M columns wide when displayed, as well as text that is displayed in a different order than it appears in the string. Is normalizing bidirectional text orthogonal to wrapping/clipping and aligning that text? Could I create a "direction translation" structure that describes how a given string can be reordered Left-to-Right, then solve the wrapping and alignment with this normalized version? In what situations are characters modified/removed/inserted as part of displaying them? (eg. punctuation being reversed when surrounding R to L text) TIA Ian Ward From ialbert at mailblocks.com Wed Nov 10 20:03:51 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 10 Nov 2004 20:03:51 -0500 Subject: distutils and Debian In-Reply-To: References: <4192AD69.5040707@sympatico.ca> Message-ID: Sam Holden wrote: >>Should this be reported as a Debian bug? > No. I would say yes ... there is no logic in crippling a standard python distribution. What else is missing? Istvan. From jfabiani at yolo.com Sun Nov 28 14:58:52 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sun, 28 Nov 2004 19:58:52 GMT Subject: Newbie MySQLdb / MySQL version problem, I think References: Message-ID: <06qqd.32905$6q2.16566@newssvr14.news.prodigy.com> Dave Merrill wrote: > Sorry for the newbness... Win2K, Python 2.3.3, MySQL 4.1.7. Downloaded and > extracted MySQL-python-1.0.0.win32-py2.3.zip. Put the whole extracted > directory into C:\Program Files\Python23\Lib\site-packages\ and renamed it > to "MySQLdb. > Why not download the 1.1.5 if you have concerns http://sourceforge.net/projects/mysql-python John From zjbywesb at search26.com Tue Nov 30 10:29:10 2004 From: zjbywesb at search26.com (vandalin) Date: 30 Nov 2004 07:29:10 -0800 Subject: Matching Control Characters References: Message-ID: <4c248b9b.0411300729.69e85d53@posting.google.com> http://www.ardice.com/Arts/Movies/Titles/1/13th_Letter,_The From deetsNOSPAM at web.de Tue Nov 23 14:19:23 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 23 Nov 2004 20:19:23 +0100 Subject: drag and drop graphics in tkinter? References: <41a2fb94$0$8155$8fcfb975@news.wanadoo.fr> Message-ID: > I'm looking for a way to use drag-and-dropping to pick up a graphic > and move it from one place to another. For example, I thought I could > get my feet wet by writing a script to represent small graphs (in the > nodes-and-vertices sense) as collections of dots and lines onscreen. > Moving the the dots around (while maintaining line-indicated > connections between dots) could furnish a graphical way of > investigating questions like planarity and isomorphism. That's not what commonly is associated with drag-and-drop - the reason beeing that the interesting thing about drag and drop is to create a sort of event in the drop-target that is filled with information about _what_ has been dropped - e.g. a file location - and then act accordingly. This is not so much about the graphical appearance, but much more about protocol issues. What you want is to utilize the canvas widget. It can create graphics primitives, and there are plenty of events available so that you get noticed when the user picks a node (presumably rendered by a circle) and drags it around. I've done that years ago, and tk was quite easy to use. But as its a more tk-specific question, I suggest you search for tk canvas examples, and translate them to tkinter. -- Regards, Diez B. Roggisch From tim.peters at gmail.com Mon Nov 1 19:45:24 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 1 Nov 2004 19:45:24 -0500 Subject: Why is heapify linear? In-Reply-To: <4186cb77$1@nntp0.pdx.net> References: <4186cb77$1@nntp0.pdx.net> Message-ID: <1f7befae04110116453cddea02@mail.gmail.com> [Scott David Daniels] > I am sorry, but in the Python 2.4 description of "heapify", I find the > description of "Transform list x into a heap, in-place, in linear time," > unbelievable. I understand the hand-wave that makes dictionary building > linear (though I have a hard time with even that). Could somebody tell > me what twist of logic makes "heapify" linear, except in the sense that > linear is coming to mean "very fast?" There are no hands waving. Dict-building is best-case and expected-case linear time, but worst-case quadratic time. For heapification, all three are linear. That's all rigorously provable (and typically are so proved in a first course on algorithmic complexity). Google on heapify linear to find proofs for heapification bounds. But you perhaps won't *believe* it until you can't deny it . So try it: """ class CmpCounter: def __init__(self, i): self.i = i def __cmp__(self, other): global cmpcount cmpcount += 1 return cmp(self.i, other.i) from heapq import heapify import random n = 10000 xs = [CmpCounter(i) for i in range(n)] def tryone(tag, xs): global cmpcount cmpcount = 0 heapify(xs) print tag, "len", len(xs), "# comparisions", cmpcount for i in range(10): random.shuffle(xs) tryone("random", xs) xs.sort() tryone("already sorted", xs) xs.sort(reverse=True) # using 2.4b1 here tryone("reverse sorted", xs) """ "Already sorted" is essentially the worst case for min-heap heapification (each new element added is then the smallest seen so far, and has to bubble all the way from the bottom of the heap-so-far to the new root location). Note that "the obvious" way to transform a list into a heap is not worst-case linear time. Linear-time heapification is due to Floyd. Someone should patent it . From steven.bethard at gmail.com Thu Nov 4 17:53:27 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Nov 2004 22:53:27 +0000 (UTC) Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> <1gmp6xu.zmiw6gs3250sN%aleaxit@yahoo.com> <1gmpyz8.11h86a71kjmdttN%aleaxit@yahoo.com> <1gmqqa3.r7hg5g17qatxkN%aleaxit@yahoo.com> <1gmqxmb.1r4easa174a86N%aleaxit@yahoo.com> <1gmr0ue.zaft2j1b4lr0nN%aleaxit@yahoo.com> Message-ID: Alex Martelli yahoo.com> writes: > [snip example decomposing float representation into mantissa, etc.] > [snip example determining struct type from first few bytes] > [snip example decomposing 16 bit error code into two 8 bit error codes] > [snip example determining utf-8 or utf-16 by trying byte stream as both] Thanks for the examples! I'm not quite convinced by the decomposition examples or the struct type example, but the UTF example is definitely convincing. I can imagine that you could extend this type of example to any case where you didn't know the actual type of a struct. Given this situation, you could try treating the bytes as each of the possible struct types, and see (heuristically or perhaps with a machine learning approach) which struct type is most appropriate. This definitely meets my criterion of treating the same set of bytes as two different structures, and it's even useful! =) Thanks! Steve From FBatista at uniFON.com.ar Mon Nov 8 15:29:19 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 8 Nov 2004 17:29:19 -0300 Subject: Escape chars in string Message-ID: [Ivo Woltring] #- I have this app that I want to be able to present in more #- than 1 language. #- To do this I use ConfigParser with an ini file. You really should check "gettext". . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.petrazzo at TOGLIunipex.it Tue Nov 2 03:36:19 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Tue, 02 Nov 2004 09:36:19 +0100 Subject: [wx] Simple image editor In-Reply-To: References: Message-ID: Jeremy Bowers wrote: > On Sat, 30 Oct 2004 11:28:35 +0200, Michele Petrazzo wrote: > > >>Please don't tell me to read the GIMP's source :). > > > Why read GIMP's source when you can use it? Because I want to understand how it work, not how the user use the tools. > Can you shell out your manipulations, and then just take a changed version > of the image back in? > > Of course, any image editor will work then, too. > > Maybe not, I don't know your needs. But it is worth thinking about. Image > editors are in the class of applications that you should go to great > lengths to avoid rewriting. To get anything beyond the Paint that shipped > with Windows 3.1 is a major effort, plus unless you really, really know > your users don't want anything but primitive text overlays, you're asking > for an infinite amount of feature requests to add things that other image > editors already have. I want to add a simple image editor into my application, that not is an image editor,but a fax client, so the features of place text/lines are the only that I need. > Plus, the naive implementations of things like > "undo" eat memory for lunch. The "undo" work yet correctly.I have three list with: 1) all the points of the lines, ... 2) text, font, color, position, dimensions, ... 3) "l" or "t", that mean line or text. Every time that I place a line, I append into list 1 all the values and into list 3 a "l". for the text is the same. When I press undo button, I pop a value from list 3, and pop a value from correspondent list. After this I rewrite all the bitmaps. It work, but if I have a lot of "objects", I must attempt that it redraw all. Thanks, Michele Petrazzo From deetsNOSPAM at web.de Thu Nov 18 10:41:01 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 18 Nov 2004 16:41:01 +0100 Subject: numarray References: <2617fd5d.0411180721.12c50d8a@posting.google.com> Message-ID: > if I just enter > >>>>Import Numeric > > I get > >>>> > > indicating that numarray is installed correctly. > > What am I doing wrong? I doubt that that works. "Import" won't do it - it yields a syntax error. What you meant is import Numarray But you have to keep in mind that importing a module that way will not put it in the global namespace. So you have to qualify function names: Numarray.array Or you import them using the "from" syntax, which will bind the Numarray names in the global namespace: from Numarray import * -- Regards, Diez B. Roggisch From alain.marcel at svd-info.fr Fri Nov 5 08:58:43 2004 From: alain.marcel at svd-info.fr (Alain) Date: 5 Nov 2004 05:58:43 -0800 Subject: PyXml and XPath implementation Message-ID: Hi ! I'm looking for an XPath implementation (even partial) on PyXML. I'm using libxml2 on Windows XP. It works well but I have to port my application on RISCOS (OS on ARM processor) where only PyXML is ported. Thanks. Alain From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Nov 3 12:38:18 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 03 Nov 2004 18:38:18 +0100 Subject: Problems with profiling results (hotshot or normal) : almost all are incorrect In-Reply-To: <41882aa4.1466900701@news.oz.net> References: <41881ba2$0$78738$e4fe514c@news.xs4all.nl> <41882aa4.1466900701@news.oz.net> Message-ID: <41891788$0$78772$e4fe514c@news.xs4all.nl> Bengt Richter wrote: > On Wed, 03 Nov 2004 00:43:31 +0100, Irmen de Jong wrote: > > >>Hello >>I haven't received any responses on my original posting, >>and it could very well be that it never made it to the newsgroup >>(because I can't find it back on my news server here). >>So I'm posting this again. Sorry if it *did* make it to >>the group.. Please consider trying my test-program that is given >>here and let me know how it works on your python installation. >> >>Thanks for any insight on this. >> > > Traceback (most recent call last): > File "C:\pywk\clp\irmen2.py", line 86, in ? > import hotshot, hotshot.stats, wait > ImportError: No module named wait > > Where does wait come from? Aww, terribly sorry. Should test any code that I post. (I called the test script "wait.py" on my system, that's why it worked here, locally) Here's a fixed version: import time def foo(): # idle wait loop time.sleep(0.5) def bar(): # busy (CPU) wait loop s=time.time() while time.time()<(s+0.5): pass def test(): for i in range(10): foo() bar() if __name__=="__main__": import hotshot, hotshot.stats import profile, pstats print "HOTSHOT profiling..." prof = hotshot.Profile("wait.prof") prof.runcall(test) prof.close() print "PROFILE DONE" stats = hotshot.stats.load("wait.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(40) print "Normal profiler..." profile.run('test()', 'wait.prof') print "profile done" stats = pstats.Stats('wait.prof') stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(40) From aleaxit at yahoo.com Sat Nov 6 12:57:03 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 Nov 2004 18:57:03 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> Message-ID: <1gmueqr.1hs16lxfjegpuN%aleaxit@yahoo.com> Dan Perl wrote: > Are you learning any new subject now and are you involved in a newsgroup as > a newbie? If you're not doing that already, python experts, please try it > and you'll probably see what it's like. No better way to see the other > side's point of view than being on the other side. What if we do, _AND_ carefully follow Eric Raymond's excellent recommendations each and every time we ask for help? Are then we allowed to loathe and despise the mass of clueless dweebs?-) I can be a newbie at a bazillion subjects, easily -- but I cannot truly be a newbie at such tasks as human interaction, social dynamics, general information retrieval and processing. I can easily guess what will happen if I enter any mailing list or newsgroup with both guns blazing out of frustration, for example, and therefore I cannot easily sympathize with anybody who _does_ behave so foolishly. It's not a matter of expertise about any specific subject, not even exactly one of skills, but rather one of personal maturity and character. I know how to search mailing list archives, or google groups ones, and considerate enough to use this easily acquired and very useful knowledge to try and avoid wasting other people's time and energy, for example, by airing some complaint that's been made a thousand times and answered very comprehensively. When I can't find an answer that way, I ask with courtesy and consideration and appreciation for the time of the people who, I hope, will be answering my questions. Etc, etc -- reread Eric's essay on how to ask for help, it's a great piece of work. That doesn't mean a newbie isn't always welcome, _if_ they show any sign whatever of being worth it. But asking for tolerance and patience against _rude_ newbies which barge in with shrill, mostly unjustified, repetitious complaints, is, I think, a rather far-fetched request. Alex From skip at pobox.com Fri Nov 19 14:42:43 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Nov 2004 13:42:43 -0600 Subject: Microsoft Patents 'IsNot' In-Reply-To: <20041119192934.EB3A81E4009@bag.python.org> References: <16798.16559.745209.751967@montanaro.dyndns.org> <20041119192934.EB3A81E4009@bag.python.org> Message-ID: <16798.19635.797903.635071@montanaro.dyndns.org> Eddie> Best way to discourage visual basic knock offs, is to try and use Eddie> visual basic, in my opinion. QOTW? S From deetsNOSPAM at web.de Tue Nov 30 17:38:10 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 30 Nov 2004 23:38:10 +0100 Subject: ANNOUNCE: Ice 2.0 released References: <22868227.0411300634.1d333921@posting.google.com> <0YidnREmZ8xECDHcRVn-oA@speakeasy.net> <22868227.0411301123.c18dec9@posting.google.com> Message-ID: > I believe whichever road you take, ZeroC is going to find itself in > problems. If ZeroC merges the changes made by this/these person(s), > how can ZeroC now sell it under a commercial license, as closed source > (violation of GPL)? If you refuse to merge the changes, you have just > given them a strong impetus to fork. History shows XEmacs and EGCS as > two such examples. AFAIK qt is licensed the same way. And there is nothing bad about forks - but they have to be GPLed too. Maybe you're not aware of an implication of GPL: A product _using_ a GPL'd library also has to be GPL. That means you can't develop a commercially marketed product on top of a GPL library - AFAIK the exact reason why the LGPL was created, so that you may not alter the lib itself and sell it, but at least sell software that _uses_ the lib. So all in all, it seems the GPL/Commercial license makes sense - it does for trolltech :) And there is nothing in GPL that forces you to integrate code you've been offered - otherwise, killing a GPL lib would mean to delete all from a CVS checkout and submit a patch from that - obviouly nobody would enforce that. -- Regards, Diez B. Roggisch From belred1 at yahoo.com Fri Nov 5 01:55:22 2004 From: belred1 at yahoo.com (Bryan) Date: Fri, 05 Nov 2004 06:55:22 GMT Subject: why python is slower than java? In-Reply-To: <418b166f$1@news.unimelb.edu.au> References: <418b166f$1@news.unimelb.edu.au> Message-ID: Maurice LING wrote: > This may be a dumb thing to ask, but besides the penalty for dynamic > typing, is there any other real reasons that Python is slower than Java? > > maurice at work, we use java and python. we have projects using swing and others using wxpython. we have applications that do intensive io and others that do intensive cpu. we have not found that python is slower than java. in fact, when it comes to gui's, our swing apps take "forever" to startup and when when garbage collector starts, the whole app just freezes for about 15 seconds. our wxpython apps, start right up and "feel" faster and snappier. can you show an example of where python's "slow" speed as compared to java's "fast" speed has negatively impacted your application or has been noticable in any way? i know this is a trolling question you have posted, but i'm actually very interested knowing why you have said this. thanks, bryan From dmerrillq at usaq.netq Tue Nov 30 08:55:37 2004 From: dmerrillq at usaq.netq (Dave Merrill) Date: Tue, 30 Nov 2004 08:55:37 -0500 Subject: RELEASED Python 2.4 (final) References: <8sGdnQjN6qGu7THcRVn-3A@rcn.net> Message-ID: Used the packaged Windows (win2k) installs of Python and all components I described. Not a C guy, no compiler, minimal knowledge about them. Dave Merrill "Anthony Baxter" wrote: > > Newb question: Is it possible/recommended to have multiple versions of > > Python installed simultaneously? Earlier, I installed 2.4rc1, and a number > > of things in my 2.3.3 install stopped working. Are there known techniques > > for managing multiple versions? > > If you're building from source, use 'make altinstall' rather than > 'make install'. > This will install Python as $prefix/bin/python2.4, and leave the > 'python' executable > alone. From nun at example.com Mon Nov 8 17:12:00 2004 From: nun at example.com (Mitja) Date: Mon, 8 Nov 2004 23:12:00 +0100 Subject: Determining combination of bits References: <8KQjd.121796$hj.4674@fed1read07> <418ff674$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Sean Berry wrote: >> Just to set everyone's mind at ease... I haven't had a >> homework assignment for about four years now. > OK, then here's a great little bit of education: > > n & -n == least significant bit of n A lapse of mind? >>> n = 6 >>> n & (-n) 2 You probably meant n&1 or perhaps n%2. From has.temp2 at virgin.net Sun Nov 7 06:46:43 2004 From: has.temp2 at virgin.net (has) Date: 7 Nov 2004 03:46:43 -0800 Subject: cherrypy/cheetah vs twisted/nevow References: <418818ca$0$19452$626a14ce@news.free.fr> <69cbbef2.0411050857.6dfe11bd@posting.google.com> Message-ID: <69cbbef2.0411070346.6c6c0eaf@posting.google.com> Carlos Ribeiro wrote in message news:... Carlos Ribeiro wrote: > I'm not sure if I understand your point, and it may be the case that > I'm really missing something. I think that, by its very definition, > templating systems (including variables, conditionals, loops, and > other control structures) *do* mix some aspects from the model into > the view. You're confusing presentation logic with business logic. In MVC, only *business* logic should go in the Model layer; presentation logic belongs elsewhere. The Model does *not* dictate how the User Interface layer(s) should receive input or present data. Think of the Model as a complete program within another program, containing all the smarts needed to do its job but providing no way for end-users to interact with that data. All it supplies is an API into which user-interface code can connect. Aside from just being good architecture by minimising the amount of coupling between code, such separation is genuinely useful. For example, one should be able to plug any number of UIs into a single Model to handle input and present data in different ways. Many Mac applications provide at least two user interfaces out of the box: a graphical user interface and an Apple event interface. Some implement more, e.g. BBEdit also provides a CLI interface, FileMaker a web interface. Web applications may provide a browser-based interface PLUS an XML-RPC/SOAP interface. And so on. A good mental test is to ask yourself: "If I remove the UI, will the Model still function if I control it programmatically directly by its API? If I replace the Model with an API stub that silently accepts input and returns dummy data, will my UI still function? Can replace one UI with another? Can I add multiple UIs, and will they all work at the same time?" > One may argue at which extent it's possible to keep both > apart -- at some point, there must be an interface -- so it may be a > matter of personal choice. MVC is quite clear about where the interface goes: between business logic and presentation logic. > My current standing (after a long break from applications development, > which allowed me to re-enter with a fresh perspective, but also a > little 'rusty') is that the templating interface should be made > simpler, Oh, I agree completely. I wrote two other templating systems before HTMLTemplate, and they were huge, complex beasts because I failed to factor the problem adequately before charging ahead with the solution. With HTMLTemplate I finally got it right. Whereas most templating systems provide direct support for both presentation logic and markup, HTMLTemplate implements support for the markup side only and leaves the host language to take care of all logic. This gives a system that is both extremely simple (turning markup into a simple object model is trivial) and incredibly powerful (as powerful as the host language, in fact, since that's what the presentation logic is written in). > that the model should take care of the intermediation. Absolutely not. Presentation logic belongs in the UI code, not the Model. With systems like Cheetah and TAL, the presentation logic is embedded within the template markup itself. I don't like this approach myself because it makes the template system responsible for supporting that logic, adding a huge amount of complexity to it (something I learned the hard way myself). See also Greenspun's Tenth Rule. With PyMeld, Nevow.Renderer and HTMLTemplate, the presentation logic goes in a separate Python script, where it clogs up neither business logic nor HTML markup and makes the templating engine a cinch to implement as the only thing it has to do is convert markup into a form the script can manipulate - a trivial task. > For example, I *feel* that repetitive elements (like > lists and reports) shouldn't be modelled as programming loops inside a > template. I really don't have a solution for this yet. This is presentation logic, so belongs in the UI layer(s). > Albeit > confusing, XSLT is a step in the right direction, but it sometimes > feels like they're trying to fit a square peg into a round hole. XSLT is a basic declarative language beneath a really horrible syntax. Like macro-style templating systems it spends an inordinate amount of effort implementing a ridiculously complex and expensive solution to what should be a trivial problem, then patting itself on the back for its incredible brilliance and devotion to hard work for successfully... reinventing the wheel (yet again). I find this sort of thing terribly depressing, because it conditions people into thinking complex solutions to complex problems are actually something to aspire to, rather than avoid as much as possible. To quote Alan Perlis: "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it." But anyway, I digress... > Nevow implement a very intriguing idea: it allows to derive the *structure* > from the template. Nevow implements six or seven extremely interesting ideas. I think its biggest problem is it does this as one huge package rather than six or seven independent modules, which makes it a bit of a bear to get on top of and also cuts down on reusability which is a shame. > I'm still looking, though. I'd suggest looking at HTMLTemplate. It's simpler than Nevow.Renderer and faster than PyMeld, mature, has no significant dependencies and is small enough to pull apart and grok (and hack) quite easily: http://freespace.virgin.net/hamish.sanderson/htmltemplate.html It also maps well to the Apple definition of MVC: - The View layer is constructed by the template compiler, which converts HTML markup into a simple, specialised object model. - The Controller layer is provided in the form of a callback function, renderTemplate (the compiler attaches this to the compiled template for your convenience) and some code to tell the compiled template to render some data, and do something useful with the result. (Graham Dumpleton has been working on a simple framework to handle all the dogsbody work here for you .) - The Model layer is entirely your own business; all it needs to do is provide an API that your Controller can talk to in order to obtain the data it needs to insert into the template. (Admittedly, the trivial examples I've provided don't show separate Model and Controller layers, but that's because they're too simple to need a proper Model. I've done more complex stuff that does though, and it works out just fine.) HTH has From sonium at gmail.com Wed Nov 3 12:08:37 2004 From: sonium at gmail.com (Sonium) Date: Wed, 03 Nov 2004 18:08:37 +0100 Subject: Problems using numarray Message-ID: Hi, I am new to numarray and I'm going to use it in a nummerical computation of planet and probe orbits. There for I created a body class, representing an gravity affected mass (like a planet or a probe). Now I have different bodys each with it's own position, velocity and mass that pull each other together by gravity. Based on the previous position and velocity I'm now calculating the positions and velocity for the next timeframe and so on... So I get a quite high amout of data because i have to store (number-of-bodys)*(number-of-timeframe) objects. Now, how can I use a numaray to store the body objects? I read the docu, but didn't figure out how to solve my problem. In C++ I just created a multidimensilnal array like data = new body[objects*timeframes] and I'm looking for something synonymous with numarray. - Sonium From michael at stroeder.com Tue Nov 2 13:40:48 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 02 Nov 2004 19:40:48 +0100 Subject: Python needs a CPyAN In-Reply-To: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> References: <4187b7a1$0$2383$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > > Just today we required a module that was not installed on our system. > > sudo perl -MCPAN -e 'install Data::Pager' > > And it was installed with all it's dependencies. I'd rather call that a security and maintenance nightmare... Ciao, Michael. From hungjunglu at yahoo.com Thu Nov 18 11:31:28 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 18 Nov 2004 08:31:28 -0800 Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) References: <30001hF2ptnqcU1@uni-berlin.de> Message-ID: <8ef9bea6.0411180831.e44ae56@posting.google.com> Carlos Ribeiro wrote: > > Dicts are not the best way to make it, because they are not ordered > :-) But perhaps we could have something like "named tuples"; > > @returns('year','month','day') > def today(): > ... > return year, month, day As someone has mentioned, usage of tuples is not very scalable and tend to lend itself to carcass entries in the long run, or simply to the breaking of compatibility. But I guess in your case, you want to do something like printing out the results, so, as long as all items are involved, an order would be beneficial. ------------------ For whatever it's worth, here are two more approaches for unordered keyword argument and return. (1) Usage of structures certainly is painful in C++, but not in Python. What I often use is some generic object: class Generic: pass def today(p): print p.message r = Generic() r.year, r.month, r.day = 2004, 11, 18 return r p=Generic() p.message = 'Hello!' result = today(p) I suspect a large number of people use this approach. Generic objects are also good for pickling/serialization. (By the way, why is the new style class "object()" made so that no dynamic attributes can be assigned to it? Compared to dictionary, generic object is very helpful as a syntax gadget and is used by many people. I am a bit surprised that it's not part of the language. Why make so many people having to resort to the "class Generic: pass" trick?) (2) Use the function object itself: def f(): if not hasattr(f,'x'): f.x = 1 else: f.x += 1 f.y, f.z = 2*f.x, 3*f.x f() print f.x, f.y, f.z f() print f.x, f.y, f.z Of course, this approach has more limited applicability. (Not good for multithreaded case, not good for renaming the function object or passing it around.) Hung Jung From martin at v.loewis.de Sat Nov 20 17:48:29 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 20 Nov 2004 23:48:29 +0100 Subject: unicode question In-Reply-To: References: Message-ID: <419fc9b9$0$198$9b622d9e@news.freenet.de> wolfgang haefelinger wrote: > I wonder especially about case 2. I can see that "print y" makes a call to > Y.__str__() . But Y.__str__() can be printed?? So what is 'print' exactly > doing? It looks at sys.stdout.encoding. If this is set, and the thing to print is a unicode string, it converts it to the stream encoding, and prints the result of the conversion. Regards, Martin From michele.petrazzo at TOGLIunipex.it Mon Nov 22 12:54:05 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 22 Nov 2004 18:54:05 +0100 Subject: zip module password Message-ID: Is there a method for add a password to a file created by zip module? Thanks, Michele From craig at postnewspapers.com.au Mon Nov 22 04:17:47 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 22 Nov 2004 17:17:47 +0800 Subject: readlines() with large file raises: IOError: [Errno 12] Cannot allocate memory In-Reply-To: <10500383.1101114384879.JavaMail.ngmail@webmail-01.arcor-online.net> References: <10500383.1101114384879.JavaMail.ngmail@webmail-01.arcor-online.net> Message-ID: <1101115067.7573.4.camel@albert.localnet> On Mon, 2004-11-22 at 17:06, nicogrubert at arcor.de wrote: > Does pyhon tries to put the content [of the readlines() operation ] > into machine's RAM (512 MB) which is not big enough so an > exception is raised? Pretty much, yeah. A memory allocation failed, probably because of running out of RAM and swap, as it loaded the entire file into RAM and made a list out of it. Consider using file.xreadlines() instead - that uses an iterator to the job and is much more memory efficient. -- Craig Ringer From holbertr at dma.org Mon Nov 29 15:20:15 2004 From: holbertr at dma.org (Rick Holbert) Date: Mon, 29 Nov 2004 15:20:15 -0500 Subject: date diff calc References: Message-ID: Here's how to do it as a one-liner: python -c "import datetime; import time; print 'Only %d days until Christmas' % (datetime.date(2004, 12, 25) - datetime.date.fromtimestamp(time.time())).days" Here's a slightly shorter way of doing it: python -c "import time; print 'Only %f more days until Christmas' % (float(time.mktime(time.strptime('2004-12-25', '%Y-%m-%d')) - time.time()) / 86400)" From riko.wichmann at remove-this.desy.de Tue Nov 30 03:49:05 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Tue, 30 Nov 2004 09:49:05 +0100 Subject: comment out more than 1 line at once? Message-ID: Dear all, is there a way in Python to comment out blocks of code without putting a # in front of each line? Somethings like C's /* block of code here is commented out */ Thanks, Riko From steve at ferg.org Wed Nov 17 10:51:43 2004 From: steve at ferg.org (Stephen Ferg) Date: 17 Nov 2004 07:51:43 -0800 Subject: seeking a new host for the "Python Grimoire" References: Message-ID: STATUS UPDATE Talking to Richie Hindle has given me the idea of setting up the Grimoire as a wiki on Python.org. I'm not a real sophisticated wiki user, but I can probably do it. I really like the idea of the Grimoire becoming community-maintained documentation, something that I've advocated for a long time, and something that I think we need more of. If the wiki idea doesn't work out, there are a couple of folks who have volunteered to host the Grimoire in the future. From janimal at mail.trillegaarden.dk Mon Nov 22 16:12:45 2004 From: janimal at mail.trillegaarden.dk (Peter.....) Date: Mon, 22 Nov 2004 22:12:45 +0100 Subject: login script to database Message-ID: <41a25361$0$17573$ba624c82@nntp06.dk.telia.net> Hi all. I want to make a login script( using python) to a homepage. The password and name is stored in a PostgreSQL database, so I have to go to connect to the database ( I know how to do that ) but I dont know how to write a login script in python and how to look if the password and name entered is the same as in the database, if it is I want to link to a webpage www.webpage.com if it isnt I want it to write a message like " Wrong password entered " Can any help me out :D Thanks for your time.. From caleb1 at telkomsa.net Sat Nov 27 21:58:56 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Sat, 27 Nov 2004 21:58:56 -0500 Subject: Delphi underrated, IDE clues for Python References: <5c882bb5.0411270517.77ccc654@posting.google.com> Message-ID: thx, I already have and use PythonForDelphi (and am on the mailing list). It works very well indeed, my impression is that Python-Delphi connection is even easier than Python-C integration (e.g. via SWIG, etc), due once again to the Delphi IDE. Drag-n-drop in the IDE gets you python code in your delphi code, or delphi units/objects accessible in python. However, Delphi is not platform indpendent (which is important for me as I use a different OS at work and at home), and I don't know if PythonForDelphi supports Kylix. I am fairly sure it doesn't support Lazarus, which IS platform independent, but not as feature-rich as Delphi. Btw, on the SHOOTOUT page, you'll see that the Delphi rank for LOC is 28. This number is pretty meaningless in practice because the IDE does a lot of code generation for you. More interesting would have been to see the rank for LOC you have to type yourself... On 27 Nov 2004 05:17:38 -0800, bearophile wrote: > Delphi is a very good language, and quite fast too: > http://dada.perl.it/shootout/delphi.html > > > Caleb Hattingh>STILL...Having a Delphi-like IDE for Python would make me > giddy. > > Maybe here you can find a way to use both at the same time: > http://www.atug.com/andypatterns/pythonDelphiTalk.htm > http://membres.lycos.fr/marat/delphi/python.htm > > Bearophile From jean-louis.nespoulous at vatech-td.fr Tue Nov 23 02:53:17 2004 From: jean-louis.nespoulous at vatech-td.fr (Jean-Louis Nespoulous) Date: 22 Nov 2004 23:53:17 -0800 Subject: Help for a newbie in Python and ZODB References: <39eca62c.0411212341.330dabdc@posting.google.com> Message-ID: <39eca62c.0411222353.4ad4f2bc@posting.google.com> Thanks, but I'll use ZODB as server and I'll get and retreive objet from a distance client using XML-RPC, do you think it's possible easily? Jean-Louis Thomas Guettler wrote in message news:... > Am Sun, 21 Nov 2004 23:41:39 -0800 schrieb Jean-Louis Nespoulous: > > > Hello everybody, > > I am in charge to develop a system who will analyse a network, type > > Three-Tier Architecture. I would like to use ZODB or (exclusive) > > PostgreSQL. But I don't know witch one to use? > > > Someone could help me > > and tell me what are the differencies between ZODB and PostgreSQL? > > PostgreSQL is a relational database. You store data in tables which > have columns and rows. You access it with SQL. PostgreSQL supports > inheritance, but you still need some mapping between your objects and the > database. You can access postgres with any programming language. > > > My system will be developped in Java. If I use ZODB how I'll make the > > transition with Python? > > If you use Java, you can't use ZODB. > > ZODB stores pickled (serialized) objects. > Here you don't need a mapping between objects and database. > SQL makes no sense with ZODB. The query language is python. > > HTH, > Thomas From exarkun at divmod.com Thu Nov 4 13:24:23 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 04 Nov 2004 18:24:23 GMT Subject: Summary: strong/weak typing and pointers In-Reply-To: Message-ID: <20041104182423.23443.953824555.divmod.quotient.1458@ohm> On Thu, 4 Nov 2004 17:39:45 +0000 (UTC), Steven Bethard wrote: > divmod.com> writes: > > > > Python 2.3 (#3, Jan 26 2004, 21:50:33) > > [GCC 2.95.3 20010315 (release)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import intrinsics, become > > >>> class phpstr(str): > > ... def __setitem__(self, index, value): > > ... become.memwrite(id(self) + 20 + index, str(value)[0]) > > ... > > >>> oldstr = intrinsics.replace(str, phpstr) > > >>> foo = 'abc' > > >>> foo[0] = 65 > > >>> foo > > '6bc' > > Oooh! So dirty! ;) > > I've never used the intrinsics module (and Googled, but apparently didn't search > for the right thing), but does this do a global replace? E.g. if my module > imports some module that calls intrinsics.replace(str, phpstr), are all the uses > of str in my module then replaced with phpstr's? > Yep, totally global. If any code in a process calls replace(), every literal will be an instance of the new type. Also, the Python process will segfault at exit, and possibly other times. This, together with your original comment ("So dirty! ;)") is why I've never bothered releasing the module :) My website (which had a page about the module) has been done for a couple weeks, which may be why google has bumped it from search results. Probably for the best, really ;) Jp From aleaxit at yahoo.com Tue Nov 16 06:25:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 16 Nov 2004 12:25:08 +0100 Subject: Zope 3.0, and why I won't use it References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> Message-ID: <1gncejc.1pmb5x2rs2cojN%aleaxit@yahoo.com> Ville Vainio wrote: > >>>>> "Alex" == Alex Martelli writes: > > Alex> where builtin 'adapt' does protocol adaptation. On the > Alex> other hand, if the semantics of those 'as' clauses were > Alex> something like: > > Alex> def x(y, z): > Alex> if type(y) is not foo: raise TypeError, 'y must be foo' > Alex> if type(z) is not bar: raise TypeError, 'z must be bar' > Alex> > > Alex> then that's the day I move to Ruby, or any other language > Alex> that remained halfway sensible (if any). > > Even if it allowed portions of the code to be statically compiled to > reach "native" performance? Or if it allowed resolving ambiguous > situations in type inference? Type declarations would of course be > optional, and they could be a big win esp. for non-cpython My prediction is that, once 'of course optional' type declaration gets in, it will become the mandated approach in most new-to-Python shops, by fallacious analogy with (say) VB and Perl's "optional" type declaration, and by dint of managers' general liking for putting silly unjustified restriction on professionals to hamper their productivity. That is going to be a huge cost. What will it buy in exchange? If typenames in a type declaration context can be statically resolved at compile-time, then so can just about every other use of names, right? After all, if the compiler can statically resolve what object 'foo' is bound to in a clause 'x as bar.foo', it means it must somehow have inferred that some 'class foo' statement will inevitably get executed before then in module bar, or whatever other attribute assignment produces that binding of name 'foo' within name 'bar'. And of course the 'foo' type will generally be built up in another module, so we're talking about a compiler that examines other modules in order to be able to compile this one. Whole-program compilation with compile-time inferred name-object bindings would be such a huge and total revolution wrt today's Python that very little would stay the same. OK, then, if that's the revolution that's in Python's future, let's see it come _first_ -- there would be huge wins without requiring any source code changes _IF_ name-to-object resolution could be uniformly done at compile-time rather than at runtime, even across modules. Though I've never seen any example of whole-program compilation and optimization done right, in practice (with compile time NOT growing faster than O(N) and soon becoming untenable for large programs), I do know that _in theory_ it's feasible -- I'd just be astonished if it was shown that Python, never having been designed for it, "just happens" to be the right language to have it finally occur. > implementations of the language. Beats reverting to C#/whatever for > situations where you want good JITtability. In CPython "adaptation" > might be the way to go, of course, but that would still enable the > same code to run on different variants of Python. If adaptation was a dialect-specific thing, it would hamper the ability to move large frameworks and applications across dialects. I don't see "falling back" to a lower-level language where you need one as a disaster. Doesn't have to be _AS_ low-level as C# or Java or C, of course; I think pyrex does a great job of showing how a restricted Python dialect/variant which, among other things, includes optional declarations, can make your life much easier. I don't see why there couldn't be pyrex# or Jirex versions, or even languages inspired from Python but farther from it than Pyrex is, such as Bobo. > Alex> syntax sugar;-) ends up being a way to ease *type-checking*, > Alex> then, well, I'll evaluate that as being on a par with easing > Alex> alcohol abuse. What > > I don't think people have been too keen to get static type checking > into the language anyway. It might be an option in pychecker, but that > should be enough. Dynamic type checking, well, that's an obvious net > loss over adaptation. I agree pychecker or the like might well have options to check on everything under the sun -- no problem. For reasons that escape me, shop rules such as "all programs will pass lint with this and that option" seem to never stick. Shop rules such as "-Wall -pedantic on all compilations and NEVER any commit of code with warnings" (a good idea, actually) or "all VB programs must have option explicit" (maybe better than nothing, given VB's typing mess, if you have to do VB) or "all perl runs will always have -w" (probably a good idea), etc, etc, _are_ observed, in practice, to stick. And there are good rules for Python, too, of course, ones that promote productivity, from 'we do not ever use "exec"' to similar edicts against 'from x import *'. As long as control freaks don't get an effective way to destroy Python's greatest strength, namely signature-based polymorphism, I'm happy... Alex From i_hate at spams.biz Tue Nov 30 09:07:43 2004 From: i_hate at spams.biz (i_hate at spams.biz) Date: Tue, 30 Nov 2004 15:07:43 +0100 Subject: private attributes in __slots__ and pickle Message-ID: <41ac7e5f$0$13412$636a15ce@news.free.fr> Hello, I've just discovered the hard way that classes declaring private variables (beginning with two underscore) can not be pickled ; double underscored attributes are just not returned by __reduce__. That's very annoying. Objects should be serializable transparently so why such obstacles ? From onurb at xiludom.gro Thu Nov 11 14:08:33 2004 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 11 Nov 2004 20:08:33 +0100 Subject: web hosting with Python In-Reply-To: <3cccb1d8.0411101416.690960c3@posting.google.com> References: <3cccb1d8.0411101416.690960c3@posting.google.com> Message-ID: <4193b6b1$0$9343$626a14ce@news.free.fr> MJR a ?crit : > Hi, > anybody could recommend web hosting company which offer professional > reseller package with Python, preferable located in Europe? http://www.modulix.com The Python part is not really advertised yet, but we do offer mod_python and Zope support. You can contact me for more informations. Bruno From tjreedy at udel.edu Mon Nov 8 15:27:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Nov 2004 15:27:47 -0500 Subject: Determining combination of bits References: Message-ID: "Sean Berry" wrote in message news:x3Qjd.121786$hj.41260 at fed1read07... > and I am given some numbers, say 22, 25, and 9. I want to determine the > keys, powers of 2, that comprise the number. > How do I get these keys? if n%2: print 'has a positive one bit' n//2 == n>>1 deletes that bit keep track of divisions/shifts and stop when n == 0 Terry J. Reedy From harry.g.george at boeing.com Tue Nov 30 09:15:31 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 30 Nov 2004 14:15:31 GMT Subject: RELEASED Python 2.4 (final) References: <8sGdnQjN6qGu7THcRVn-3A@rcn.net> Message-ID: "Dave Merrill" writes: > Newb question: Is it possible/recommended to have multiple versions of > Python installed simultaneously? Earlier, I installed 2.4rc1, and a number > of things in my 2.3.3 install stopped working. Are there known techniques > for managing multiple versions? > > Thanks, > > Dave Merrill > > I can only speak for *NIX systems; don't know about MS Win** systems. The quick answer is "Yes, it can be done". 1. Build and install as make altinstall This installs, e.g.: /usr/local/ bin/ python2.3 lib/ python2.3 It does NOT also make an entry at /usr/local/bin/python. Thus any scripts which call for "python" or "/usr/bin/env python" get the default version. 2. Make a wrapper script, e.g. /usr/local/bin/py23: unset PYTHONHOME PYTHONPATH /usr/local/bin/python2.3 "$@" 3. Use "py23" to build site-packages. Since you need to do this repeatedly, it is best to save the build scripts on a python-version basis. E.g., a "go23" script. Inside the scripts, use "py23" as appropriate wherever you would have used "python". e.g.: .... export PKGVER=Numeric-23.0 ln -s ../${PKGVER}.tar.gz . gzip -cd ${PKGVER}.tar.gz | gtar xvf - cd ${PKGVER} py23 setup.py build py23 setup.py install cd .. .... 4. When another python version shows up, copy the go23 to go24, edit it for py23-->py24, and start building. Use either version at the commmand line or in other scripts via py23 or py24. NOTE: In cgi's, give the full path, e.g.: #!/usr/local/bin/python2.3 -- Harry George harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From TheDolphin at ivonet.nl Mon Nov 8 15:20:11 2004 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Mon, 8 Nov 2004 21:20:11 +0100 Subject: Escape chars in string Message-ID: <418fd4fb$0$147$3a628fcd@reader1.nntp.hccnet.nl> Dear Pythoneers, I have this app that I want to be able to present in more than 1 language. To do this I use ConfigParser with an ini file. My question: when I 'get()' the message with ConfigParser the \t in the string is a litteral and is not translated to a tab. Why is this so? if I do tests with somthing like s = '&Quit\tAlt-Q' it does work. What is the difference? and how can I get the desired behavior? e.g. [msg_quit] uk = &Quit\tAlt-Q nl = &Stoppen\tAlt-S Hope y'all can help Ivo. From reinhold-birkenfeld-nospam at wolke7.net Wed Nov 3 11:57:21 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 03 Nov 2004 17:57:21 +0100 Subject: What is Python's answer to Perl 6? In-Reply-To: References: <2uh4j7F2a86uqU1@uni-berlin.de> Message-ID: <2usgvoF1te0btU1@uni-berlin.de> Y2KYZFR1 wrote: > Reinhold Birkenfeld wrote in message news:<2uh4j7F2a86uqU1 at uni-berlin.de>... >> Hello, >> >> another Perl/Python question: the subject says it all. >> >> Perl is going to change dramatically to become a more powerful and >> easier to (read|write) language. >> >> Is Python taking a similar step (-> Python 3) some time in the near future? >> >> Reinhold > > nice troll bait . . . Yes, I confess, the article was intendedly trolly. But I got interesting views on the issue, and for that I want to thank you all. > Python has always been the most READABLE and WRITABLE language, and > will continue to be extremely MAINTANCE friendly. > > Perl has always been a WRITE only, MAINTANCE nightmare language. For > MANY reasons. > Nothing in the Perl 6 docs leads me to believe that it will be any > less cryptic and obfuscated and propeller head appealing than 5. More > complicated if anything. I read through the Apocalypses, etc., and my first thought was: Wow, so many features! But afterwards I realized that this featurism combined with Perl ideology MUST lead to a total confusion in programming. Perl is neat as long as it does what you mean - it helps you in that, but once the DWIMmyness is too dumb to realize what you want, you have a double-hard time finding a solution. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From firemoth at gmail.com Thu Nov 18 21:02:46 2004 From: firemoth at gmail.com (Timothy Fitz) Date: Thu, 18 Nov 2004 21:02:46 -0500 Subject: Exponential Notation and integers In-Reply-To: References: Message-ID: <972ec5bd041118180239011419@mail.gmail.com> My comment is more of a linguistic complaint. The differences between an integer (type int or long) and a float in practice are large, shouldn't 1e100 be of an integer type, since it -is- an integer? The default practice here of making it a float just seems wrong. [Peter Hansen] > Maybe something like this would help the OP: > > >>> def number(x): > ... return int(float(x)) > ... > >>> MYCONSTANT = number('1.344e3') > >>> print MYCONSTANT > 1344 Yes, this would work in some cases, but not where it matters. Floats have a significant amount of error when you are talking about very large numbers, which is the only time you would want integer exponential literals anyway, examples of errors: >>> long(1e100) 10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104L >>> 1e20 == 10 ** 20 + 8192 True >>> long(1e23) == 10 ** 23 False The worst part is that because python will implicitly convert between floats and integers, this can all happen silently and come back and bite you where you least expect it. From carribeiro at gmail.com Mon Nov 22 07:24:49 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 22 Nov 2004 10:24:49 -0200 Subject: The Microsoft Platform Ahead by David Platt; thoughts about Python and Zope In-Reply-To: References: Message-ID: <864d3709041122042455f1164a@mail.gmail.com> On Sun, 21 Nov 2004 19:16:48 GMT, John Benson wrote: > Hi, I've been reading the above-titled book and it looks like some major > Python and Zope features have been cherry-picked for pushing down into .NET, > like application memory management (Python interpreter), and prefabricated > website user management (Zope). I would be concerned if Microsoft was pushing for patents on things previously implemented by Python or Zope. > Will the open-source web service frameworks suffer the same fate as the > Netscape browser? Microsoft has show with the IE 6 fiasco that they have no long-term commitment. As soon as they think that they have obliterated competition they stop developing. And their customers are learning it too. For many companies older versions, such as NT4 and Win98 are still quite usable... but as MS discontinues support, it *forces* them to upgrade. Worse: there are applications written for older frameworks that simply will not be supported in the long term. It's why so many people are concerned about XForms, Avalon and stuff -- they have bought MS technology previously, and they will have to buy it again, with all the upgrade cost, just to keep working. Not a good way to run a business. > The most likely scenario I see is that Python will remain important as a > standalone language and one of the Microsoft CLR (Common Language Runtime) > language alternatives (like VB.NET and C#) but that great frameworks (like > Zope and Twisted) will be crowded out as Microsoft appropriates and > repackages their functionality. Comments? Perhaps I'm a little paranoid, but I am afraid that the CLR version of Python may lead to a split of sorts in the long term. Jython is always a little behind, but as far as I know, it still follows C Python steps. The CLR is a *big* library, and it's backed by Microsoft, which makes it quite attractive for a number of developers. I'm afraid that its direct use may lead to a distinct 'dialect' of sorts (due to the use of the CLR) than C Python with the standard Python library. The language is the same, but the programs would hardly be portable (I don't place my bets on Mono either). But again, I may be just paranoid :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From nhodgson at bigpond.net.au Sat Nov 27 01:02:22 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 27 Nov 2004 06:02:22 GMT Subject: win32 problem with WM_COPYDATA References: Message-ID: Chris: > wc.lpszClassName = "QServer" > ... > "QuoteServer App", > ... > wnd = win32gui.FindWindow("QuoteServer", None) Using the same name helps. > ... > buff = struct.pack('11s', "XXXXX: YYYY") > print win32gui.SendMessage(wnd, win32con.WM_COPYDATA, 0, buff) Copydata does not take an arbitrary pointer, it requires a correctly initialized COPYDATASTRUCT. From a Mark Hammond post: import struct, array int_buffer = array.array("L", [0]) char_buffer = array.array("c", "the string data") int_buffer_address = int_buffer.buffer_info()[0] char_buffer_address, char_buffer_size = char_buffer.buffer_info copy_struct = struct.pack("pLp", # dword *, dword, char * int_buffer_address, char_buffer_size, char_buffer_address) # find target_hwnd somehow. win32gui.SendMessage(w, WM_COPYDATA, target_hwnd, copy_struct) Neil From rambam at bigpond.net.au Mon Nov 8 02:35:35 2004 From: rambam at bigpond.net.au (Israel Raj T) Date: Mon, 08 Nov 2004 07:35:35 GMT Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <1gmw2us.eerwmfbnb899N%aleaxit@yahoo.com> Message-ID: <87vfcgkd3e.fsf@pop-server.bigpond.net.au> Roy Smith writes: > mention that I know what the program drum is used for on an 029 card > punch. I am however typing this from my wireless PowerBook :-) I hate to say this, but my kids have had 802.11g on their notebooks since the age of 12 ( ie : nearly 2 years now). From aleaxit at yahoo.com Mon Nov 8 02:25:00 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 8 Nov 2004 08:25:00 +0100 Subject: Floating point -> string conversions References: Message-ID: <1gmxb89.r6ndtk17sltbgN%aleaxit@yahoo.com> John Fouhy wrote: ... > Why do the string and default floating point representations get rounded? > > (and is this documented anywhere?) Sure, right in the "Tutorial (start here)" for example. http://www.python.org/dev/doc/devel/tut/node16.html Alex From mesteve_bpleaseremovethis at hotmail.com Mon Nov 15 21:36:39 2004 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Tue, 16 Nov 2004 02:36:39 GMT Subject: Redirecting system output quietly References: Message-ID: cmdline = 'whatever command you want to run' pipe = os.popen(cmdline + " 2>&1") for line in pipe.readlines(): tempList.append(line) rc = pipe.close() if rc: ErrorResult = 1 else: fg.ErrorResult = 0 "Eddie Parker" wrote in message news:mailman.6395.1100563802.5135.python-list at python.org... > Look at the 'popen' modules. > > (I believe their under the os module). > > -e- > > -----Original Message----- > From: python-list-bounces+eddie=replicon.com at python.org > [mailto:python-list-bounces+eddie=replicon.com at python.org] On Behalf Of > Madhusudhanan Chandrasekaran > Sent: November 15, 2004 5:03 PM > To: python-list at python.org > Subject: Redirecting system output quietly > > Hi, > I am a newbie here. I want to know how to redirect os.system("ls -af") > to a string variable without it barfing the answer of ls -af on the > screen. > > Thanks in advance, > Madhusudhanan.C > -- > http://mail.python.org/mailman/listinfo/python-list > > --- > Incoming mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 > > > From fredrik at pythonware.com Sat Nov 27 02:25:43 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Nov 2004 08:25:43 +0100 Subject: Number of colors in an image References: <1075192482.20041126193704@geochemsource.com> Message-ID: Laszlo Zsolt Nagy wrote: > How can I determine the number of colors used in an image? I tried to > search on Google but I could figure out. I read the PIL handbook but I > do not see how to do it. Can anyone help? PIL 1.1.5 has a "getcolors" method: http://effbot.org/zone/pil-image.htm#image-getcolors-method im.getcolors() => a list of (count, color) tuples or None im.getcolors(maxcolors) => a list of (count, color) tuples or None (New in 1.1.5) Returns an unsorted list of (count, color) tuples, where the count is the number of times the corresponding color occurs in the image. If the maxcolors value is exceeded, the method stops counting and returns None. The default maxcolors value is 256. To make sure you get all colors in an image, you can pass in size[0]*size[1] (but make sure you have lots of memory before you do that on huge images). From steven.bethard at gmail.com Wed Nov 24 12:40:34 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 24 Nov 2004 17:40:34 GMT Subject: How to get an item from a simple set? In-Reply-To: References: Message-ID: Pete Forman wrote: > Steven Bethard writes: > > >>I still tend to write the extra line in cases like this -- it >>guarantees that the set is really the size that I think it is, where >>the iter(s).next() solution will not raise an exception if the set >>is actually larger. > > > The preceding line in my code is > if len(s) == 1: > So is this just one branch of a case statement? What do you do in the case that len(s) != 1? And which one happens more often? If I have two possible unpackings of an iterable and I know one is much more common than the other, I often do something like: try: x, y = s # more common unpacking except ValueError: [x], y = s, None # less common ('exceptional') unpacking This is a reasonable pattern if your code really does favor one branch substantially over the other. But dont' take my word for it. ;) Here's what timeit says: ----- test.py ---- def test_cond(*args): if len(args) == 1: [x], y = args, None elif len(args) == 2: x, y = args else: raise ValueError('wrong number of arguments') def test_try(*args): try: x, y = args except ValueError: [x], y = args, None def test(fn, single_times, double_times): for _ in range(single_times): fn(1) for _ in range(double_times): fn(0, 1) ---- command prompt ---- >python -m timeit -s "import test" "test.test(test.test_cond, 10, 10)" 10000 loops, best of 3: 26.7 usec per loop >python -m timeit -s "import test" "test.test(test.test_try, 10, 10)" 10000 loops, best of 3: 116 usec per loop >python -m timeit -s "import test" "test.test(test.test_cond, 1, 100)" 10000 loops, best of 3: 132 usec per loop >python -m timeit -s "import test" "test.test(test.test_try, 1, 100)" 10000 loops, best of 3: 99.8 usec per loop As you can see, when the try/except block is slower when the two branches get traversed approximately equally, but faster when one branch is substantially favored over the other. Steve From jeff at ccvcorp.com Thu Nov 18 23:41:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 18 Nov 2004 20:41:41 -0800 Subject: Building a word list from multiple files In-Reply-To: References: <3oqdnVtPVOyFMgHcRVn-rA@comcast.com> Message-ID: <10pqu52ep6mn34a@corp.supernews.com> Manu wrote: >hi, > > >>1) How large are the files you are reading (e.g. can they >>fit in memory)? >> >> > >The files are email messages. >I will using the the builtin email module to extract only the content >type which is plain text or in html.So no line by line processing is >possible unless >i write my own parser for email. > > The email package can do that parsing for you -- it's not too difficult to feed it a raw message file and get back only the text and/or html payload. >>If not, preprocess the files and use shelve to save a >>dictionary that has already been processed. When you >> >> > >This is what i was planning to do.Once the processing is done for a >set of files they are never processed again.I was going to store the >dict as a string in a file and then use eval() to get it back. > > Use the shelve module instead of eval()ing it yourself -- the shelve authors have already done all of the hard work for you. It'll act almost like a regular dictionary, but is extremely easy to save to disk and reload later. This is why Python is called "batteries included". :) Jeff Shannon Technician/Programmer Credit International From jbperez808 at wahoo.com Thu Nov 11 01:43:15 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 11 Nov 2004 14:43:15 +0800 Subject: Tkinter and WCK (was Re: How come wxPython isn't in the standard library?) In-Reply-To: References: Message-ID: <2vgfe5F2m8raqU1@uni-berlin.de> BJ?rn Lindqvist wrote: > See: http://www.wxpython.org/quotes.php. especially: > > "wxPython is the best and most mature cross-platform GUI toolkit, > given a number of constraints. The only reason wxPython isn't the > standard Python GUI toolkit is that Tkinter was there first." - Guido > van Rossum I think there's another reason not to standardize on wxPython and it's that its API is not at all pythonic. It reminds me too much of a C++ API. Tkinter's is far easier to use and learn. (PyGtk would be 2nd while PyQt's API, in my experience is just as C++-like and hard to understand as wxPython's) Tkinter's two real cons are that: a) it is [supposed to be] ugly (but see my replies below) b) it is an additional layer and thus slow For both a) and b), one big hope for improvement is that Fredrik Lundh's Tkinter 3000 / Widget Construction Kit (WCK) has been revived. You can now do your own Tkinter widgets in Python. WCK's API has the traditional pythonic design (lean, mean, easy to learn) typical of Fredrik Lundh's creations (like ElementTree and ElementTidy). WCK widgets might actually provide better performance as you don't have the additional Tk layer to go through (or less of it). I also saw some work to allow Tk widgets to be written in native Win32 over at effbot.org! The fact that you can now easily do your own Tkinter widgets using WCK also means that we might soon see a lot of WCK widgets which are prettier than the Tk ones. There are already some samples over at effbot.org. > Guess, that answers my question, but isn't "Tkinter was there first" a > very bad answer? :) It is kinda ugly too, so I wonder why it can't be > replaced? Tkinter is a lot less ugly today than it used to be because Tk has adopted a more native look (i'm talking about windows here, dunno about other platforms). You can actually turn off that non-standard tear-off menu widget (which I believe is responsible for as much as 80% of the Tkinter is ugliy comments) easily too. Without that tear-off menu disabled, I bet you won't be able to tell that a modern Tkinter app from a native Win32 one. From jepler at unpythonic.net Mon Nov 8 15:44:07 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Nov 2004 14:44:07 -0600 Subject: Escape chars in string In-Reply-To: <418fd4fb$0$147$3a628fcd@reader1.nntp.hccnet.nl> References: <418fd4fb$0$147$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <20041108204406.GB3567@unpythonic.net> Python 2.3 has a 'string-escape' codec. If you have a string like '\\t' (a literal backslash followed by a t) and want to turn it into the string '\t' (a tab character), you can use it for that purpose: >>> r"a\tb".decode("string-escape") 'a\tb' Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From user at host.invalid Sun Nov 28 12:16:40 2004 From: user at host.invalid (Heikki Orsila) Date: Sun, 28 Nov 2004 17:16:40 +0000 (UTC) Subject: [ANN] rpncalc-1.0 RPN Calculator For Python References: <41a9fd4e$1_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > The .tar.gz file seems to be corrupt, opening it with WinZip it > uncompresses the .gz then I get "Error reading header after processing 0 > entries." Bug in winzip? tar xfz rpncalc-1.0.tar.gz works just fine. However, there's an invalid symlink inside the package: $ tar tvfz rpncalc-1.0.tar.gz ... lrwxrwxrwx rlb/rlb 0 2004-11-22 00:11:06 rpncalc-1.0/examples/poly.py -> /data/projects/poly/poly.py $ md5sum rpncalc-1.0.tar.gz 0b8eb872fb0937eca079489e184ddf9f rpncalc-1.0.tar.gz Is your packet valid? Check the md5sum. -- Heikki Orsila Barbie's law: heikki.orsila at iki.fi "Math is hard, let's go shopping!" http://www.modeemi.fi/~shd From deetsNOSPAM at web.de Mon Nov 8 14:35:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 08 Nov 2004 20:35:08 +0100 Subject: Comparing two minidom objects References: <727daa7e.0411081033.276d5eba@posting.google.com> Message-ID: > res = res and tree_eq(ac, bc) The aggregation is actually not necessary, as we shourtcircuit the and'ing of the node comparisions. -- Regards, Diez B. Roggisch From jgoerzen at complete.org Fri Nov 12 16:29:58 2004 From: jgoerzen at complete.org (John Goerzen) Date: Fri, 12 Nov 2004 21:29:58 +0000 (UTC) Subject: Seeking a good home for OfflineIMAP Message-ID: Hi, I'm the author of OfflineIMAP[1], a bidirectional IMAP synchronization tool. Its job is to let you read IMAP mail with any mail reader that can understand a Maildir, and to keep your mail readers in sync on all your different computers. Here's the problem. I consider OfflineIMAP basically finished. It does more than I ever expected out of it, and I haven't lost any mail from in its entire lifespan. I've done a poor job lately of tracking down bugs that people have submitted and generally of maintaining the code. Part of that is because I don't have time. Part is, I admit, that the problems are just not interesting to me, since OfflineIMAP works fine for me already. I know a lot of people find OfflineIMAP useful, and I feel that I'm letting people down sometimes. So I am asking here for somebody (or beter, several people) that would like to take over development and maintenance on OfflineIMAP. If you don't want that, maybe you could at least handle bug reports and send me diffs. I'm content still making releases, or else pretty much ending my involvement. I could put my Subversion repository back up again, and you could hack on that with me, or you could just take it over to *forge and go your own way. Whatever you prefer. I'm happy to continue hosting the mailing list and answer the "wtf did you do there" questions. OfflineIMAP is pure Python, highly modular, and (I think) easy to work with. With one exception: the IMAP communication code. And that is because it has to use imaplib, which doesn't lend itself very well to, erm, clean code :-) If you're interested, I'd encourage you to sign up[2] for the offlineimap list and post there, so we can get started right away. Thanks, John [1] http://quux.org/devel/offlineimap [2] Send "subscribe" to offlineimap DASH request aT complete dOt org From ndbecker2 at verizon.net Wed Nov 3 18:47:35 2004 From: ndbecker2 at verizon.net (Neal Becker) Date: Wed, 03 Nov 2004 18:47:35 -0500 Subject: ANN: New configuration module released References: <2e37dc1.0411030650.ff44840@posting.google.com> <418956E9.8000600@red-dove.com> Message-ID: Vinay Sajip wrote: > Neal D. Becker wrote: >> Looks good so far. >> >> The boost c++ library (about to be released) has a new program_options >> parser. One feature I appreciate in the design, is that the source of >> options is seperated from the rest of the design. This means that, out >> of the box, it reads options from command line, from config files, and >> from >> env variables. Probably not hard to extend if anyone could think of a >> reason. >> >> I believe a decent config module should at least handle both config files >> and command line options. ENV variables are a nice touch too. >> > > Python already has the optparse module for command-line options, and > it's pretty good. I'll be looking at ways in which access to > command-line options parsed via optparse can be made available through > the config API, without duplication of code. > The point is, you would like to specify the options once, and use this single specification for all option sources - instead of redundantly having to specify that there is a 'verbosity' option that takes a value of 'int' and has a default of 'whatever', and do this once (and with different syntax) for each source - config files, command line, etc. From terti at mighty.co.za Mon Nov 15 15:52:42 2004 From: terti at mighty.co.za (tertius) Date: Mon, 15 Nov 2004 22:52:42 +0200 Subject: round() to nearest .05 ? Message-ID: Hi, I'm trying to round my float total to the nearest .05 cents. 12.01 should produce 12.00 0.14 should produce 0.10 2.28 " 2.25 703.81 " 703.80 "%.02f"%100.0099 produces 100.01 (which I know is right) No combination of round and/or "%.02f" works for me. What's the best way to get there? Should I write a function to manage my rounding or is there a simpler/better way? TIA T From duncan.booth at invalid.invalid Tue Nov 23 04:47:45 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Nov 2004 09:47:45 GMT Subject: [Beginner] delete items of [] also from memory References: <72c8d50d.0411220933.203ca8f0@posting.google.com> Message-ID: Peter wrote: > "Birgit Rahm" wrote in message > news:... >> Hello newsgroup, >> >> I am a beginner, so I am asking maybe immoderate questions. >> I want to delete a [] variable, after filling it with complex >> objects. How should I do it? >> e.g. >> AAA = [] >> AAA = [B, C, D, E, F] >> Can I >> 1) AAA = [] >> 2) del AAA[0:] >> 3) ? >> whats about the computers memory, will it get free? Or will it get >> more and more while Python is running? > > I too am a novice, so am prepared to be corrected if this is wrong. > > I don't think you need to worry - Python handles memory allocation > automatically. Names are not specifically allocated to memory, and > when the last reference to a name is deleted all the associated memory > is freed. It depends on what the original poster meant by 'complex' objects. Objects with circular references may not be freed until the garbage collector kicks in, and objects with circular references and a __del__ method may not be freed at all. However, provided you avoid writing __del__ methods on such objects, the memory may not be freed immediately but it will be freed eventually. Objects which are not involved in any cyclic references will be freed, as you say, as soon as the last reference goes. ('Freed' in this context means released for reuse by Python --- don't ever expect the process to release memory back to the rest of the system.) From heikowu at ceosg.de Sat Nov 6 05:39:18 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 6 Nov 2004 11:39:18 +0100 Subject: Add a file to a compressed tarfile In-Reply-To: <20041105101135.F83C.JCARLSON@uci.edu> References: <20041105101135.F83C.JCARLSON@uci.edu> Message-ID: <200411061139.18926.heikowu@ceosg.de> Am Freitag, 5. November 2004 19:19 schrieb Josiah Carlson: > I am not aware of any such method. I am fairly certain gzip (and the > associated zlib) does the following: > > while bytes remaining: > reset/initialize state > while state is not crappy and bytes remaining: > compress portion of remaining bytes > update state > > Even if one could discover the last reset/initialization of state, one > would still need to decompress the data from then on in order to > discover the two empty blocks. This is not entirely true... There is a full flush which is done every n bytes (n > 100000 bytes, IIRC), and can also be forced by the programmer. In case you do a full flush, the block which you read is complete as is up till the point you did the flush. From the documentation: """flush([mode]) All pending input is processed, and a string containing the remaining compressed output is returned. mode can be selected from the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, or Z_FINISH, defaulting to Z_FINISH. Z_SYNC_FLUSH and Z_FULL_FLUSH allow compressing further strings of data and are used to allow partial error recovery on decompression, while Z_FINISH finishes the compressed stream and prevents compressing any more data. After calling flush() with mode set to Z_FINISH, the compress() method cannot be called again; the only realistic action is to delete the object.""" Anyway, the state is reset to the initial state after the full flush, so that the next block of data is independent from the block that was flushed. So, you might start writing after the full flush, but you'd have to make sure that the compressed stream was of the same format specification as the one previously written (see the compression level parameter of compress/decompress), and you'd also have to make sure that the gzip header is supressed, and that the FINISH compression block correctly reflects the data that was appended (because you basically overwrite the finish block of the first compress). Little example: >>> import zlib >>> x = zlib.compressobj(6) >>> x >>> a = x.compress("hahahahahaha"*20) >>> a += x.flush(zlib.Z_FULL_FLUSH) >>> a 'x\x9c\xcaH\xcc\x18Q\x10\x00\x00\x00\xff\xff' >>> b = x.flush(zlib.Z_FINISH) >>> b '\x03\x00^\x84^9' >>> x = zlib.compressobj(6) # New compression object with same compression. >>> c = x.compress("hahahahahaha"*20) >>> c += x.flush(zlib.Z_FULL_FLUSH) >>> c 'x\x9c\xcaH\xcc\x18Q\x10\x00\x00\x00\xff\xff' >>> d = x.flush(zlib.Z_FINISH) >>> d '\x03\x00^\x84^9' >>> e = a+c[2:] # Strip header of second block. >>> x = zlib.decompressobj() >>> f = x.decompress(e) >>> len(f) 480 # Two times 240 = 480. >>> f 'haha...' # Rest stripped for clarity. So, as far as this goes, it works. But: >>> x = zlib.decompressobj() >>> e = a+c[2:]+d >>> f = x.decompress(e) Traceback (most recent call last): File "", line 1, in ? zlib.error: Error -3 while decompressing: incorrect data check You see here that if you append the new end of stream marker of the second block (which is written by x.flush(zlib.Z_FINISH)), the data checksum is broken, as the data checksum is always written for the entire data, but leaving out the end of stream marker doesn't cause data-decompression to fail. I know too little about the internal format of a gzip file (which appends more header data, but otherwise is just a zlib compressed stream) to tell whether an approach such as this one would also work on gzip-files, but I presume it should. Hope this little explanation helps! Heiko. From pythongnome at hotmail.com Sun Nov 21 08:47:53 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 21 Nov 2004 13:47:53 GMT Subject: instant messenging In-Reply-To: <2004112016211983792%craig@yumaca> References: <2004112016211983792%craig@yumaca> Message-ID: craig wrote: > On 2004-11-19 15:08:24 -0700, Lucas Raab said: > >> Are there any instant messenging programs out there for use in a >> Python app?? I've heard of Jabber, but never looke into it. > > > There are other instant messaging platforms, besides jabber. I use > AIM(AOL Instant Messenger) quite a bit, and here is a python > implementation: http://www.jamwt.com/Py-TOC/ > > I use it as a BOT, I can share my code if you care. > > Hope this helps, > -Craig > Thank you. Please do. From zach at cs.uni-bonn.de Wed Nov 24 13:38:20 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 24 Nov 2004 18:38:20 GMT Subject: teaching OO References: Message-ID: > Just out of interest, did the students get confused between > polymorphism acheived through duck-typing and polymorphism acheived i haven't gotten so far yet. and this semester, i won't do everything in parallel. But I can say that it is very convincing to explain dynamic typing vs. static typing, and weakly typed vs. stringly typed by contrasting how things work in python vs how they work in c++. > way to perform structured education (my teacher friends remind me of hm, i'm not an educated teacher, just an assistant professor -- could you please explain to me what "structured education" means? ;-) Cheers, Gab. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From ptmcg at austin.rr._bogus_.com Thu Nov 18 17:19:52 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 18 Nov 2004 22:19:52 GMT Subject: TPG error when using 't' as the first letter of a token References: Message-ID: "Andrew James" wrote in message news:mailman.6536.1100768465.5135.python-list at python.org... > Gentlemen, > > I'm running into a problem whilst testing the parsing of a language I've > created with TPG . It seems that for some reason, TPG balks when I try > to parse an expression whose first letter is 't' (or, in fact, at any > time when 't' is at the beginning of a token). This doesn't happen with > any other letter (as far as I know), nor if the 'T' is capitalised. > > My grammar looks like this: > > # Tokens > separator space '\s+'; > token Num '\d+(.\d+)?'; > token Ident '[a-zA-Z]\w*'; > token CharList '\'.*\''; > token CatUnOp '~'; > token CatOp '[/\^~]'; > token MetaOp '[=\+\-!]'; > token Date '\d\d-\d\d-\d\d\d\d'; > token FileID '(\w+\.\w+)' > ; > # Rules > START -> CatExpr '\?' '[' MetaExpr ']' > | CatExpr > | FileID > ; > CatExpr -> CatUnOp CatName > | CatName (CatOp CatName)* > | CatName > ; > CatName -> Ident > #| '(' CatExpr ')' > ; > MetaExpr -> MetaCrit (',' MetaCrit)* > ; > MetaCrit -> Ident MetaOp Value > ; > Value -> CharList | Num | Date > ; > > My test script like this: > > if __name__ == '__main__': > """ For testing purposes only """ > parseTests = ('This/is/a/simple/test', 'another/simple/test', > "a/test/with/[author='drew']") > for line in parseTests: > try: > print "\nParsing: %s \n%s\n" % (line,"="*(len(line)+9)) > qp = MFQueryParser() > print qp(line) > except Exception, inst: > print "EXCEPTION: " + str(inst) > > FYI, as a comparative data point, here is your parser implemented using pyparsing. I had to change your last test case because it didn't seem to match your grammar. -- Paul (Download pyparsing at http://pyparsing.sourceforge.net.) from pyparsing import alphas, nums, alphanums, Word, Optional, oneOf, Group, \ Literal, Combine, sglQuotedString, Forward, delimitedList, ZeroOrMore, OneOrMore integer = Word(nums) num = Combine(integer + Optional("." + integer)) identChars = alphanums + "_$" ident = Word(alphas, identChars) charList = sglQuotedString unop = Literal("~") binop = oneOf("/ ^ ~") metaOp = oneOf("= + - !") date = Combine( Word(nums,exact=2) + "-" + Word(nums,exact=2) + "-" + Word(nums,exact=4) ) fileId = Combine( Word(identChars) + "." + Word(identChars) ) value = charList | date | num metaCrit = ident + metaOp + value metaExpr = Group(delimitedList( metaCrit )) expr = Forward() name = ident | Group( "(" + expr + ")" ) expr << Group( ( unop + name ) | ( name + ZeroOrMore(binop + name) ) ) start = Group( expr + "?" + "[" + metaExpr + "]" ) | expr | fileId parseTests = ( 'This/is/a/simple/test', 'tanother/simple/test', "a/test/with?[author='drew']" ) for t in parseTests: print start.parseString(t) Output: ===== [['This', '/', 'is', '/', 'a', '/', 'simple', '/', 'test']] [['tanother', '/', 'simple', '/', 'test']] [[['a', '/', 'test', '/', 'with'], '?', '[', ['author', '=', "'drew'"], ']']] From gabriel.cooper at mediapulse.com Wed Nov 10 14:31:32 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Wed, 10 Nov 2004 14:31:32 -0500 Subject: Concise idiom to initialize dictionaries In-Reply-To: <4191E3FA.5070607@romulo.de> References: <89D59C407D04D54AA82DC8BA312D430D10C6175C@enyc11p32001.corpny.csfb.com> <4191E3FA.5070607@romulo.de> Message-ID: <41926C94.3060006@mediapulse.com> Rainer Mansfeld wrote: > Being a C/C++ programmer with only a couple of weeks of Python > experience, I'd simply do: > > a = b = c = d = e = f = g = h = i = j = k = l = {} > > That's clear and compact, but is it 'pythonic'? That notation would make each variable a reference to the same dictionary: >>> a = b = c = d = {} >>> a['test'] = 1 >>> b {'test': 1} >>> From vze4rx4y at verizon.net Mon Nov 29 01:49:36 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 29 Nov 2004 06:49:36 GMT Subject: Decimal printing without the exponent References: <%0oqd.478158$D%.433430@attbi_s51> Message-ID: <4Ezqd.1390$_C2.401@trndny01> "Bryan" wrote in message news:%0oqd.478158$D%.433430 at attbi_s51... > is there a way to make the Decimal class not print the exponent version of the > decimal? > > > >>> str(Decimal('1010')) > '1010' > >>> str(Decimal((0, (1, 0, 1), 1))) > '1.01E+3' > >>> > > how do you make the 2nd example print 1010? The quantize method will convert to any desired exponent (zero in your example): >>> d = (Decimal((0, (1, 0, 1), 1))) >>> d Decimal("1.01E+3") >>> d.quantize(Decimal(1)) Decimal("1010") Raymond Hettinger From rcs333 at online.no Fri Nov 26 22:19:44 2004 From: rcs333 at online.no (RCS) Date: Sat, 27 Nov 2004 04:19:44 +0100 Subject: Protecting Python source In-Reply-To: References: Message-ID: Alan Sheehan wrote: > Hi pythonistas, > > I am looking for methods of deploying applications with end users so > that the python code is tamper proof. What are my options ? An interesting question is, what makes your source code so innovative as to mandate this tamper proof thing? Just wondering. QXX From fumanchu at amor.org Fri Nov 19 20:25:45 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Nov 2004 17:25:45 -0800 Subject: generic object - moving toward PEP Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3245261@exchange.hqamor.amorhq.net> Steven Bethard wrote: > This doesn't really have anything to do with the proposal. We're not > suggesting a named-tuple here (though see a recent (current?) thread > that is). The 'bunch' class, or whatever you want to call it, is > intended to support dotted-attribute access, in contrast to dict's > sequential [] access. Oops. Got my threads mixed up. Sorry. Robert Brewer MIS Amor Ministries fumanchu at amor.org From jstroud at mbi.ucla.edu Sun Nov 7 00:46:35 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 6 Nov 2004 21:46:35 -0800 Subject: Python for Reverse Engineering In-Reply-To: <418C54E9.2000409@vt.edu> References: <418c50ad$1_3@omega.dimensional.com> <418C54E9.2000409@vt.edu> Message-ID: <200411062146.35968.jstroud@mbi.ucla.edu> > > Care to post the 100 strings so others can have a look? > > I'd rather not do that. If your friend was worth his salt as an algorithm writer, he'd be more than willing to let you post a mere 100 strings. For any good generator, this would be paltry compared to the number of strings it would take to figure out the algorithm. But--he is probably making impossible claims here, anyway... > Reading about cryptanalysis might prove fruitful. Perhaps your friend should pay heed to this as well. James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From premshree_python at yahoo.co.in Thu Nov 11 14:16:46 2004 From: premshree_python at yahoo.co.in (Premshree Pillai) Date: Thu, 11 Nov 2004 19:16:46 +0000 (GMT) Subject: Beginner's scoping question In-Reply-To: <4ef0f3a4.0411101240.21132006@posting.google.com> Message-ID: <20041111191646.99526.qmail@web8507.mail.in.yahoo.com> --- Alan Little wrote: > a=1 > b=[] > class C(): > def __init__(self): > a=2 > b.append(3) > > c = C() > > print b > # [3] > > # but ... > print a > # 1 > > ??? > -- > http://mail.python.org/mailman/listinfo/python-list > You probably already got your answer. Just wanted to point out that -- class C(): -- is incorrect. Should be class C: :-) --Premshree ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From bokr at oz.net Wed Nov 17 06:22:25 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 17 Nov 2004 11:22:25 GMT Subject: eval syntax problem References: <86pt2c3lgx.fsf@mut.mteege.de> Message-ID: <419b3150.282995165@news.oz.net> On Wed, 17 Nov 2004 09:53:12 +0100, Matthias Teege wrote: > >Moin, > >what is wrong with > >eval('print %s %s %s' % ('%s', '%', 'foo')) print is a statement, which eval does not like. Use exec for statements, but it is usually a sign that you haven't yet learned a better way of doing something if you are a newbie and resorting to eval or exec ;-) > >I try to pass a format string to an assignment. Like this > >fmt='%.2f' >a=1 >b="fmt %" % a >>> fmt = '%.2f' >>> a=1 >>> b="fmt %" % a Traceback (most recent call last): File "", line 1, in ? ValueError: incomplete format Did you not understand that message? It means that "fmt %" is missing something, which makes it incomplete ;-) If you look in docs, you can find how to make formats. The one in fmt is ok. So what you want to do is use that in a normal format % stuff_to_format expression: >>> b=fmt % a >>> a 1 >>> b '1.00' You could complete the format in the error, and try again. (interactively, you can just type the expression without assigning its value, that way the interepreter will show a string representation of the result (unless it's None, in which case it doesn't print anything). >>> "fmt %" % a Traceback (most recent call last): File "", line 1, in ? ValueError: incomplete format >>> "fmt %s" % a 'fmt 1' >>> Regards, Bengt Richter From speno at net.isc.upenn.edu Fri Nov 5 17:20:32 2004 From: speno at net.isc.upenn.edu (John P. Speno) Date: Fri, 5 Nov 2004 22:20:32 +0000 (UTC) Subject: Simple thread pools References: Message-ID: In Jacob Friis writes: >I have built a script inspired by a post on Speno's Pythonic Avocado: >http://www.pycs.net/users/0000231/weblog/2004/01/04.html#P10 >I'm setting NUM_FEEDERS to 1000. >Is that crazy? >Are there a better solution? I'm flattered, but I suggest you avoid using Threads and instead consider what serveral others have already mentioned: Twisted. You can find more info here: http://twistedmatrix.com If my memory serves me right (IMMSMR?), a user on the Twisted Python mailing list posted not too long ago (today?) about coding an RSS aggregator using Twisted. Hey, that user was you! :-) Going farther back, on March 31, Valentino Volonghi posted about his RSS code too. http://twistedmatrix.com/pipermail/twisted-python/2004-March/007390.html Take care. From bokr at oz.net Thu Nov 18 22:40:30 2004 From: bokr at oz.net (Bengt Richter) Date: Fri, 19 Nov 2004 03:40:30 GMT Subject: Are multiple return values really harmful? (Re: determining the number of output arguments) References: <30001hF2ptnqcU1@uni-berlin.de> <419bbf2a.319309032@news.oz.net> <10ppt1bt5q38d0d@corp.supernews.com> Message-ID: <419d6a2b.428622776@news.oz.net> On Thu, 18 Nov 2004 11:16:31 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >>Maybe keyword unpacking could spell that with a '**' assignment target, >>e.g., >> >> ** = foo() # update local bindings with all legal-name bindings in returned dict >> >> > >I would *not* like to see this. ISTM that, when reading a function, I >should be able to see where every name in that function came from. >Having global values appear from outside of the function is bad enough; >introducing a new way to magically create variables whose names I can't ^^^^^^ Not create, just rebind existing locals. >see would be (IMO) very, very bad. All things in moderation. But I agree that you would have to know and trust foo ;-) Regards, Bengt Richter From zach at cs.uni-bonn.de Fri Nov 5 11:40:01 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 5 Nov 2004 16:40:01 GMT Subject: Usage statistics? Message-ID: For some reason, I would like to have some statistics about how often Python is used in the *scientific* communities (such as astronomy, genetics, electrical engineering, ...), as opposed to C++ or Java or other "common" programming languages. I know about TIOBE's Programming Community Index, and Francois Labelle's statistics from sourceforge. Any pointers or insights will be highly appreciated Best regards, Gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From zach at cs.uni-bonn.de Tue Nov 2 16:32:55 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 2 Nov 2004 21:32:55 GMT Subject: strong/weak typing and pointers References: <4187aafe$1@nntp0.pdx.net> Message-ID: > (1) Weakly-typed languages allow you to take a block of memory that was > originally defined as one type and reinterpret the bits of this block as another > type[1]. (This is the definition usually used in Programming Languages > literature.) So, according to that, Perl is strongly typed? Thanks a lot in advance, Gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From DesertLinux at netscape.net Wed Nov 17 10:37:42 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 17 Nov 2004 15:37:42 GMT Subject: Newbie: Python & ADFGVX Cipher Cracking? In-Reply-To: References: <4mJmd.1242$Tq6.565@newsread3.news.pas.earthlink.net> Message-ID: Hi Andreas, That works GREAT!! Thanks for the help... It is appreciated! Byron --- Andreas Lobinger wrote: > Aloha, > > Byron wrote: > >> I am working on building a program that cracks "ADFGVX" ciphers. >> However, I have run into a minor problem, which has to do with >> figuring out all of the possible character re-arrangement >> combinations. sible ways: > > >> Is there a python function in which I can sent a string of characters >> to -- and it will provide me with a list of all possible combinations >> available? > > > I thought i had encountered something like that in random or so, but > in fact a working solution is used as an _example_ in refman 2.1.8. > > def perm(l): > # Compute the list of all permutations of l > if len(l) <= 1: > return [l] > r = [] > for i in range(len(l)): > s = l[:i] + l[i+1:] > p = perm(s) > for x in p: > r.append(l[i:i+1] + x) > return r > > lobinger at biscuit: python > Python 2.2.2 (#3, Apr 10 2003, 17:06:52) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. > >>> import perm > >>> perm.perm('ABC') > ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] > >>> > > Wishing a happy day > LOBI From tjordah at start.no Thu Nov 25 09:14:54 2004 From: tjordah at start.no (Lars Moastuen) Date: 25 Nov 2004 06:14:54 -0800 Subject: Extending classes written in C++ using SWIG Message-ID: <99efe53b.0411250614.1f0c0e3c@posting.google.com> Im trying to extend a class written in C++ in Python and use this extended class in a C++ call... I made an example to clarify: -- Foo.h -- #ifndef FOO_H #define FOO_H #include using namespace std; class Foo; class Bar; class Bar { public: Bar() {}; ~Bar() {}; virtual char* DoBar() const { return "Bar"; }; }; class Foo { public: Foo() {}; ~Foo() {}; virtual void DoFoo(Bar* someBar) { cout << someBar->DoBar() << endl; }; }; #endif -- Foo.cpp -- #include "Foo.h" -- swig.i -- %module test %{ #include "Foo.h" %} %include "Foo.h" -- UseFoo.py -- #!/usr/bin/env python from test import *; class ExtendedBar(Bar): def __init__(self): Bar.__init__(self); def DoBar(self): return "ExtendedBar"; bar = ExtendedBar(); foo = Foo(); foo.DoFoo(bar); ------------ I now expect to get "ExtendedBar" as output from UseFoo.py (since I've declared DoBar() as virtual, but I get "Bar".... I'm using SWIG 1.3.1 to create the bindings from Python to C++. (swig -python -c++) Can anyone tell me why? Is there a way to remedy this?? Thx, Lars Moastuen From apardon at forel.vub.ac.be Tue Nov 16 03:13:17 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Nov 2004 08:13:17 GMT Subject: Will python ever have signalhandlers in threads? References: Message-ID: Op 2004-11-15, Jp Calderone schreef : > On 15 Nov 2004 11:44:31 GMT, Antoon Pardon wrote: >>Op 2004-11-15, Peter Hansen schreef : >> > Antoon Pardon wrote: >> >> AFAIU the Queue module doesn't block on a full/empty queue when >> >> a timeout is specified but goes in a loop sleeping and periodically >> >> checking whether place/items are available. With signals that >> >> can be sent to a thread the queue could just set an alarm and >> >> then block as if no timeout value was set and either unblock >> >> when place/items are available or get signalled when the timeout >> >> period is over. >> > >> > I'm fairly sure that the Queue uses an internal Event >> > (or REvent?) to signal when space or a new item is >> > available, so I believe your description (and possibly >> > conclusion) above is wrong. There should be no >> > "periodical check", as that would imply polling. Check >> > the source if you're interested. >> >> I did check the source, I just didn't study it carefully >> and got my understanding mostly from the comments. >> But anyway here is the relevant part and IMO we have >> a polling loop here. >> > > You are correct, but why does it matter? The Queue class works. Does it? I'm not so sure. If two consumers ask simultaneously for an element from the same empty queue. One consumer simply blocking and the other using a timeout, I think that if an element is produced within the timeout period the chance for the element going to either consumer should be equal. I doubr very much we have that in the current situation. > Why should Python be changed in a difficult and complex way to... It doesn't change python, it changes an implementation. Sometimes difficult and complex implementation do a better job than easier implementations. That we already have an implementation that works is therefore not a strong argument against an other implementation. > make the Queue class continue to work? If you can give other examples > of the uses you have in mind, that might help convince people of the > value of this change. But be sure you give examples of things that don't already work. Well how about the following code, it works in the main thread, but doesn't in a normal thread according to the documentation: class SystemAlarm(Exception): pass def ringalarm(signum, frame): raise SystemAlarm signal.signal(signal.SIGALRM, ringalarm) def lock(fl): ''' lock a file. If the parameter is a string, first open it. If the lock couldn't be aquired in five minutes, raise an exception. ''' if isinstance(fl, type('')): fd = os.open(fl, os.O_RDWR | os.O_CREAT , 0700) fl = os.fdopen(fd, 'r+') signal.alarm(300) try: fcntl.flock(fl, fcntl.LOCK_EX) signal.alarm(0) except SystemAlarm: raise IOError("Couldn't aquire lock;") except: signal.alarm(0) raise -- Antoon Pardon From lbates at syscononline.com Thu Nov 18 09:18:12 2004 From: lbates at syscononline.com (Larry Bates) Date: Thu, 18 Nov 2004 08:18:12 -0600 Subject: Building a word list from multiple files In-Reply-To: References: Message-ID: <3oqdnVtPVOyFMgHcRVn-rA@comcast.com> Manu wrote: > Hi, > > Here's what i want to accomplish. > I want to make a list of frequenctly occuring words in a group of > files along with the no of occurances of each > The brute force method will be to read the file as a string,split,load > the words > into a dict with words as key and no of occurances as key. > Load the next file ,iterate through the new words increment the value > if there is > a match or add a new key,value pair if there is none. > repeat for all files. > > is there a better way ?? > > > Thanks in advance. > Manu Manu, There are some things we would need to know to specifically answer your question. I've tried to answer it with some "assumptions" about your data/usage: 1) How large are the files you are reading (e.g. can they fit in memory)? If not, you will need to read the file a line at a time and process each line individually. 2) Are the words in the file separated with some consistent character (e.g. space, tab, csv, etc). If not, you will probably need to use regular expressions to handle all different punctuations that might separate the words. Things like quotes, commas, periods, colons, semi-colons, etc. Simple string split won't handle these properly. 3) Do the "files" change a lot? If not, preprocess the files and use shelve to save a dictionary that has already been processed. When you add/change one of the files run this process to recreate and shelve the new dictionary. In your main program get the shelved dictionary from the preprocess program so that you don't have to process all the files every time. Hope info helps, Larry Bates Syscon, Inc. From andreas at kostyrka.org Sun Nov 14 09:33:33 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 14 Nov 2004 15:33:33 +0100 Subject: numarray + cPickle problem In-Reply-To: <1100366822.119444.157780@z14g2000cwz.googlegroups.com> References: <1100326589.669597.252570@f14g2000cwb.googlegroups.com> <1100366822.119444.157780@z14g2000cwz.googlegroups.com> Message-ID: <20041114143333.GA30323@kostyrka.org> On Sat, Nov 13, 2004 at 09:27:02AM -0800, Bill Mill wrote: > A couple more details: > > I'm using Python 2.3.4 and numarray 1.1. I've now found the > numarray.array_persist module, which will let me pickle numarrays an > alternative way, but I'd still like to know what's going on here. I can > definitely pickle numarray.array objects in trivial cases. > > Why doesn't Python raise an Unpickleable error? Why is it trying to > import generic? Just a guess: the generic submodule is a C language module that doesn't know that it's meant to be a submodule. -> So it believes it's just "generic.numarray" and not correctly "numpy.generic.numarray". Andreas From autismuk at autismuk.muralichucks.freeserve.co.uk Wed Nov 24 02:36:26 2004 From: autismuk at autismuk.muralichucks.freeserve.co.uk (Paul Robson) Date: Wed, 24 Nov 2004 07:36:26 +0000 Subject: Microsoft Patents 'IsNot' References: Message-ID: On Tue, 23 Nov 2004 18:35:01 +0000, Lenard Lindstrom wrote: >> I bought a copy of this in I reckon about 1986ish. Visual Basic debuted in >> 1991. > > I would hope that a rewrite of Claim-2 of the patent is required before the patent > is accept (if it is not outright rejected). Claim-2 is too vague to be meaningful. > Proper definitions of "BASIC" and "derived" are missing. I imaging the patent is > intended to protect Visual Basic.NET rather than restrict unrelated languages > like Delphi and Python anyways. It's blatantly obvious to me that the C# classes, ASP.NET etc. are knock offs of the Delphi design. They also bear little resemblance beyond the most basic syntactic stuff to VB6.0 let alone VB1.0 From peter at engcorp.com Mon Nov 29 10:33:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 29 Nov 2004 10:33:40 -0500 Subject: how to drop all thread ?? In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Leon wrote: > > >>if class A( >>use threading,thread module >>) to produce 100 thread,how to drop its (100 thread) when its running > > > By exiting. There is no other way to stop a thread by force. Note that even trying to exit won't work, if the threads are not marked as "daemon" threads... Only by calling .setDaemon(True) on the threads before they are started will you be able to terminate them all just by exiting. -Peter From exarkun at divmod.com Sun Nov 7 11:53:57 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Sun, 07 Nov 2004 16:53:57 GMT Subject: determine IP In-Reply-To: <85030DD4-30DB-11D9-A056-003065B11E84@leafe.com> Message-ID: <20041107165357.14104.909475493.divmod.quotient.1252@ohm> On Sun, 7 Nov 2004 11:38:57 -0500, Ed Leafe wrote: >On Nov 7, 2004, at 11:04 AM, exarkun at divmod.com wrote: > > >> is there a cross platform way to determine a local machines IP on a > >> network (LAN or internet) in python? > >> > > > > s = socket.socket() > > s.connect(('google.com', 80)) > > print s.getsockname() > > If you are on a NAT machine on the local network, the above will > return the public IP of the network. If you change the target from > 'google.com' to a machine on your subnet that will accept the > connection, you'll get the local IP address. The above code will _always_ return the local IP address, regardless of NAT configuration. For example, running on my desktop: >>> import socket >>> s = socket.socket() >>> s.connect(('google.com', 80)) >>> print s.getsockname() ('192.168.42.4', 40044) >>> Jp From jepler at unpythonic.net Tue Nov 9 15:21:23 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 9 Nov 2004 14:21:23 -0600 Subject: Embedding Python in a multi-threaded C++ application In-Reply-To: <560b81a404110910492229b9df@mail.gmail.com> References: <560b81a404110910492229b9df@mail.gmail.com> Message-ID: <20041109202122.GC3878@unpythonic.net> Perhaps you can use PyErr_SetInterrupt() to create a KeyboardInterrupt in the Python thread. void PyErr_SetInterrupt( ) This function simulates the effect of a SIGINT signal arriving -- the next time PyErr_CheckSignals() is called, KeyboardInterrupt will be raised. It may be called without holding the interpreter lock. There's no way to "clean up" after Python if you terminate its thread---Python's datastructures could be in an inconsistent state, so just releasing a lock wouldn't do you any good. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hongqn at gmail.com Fri Nov 12 04:32:50 2004 From: hongqn at gmail.com (Qiangning Hong) Date: Fri, 12 Nov 2004 17:32:50 +0800 Subject: long-run repeatly timer? In-Reply-To: References: Message-ID: At first I showed my test code: import threading def timer_handler(): threading.Timer(10, timer_handler).start() do_something() timer_handler() But it's tick interval is slightly more than 10 seconds because of creating of Timer object. John Hoffman shows his code: from time import time, sleep t = time() while True: do_something() t += 10 sleep(t-time()) His code can call do_something() exactly every 10 seconds, but if the system time is changed by GPS module, the counter will behave abnormal: if the system clock is adjusted backward, the timer will pause for some time; if the system clock is adjusted foreward, the timer will stop forever. Jonh A Meinel provides a modified version of above code: t = time() while True: do_something() t += 10 now = time() interval = t - now # If the time skews enough that we are outside of are 10 second # interval, switch back to a 10 second pulse if interval < 0 or interval > 10: interval = 10 t = now + interval sleep(interval) It does avoid the long waiting and forever-stopping, but it can not guaratee the tick interval as 10 seconds. Qiangning Hong wrote: > I asked this question on comp.python.wxpython using the subject "a > wx.Timer like timer without wx package?" and David Fraser there > suggested me to ask here for a more general solution. > > I am implementing a long-run sample-and-record system. It collects data > from a PCI card every 10 seconds, saves the data (timestamped with the > current system time) in the hard disk, and shows them on the screen. > There is also a GPS receiver module exists on the system, which correct > the system time (and the hardware time) when it drifts away too much, > however, I can not access the source code of this module. > > The system requires the average sample rate is 6 times per minute to > analysis. If the OS clock runs too fast or too slow, we can get the > infomation by the GPS module's log file, and then correct the analysised > result with that infomation. > > So, wo need the counter (a repeatly timer for collecting data) to meet > these requirements: > > 1. fires 6 times per minute, or to say, fires 60*24*360 times per 60 days. > 2. will not be affected by the change of system time, foreward or backward. > 3. no need for external hardware device, of cource. > 4. not depend on any GUI package for it's a console based app. > 5. works on a Windows mechine, cross-platform solution is better. > > How can I implement such a timer? Thanks in advance. > From jerf at jerf.org Fri Nov 19 23:19:44 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 19 Nov 2004 23:19:44 -0500 Subject: instant messenging References: Message-ID: On Fri, 19 Nov 2004 22:08:24 +0000, Lucas Raab wrote: > Are there any instant messenging programs out there for use in a Python > app?? I've heard of Jabber, but never looke into it. Jabber is a particularly good choice if you are really looking to use it in a *program*, i.e., programs shipping data around to other programs, because it is the only IM protocol (AFAIK) that actually was built with that in mind, with traditional IM being layered on top of that. I don't know how easy it is to start with PyJabber and learn from scratch, as I've worked with Jabber too much to have a fresh perspective. Shouldn't be too hard, though. From eternalsquire at comcast.net Thu Nov 4 00:20:58 2004 From: eternalsquire at comcast.net (The Eternal Squire) Date: Wed, 03 Nov 2004 22:20:58 -0700 Subject: pep 336: Make None Callable In-Reply-To: References: Message-ID: Why not? Aahz wrote: > In article , > The Eternal Squire wrote: > >>Title: Make None Callable > > > No, *no*, *NO*, and *HELL NO*. > > OTOH, once the BDFL Pronounces, we can return to laughing and pointing > the next time this comes up. From jcarlson at uci.edu Tue Nov 2 11:50:45 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 02 Nov 2004 08:50:45 -0800 Subject: slice object unpickable In-Reply-To: <8dad5312.0411020229.6c1cf61a@posting.google.com> References: <8dad5312.0411020229.6c1cf61a@posting.google.com> Message-ID: <20041102084836.F7D5.JCARLSON@uci.edu> sdementen at hotmail.com (Sebastien de Menten) wrote: > > Hi, > > I wonder why the slice object is not pickable via pickle or cPickle. > E.g.: [snip slice pickling] I don't know why clice pickling was disabled. To get past it, why not just store the argument tuples that lead to slices? (sli.start, sli.stop, sli.step) - Josiah From apardon at forel.vub.ac.be Fri Nov 19 04:05:23 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Nov 2004 09:05:23 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: On 2004-11-19, Tim Peters wrote: > ... > > [Antoon Pardon] >> Sure but that is not enough is it? The work for letting one thread >> raise an exception in an other thread is done. > > Are you talking about the internal PyThreadState_SetAsyncExc gimmick? > If so, that's got nothing to do with signals. If that's all you want, > say so, and leave signals out of it. I'm talking about PyThreadState_SetAsyncExc only as a throw in response to your previous remark. The main subject is signals. > As to whether the work is done, emphatically no, it isn't. I hadn't > looked at its implementation before, so just did. That uncovered a > critical bug "by eyeball", which may delay the release of Python 2.4. > Happy now ? Well wether the work is done or not hardly seems to matter. The documentation as worded now seems to make it clear, this isn't going get into the language > Seriously, that's just an error in the C coding. The work for a > Python-level feature hasn't even begun. I'd guess it's about 5% of > the way there (believe it or not, writing C code is typically the > least time-consuming part of any language feature). As I understand the doc, one doesn't plan to begin working on a Python-level feature and even if someone else implements it, it has no chance of getting in the language. As I read the docs it is not so much a question of the feature not being ready for the langauge, but a question of Guido not wanting the feature to be in the language. This just to show that having someone implement it, is not the biggest hurdle as your prevous remark seemed to suggest to me. But that is enough of this tangent (although I did find your remarks about it interesting) >> To be more specific, the documentation of the signal >> module states the following. >> >> ... only the main thread can set a new signal handler, and the main >> thread will be the only one to receive signals (this is enforced by >> the Python signal module, even if the underlying thread implementa- >> tion supports sending signals to individual threads). >> >> The question I have is the following. That the main thread is the only >> one to receive signals, is that purely implemented in the signal module >> or is there some interpreter magic that supports this, which can >> cause problems for an alternative signal module. > > Read the code? As I said before, I pay no attention to the signal > module, and the only way I could answer these questions is by studying > the code too. Maybe someone else here already knows, and will chip > in. Well I'll wait a few days to see if someone does, otherwise I'll see I can find enough time to dive into the code. Although you can't help me with my main question, I like to express my appreciation for your responses. They have been very insighfull and I'll be sure to use them to my advantage. -- Antoon Pardon From keir at thelawsons.plus.com Sun Nov 7 10:52:42 2004 From: keir at thelawsons.plus.com (Keir Lawson) Date: Sun, 07 Nov 2004 15:52:42 +0000 Subject: determine IP Message-ID: <1099842762.14624.0.camel@debian> is there a cross platform way to determine a local machines IP on a network (LAN or internet) in python? Keir Lawson -- From belred1 at yahoo.com Tue Nov 16 09:55:04 2004 From: belred1 at yahoo.com (Bryan) Date: Tue, 16 Nov 2004 14:55:04 GMT Subject: adaptation (was: Zope 3.0, and why I won't use it) In-Reply-To: <1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> References: <20041114200132.20649.1982992758.divmod.quotient.5222@ohm> <1gnbf8z.mirt8m687hvbN%aleaxit@yahoo.com> <1gnc2jt.uw5i19s61aieN%aleaxit@yahoo.com> <1gncdvv.1y2msbz1yc1gaeN%aleaxit@yahoo.com> Message-ID: alex, you've mentioned several times the concept of adapting parameters to a method. but i'm not able to understand your few examples. can you go more into depth (and with simpler examples) on this topic? thanks, bryan From clarence at silcom.com Wed Nov 3 02:34:10 2004 From: clarence at silcom.com (Clarence Gardner) Date: 2 Nov 2004 23:34:10 -0800 Subject: getting socket.bind() exception, but no actual error References: <1224a8f9.0411011045.6740c5d8@posting.google.com> <1224a8f9.0411021007.26ec80da@posting.google.com> <4187d4fc$1_4@omega.dimensional.com> Message-ID: <1224a8f9.0411022334.66644d67@posting.google.com> mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<4187d4fc$1_4 at omega.dimensional.com>... ? Because you get "Address already in use" exceptions due > to old connections still being in the TIME_WAIT state? If so, are > you aware that server processes should usually set the SO_REUSEADDR > socket option before calling bind()? Or is there some other reason > that bind() fails? No, that's the only issue. I thought using that option was frowned upon, but it's also been a couple of years since I needed to think about such things, and I was too lazy to look it up for now. From changli_to at hotmail.com Thu Nov 25 21:58:16 2004 From: changli_to at hotmail.com (Chang LI) Date: 25 Nov 2004 18:58:16 -0800 Subject: The use of : Message-ID: <89cc6e1f.0411251858.40b6bbc7@posting.google.com> Some statements use : in the tail such as while x > 0: and def func(): What is the meaning and the usage of : in Python? From maxm at mxm.dk Fri Nov 19 04:28:35 2004 From: maxm at mxm.dk (Max M) Date: Fri, 19 Nov 2004 10:28:35 +0100 Subject: imaplib ... understanding the result from a fetch of RFC822s In-Reply-To: References: Message-ID: <419dbc5f$0$197$edfadb0f@dread12.news.tele.dk> Jp Calderone wrote: > Parsing IMAP4 is rather involved. imaplib does a minimal job of it, and leaves many of the details up to you. For a more complete parser, see Twisted's IMAP4 support: http://www.twistedmatrix.com/ OK. Thanks. There is a few odd things in imaplib. Like an empty resultset being returned as [None] instead of just [] -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From tiarno at sas.com Mon Nov 1 10:49:54 2004 From: tiarno at sas.com (Tim Arnold) Date: Mon, 1 Nov 2004 10:49:54 -0500 Subject: fastest way for humongous regexp search? Message-ID: Hi, I've got a list of 1000 common misspellings, and I'd like to check a set of text files for those misspellings. I'm trying to figure out the fastest way to do it; here's what I'm doing now (below). I'm still learning Python, love it, and I'm pretty sure that what I'm doing is naive. Thanks for taking the time to look at this, --Tim ---------------------------------------------------------------------------- ---------- (1) Create one humongous regexp, compile it and cPickle it. The regexp is like this: misspelled = ( '\\bjudgement\\b|' + '\\bjudgemental\\b|' + '\\bYorksire\\b|' + '\\bYoyages\\b') p = re.compile(misspelled, re.I) f = open('misspell.pat', 'w') cPickle.dump(p,f) f.close() ---------------------------------------------------------------------------- ---------- (2) Check the file(s), report the misspelling, the line number and the actual line of text. - only warns on multiple identical misspellings - using 'EtaOinShrdlu' as a nonsense line-marker; tried \n but that didn't give correct results. - running on HP Unix, Python 2.2 f = open('misspell.pat', 'r') p = cPickle.load(f) a = open('myfile.txt').readlines() s = 'EtaOinShrdlu'.join(a) mistake = {} for mMatch in p.findall(s): if mistake.get(mMatch,0): print 'Warning: multiple occurrences of mistake "%s" ' % mMatch else: mistake[mMatch] = s.count('EtaOinShrdlu', 0, s.index(mMatch)) for k, v in mistake.items(): print 'Misspelling: "%s" on line number %d' % (k, mistake[k]+1) print '%s \n' % a[mistake[k]] From iddwb at moroni.pp.asu.edu Tue Nov 16 11:26:49 2004 From: iddwb at moroni.pp.asu.edu (David Bear) Date: Tue, 16 Nov 2004 16:26:49 +0000 (UTC) Subject: simple symetric encryption advice Message-ID: I would like some advice on what crypto lib to use. I am writing a cgi app that will store sensative data in a backend postgresql server. I have some simple numeric data I would like to make as safe as possible, without too much overhead. The goal would be to store the information in a simple reversable encrypted form. The encryption key would live only in the python app that was accessing the data. So perhaps there are two general questions that could be asked. 1) has anyone else done this, and was it worth the extra overhead in terms of data security.. yes, I know the system will only be as secure as the python code. 2) more important to me, what crypto lib would make sense to use. I was looking at using symetric key ciphers because the data will need to be decrypted as well. I looked at the rotor class but there's a big note that it has been deprecated.. Anyone have a recommendation as to something better? by better I would mean: 1) something reasonably fast, (retreiving 1000 tupples of something should require much time to decrypt) 2) something that the code is fairly well reviewed and tested -- (I know all python modules are well reviewed and tested, but there must be some modules that are more equal than others;)). Any advice appreciated. From jcarlson at uci.edu Sat Nov 13 16:00:54 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 13 Nov 2004 13:00:54 -0800 Subject: Creating combination of sequences In-Reply-To: <419659FA.7080100@rogers.com> References: <7dc80c2.0411131026.c4cf2e@posting.google.com> <419659FA.7080100@rogers.com> Message-ID: <20041113124243.F909.JCARLSON@uci.edu> "Mike C. Fletcher" wrote: > > Minho Chae wrote: > > >Hello, python lovers!! > > > >I'm trying to create combinations of sequences. > > > > > A simple recursive generator should produce what you want while being > fairly easy to read... > > >>> def permute( choices, length=8 ): > ... if length > 1: > ... for suffix in permute(choices,length-1): > ... for choice in choices: > ... yield choice + suffix > ... else: > ... for choice in choices: > ... yield choice > > That's not the same ordering you wanted, but that's merely a matter of > swapping the order of choice and suffix. Or even the better non-recursive 'base-k' version... Note that a permutation is just a reordering of the set of elements that one has. There are only n! number of permutations of any arbitrary sequence (assuming the n items are unique). I can't remember the mathematical name of what the OP wanted (because my brain is dumb today). def blah(choices, length, force_string=0): lch = len(choices) length = long(length) if lch <= 0: raise ValueError, "choices must be a sequence of at least 1 item" if length <= 0: raise ValueError, "length must be an integer >= 1" #use longs and a while loop because we may be dealing with sequences #>= 2**31 in size, and we may be using Python < 2.4 cur = 0L m = lch**length while cur < m: l = [choices[(cur//(lch**i))%lch] for i in xrange(length-1, -1, -1)] if force_string: yield ''.join(map(str, l)) else: yield l cur += 1 >>> for i in blah('atcg', 2, 1): ... print i ... aa at ac ag ta tt tc tg ca ct cc cg ga gt gc gg >>> - Josiah From drew at gremlinhosting.com Thu Nov 18 11:50:43 2004 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 18 Nov 2004 16:50:43 +0000 Subject: SPARK v.s. PLY In-Reply-To: References: Message-ID: <1100796643.27722.52.camel@odin> Alan, You might also want to have a look at TPG (Toy Parser Generator): http://christophe.delord.free.fr/en/tpg The documentation is pretty good, feature list extensive and though there aren't too many examples and you'll have to write your own grammar, it might be worth trying. I'm working on a small language implementation at the moment and have found TPG to be pretty easy to use (but fairly difficult to bugfix) Regards, Andrew From russblau at hotmail.com Wed Nov 10 11:01:55 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 10 Nov 2004 11:01:55 -0500 Subject: [development doc updates] References: Message-ID: <2vesbrF2l9aegU1@uni-berlin.de> "Fred L. Drake" wrote in message news:mailman.6215.1100101627.5135.python-list at python.org... > The development version of the documentation has been updated: > > http://www.python.org/dev/doc/devel/ > > Lots of changes to how tables are actually formatted, with much of the > styling moved from the HTML to the CSS stylesheet. > > Tables also look nicer in supporting browsers. > > Please review the tables and report any strange presentations; be sure > to include the specific browser (including platform and version!) in > your report. Using MSIE 6.0 on Windows XP Professional, the tables have borders on the left and bottom, but no borders on the top and right sides. The interior borders between cells are fine. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From aldo at nullcube.com Tue Nov 16 01:14:36 2004 From: aldo at nullcube.com (Aldo Cortesi) Date: Tue, 16 Nov 2004 17:14:36 +1100 Subject: [ANNOUNCE] Cubictemp v0.4 Message-ID: <20041116061436.GA22676@nullcube.com> Cubictemp Cubictemp is a small, elegant, security-conscious HTML templating system. See the manual referenced from the Cubictemp page for more information. http://www.nullcube.com/software/cubictemp.html -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From stani_ at hotmail.com Sun Nov 14 16:32:16 2004 From: stani_ at hotmail.com (SM) Date: 14 Nov 2004 13:32:16 -0800 Subject: Pyrex on Windows Message-ID: <99230dbb.0411141332.3594e925@posting.google.com> Hi, I would like to play with Pyrex for Windows. I have no clue how to install it including a c compiler. Anyone using pyrex on windows who could give a quickstart? Stani http://spe.pycs.net http://www.stani.be From dieringe at zedat.fu-berlin.de Mon Nov 22 03:38:55 2004 From: dieringe at zedat.fu-berlin.de (Martin Dieringer) Date: Mon, 22 Nov 2004 09:38:55 +0100 Subject: split large file by string/regex Message-ID: I am trying to split a file by a fixed string. The file is too large to just read it into a string and split this. I could probably use a lexer but there maybe anything more simple? thanks m. From me at privacy.net Sat Nov 20 08:06:04 2004 From: me at privacy.net (Dan Sommers) Date: 20 Nov 2004 08:06:04 -0500 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: On Sat, 20 Nov 2004 07:18:32 GMT, Andrew Dalke wrote: > Peter Hansen wrote: >> Nope. That's that nasty ol' Java thinkin'. ;-) >> Basically, given the dynamicism that is Python's hallmark, >> you can't guarantee that any given function won't raise >> an arbitrary exception. > One of my puzzlements about Java 10 years ago or so was > why it decided to go the "must declare every exception" route. > Consider this simple and naive numeric integrator > def integrate(f, start, end, n): > delta = (end-start)/float(n) > x = start + delta / 2 > sum = 0.0 > for i in range(n+1): > sum = sum + f(x) > x += delta > return sum / (n+1) > That function cannot define all the exceptions that can be > raised because f itself can raise an arbitrary exception. Eg, [ cool example of f reading data from a file-system cache snipped ] > Again, IOError might be considered a system-level error > such that it doesn't need declaring. Then change it to > polling some URL ("http://cache.server/" + str(x)) when the > network is down, or getting it from some SQL database when > the password is incorrect, or anything else that cannot be > determined until actually calling f(). And what if f has its own run-time plug-in mechanism? > It looks like the only thing to do is convert all such > unhandled exceptions and wrap them in a catch-all generic > exception. I think I've seen people do that. But if so, > what's the point of having typed exceptions? IMO (and maybe I'm just restating the obvious; it wouldn't be the first time ), "the list of exceptions f is allowed to raise" shouldn't be part of the interface of integrate, but rather "the list of exceptions integrate will handle gracefully" should be. Resumably, the caller of f, or some entity far enough up the call chain, anyway, knows something about f that integrate does not. In some cases, that entity could be a human sitting at an interactive console, and that human would like to know if/when f raises exceptions not handled by integrate. As to the original question, I agree: there's no way that integrate can know every exception f might raise, and there's no reason it should, either. f *must be content* with handling what it promises to handle and letting everything else pass through it unchanged. Logically, f is part of the *caller* of integrate rather than being among the functions integrate *calls*. Regards, Dan -- Dan Sommers Never play leapfrog with a unicorn. From kent3737 at yahoo.com Thu Nov 11 10:42:50 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 11 Nov 2004 10:42:50 -0500 Subject: re.compile.match() results in unicode strings - why? In-Reply-To: <2vh2mlF2lbkrdU1@uni-berlin.de> References: <2vh2mlF2lbkrdU1@uni-berlin.de> Message-ID: <419388f2$2_2@newspeer2.tds.net> Axel Bock wrote: > Hi, > > I am doing matches with the re module, and I am experiencing a strange > problem. I match a string with > exp = re.compile(blah) > m = exp.match(string) > a,b,c,d = m.groups() > now a,b,c,d are all string variables, and they all come out as unicode > strings (u"xxx"). Apparently if the input strings are unicode then the groups will be as well: >>> import re >>> r=re.compile('(ab)') >>> r.match('abc').groups() ('ab',) >>> r.match(u'abc').groups() (u'ab',) Are you sure that exp is not a unicode string? Kent From jacek.generowicz at cern.ch Tue Nov 9 08:13:57 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Nov 2004 14:13:57 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <87d5ysbkq9.fsf@pop-server.bigpond.net.au> <4b39d922.0411051555.24f31663@posting.google.com> Message-ID: finite.automaton at gmail.com (Lonnie Princehouse) writes: > Yes, wxPython is typically quicker than swing. It's not fair to use > this in a generic Python-vs-Java speed shootout, though, since > wxPython is just a wrapper around wxWidgets' C++ code; you're really > comparing C++ vs. Java here. And Python's list.sort is just a wrapper around C code. So I guess that it's not fair to use that, or any other Python built-in function, in a Python-vs-X speed shootout. This would mean you can't use Python classes in such a shootout either, as type.__new__ and object.__new__ are both also merely wrappers around C code ... not to mention Python dictionaries: wrappers around C code which are used in just about every name lookup in Python. So, the conclusion is that it's not fair to use Python in a Python-vs-X speed shootout. I rather like that conclusion :-) From richardblackwood at cloudthunder.com Sat Nov 6 18:30:01 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sat, 06 Nov 2004 18:30:01 -0500 Subject: Python OS In-Reply-To: References: Message-ID: <418D5E79.4040602@cloudthunder.com> >>P.S. If one can program interrupt routines in C, they can do the same >>in Python. >> >> > >Show me how you set the interrupt jumptables to your routines in python and >how you write time-critical code which has to be executed in a few hundred >cpu-cycles. And how good that works together with the GIL. > > > > Here is my logic: If one can do X in C and Python is C-aware (in other words Python can be exposed to C) then Python can do X via such exposure. From hills838 at hotmail.com Mon Nov 22 19:08:14 2004 From: hills838 at hotmail.com (hills) Date: Tue, 23 Nov 2004 08:08:14 +0800 Subject: The limitation of the Photon Hypothesis Message-ID: <20041123000916.EB6B31E4003@bag.python.org> Please reply to hdgbyi at public.guangzhou.gd.cn. Thank you! The limitation of the Photon Hypothesis According to the electromagnetic theory of light, its energy is related to the amplitude of the electric field of the electromagnetic wave, W=eE^2(where E is the amplitude). It apparently has nothing to do with the light's circular frequency v. To explain the photoelectric effect, Einstein put forward the photon hypothesis. His paper hypothesized light was made of quantum packets of energy called photons. Each photon carried a specific energy related to its circular frequency v, E=hv. This has nothing to do with the amplitude of the electromagnetic wave. For the electromagnetic wave that the amplitude E has nothing to do with the light's frequency v, if the light's frequency v is high enough, the energy of the photon in light is greater than the light's energy, hv>eE^2. Apparently, this is incompatible with the electromagnetic theory of light. THE UNCERTAINTY PRINCIPLE IS UNTENABLE By re-analysing Heisenberg's Gamma-Ray Microscope experiment and one of the thought experiment from which the uncertainty principle is demonstrated, it is actually found that the uncertainty principle cannot be demonstrated by them. It is therefore found to be untenable. Key words: uncertainty principle; Heisenberg's Gamma-Ray Microscope Experiment; thought experiment The History Of The Uncertainty Principle If one wants to be clear about what is meant by "position of an object," for example of an electron., then one has to specify definite experiments by which the "position of an electron" can be measured; otherwise this term has no meaning at all. --Heisenberg, in uncertainty paper, 1927 Are the uncertainty relations that Heisenberg discovered in 1927 just the result of the equations used, or are they really built into every measurement? Heisenberg turned to a thought experiment, since he believed that all concepts in science require a definition based on actual, or possible, experimental observations. Heisenberg pictured a microscope that obtains very high resolution by using high-energy gamma rays for illumination. No such microscope exists at present, but it could be constructed in principle. Heisenberg imagined using this microscope to see an electron and to measure its position. He found that the electron's position and momentum did indeed obey the uncertainty relation he had derived mathematically. Bohr pointed out some flaws in the experiment, but once these were corrected the demonstration was fully convincing. Thought Experiment 1 The corrected version of the thought experiment Heisenberg's Gamma-Ray Microscope Experiment A free electron sits directly beneath the center of the microscope's lens (please see AIP page http://www.aip.org/history/heisenberg/p08b.htm or diagram below) . The circular lens forms a cone of angle 2A from the electron. The electron is then illuminated from the left by gamma rays--high-energy light which has the shortest wavelength. These yield the highest resolution, for according to a principle of wave optics, the microscope can resolve (that is, "see" or distinguish) objects to a size of dx, which is related to and to the wavelength L of the gamma ray, by the expression: dx = L/(2sinA) (1) However, in quantum mechanics, where a light wave can act like a particle, a gamma ray striking an electron gives it a kick. At the moment the light is diffracted by the electron into the microscope lens, the electron is thrust to the right. To be observed by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A. In quantum mechanics, the gamma ray carries momentum as if it were a particle. The total momentum p is related to the wavelength by the formula, p = h / L, where h is Planck's constant. (2) In the extreme case of diffraction of the gamma ray to the right edge of the lens, the total momentum would be the sum of the electron's momentum P'x in the x direction and the gamma ray's momentum in the x direction: P' x + (h sinA) / L', where L' is the wavelength of the deflected gamma ray. In the other extreme, the observed gamma ray recoils backward, just hitting the left edge of the lens. In this case, the total momentum in the X direction is: P''x - (h sinA) / L''. The final x momentum in each case must equal the initial X momentum, since momentum is conserved. Therefore, the final X moment are equal to each other: P'x + (h sinA) / L' = P''x - (h sinA) / L'' (3) If A is small, then the wavelengths are approximately the same, L' ~ L" ~ L. So we have P''x - P'x = dPx ~ 2h sinA / L (4) Since dx = L/(2 sinA), we obtain a reciprocal relationship between the minimum uncertainty in the measured position, dx, of the electron along the X axis and the uncertainty in its momentum, dPx, in the x direction: dPx ~ h / dx or dPx dx ~ h. (5) For more than minimum uncertainty, the "greater than" sign may added. Except for the factor of 4pi and an equal sign, this is Heisenberg's uncertainty relation for the simultaneous measurement of the position and momentum of an object. Re-analysis The original analysis of Heisenberg's Gamma-Ray Microscope Experiment overlooked that the microscope cannot see the object whose size is smaller than its resolving limit, dx, thereby overlooking that the electron which relates to dx and dPx respectively is not the same. According to the truth that the microscope can not see the object whose size is smaller than its resolving limit, dx, we can obtain that what we can see is the electron where the size is larger than or equal to the resolving limit dx and has a certain position, dx = 0. The microscope can resolve (that is, "see" or distinguish) objects to a size of dx, which is related to and to the wavelength L of the gamma ray, by the expression: dx = L/(2sinA) (1) This is the resolving limit of the microscope and it is the uncertain quantity of the object's position. The microscope cannot see the object whose size is smaller than its resolving limit, dx. Therefore, to be seen by the microscope, the size of the electron must be larger than or equal to the resolving limit. But if the size of the electron is larger than or equal to the resolving limit dx, the electron will not be in the range dx. Therefore, dx cannot be deemed to be the uncertain quantity of the electron's position which can be seen by the microscope, but deemed to be the uncertain quantity of the electron's position which can not be seen by the microscope. To repeat, dx is uncertainty in the electron's position which cannot be seen by the microscope. To be seen by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A, so we can measure the momentum of the electron. But if the size of the electron is smaller than the resolving limit dx, the electron cannot be seen by the microscope, we cannot measure the momentum of the electron. Only the size of the electron is larger than or equal to the resolving limit dx, the electron can be seen by the microscope, we can measure the momentum of the electron. According to Heisenberg's Gamma-Ray Microscope Experiment, the electron??s momentum is uncertain, the uncertainty in its momentum is dPx. dPx is the uncertainty in the electron's momentum which can be seen by microscope. What relates to dx is the electron where the size is smaller than the resolving limit. When the electron is in the range dx, it cannot be seen by the microscope, so its position is uncertain, and its momentum is not measurable, because to be seen by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A, so we can measure the momentum of the electron. If the electron cannot be seen by the microscope, we cannot measure the momentum of the electron. What relates to dPx is the electron where the size is larger than or equal to the resolving limit dx .The electron is not in the range dx, so it can be seen by the microscope and its position is certain, its momentum is measurable. Apparently, the electron which relates to dx and dPx respectively is not the same. What we can see is the electron where the size is larger than or equal to the resolving limit dx and has a certain position, dx = 0. Quantum mechanics does not rely on the size of the object, but on Heisenberg's Gamma-Ray Microscope experiment. The use of the microscope must relate to the size of the object. The size of the object which can be seen by the microscope must be larger than or equal to the resolving limit dx of the microscope, thus the uncertain quantity of the electron's position does not exist. The gamma ray which is diffracted by the electron can be scattered into any angle within the cone of angle 2A, where we can measure the momentum of the electron. What we can see is the electron which has a certain position, dx = 0, so that in no other position can we measure the momentum of the electron. In Quantum mechanics, the momentum of the electron can be measured accurately when we measure the momentum of the electron only, therefore, we have gained dPx = 0. And, dPx dx =0. (6) Thought Experiment 2 Single Slit Diffraction Experiment Suppose a particle moves in the Y direction originally and then passes a slit with width dx(Please see diagram below) . The uncertain quantity of the particle's position in the X direction is dx, and interference occurs at the back slit . According to Wave Optics , the angle where No.1 min of interference pattern can be calculated by following formula: sinA=L/2dx (1) and L=h/p where h is Planck's constant. (2) So the uncertainty principle can be obtained dPx dx ~ h (5) Re-analysis The original analysis of Single Slit Diffraction Experiment overlooked the corpuscular property of the particle and the Energy-Momentum conservation laws and mistook the uncertain quantity of the particle's position in the X direction is the slit's width dx. According to Newton first law , if an external force in the X direction does not affect the particle, it will move in a uniform straight line, ( Motion State or Static State) , and the motion in the Y direction is unchanged .Therefore , we can learn its position in the slit from its starting point. The particle can have a certain position in the slit and the uncertain quantity of the position is dx =0. According to Newton first law , if the external force at the X direction does not affect particle, and the original motion in the Y direction is not changed , the momentum of the particle in the X direction will be Px=0 and the uncertain quantity of the momentum will be dPx =0. This gives: dPx dx =0. (6) No experiment negates NEWTON FIRST LAW. Whether in quantum mechanics or classical mechanics, it applies to the microcosmic world and is of the form of the Energy-Momentum conservation laws. If an external force does not affect the particle and it does not remain static or in uniform motion, it has disobeyed the Energy-Momentum conservation laws. Under the above thought experiment , it is considered that the width of the slit is the uncertain quantity of the particle's position. But there is certainly no reason for us to consider that the particle in the above experiment has an uncertain position, and no reason for us to consider that the slit's width is the uncertain quantity of the particle. Therefore, the uncertainty principle, dPx dx ~ h (5) which is demonstrated by the above experiment is unreasonable. Conclusion Every physical principle is based on the Experiments, not based on MATHEMATICS, including heisenberg uncertainty principle. Einstein said, One Experiment is enough to negate a physical principle. >From the above re-analysis , it is realized that the thought experiment demonstration for the uncertainty principle is untenable. Therefore, the uncertainty principle is untenable. Reference: 1. Max Jammer. (1974) The philosophy of quantum mechanics (John wiley & sons , Inc New York ) Page 65 2. Ibid, Page 67 3. http://www.aip.org/history/heisenberg/p08b.htm Single Particles Do Not Exhibit Wave-Like Behavior Through a qualitative analysis of the experiment, it is shown that the presumed wave-like behavior of a single particle contradicts the energy-momentum conservation laws and may be expained solely through particle interactions. DUAL SLIT INTERFERENCE EXPERIMENT PART I If a single particle has wave-like behavior, it will create an interference image when it has passed through a single slit. But the experimental result shows that this is not the case Only a large number of particles can create an interference image when they pass through the two slits. PART II In the dual slit interference experiment, the single particle is thought to pass through both slits and interfere with itself at the same time due to its wave-like behavior. The motion of the wave is the same direction as the particle. If the particle passes through a single slit only, it can not be assumed that it has wave-like behavior. If it passes through two slits, it, and also the acompanying wave must be assumed to have motion in two directions. But a wave only has one direction of motion. PART III If one slit is obstructed in the dual slit interference experiment and a particle is launched in this direction, then according to Newton??s first law, (assuming no external forces,) it will travel in a uniform straight line. It will not pass through the closed slit and will not make contact with the screen. If it has wavelike behavior, there is a probability that it will make contact. But this will negate Newton??s first law and the law of conservation of energy and momentum. Both quantum mechanics and classical mechanics are dependent on this law. THE EXPLANATION FOR THE WAVE-LIKE BEHAVIOR OF THE PARTICLE In the dual slit interference experiment, if one slit is unobstructed, particles will impact at certain positions on the screen. But when two slit are open, the particles can not reach these positions. This phenomenon brings us to the greatest puzzle regarding the image of the particle. But when we consider that the particle may experience two or more reflections, the puzzle may be resolved. As indicated, when one of the slits is obstructed, the particles that move towards this slit can not get to the screen. However, they can return to the particle source by reflection and then pass through the open slit and reach the above positions since they have different paths when one or two slits are open. This indicates that wave-like behavior may be explained solely on the basis of particle interactions. EXPERIMENTAL TEST The above may be tested by an experiment which can absorb all the particles that move towards the closed slit. If one slit is obstructed by the stuff which can absorb all the particles that move towards it, the intensity of some positions on the screen should decrease. THE CONCLUSION Single particles do not exhibit wave-like behavior. The similarity of wave and particle behavior may be attributed to initial impulse and path. The quantum mechanical explanation is suspect, since the probability of one particle and one particle among a large quantity reaching the screen is equal in mathematics and physics. Author : BingXin Gong Postal address : P.O.Box A111 YongFa XiaoQu XinHua HuaDu GuangZhou 510800 P.R.China E-mail: hdgbyi at public.guangzhou.gd.cn Tel: 86---20---86856616 From bokr at oz.net Tue Nov 2 14:24:34 2004 From: bokr at oz.net (Bengt Richter) Date: Tue, 02 Nov 2004 19:24:34 GMT Subject: dicts & lists together References: Message-ID: <4187de79.1447401863@news.oz.net> On Tue, 02 Nov 2004 13:45:38 -0500, Brad Tilley wrote: >I have a dict that associates strings to numbers like this {'abc': 1, >'xyz':2, '123':3,...} I am then given a list of strings ['abc', 'xyz', >'123',...] and asked to associate a number to each string in the list >according to the string's value in the dict. I am at a loss as to how to >do this, can someone show me where to start? Associate as in list of number,string pairs? >>> dct = {'abc':1, 'xyz':2, '123':3} >>> strings = ['abc','xyz','123','error'] >>> [(dct[s],s) for s in strings] Traceback (most recent call last): File "", line 1, in ? KeyError: 'error' >>> [(dct.get(s, 99999),s) for s in strings] [(1, 'abc'), (2, 'xyz'), (3, '123'), (99999, 'error')] Regards, Bengt Richter From steven.bethard at gmail.com Fri Nov 19 12:21:37 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 19 Nov 2004 17:21:37 GMT Subject: returning unordered keyword arguments from a function (WAS: Are multiple return values really harmful?) In-Reply-To: <8ef9bea6.0411190633.4da78912@posting.google.com> References: <30001hF2ptnqcU1@uni-berlin.de> <8ef9bea6.0411180831.e44ae56@posting.google.com> <8ef9bea6.0411190633.4da78912@posting.google.com> Message-ID: Hung Jung Lu wrote: > >>>Steven Bethard wrote: >>>>>>>r = object(year=2004, month=11, day=18) > [snip a bunch of good arguments for including generic objects] It does sound like there's some support for putting something like this into the language. My feeling is that the right place to start would be to put such an object into the collections module. (If necessary, it could get moved to builtins later.) Is this something a PEP should be written for? Steve From riko.wichmann at remove-this.desy.de Fri Nov 19 04:03:47 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Fri, 19 Nov 2004 10:03:47 +0100 Subject: activating history in Python 2.3.4 Message-ID: dear all, lately, I installed Python 2.3.4 from sources (after having 2.2 for some time). However, running Python interactively, I cannot recall the histroy of command with cursor-up or down anymore (just get ^[[A for example). As far as I could find out, it has something to do with GNU readline. When I do >>> import readline Traceback (most recent call last): File "", line 1, in ? ImportError: No module named readline things seem to be clear. However, since my old Python 2.2 seems to have readline it means, gnu readline is in principle available. How can I activate history, or where do I get the readline module from? Thanks and cheers, Riko From pecora at anvil.nrl.navy.mil Sun Nov 7 21:05:32 2004 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sun, 07 Nov 2004 21:05:32 -0500 Subject: Installed MacPython 10.3 Addons - Can't find Modules, even standard ones. References: Message-ID: In article , Maurice LING wrote: > Did you ever install Python through Fink or had used Fink before? > > Try to do > import sys > sys.path() > and see where it points to? > > My suspicion is that there are more than one pythons in your system now... > > Cheers > maurice Ah...Good idea. Will give that a go. I did not install any Fink stuff ever. Only thing I had was the old Python 2.2 for Jaguar from 2003. That seemed to be deleted automatically when I installed the 2.3 addons. -- Lou Pecora (my views are my own) From eric_brunel at despammed.com Tue Nov 30 06:11:38 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 30 Nov 2004 12:11:38 +0100 Subject: Problem with tkinter mainloop In-Reply-To: References: Message-ID: <41ac53ac$0$30438$8fcfb975@news.wanadoo.fr> k2riddim wrote: > Hello, > I'm a beginner with Python and Tkinter development. > My application parse links in an html file. And I use Tkinter to > implement a GUI. This GUI has a button to launch the parse treatment, > and a status bar to show the state of the treatment. > I know that because of the mainloop, my tkinter application freeze > while my treatment isn't finished. That's why my status bar doesn't > update herself in real time. > I wanted to use the after or the after_idle function, but I don't > really understand why it doesn't work. after and after_idle won't help you: the action you register in these methods are called only when the main loop gets back the control, and your problem is precisely that the main loop does not get it... The method you're probably looking for is update_idletasks: it updates the display without getting any user event. There's another method called update, but this one does process user events, so it may call some of your code if such an event is pending. This is usually not what you want to do, except in some very rare cases. Here is how it may look like in your code, along with a few remarks on your code: > > My apps is build approximately like that : > > ---Gui.py--- > class Gui(Frame): Why do you inherit from Frame? A Tkinter Frame is a generic container widget; this is not a window. IMHO, you'd better inherit from Tk for your main window or from Toplevel for other windows. You'd also get better control on the actual window, since some of the methods available on Tk and Toplevel are not available on other widgets (e.g. geometry or protocol) > def __init__(self): > ... > def launchTreatment(self): > b = Treatment() > self.after(b.treatment.parse) This cannot be your code; the after methods takes two parameters: the number of milliseconds to wait before the action will be called and the action itself. You only provide the action here. But again, the after method won't help you to get what you want... > > ---Treatment.py--- > class Treatment(): > def __init__(self): > ... > def parse(self): > ... > GUIinstance.status.set("state 1") This is where the GUIinstance.update_idletasks() should go. > ... > GUIinstance.status.set("state 2") Another GUIinstance.update_idletasks() here. > > > ---Main.py--- > #instanciation of classes > GUIinstance = Gui Again, this cannot be your code, since you do not instantiate the class here. The correct line should be: GUIinstance = Gui() It is usually far better to post a working example demonstrating the problem you have instead of just extracting a few lines of your whole code. This will help people who are willing to help to understand exactly what is going on. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From aleaxit at yahoo.com Mon Nov 1 02:46:09 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 1 Nov 2004 09:46:09 +0200 Subject: List problem References: <1gmiyon.jvyq1w1ob9r59N%aleaxit@yahoo.com> <41853d5f.1278687054@news.oz.net> <1gmjqh9.oialil1r1xwffN%aleaxit@yahoo.com> <41858eaa.1299498379@news.oz.net> Message-ID: <1gmkg86.1nzf8g91e7yby5N%aleaxit@yahoo.com> Bengt Richter wrote: ... > >def delsome_am(n=1000000, todel=[2]): > > a = range(n) > > a = [x for x in a if x not in todel] > ^-- shud be a[:] ;-) > (I think the missing return a is in the noise ;-) Right, sorry. > >kallisti:/tmp alex$ python -mtimeit -s'import br' 'br.delsome_br()' > >10 loops, best of 3: 4.44 sec per loop > >kallisti:/tmp alex$ python -mtimeit -s'import br' 'br.delsome_am()' > >10 loops, best of 3: 3.92 sec per loop > > > I thought you had 'way faster machines than mine. Neither time is an > improvement over delsome_br for 2.3.2 on my old box. I wonder what's up. I ran these on an 800 MHz laptop, the one I invariably use for netting -- best ergonomics. OK, I'll try with faster machines when I get a chance -- I'm surprised you measure almost a 1:2 ratio with _br faster. Alex From jerf at jerf.org Wed Nov 17 20:49:06 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 17 Nov 2004 20:49:06 -0500 Subject: don't NaN & infinities hide FP errors References: <940ee3e8.0411170130.31d247@posting.google.com> Message-ID: On Wed, 17 Nov 2004 01:30:33 -0800, kartik wrote: > Since Python floats are implemented using C doubles, assuming IEEE 754 > compliance, certain operations should result in NaN or infinity. Don't > such special values hide errors? Would we want our variables to be in > such states? I feel it would be better if a floating point division by > zero (or other actions that produce NaNs or infinities) throws an > exception, just like an integer divide by zero. > > Am I right? You may think, while dealing with your problems and programs, that NaN is an error. I may want them, because NaN, Inf, and exceptions are not the same things. If you're working with floats, you're *already* in a domain where *everything* might hide an error. Along with everybody else's reply (including Tim Peter's which should be considered "definitive"), I'd add that trying to create a float-based system that *doesn't* "hide errors" is basically a contradiction in terms. All you can do is make a few choices about which errors you want. From djdennie69 at hotmail.com Fri Nov 5 08:52:18 2004 From: djdennie69 at hotmail.com (Dennis Hotson) Date: Sat, 06 Nov 2004 00:52:18 +1100 Subject: Add a file to a compressed tarfile References: Message-ID: On Fri, 05 Nov 2004 13:40:22 +0000, Martin Franklin wrote: > On Fri, 05 Nov 2004 13:26:22 -0000, Martin Franklin > wrote: > >> On Sat, 06 Nov 2004 00:13:16 +1100, Dennis Hotson >> wrote: >> >>> Hi, >>> >>> I'm trying to write a function that adds a file-like-object to a >>> compressed tarfile... eg ".tar.gz" or ".tar.bz2" >>> >>> I've had a look at the tarfile module but the append mode doesn't >>> support >>> compressed tarfiles... :( >>> >>> Any thoughts on what I can do to get around this? >>> >>> Cheers! >> > > > > > Sorry I just re-read your message after sending my reply.... Ahh ok... Yeah, I've already seen the docs... thanks anyway! :D I'm currently trying to read all of the files inside the tarfile... then writing them all back. Bit of a kludge, but it should work.. Cheers! Dennis From Python at IvoNet.nl Wed Nov 10 15:04:55 2004 From: Python at IvoNet.nl (Ivo Woltring) Date: Wed, 10 Nov 2004 21:04:55 +0100 Subject: ConfigParser References: Message-ID: <2rs4p01b9uugvd6huie5g3oebbe8n2ueo3@4ax.com> On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo wrote: >Regards. > >Since sections in CongiParser files are delimited by [ and ], why >there is not an escape (and unescape) function for escaping >&, [, and ] characters to &, [ and ] ? > > > > >Thanks Manlio Perillo By the way I did some testing because i have a similar thing going on right now. I found out that [section] option = [Ivo Woltring] is valid and does not have to be translated to [section] option = [Ivo Woltring] to work. so my current class is a bit unnessesary: # # IniFile extents the ConfigParser with my own functions # __author__ = "Ivo Woltring" __version__ = "01.00" __copyright__ = "Copyright (c) 2004 Ivo Woltring" __license__ = "Python" from ConfigParser import * class IniFile(ConfigParser): """IniFile Is an extention on the ConfigParser class. It overrulles the write method so it can write directly to a file provided as a parameter. The whole filehandling is done by the IniFile.write(fp) method. """ def __init__(self, defaults=None): ConfigParser.__init__(self, defaults) # supers init self.replace = [('[','['), (']',']'), ] def write(self,fp): """write(filename) --> written file""" try: f = open(fp,'w') except IOError: raise IOError #ConfigParser.write(self,f) self._write(f) f.close() def _replace(self, txt ,reverse=False): """Replace the self.replace stuff""" for source, target in self.replace: if reverse: txt=txt.replace(target, source) else: txt=txt.replace(source, target) return txt def get(self, section, option, raw=False, vars=None): # override the get() method of super """get(section, option, [raw=False], [vars=None]) --> String this get() is an extention on the origional ConfigParser.get() This one translates html style '[' to '[' etc. """ if raw: return ConfigParser.get(self, section, option, raw, vars) # call the get of super return self._replace(ConfigParser.get(self, section, option, raw, vars)) def _write(self, fp): """Write an .ini-format representation of the configuration state.""" if self._defaults: fp.write("[%s]\n" % DEFAULTSECT) for (key, value) in self._defaults.items(): fp.write("%s = %s\n" % (key, self._replace(str(value).replace('\n', '\n\t'), reverse=True))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) for (key, value) in self._sections[section].items(): if key != "__name__": fp.write("%s = %s\n" % (key, self._replace(str(value).replace('\n', '\n\t'), reverse=True))) fp.write("\n") if __name__=="__main__": import sys,os p = IniFile() p.add_section('section') p.set('section','option','[Ivo Woltring]') p.write(os.path.splitext(sys.argv[0])[0]+'.ini') print p.get('section','option') print p.get('section','option', raw=True) raw_input('Press enter to continue...') have fun... I do, Cheerz, Ivo. From nospam at nospam.com Fri Nov 5 19:51:30 2004 From: nospam at nospam.com (Mark Schonewille) Date: Sat, 06 Nov 2004 01:51:30 +0100 Subject: Color schemes In-Reply-To: <18282ecb.0410301418.1ee469f5@posting.google.com> References: <41838c6e$0$7153$d5255a0c@news.wanadoo.nl> <18282ecb.0410301418.1ee469f5@posting.google.com> Message-ID: <418c2006$0$34293$cd19a363@news.wanadoo.nl> Josiah and M.E., Thanks you for your replies. As I understand from your answers, the colorised scripts on web sites have little to do with the use of colorisation in script editors by Python programmers, but those programmers who prefer an editor with colorisation features probably apply colorisation rules similar to the pretty looking scripts on websites and there probably is't a standard colour scheme. Best, Mark M.E.Farmer wrote: > Mark Schonewille wrote in message news:<41838c6e$0$7153$d5255a0c at news.wanadoo.nl>... > >>Is anyone using a color scheme for his Python scripts? > > Yes. > >>I suspect most people are using a text editor which may or may not support >>colorisation of scripts. > > Good intuition, because some do and some don't :) > Many of the python editors out now are based on Scintilla. > Scintilla is a capable, colorizing, folding, text widget on 'roids. > >>Do you use a similar script in a Python IDE or in your text >>editor to colorize your Python scripts? > > I use an editor that is based on Scintilla . > To convert python source to colorised html for webpages and documentation, > I have been writing a module called PySourceColor. > It is a based on token and tokenize. > If you are intrested you can find it here: > 'http://bellsouthpwp.net/m/e/mefjr75/' > This is a new version and has many improvements. > Also there is a version of pydoc there that serves up colorized html. > HTH, > M.E.Farmer -- eHUG coordinator http://home.wanadoo.nl/mark.sch http://www.ehug.info From M.Waack at gmx.de Sun Nov 21 14:27:40 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sun, 21 Nov 2004 20:27:40 +0100 Subject: How can I interrupt os.system(cmd)? References: Message-ID: Carl wrote: > What options do I have to control execution of external programs > from Python? You have the same options as your OS offers. At least under Unix you can run a command by using one of the popen()-functions or using the commands module (I would suggest the latter for you). All these procedures give you the process id (pid) of the started process. You can wait() for this process or you can control it by sending it signals using the kill() function. The python docs contains all information necessary to use these functions. Read the pages about the modules os, popen and commands. Most of these functions should be available under all OS. Mathias From jfine at pytex.org Sun Nov 14 07:30:40 2004 From: jfine at pytex.org (Jonathan Fine) Date: Sun, 14 Nov 2004 12:30:40 +0000 Subject: Smart dummy objects Message-ID: <41974FF0.4080207@pytex.org> I'd appreciate comments on what I'm doing. Please be kind, I'm a new kid on the block. Here's my application. I'm writing some test code. (I'm a recent convert to unit testing.) I want to test a series of changes to an object. The change methods return self, so I can form chains. Like so: x = obj.this().that(12).other(x=3, y=12) assert x is obj A Dummy class (easily coded) allows: d = Dummy() y = d.this().that(12).other(x=3, y=12) assert y is d to execute without errors. Function calls (and getting attributes) do not change d. And these operations return self. I'm looking for a SmartDummy class. So that: sd = SmartDummy() sd.this.that(12).other(x=3, y=12) assert z is sd always executes without errors (it's a Dummy) ... ... and because it's a SmartDummy, magic = sd.special_method_name(obj) is equivalent to magic = obj.this().that(12).other(x=3, y=12) even to the raising of exceptions. This allows a chain of changes to be stored in a SmartDummy. And then applied to a succession of real objects. Before writing much code, I did a google for "SmartDummy" and "smart dummy" in this newsgroup. I got no hits, which discouraged me. I then searched all newsgroups. Got 24 and 39,200 hits resp. http://groups.google.com/groups?hl=en&lr=&q=SmartDummy http://groups.google.com/groups?hl=en&lr=&q=Smart+Dummy&btnG=Search&meta= The 24 were not helpful, the 39,200 too many. A search of the web for SmartDummy was not helpful. http://www.google.com/search?hl=en&lr=&q=SmartDummy But "Smart Dummy" was. http://www.google.com/search?q=Smart%20Dummy&hl=en&lr=&sa=N&tab=gw The very first hit was: http://www.tc.gc.ca/mediaroom/releases/nat/2004/04-h082e.htm It announced the Canadian debut of: === WorldSID (World Side Impact Dummy) was born out of a need to have a world harmonized crash test dummy that would better simulate the motions of a human in side impact crash testing. === This encouraged me. Smart Dummies are important. They can save lives. Maybe they are a good idea. Let's try to make a Python SmartDummy. So I went ahead and spend the morning coding up my SmartDummy class. Much of it is now working, but it's not yet ready for its Python debut. Hope this of interest. BTW, I'm a bit of a Python newbie, particularly regarding culture. This is my first post to comp.lang.python. (I was a lurker.) However, I am a regular on comp.text.tex. As I said, I'd appreciate your comments on this. Jonathan From newsgroups at jhrothjr.com Tue Nov 2 09:49:29 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 2 Nov 2004 08:49:29 -0600 Subject: Python needs a CPyAN References: Message-ID: <10of7jtm07h7f77@news.supernews.com> How does the Python Package Index not meet this need? I can think of one very serious difference, which has kept me from placing a module in the PPI. John Roth "Stephen Ferg" wrote in message news:b16e4ef7.0411020539.4c6aa338 at posting.google.com... >I am a very satisfied user of Python and have been for number of > years. I would never willing use another language. I wish all good > things for Python, and that moves me to express some thoughts about > Python's future prospects. [rest of post snipped] From noway at sorry.com Wed Nov 24 22:44:50 2004 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 25 Nov 2004 03:44:50 GMT Subject: zip module password References: Message-ID: Thomas Heller wrote: >>> suggests that there is no such support in the standard zipfile >>> module yet, but that a patch has been available for some time (but has >>> not yet been accepted). >> >> "has not yet been *commented*" or even looked at would be more >> appropriate. In fact, it is no wonder that it is my sole >> contribution to Python -- I found the lack of responsiveness so >> depressing. > > Here's one possible way to push it further: > http://mail.python.org/pipermail/python-dev/2004-October/049495.html I am sorry for Martin, but this looks like total bullshit to me. I am *not* qualified to review Python patches because I am not a Python developer. If I review 10 patches, my work could be totally useless, if not even dangerous for Python itself. I could easily miss blatant bugs, suggest wrong things, understand interface decisions wrong. It would be a total waste of time for me; plus, some real Python developer would have to double-check my work, because it would be completely fool for them to just blindly trust my reviews. And if they carefully double-check my work, they could spend that very time by reviewing the patches themselves. Usually, you get involved in development by submitting small patches, getting reviews and comments, learning by your errors, and understanding things as you go. If the only way to get a review is to produce 10 reviews out of *no* experience, you do not have time to learn. Plus, it is really surprising to me that the Python team is so developed-starved to ask random people whose experience is totally unknown to review patches on their behalf. If they need more developers, they could stop improving Python for some months, just how long it takes them to review all those patches. Nobody would scream and they might end up with a bunch of new wannabe developers to help them. -- Giovanni Bajo From nick at craig-wood.com Sun Nov 14 08:30:38 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 14 Nov 2004 13:30:38 GMT Subject: .pyc files... References: <1100420230.124422.169890@f14g2000cwb.googlegroups.com> Message-ID: Eddie Parker wrote: > Stephen Waterbury wrote: > > alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" > > or with backticks: rm -rf `find . -name '*.pyc'` > Hrmm, this is more a *NIX discussion, but I'm curious: > > That could be problematic if you have too many .pyc files found - overflow > the command buffer, no? > > Something like: "find . -name '*.pyc' | xargs -i rm -f {}", would solve > that, as xargs executes each encountered argument individually, I believe (I > think the -exec command does similar, in Stephen's original post). the -exec will spawn rm for each file which is inefficient as will your xargs solution. However find . -name '*.pyc' | xargs rm -f Just spawns one rm. If the number of files gets too big for a command line then xargs spawns another rm. This isn't bullet proof though - consider what happens when you get file names with 's in etc... This *is* bullet proof though find . -name '*.pyc' -print0 | xargs -0 rm -f And if you don't want an error when there aren't any files find . -name '*.pyc' -print0 | xargs -0r rm -f End unix sysadmin lecture ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lists at debpro.webcom.dk Thu Nov 4 10:21:36 2004 From: lists at debpro.webcom.dk (Jacob Friis) Date: Thu, 04 Nov 2004 16:21:36 +0100 Subject: Simple thread pools Message-ID: <418A4900.7020304@debpro.webcom.dk> I have built a script inspired by a post on Speno's Pythonic Avocado: http://www.pycs.net/users/0000231/weblog/2004/01/04.html#P10 I'm setting NUM_FEEDERS to 1000. Is that crazy? Are there a better solution? Thanks, Jacob From steven.bethard at gmail.com Mon Nov 29 18:56:29 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 29 Nov 2004 23:56:29 GMT Subject: documentation for PyArg_ParseTupleAndKeywords Message-ID: I'm just starting to play around with the Python source. (Specifically, I'm looking at adding a key argument to max/min like sorted has.) Can anyone direct me to the documentation on how PyArg_ParseTupleAndKeywords, etc. work? In particular, I can't figure out how the format arg to vgetargskeywords should be specified... Thanks, Steve From mwm at mired.org Fri Nov 5 22:39:10 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 05 Nov 2004 21:39:10 -0600 Subject: Python for Reverse Engineering References: Message-ID: Brad Tilley writes: > A friend of mine wrote an algorithm that generates strings. He says > that it's impossible to figure out exactly how the algorithm > works. That may be true, but I think if I had enough sample strings > that I could write a program to identify patterns in the strings and > then produce strings with similar patterns. He disagrees with me. He > gave me 100 strings to analyze. > > I wrote a script to read each string and build a list of characters > present. I've discovered that he only uses 20 alpha/numeric chars to > generate the strings and that each string sums up to a value between > 1000 and 1200 when I assign each char in the string its ASCII value. > > What else might I do to analyze these things? As it stands now, I can > generate an acceptable string on ever 100th attempt or so, but I'd > like to do better than this. Build a markov chain generator. Basically, build tuples of characters of length N, and use those to index a dictionary containing a list (or string) of characters that follow that list of characters in your input strings. So, with N equal 2, and d[('a', 'b')] = ['c', 'd', 'e'] you'd know that the strings abc, abd and abe appeared in the text. To gennerate a string, pull a random key from the dictionary, then choose random characters from the list that the last N characters treated as a tuple index in the dictionary. Larger values of N generate strings that more closely resemble the input text. Optionally, make the objects stored in the dictionary keep a count of how many times each character appears, and choose one randomly weighted by those counts. I've got a markov chain generator that works on words if you really want to see one. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From chris.cavalaria at free.fr Tue Nov 2 19:17:37 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Wed, 03 Nov 2004 01:17:37 +0100 Subject: strong/weak typing and pointers References: <4187aafe$1@nntp0.pdx.net> <41880188$0$14993$626a14ce@news.free.fr> Message-ID: <418823a1$0$14963$626a14ce@news.free.fr> Steven Bethard wrote: > Christophe Cavalaria free.fr> writes: >> >> If by ML you thing of OCaml you should try again. OCaml isn't type safe >> because of a few modules of the standard library. The marshaling module >> comes to mind. Using it you can "typecast" a pointer to an integer as a >> pointer to a string and segfault in the process because the unmarshal >> function trusts the caller to cast the result in the good type. > > Thanks, I knew I'd read something like that somewhere. Totally surprised > me too 'cause I figured that, of all people, ML folks would be the most > afraid of a module like this. =) > > Steve Marshaling ( Python calls it pickling ;) ) is somthing needed in the standard library of any good language. Too bad for them that the OCaml language makes it impossible to implement. From gh at ghaering.de Sun Nov 21 17:44:37 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 21 Nov 2004 23:44:37 +0100 Subject: Small Database Needed In-Reply-To: <20041121145440.85318.qmail@web14004.mail.yahoo.com> References: <20041121145440.85318.qmail@web14004.mail.yahoo.com> Message-ID: <41A11A55.4000103@ghaering.de> Kevin McBrearty wrote: > Hello All, > > I'm looking at implementing DB in my program for > analysis of CAD (STL Files). This database will > require the basic functionality. > > Query > Sort > Delete/Add Records > [...] pysqlite should fit your requirements nicely. Get it here: http://sourceforge.net/project/showfiles.php?group_id=54058 On Windows just use the binary installer, this is all you need. On *nix if you're lucky (Debian, FreeBSD, maybe others) it is packaged for you. Or you have to build it yourself. If you don't want or don't actually need a relational database, metakit or the bsddb package included with Python could also be enough. I haven't used either, though. -- Gerhard From autismuk at autismuk.muralichucks.freeserve.co.uk Sat Nov 13 15:00:23 2004 From: autismuk at autismuk.muralichucks.freeserve.co.uk (Paul Robson) Date: Sat, 13 Nov 2004 20:00:23 +0000 Subject: Advice needed References: Message-ID: On Sat, 13 Nov 2004 16:57:41 +0000, Premshree Pillai wrote: > Lots of reasons why you should learn Python. I'll > leave that to others in the mailing-list. :) > > I'm not sure where I heard the following, but I've > heard it: > "If God did OOP, he'd do it in Python." If God did it he might have figured out len() should be a method... From tismer at stackless.com Wed Nov 24 12:35:11 2004 From: tismer at stackless.com (Christian Tismer) Date: Wed, 24 Nov 2004 19:35:11 +0200 Subject: Paid Research Project on Stackless 3.1 In-Reply-To: <1gm8k08.2z1kw7u3x98rN%aleaxit@yahoo.com> References: <468v42-c23.ln1@nb2.stroeder.com> <1gm8k08.2z1kw7u3x98rN%aleaxit@yahoo.com> Message-ID: <41A4C64F.2010700@stackless.com> Alex Martelli wrote: ... > Wish I didn't have the Cookbook's 2nd ed at such a critical stage > (blocked on contributors' permissions, UGH, and requiring lots of time > and non-programming effort to work around the block), plus much else > cooking, or I'd consider taking it up myself (being peeved that I wasn't > listed among Christian's "real hardcore system hackers with many years > of experience" -- well I _do_ have the many years, at least!-)... Oops! Sorry about that. When I wrote this, I was just thinking of some attendants of the Stackless sprint who went quite deeply into the stuff. Thinking of a challenge for students. Of course that sentence about many years of experience makes no sense in that context. I guess I was very tired and afraid of getting too many replies. Having a company with a larger contract, I saw this as way to save guys like you and me from a boring debug marathon, because we have enough different things to do. Hoping very much to see you on the next pypy sprint -- chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jeff at ccvcorp.com Thu Nov 11 14:20:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 11 Nov 2004 11:20:11 -0800 Subject: Tkinter and WCK (was Re: How come wxPython isn't in the standard library?) In-Reply-To: <2vgfe5F2m8raqU1@uni-berlin.de> References: <2vgfe5F2m8raqU1@uni-berlin.de> Message-ID: <10p7elrkgnmh75@corp.supernews.com> Jon Perez wrote: > I think there's another reason not to standardize on > wxPython and it's that its API is not at all pythonic. > It reminds me too much of a C++ API. Indeed, one of wxPython's design criteria is that it remains fairly close to the underlying C++ API -- it is explicitly a fairly thin wrapper, not a complete retooling. (Though there are several retoolings built on top of wxPython, notably PythonCard.) I think that, despite the sometimes awkwardness for Python programmers, this is a laudable goal. For one, it means that it's that much easier to combine Python and C++ in a single wxPython/wxWidgets multilanguage application. For another, considering that wxPython is essentially a one-man project, it means that Robin can spend more time exposing functionality and less time hiding syntax, so that overall wxPython ends up being more powerful than it would otherwise. ;) On the other hand, I *do* agree that the non-Pythonic API does make for a barrier in including wxPython in the standard library. The initial learning curve for wxPython is rather steeper than that for Tkinter (though it isn't at all bad if one already has C++ GUI programming experience). Especially when starting from zero, it's easier to figure out how to get a simple GUI running under Tkinter. The downside of Tkinter is that it is, in general, less flexible and less powerful than wxPython -- simple stuff is easier in Tkinter, but complex stuff is generally harder. Personally, I much prefer using wxPython. (But then, I did play around with C/C++ Windows programming long before I discovered Python.) However, I can also see that the Tkinter toolkit is more appropriate for standard-lib usage than wxPython is. And really, it's not like it's all that difficult to install both Python and wxPython when distributing an application... Jeff Shannon Technician/Programmer Credit International From rambam at bigpond.net.au Fri Nov 5 06:26:07 2004 From: rambam at bigpond.net.au (Israel Raj T) Date: Fri, 05 Nov 2004 11:26:07 GMT Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> Message-ID: <87d5ysbkq9.fsf@pop-server.bigpond.net.au> Maurice LING writes: > This may be a dumb thing to ask, but besides the penalty for dynamic > typing, is there any other real reasons that Python is slower than > Java? Do you have any data to support this ? On Windows XP, Windows NT and Linux (Gentoo ), I have consistently found python apps using wxpython to be far faster to load and to be far more responsive than Java apps. From mc79 at cse.buffalo.edu Mon Nov 15 19:03:01 2004 From: mc79 at cse.buffalo.edu (Madhusudhanan Chandrasekaran) Date: Mon, 15 Nov 2004 19:03:01 -0500 Subject: Redirecting system output quietly In-Reply-To: <6542462a.0411151555.5fe41de4@posting.google.com> References: <1gn8ja3.7d3sbhuk94khN%aleaxit@yahoo.com> <6542462a.0411151555.5fe41de4@posting.google.com> Message-ID: Hi, I am a newbie here. I want to know how to redirect os.system("ls -af") to a string variable without it barfing the answer of ls -af on the screen. Thanks in advance, Madhusudhanan.C From hari04 at gmail.com Mon Nov 15 16:01:52 2004 From: hari04 at gmail.com (Hari Pulapaka) Date: 15 Nov 2004 13:01:52 -0800 Subject: Set like feature Message-ID: <1100552512.672456.317420@c13g2000cwb.googlegroups.com> Hi, I have a list of space delimited strings ending in a newline. Eg: a = ['a sfds sdf s df 34 ew\n', 'df sdf s f s ssf\n'] Now inside each row, I have a space delimited list of fields. Now I want to compare the fields in each row of the array and see which fields do not match. Think of it as a 2 dimensional array of size mn, and comparing each each element on a column by column basis. I am using python2.2 so no sets. Can anyone think of an efficient way to do this? Thanks, Hari From peter at engcorp.com Fri Nov 12 23:01:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Nov 2004 23:01:37 -0500 Subject: a very newbie question about threading In-Reply-To: References: <9c3edc58.0411121629.45652543@posting.google.com> Message-ID: Jeremy Bowers wrote: > On Fri, 12 Nov 2004 16:29:53 -0800, Chris Patton wrote: >>I've recenently stumbled upon a concept known as "threading". > > I'd add that with no insult intended, "threading" and "very newbie" do not > go together well. Threading is the most common source of the notorious > "heisenbug", ... > Generally, unless you *know* you need them, you don't, ... Excellent post, Jeremy, though I think it's worth adding something like this: Python makes writing threaded code much more straightforward than many languages, and also provides some protection from some types of bugs which are almost ubiquitous in threaded applications in some other languages. By sticking with the Queue object (see the module by that name) as the sole means of communication between threads, the vast majority of other thread-related problems simply disappears. Not all of them -- and Jeremy's caution about threads giving even expert programmers pause applies -- but in general Python's not a bad place to learn and use threads... -Peter From maxm at mxm.dk Fri Nov 5 03:18:40 2004 From: maxm at mxm.dk (Max M) Date: Fri, 05 Nov 2004 09:18:40 +0100 Subject: Extract Title from HTML documents In-Reply-To: References: Message-ID: <418b36ac$0$304$edfadb0f@dread12.news.tele.dk> Nickolay Kolev wrote: > Hi all, > > I am looking for a way to extract the titles of HTML documents. I have > made an honest attempt at doing it, and it even works. Is there an > easier (faster / more efficient / clearer) way? You anly need one tag here, so using a regex is ok. linkPattern = re.compile('(((.*?)))', re.I|re.S) match = linkPattern.search(source) if match is None: result = '' result = match.group(0) If you need more than just the title I would definitely go with BeautifulSoap. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From goodger at python.org Tue Nov 2 09:00:26 2004 From: goodger at python.org (David Goodger) Date: Tue, 02 Nov 2004 09:00:26 -0500 Subject: python backward incompatibilities In-Reply-To: References: Message-ID: [Peter Maas] > I tried to find a comprehensive list of Python backward incompatibilities > without success. What is the fastest way to compile such a list > (with code examples / expected results)? Thanks for your hints. PEP 290 would be a good start: http://www.python.org/peps/pep-0290.html -- David Goodger -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 264 bytes Desc: OpenPGP digital signature URL: From irmen at -nospam-remove-this-xs4all.nl Wed Nov 10 15:12:23 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 10 Nov 2004 21:12:23 +0100 Subject: get element text in DOM? In-Reply-To: References: Message-ID: <41927627$0$568$e4fe514c@news.xs4all.nl> Juliano Freitas wrote: > How can i get the text between the tags?? > > >>>>xml = """ texto """ You must know that the text between the tags is a DOM element by itself, namely a TEXT node, which is a child of the elment node formed by the tag. So try; xml = """ texto """ from xml.dom import minidom document = minidom.parseString(xml) element = document.getElementsByTagName('teste') textelt=element[0].firstChild print textelt.nodeType, textelt.nodeValue and it will print: 3 texto --Irmen From kent3737 at yahoo.com Wed Nov 10 11:02:15 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 10 Nov 2004 11:02:15 -0500 Subject: [development doc updates] In-Reply-To: References: Message-ID: <41923be3$1_2@newspeer2.tds.net> Fred L. Drake wrote: > The development version of the documentation has been updated: > > http://www.python.org/dev/doc/devel/ > > Please review the tables and report any strange presentations; be sure > to include the specific browser (including platform and version!) in > your report. Do you wath the reports here or in the bug tracker? Anyway here is one: Using Firefox 1.0 and Firefox 1.0PR on Win2K, the tables are missing the left and right borders. For example in Section 2.3.6, the table of operations for sequence types, in the 2.3.4 docs I have a black border on left, right and bottom; in the dev docs it is only on the bottom. Kent From gustavo.cordova at q-voz.com Tue Nov 30 13:24:22 2004 From: gustavo.cordova at q-voz.com (=?ISO-8859-1?Q?Gustavo_C=F3rdova_Avila?=) Date: Tue, 30 Nov 2004 12:24:22 -0600 Subject: comment out more than 1 line at once? In-Reply-To: References: Message-ID: <41ACBAD6.60704@q-voz.com> Rob Williscroft wrote: >Riko Wichmann wrote in news:cohc71$2pqli$1 at claire.desy.de in >comp.lang.python: > >>Dear all, >> >>is there a way in Python to comment out blocks of code without putting a >># in front of each line? Somethings like C's >> >>/* >> block of code here is commented out >>*/ >> >if False: > > (indented) block of code here is commented out > >I've no idea how efficient it is compared to triple-quoted strings >or line by line comments. But (at least with the editors I use) it >does retain the syntax highlighting, which I quite like YMMV. > >BTW for C and C++: > >#if 0 > > block of code here is commented out > /* with embeded comments ! */ > >#endif > >Rob. > Actually, it's infinitly [sp?] more defficient (contrary of efficient?) than triple-quoted strings or line-by-line comments, because those two never make it to execution stage, because they're dropped by the compiler. :-) -- Gustavo C?rdova Avila *Tel:* +52 (81) 8130-1919 ext. 127 Integraciones del Norte, S.A. de C.V. Padua #6047, Colonia Sat?lite Acueducto Monterrey, Nuevo Le?n, M?xico. From niels_bohr at uol.com.br Sat Nov 6 23:52:43 2004 From: niels_bohr at uol.com.br (=?ISO-8859-1?Q?F=E1bio?= Mendes) Date: Sun, 07 Nov 2004 02:52:43 -0200 Subject: why python is slower than java? In-Reply-To: References: <418b166f$1@news.unimelb.edu.au> <418D61D3.3040904@acm.org> Message-ID: <1099803163.11311.57.camel@localhost.localdomain> Em S?b, 2004-11-06 ?s 22:07 -0500, Roy Smith escreveu: > Terry Hancock wrote: > > And I have certainly written some extremely poorly optimized > > Python programs that positively *crawled*. > > My guess is the poor performance had nothing to do with the language you > wrote it in, and everything to do with the algorithms you used. Well, try to write a Linear Algebra algorithm in pure python... Then you'll see that pyrex, scipy or the C API are your friends. Of course algorithmis matters, but for some intensive CPU applications python can be as slow as 1/100 C using the same algorith. This, of course, matters. At least if your program is running this kind of operation most of the time. > Local optimizations rarely gets you more than a factor of 2 improvement. > Choice of language (at least within the same general catagory such as > comparing one native compiled language to another, or one virtual > machine language to another) probably has a somewhat broader range, but > still a factor of 10 would be quite surprising. 10x or 20x difference is likely to hurt you. If you have a 20x slower computer were you be using the same apps as you use now? For scientific simulations (which interest me most), it's the difference between get your results after 1day calculation of one month... > To get really bad performance, you need to pick the wrong algorithm. A > project I worked on a while ago had a bit of quadratic behavior in it > when dealing with files in a directory. Most of our customers dealt > with file sets in the 100's. One customer had 50,000 files. Going > from, say, 500 to 50,000 is a 100-fold increase in N, and gave a > 10,000-fold increase in execution time. This is an extreme case, but is a typical behaviour of how a good algorithm can modify the execution times of your program: scaling up neatly. The language matters indeed, but python is well served in a broad range of libs. For the most CPU intensive tasks there are usually python bindings for C/C++/Fortran libraries, so it's usually possible to execute python code at native speeds. This is why I use python in my (simple) physics applications: scipy gives me a very good interface for evaluating heavy numeric stuff. When I program in C++ I'm usually tempted to write a lot of code from the scratch, for I'm lazy to search for the write libs and learn how they work. I'm a physicist, not a real programer, so this end up with C++ code slower than python's (which uses scipy magic). The point I want to make here is that library programmers usually makes much better (in the sense it's faster) code than an application programmer. So, in any language, if you want to write a big project from the scratch, you'll probably end up with a buggy, slow and cumbersome library for the 'low level' stuff, and the high level interface will never move on. If you pick up the existing libs and extend them to tailor your needs, you have better chances of success. Python seems to be better than java in this point (at least in the OSS arena), for there is an enourmously bigger set of libraries you can start with, and is easier to wrap C/C++/Fortran code to it. So the likely 10% or so runtime penalty I get for running a C lib through python is more than paid in application development time. To me, what matters is: can a __python program__ run as fast as a __c program__? In lots of cases: yes, just use the right lib. All this 'java interpreter is faster than python interpreter' nonsense doesn't appeal to me. For intensive CPU operations, neither interpreters are good, or even decent, so there is no subistitute for a good o' low level implementation. Can java use those implementations as easyly as python? --No-- Does java have a comparable set of low level (fast!) libs wrapped to it? --Not as rich as python--. So forget the language shootout contest! Those are not real world examples, they're complete crap. Python has a richer set of faster libs than java. Use them, so when it matters, python usually can be faster than java. This is enough for me for saying that python IS faster than java. If you care much, a python program can be almost as fast as a C one, just use a python wrapper to a C lib or use pyrex! This is not saying that language doesn't matter. Not all so called scripting languages have the same facilities as python. For instance perl is very optimized to regex substitution, but lacks more broad biddings for, for example numeric libraries. We're lucky to use python, we're lucky that it has so many facilities. Other scripting languages have nice syntax, powerful builtin objects and other gizmos that make them much more expressive and productive than the low level counterparts. IMHO python is unique in the fact that it also provides very nice set of wrapped low level libraries to run runtime critical pieces of code, so in a lot of cases we can get the best of both worlds. Java is too much a in between for me: execution not so fast, but not so slow; development not so fast, but not so slow; builtins not so expressive, but not so low level either; it is not that good, neither that bad, etc... Cheers, Fabio From sholden at flexal.cs.usyd.edu.au Thu Nov 11 18:55:47 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 11 Nov 2004 23:55:47 GMT Subject: distutils and Debian References: <4192AD69.5040707@sympatico.ca> <1UKkd.32427$km5.1574845@news20.bellglobal.com> Message-ID: On Thu, 11 Nov 2004 13:36:22 -0500, Colin J. Williams wrote: > Robert Kern wrote: >> Colin J. Williams wrote: >> >>> I have installed the Python*-dev packages, but my present problem >>> centres on installing distutils. >> >> >> Why are you trying to install distutils over the one provided by >> python-dev? It's probably not a good idea. > I am doing this because there is no distutils in the Debian packages for > Python2.3.4 or Python 2.3.4-dev. What debian are you using? On unstable (x86) I get: ; apt-cache search distutils | grep python2\\.3 python2.3-dev - Header files and a static library for Python (v2.3) python2.3-scipy-core - low level utilities for scipy (for python 2.3) ; dpkg -L python2.3-dev | grep distutils/__init__ /usr/lib/python2.3/distutils/__init__.py ; python2.3 -V Python 2.3.4 On stable (x86) I get: ; apt-cache search distutils | grep python2\\.3 python2.3-dev - Header files and a static library for Python (v2.3) ; dpkg -L python2.3-dev | grep distutils/__init__ /usr/lib/python2.3/distutils/__init__.py ; python2.3 -V Python 2.3b2+ I can't see a python2.3.4 package anywhere... I you are using stable you should be able to pull 2.3.4 from testing, assuming it's in there of course (and if not from unstable)... -- Sam Holden From tzot at sil-tec.gr Fri Nov 26 17:57:35 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 27 Nov 2004 00:57:35 +0200 Subject: Introduction/box References: Message-ID: <25dfq09do1vvpd62b6bkjn73np33m3761j@4ax.com> On Fri, 26 Nov 2004 22:21:45 +0000, rumours say that cm012b5105 might have written: >Hello every body this is my first post i would just like to say im new to to >python iv tried out several different tutorials.And i think its great anyway >i would like to ask a question if i may i want to know how to make a >box /square i was hoping some one would tell me. That way i would have >something to work off,iv just downloaded pygame and i haqve done all my >practice using "idle" thanks I know almost nothing about PyGame, but a quick search using Google brought this up: http://aspn.activestate.com/ASPN/Mail/Message/pygame-users/2031142 It could help. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From rich_NOSPAM_ at _NOSPAM_holmteam.net Sun Nov 14 21:48:47 2004 From: rich_NOSPAM_ at _NOSPAM_holmteam.net (RichH) Date: Sun, 14 Nov 2004 20:48:47 -0600 Subject: HELP : pystemmer win32 binary References: <20041110073441.70719.qmail@web41523.mail.yahoo.com> Message-ID: In article , bingham at cenix-bioscience.com says... > kent sin wrote: > > >I urgently need a binary version of pystemmer. I am > >using python 2.3 and windows 2000. > > > >I have try to download the free MSVC toolkit. But > >don't known how to do it myself. > > > AFAIK, the free MS compiler will not help you here, because binaries > created with it are incompatible with MSVC 6.0, with which Python 2.3 is > built. You can build Python 2.3 extensions using MinGW, however. See > http://www.mingw.org/MinGWiki/index.php/Python%20extensions. > Incompatible? About the only thing I have problem with is the print method in C++. I use 7.1 to compile all my extensions. MSVC is crap for any kind of standard C++. Remember, the python C API is extern "C", so compiling with 7.1 isn't an issue unless you use shared crt structs (like the FILE* in print). Cheers, Rich From tim.tadh at gmail.com Fri Nov 19 13:05:31 2004 From: tim.tadh at gmail.com (Tim Henderson) Date: 19 Nov 2004 10:05:31 -0800 Subject: Class Encapsulation Errors in Python 2.3.3 References: <47f7cc78.0411182007.1b77c2b1@posting.google.com> Message-ID: <47f7cc78.0411191005.7b793bf@posting.google.com> Here is a partial implementation, i don't have the code with me but this is how the songs list is made code: ------------------------------------------- class Album: name = '' songs = [] artist = '' def __init__(self, name, artist): self.name = name self.artist = artist ------------------------------------------- after reading the code i came up with a possible solution: possible code: ------------------------------------------- class Album: name = '' songs = False artist = '' def __init__(self, name, artist): self.name = name self.artist = artist if songs == False: songs = [] ------------------------------------------ i will test this when i get home, and update the thread with results cheers Tim Henderson "Dan Perl" wrote in message news:... > Please post the implementation of the Album class. The problem is coming > probably from the way the Songs list is defined or initialized. That is, > the definition or the initialization probably cause the list object that is > assigned to Songs to be shared by all the Album instances. But I (and > likely no one else) can say exactly what the problem is without seing the > code. > > Dan > > "Tim Henderson" wrote in message > news:47f7cc78.0411182007.1b77c2b1 at posting.google.com... > > Hi i have some errors in my code that i can't find the reason for here > > is the error > > > > i have 3 classes: > > -Song > > -Album > > -Artist > > > > Song has 3 pieces of data with getter and setter meathods: > > -Name | i.e. song name > > -Album > > -Artist > > > > Album has 3 pieces of data: > > -Songs | a list of Song() instances > > -Name > > -Artist > > > > Artist has 4 pieces of Data: > > -Name > > -Songs | a list of Song() instances > > -Albums |a list of Album() instances > > -unknownAlbum | the album a song is put into if it doesn't have an > > album > > > > > > now the problem arises when i add songs into multiple albums like > > this: > > Code: > > ------------------------------------------------ > > s = Song('song 1') > > s2 = Song('song 2') > > > > a = Album('hey') > > a.addSong(s) > > ab = Album('yeayea') > > print a > > print ab > > ab.addSong(s2) > > print > > print a > > print ab > > ------------------------------------------------ > > Output: > > ************************************************ > > hey song 1 hey | > > yeayea song 1 hey | > > > > hey song 1 hey | song 2 yeayea | > > yeayea song 1 hey | song 2 yeayea | > > ************************************************ > > > > the "hey" album has "song 1" as it is suppose to however so does > > "yeayea" even though when "song 1" was put in the album "hey" 'yeayea' > > didn't even exist yet. > > > > Why is this happening. I checked the actually memory refrence for each > > instance and they are different, these supposidly isolated different > > intances of clases are linked for some inexplicable reason. > > > > Does any one know why this is happening and how i can fix it? > > > > cheers > > Tim Henderson From rkern at ucsd.edu Sun Nov 21 12:31:11 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 21 Nov 2004 09:31:11 -0800 Subject: Looking for a good interactive shell In-Reply-To: References: Message-ID: Tomas wrote: > Hi! > > I'm looking for a replacement for the standard interactive python shell. So > far I've tried IPython and PyCrust. I liked both, but I'm not 100% happy > with any of them. My main complaint about IPython is its missing support for > multiline editing. To do multiline editing, it has to start an external > editor, but then I lose all the nice features like autocompletion. > > PyCrust supports multiline editing, but the autocompletion is not as good as > in IPython. It also lacks many of IPython's advanced features, like > pdb-integration, magic commands and custom macros. > > Does anyone know of any other interactive python shells with good code > completion and multiline editing? Not really. IPython is being rewritten to be more flexible and modular so that the niceties like pdb integration, magic commands, and macros can be integrated into PyShell, for example. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pierre.barbier at cirad.fr Tue Nov 9 04:37:59 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 09 Nov 2004 10:37:59 +0100 Subject: Mixing Python And Bash In-Reply-To: References: Message-ID: <41908f93$0$32237$636a15ce@news.free.fr> Tom Purl a ?crit : > I just wrote a Python script that is going to be called from bash script. > If the Python script fails, I want the bash script to also stop running. > Unfortunately, I can't seem to get that to work. Here's the script so > far: > > # custom python script > /usr/bin/python /home/username/Dev/Python/packZODB.py \ > -s"gsgmc.sigma.zettai.net" -b 7 > > # next program > /usr/bin/someOtherProgram > > I don't want the second program to run if the first program fails. Isn't > that the default in bash? If someone could please point me in the right > direction regarding this problem, I would really appreciate it. > > Thanks in advance! > > Tom Purl > If you only have 2 programs (or few programs) you can use : prog1 && prog2 Then prog2 will only be launched if prog1 succeeded ... Pierre From jbors at mail.ru Wed Nov 3 23:18:45 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Wed, 3 Nov 2004 20:18:45 -0800 Subject: ANN: PyMedia-1.2.3.0-pre2 is out Message-ID: <02d301c4c225$61593030$0200a8c0@amr.corp.intel.com> Hi all, Finally I have managed to make a pre-release for version 1.2.3.0 What is it ? ---------------------------------------------------------------- PyMedia is a Python module for avi, mp3, ogg, wma, divx and other media formats processing. It is crossplatform and can work on Windows, Linux and cygwin. PyMedia is based upon the following libraries : libavcodec, libavformat, libdvdcss, libdvdread It has simple and yet powerful interface. Check out the tutorial section: http://pymedia.org/tut/ Features ---------------------------------------------------------------- 1. Audio decoding/encoding for the following types: - mp2, mp3, ac3, ogg, wma, aac 2. Video decoding/encoding for the following types: - mpeg1,2 ( dvd, vcd, svcd ), mpeg4, xvid, asf 3. Video/Audio muxing for mpeg files only 4. Direct access to sound device( Input/Output ). Input is synchronous in Linux. 5. Sound manipulation classes such as Resampler and SpectrAnalyzer 6. Direct access to cdda tracks for easy grabbing and encoding Audio CDs 7. Direct access to dvd tracks for playing DVD movies( all types ) 8. Ability to convert video frames from YUV<->BMP formats 9. Simple interface and portability( Windows/Linux/cygwin ) Changelog ---------------------------------------------------------------- - VFrame has new method: convert(). Allow you to convert it to any other format( RGB<->YUV ) - resampler works as expected now - VFrame can be created explicitly( allows to create your own movies from the set of pics ) - wma can play small chunks - windows ISound interface get fixed( patch from Raefer Gabriel ) - windows OSound interface get fixed, no freezing anymore - windows binary supports MMX optimization( 30% boost ) - audio.muxer has new method mux and flush. To be compatible with every stream format not only MPEG. - CLE266 chipset support included for HW DVD playback on Linux with Directfb/pydfb( experimental ! ) - seeking supported for video/audio - new Mixer interface - meta tags for ogg, wma and mp3 can be changed and written back to the file - aac playback support( experimental ! ) Downoad ---------------------------------------------------------------- Just check the http://pymedia.org and download the latest version (1.2.3.0-pre2). You may download Windows binaries as well. How to use ---------------------------------------------------------------- Please see the tutorial on how to install and use: http://pymedia.org/tut/ License ---------------------------------------------------------------- At the moment the whole module is GPL because of libdvdread and libdvdcss. I have plans to make it LGPL eventually. Enjoy, Dmitry/ From forget-it at no-spam.com Sun Nov 21 20:27:33 2004 From: forget-it at no-spam.com (Phillip) Date: Mon, 22 Nov 2004 02:27:33 +0100 Subject: Nagging problem with MySQLdb Message-ID: Hi. I hate the way one has to jump through countless hoops to put data in a db and get it out again. The straightforward MySQLdb Interface requireing this SQL stuff being a point in case (against SQL and those RDBs that is). Since other programms have to access this data I'm forced to use a classical DB and actually have managed to set up Mysql and a presumably working connection from Python to it. I've gotten so far as to avoid errors with this sucky SQL language. (Guess I've gotten to pampered by Python lately :-) ) However, for about 20 hrs. now I've been trying to write data into an existing table. Until now no success. I hope somebody can help me with this. Here's the relevant code: >>>>>> ... #Setting up DB connection, initializing DB cursor elefantDb = MySQLdb.connect(user="runbase",db="elefant") baseFeed = elefantDb.cursor() # going through the DictList and adding the # datasets into the db for line in sourceLinesDictList: # also adding some data for fields that the DB table has but our # DictList does't (data01,02,29) data01 = 'source-one' data02 = '0', data03 = line['payments-status'], data04 = line['order-id'], data05 = line['order-item-id'], data06 = line['payments-date'], data07 = line['payments-t-id'], data08 = line['item-name'], data09 = line['listing-id'], data10 = line['sku'], data11 = float(line['price'].replace(',','.',1)), data12 = float(line['shipping-fee'].replace(',','.',1)), data13 = line['quantity-purchased'], data14 = float(line['total-price'].replace(',','.',1)), data15 = line['purchase-date'], data16 = int(line['batch-id']), data17 = line['buyer-email'], data18 = line['buyer-name'], data19 = line['recipient-name'], data20 = line['ship-address-1'], data21 = line['ship-address-2'], data22 = line['ship-city'], data23 = line['ship-state'], data24 = int(line['ship-zip']), data25 = line['ship-country'], data26 = line['special-comments'], data27 = line['upc'], data28 = float(line['VAT'].replace(',','.',1)), data29 = 'fresh-unassigned' baseFeed.execute( """INSERT INTO position (plattform, position_id, payments-status, order-id, order-item-id, payments-date, payments-t-id, item-name, listing-id, sku, price, shipping-fee, quantity-purchased, total-price, purchase-date, batch-id, buyer-email, buyer-name, recipient-name, ship-address-1, ship-address-2, ship-city, ship-state, ship-zip, ship-country, special-comments, upc, vat, elefant-signal) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""" [data01, data02, data03, data04, data05, data06, data07, data08, data09, data10, data11, data12, data13, data14, data15, data16, data17, data18, data19, data20, data21, data22, data23, data24, data25, data26, data27, data28, data29] ) <<<<<< The error I get with this one is: "TypeError: string indices must be integers" The other wariant I've tried (using a tuple) with >>>>>> ...# the same stuff as above and: (data01, data02, data03, data04, data05, data06, data07, data08, data09, data10, data11, data12, data13, data14, data15, data16, data17, data18, data19, data20, data21, data22, data23, data24, data25, data26, data27, data28, data29) <<<<<< returns: "TypeError: 'str' object is not callable" baseFeed.execute() function causing these errors. I'm totaly void of possible answers now. The problem apparently also being scarce and false MySQL and MySQLdb documentation *shrug*. Can anyone help? Thanks a lot in advance. Phillip From kartick_vaddadi at yahoo.com Wed Nov 17 04:30:33 2004 From: kartick_vaddadi at yahoo.com (kartik) Date: 17 Nov 2004 01:30:33 -0800 Subject: don't NaN & infinities hide FP errors Message-ID: <940ee3e8.0411170130.31d247@posting.google.com> Since Python floats are implemented using C doubles, assuming IEEE 754 compliance, certain operations should result in NaN or infinity. Don't such special values hide errors? Would we want our variables to be in such states? I feel it would be better if a floating point division by zero (or other actions that produce NaNs or infinities) throws an exception, just like an integer divide by zero. Am I right? From golux at comcast.net Sun Nov 14 03:06:26 2004 From: golux at comcast.net (Stephen Waterbury) Date: Sun, 14 Nov 2004 03:06:26 -0500 Subject: .pyc files... In-Reply-To: References: Message-ID: <41971202.3010006@comcast.net> Eddie Parker wrote: > OK, stupid question, but it?s been bothering me for ages.. J > > I love Python to bits, but .pyc files always litter my source tree, and > they?ve always bothered me. ... One solution (on unices, at least): alias cleanpy="find . -name '*.pyc' -exec rm {} ';'" Run after each test, or when feeling anal. ;) Steve From rkern at ucsd.edu Sat Nov 20 02:13:05 2004 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 19 Nov 2004 23:13:05 -0800 Subject: stopping the sound server in PySol code -- how? In-Reply-To: References: Message-ID: Lynn wrote: > I have a SuSe 9.1 linux box (although this isn't a new issue) with > reasonably up to date everything. When I run PySol, it grabs the sound > system in a rude and complete way. > > I don't listen to sound and I NEED my sound system available even if PySol > is running. > > Does anyone have a simple way of ripping the sound functionality our of > PySol? I've not enough of a python programmer to deal with this. > Everything I've tried has just generated a ton of errors. How did you install PySol? RPMs? Is there a PySol-sound package that you can choose not to install? If PySol doesn't find its sound support module, it won't bother with sound. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From svenn.are at bjerkem.de Mon Nov 8 17:05:49 2004 From: svenn.are at bjerkem.de (svenn.are at bjerkem.de) Date: 8 Nov 2004 14:05:49 -0800 Subject: Help on installing PyQt on MacOSX 10.3 needed Message-ID: <5fb00e69.0411081405.35d40c1b@posting.google.com> Hi, I wanted to run a program that is written in PyQt on my mac, and went over to Riverbank to get PyQ 3.13 and SIP 4.1.1 sources. I followed the installation guide except for the compiling python as Macosx already has python. I had no problem with compiling SIP and also no problem with compiling PyQt nor did I have any error message during make install. Now the last step in the install documentation says that I have to edit several files regarding python itself, and then recompile it. This is where I got stuck. The mac native python cannot find the package qt with a import qt command on the commandline, and I have no experience whatsoever with python. Maybe somebody has been successful installing PyQt with the native python in macosx 10.3 and can help me? -- Svenn From cm012b5105 at blueyonder.co.uk Sun Nov 28 15:02:08 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Sun, 28 Nov 2004 20:02:08 +0000 Subject: graphics Message-ID: <200411282002.08826.cm012b5105@blueyonder.co.uk> i want to write a simple programme to create a box in other words just a square so that when some one clicks the icon a square will appear could some one help me do this please From esj at harvee.org Tue Nov 2 09:09:14 2004 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 02 Nov 2004 09:09:14 -0500 Subject: saved sys.path In-Reply-To: <1gmm44d.3ayblzifiogeN%aleaxit@yahoo.com> References: <%Xmhd.29071$g4.544104@news2.nokia.com> <1gmkht7.1e1lg86qerk5N%aleaxit@yahoo.com> <1gmlelr.q7q1rz5rc37oN%aleaxit@yahoo.com> <1gmm44d.3ayblzifiogeN%aleaxit@yahoo.com> Message-ID: <4187950A.3090304@harvee.org> Alex Martelli wrote: > Eric S. Johansson wrote: > ... > >>file, command_name.path, would contain all of the search as necessary >>for a command called by the same name. this technique would allow for a >>common platform independent method of finding application-specific >>modules and automatically generated paths for site-specific >>relocation/configuration. >> >>As I write this, it occurs to me that a provisional body of code to >>experiment with the technique would possibly serve the community well. >> I will generate something tomorrow for public scrutiny as I am up past >>my bedtime. Thank you for triggering the idea. > > > You're welcome. Implementation should be easy, if you think that > architecture is sound. Consider site.py, specifically the end of > function addsitedir(sitedir), which currently goes: ... hmm you must have a later bedtime than me. :-) I was thinking a slightly different direction in terms of integration etc. but these are good ideas too and I will lift with appropriate credits. > I would suggest .appath or something that stands out more than .path > which looks too much like .pth -- just IMHO. true. I have come to accept the fact that I should never be allowed to name anything except the occasional pet. Personally I preferred an extension that is speech recognition friendly since all of these mangled names really hurt to type and are incredibly difficult to spell out phonetically given current speech recognition accuracy's for nonhuman language text sequences. > As to whether the whole architecture is sound -- I pass. I'm not sure I > see why it makes sense to have a foo.appath (or foo.path as you'd want > it) that presumably gets autoedited during install to contain the > relevant dirs, rather than just autoedit foo.py, the main script, whose > purpose should, after all, be exactly to set up the environment > (sys.path first and foremost) before importing and running the real > stuff. The current bar.pth arrangement makes sense exactly because it's > _not_ tied to apps, but to sites -- where has this site chosen to > install some backage 'bar' which must be made available for import to > all scripts running at this site. An application, as opposed to a > package, gets to run its own code ("main script") and thus would seem > not to need such arrangements. from my perspective, it makes a great deal of sense. If you are making modules for general use, site-packages is a great place to deposit your work. However, if you are building applications which have collections of modules that need to be imported, site-packages is not the place to put them especially if there is a risk of a namespace collision. I will confess to not being very familiar with the foo.py model you describe and references would be welcome. my philosophical base is one of separation of code and data. Which means that configuration data such as search paths etc. belong "somewhere else". Also to modify a program file even when it does nothing but set up the context, makes me really uncomfortable from a environment management and security perspective. That's awfully close to what a worm or a virus would do as part of its reproductive imperative. although, even I would admit that a python based worm would probably starve to death... so anything I can do to keep code static and as identical as possible to what was dropped out of darcs yet still be flexible enough to accommodate different installation locations, I consider a win. we have a couple philosophies that work for different people. It would be nice to have enough room to include both. ---eric PS, here's hoping for a clear regime change here in the states. Wish us luck. From bvande at po-box.mcgill.ca Sun Nov 7 02:36:37 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 07 Nov 2004 02:36:37 -0500 Subject: Newsgroup mood [was] why python is slower than java? In-Reply-To: <418DBAD1.70702@acm.org> References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> <418DBAD1.70702@acm.org> Message-ID: <418DD085.2080300@po-box.mcgill.ca> Maurice LING said unto the world upon 2004-11-07 01:04: > > 3) Links to threads that answer common questions > >> Yes, there is an FAQ and yet people still ask why Python gets division >> wrong. But I've often seen people dig up links to threads for questions >> perhaps not so common to be written up in an FAQ, but perhaps common >> enough to merit linking on a wiki page. I'm not under the illusion >> that it would solve the problem on its own, but it might well head >> some repeat questions off. For those it doesn't, it would give an easy >> way to answer. >> > This may be useful but it will certainly bring us a new set of questions > then, in the form of "is this still holds for > ?" Although computer science stems from > mathematics, it had lost an important aspect of mathematics, that is, > "once proven true is forever true." > > maurice Dang. I already suspected that only a minority would check such a resource. On reflection, I think you are likely correct many of that minority would then end up asking the sort of question you indicate. That *would* be better, but probably not enough so as to make the effort of maintaining the resource seem worth the candle. :-( Of the 3 parts I posted about, this one was the one I am least able to do a draft of anyway. I think I will take a go at the other two, though. Best, Brian vdB From chris.cavalaria at free.fr Tue Nov 2 19:16:19 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Wed, 03 Nov 2004 01:16:19 +0100 Subject: strong/weak typing and pointers References: <2upctrF2dhnfeU1@uni-berlin.de> <418800a8$0$14976$626a14ce@news.free.fr> Message-ID: <41882354$0$14963$626a14ce@news.free.fr> Steven Bethard wrote: > Christophe Cavalaria free.fr> writes: >> >> One could say that the common definition of weakly typed languages >> cannont apply for a dynamicaly type language. Let's face it, once you've >> implemented a dynamicaly typed language, it seems very hard to use one >> piece of data as the wrong type. > > While I agree that it would be kind of foolish to implement a dynamically > typed language that wasn't strongly-typed (PL theory definition), there's > no reason you *couldn't* -- your language would just need to provide some > sort of 'cast' function that did the conversion at runtime. > > For example, say the memory block for an object instance was allocated > like: > > [0] pointer to class object > [1] pointer to dictionary object (holding variables) > > Then maybe you could do something like: > int1, int2 = cast(object(), list(int)) > Given, I can't see any use for such behavior, but you *could* do it if you > had a > weakly-typed dynamic language and you knew how it allocated objects. At > some level, you always have bits -- whether it makes any sense to > reinterpret them depends on exactly what the bits originally meant. In any good dynamicaly typed language, the object must know what it is thus there is no way to do a reinterpret_cast like in C or C++. It is meaningless. Doing it anyway is insane as you have pointed. It's only goal beeing to add in the flaws of the weakly static typed languages to a contrived example. >> What we can do is extend the definition of weakly typed language to >> something like : "A weakly typed language is a language that often uses >> incorectly some piece of data by applying to it the wrong type" Such >> definition would include any language that is too liberal with the type >> coertion like php. > > Don't get me wrong -- I do understand your point. In every case I can > think of, there is no reason to want weak-typing (PL theory definition) in > a > dynamically-typed language. On the other hand, I haven't really seen any > good cases for wanting weak-typing in a statically-typed language either. > > Note that PHP doesn't fit your definition above anyway. When PHP allows: > > "a" + 10 == 10 > > it's not incorrectly using "some piece of data by applying to it the wrong > type". It's doing exactly what it tells you it'll do. This is *correct* > response given the PHP language definition. Incorrectly is a view of the mind in that case. From my point of view it is incorrect. And you could argue that taking a float * and casting it into a int * gives us a predictable behaviour. It'll still be wrong to do it unless it was exactly what you wanted to do. And in that case you can create explicit language constructs to do the trick. > In addition, you *can* create a statically-typed language that is strongly > typed > (PL theory definition) but also very liberal with type coercion. What > would you > call such a language? Since being liberal with type coercion and allowing > bit reinterpretation are orthogonal, why not keep the two separate terms? > > My issue here is that I don't think we should confuse an already easily > confused > term by giving it a second meaning. I see your point but I must add that I wasn't giving that term a second meaning. Just like in mathematics when you take a theory and you create a new theory that encompases the old one, I was giving a new definition for the term. > If there aren't any dynamically typed > languages that are also weakly-typed, that's ok -- it doesn't mean we > should change the meaning of "weakly-typed" for these languages. > > Steve From gandalf at geochemsource.com Fri Nov 26 18:56:28 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Sat, 27 Nov 2004 00:56:28 +0100 Subject: Number of colors in an image In-Reply-To: References: Message-ID: <1804107377.20041127005628@geochemsource.com> Hello David, Friday, November 26, 2004, 11:18:04 PM, you wrote: > For example, for an RGB image: > import sys > from PIL import Image > from itertools import izip, repeat > if __name__ == "__main__": > im = Image.open(sys.argv[1]) > r = im.getdata(0) > g = im.getdata(1) > b = im.getdata(2) > print 'Number of colors =', len(colors) Thank you, this was very helpful. I'll try to use this one instead of ImageMagick. (The identify program does not work in some cases...) -- Best regards, Laszlo mailto:gandalf at geochemsource.com web:http://designasign.biz From apardon at forel.vub.ac.be Tue Nov 23 02:48:52 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Nov 2004 07:48:52 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: Op 2004-11-22, Michael Hudson schreef : > I'm not really reading comp.lang.python at the moment, but found this > thread via the Python-URL... > > Tim Peters writes: > >> The only currently active contributor I can think of who cares about >> signals enough to actually work on them is Michael Hudson, but his >> interest seems limited to keeping the interactions been Python's GNU >> readline wrapper and signals working across incompatible details of >> signal semantics on Unixish boxes. It's possible I'm wrong, and he'd >> really love to work much more on signals, but feels inhibited by >> Guido's well-known dislike of the beasts. > > I think you're more or less right. A couple of years ago I got pretty > badly discouraged attempting to support sigprocmask and friends from > Python, and came to conclusion that noone who cares about portability > -- not just no Python programmers, but *noone at all* -- mixes threads > and signals, because the cross platform behaviour is a total mess, and > in many cases is just plain buggy (I believe the FreeBSD version of > libc_r for 5.something contains a fix that is a direct consequence of > my efforts, for example). Even linking with the threading libraries > was enough to stuff things up mightily in some circumstances. > > We Do Not Want To Go There. Well for the moment I don't care about portability that much. I do understand this is a big issue for something in the standard library and with your remarks consider my question in the subject answered with no. I do think it is a pity that the crossplatform behaviour is such a total mess but for the moment that can't be helped. I'll just experiment a bit my self on the boxes I'm interested in. -- Antoon Pardon From arambo314 at hotmail.com Thu Nov 18 12:53:28 2004 From: arambo314 at hotmail.com (Arthur Rambo) Date: 18 Nov 2004 09:53:28 -0800 Subject: Newbie: Python & ADFGVX Cipher Cracking? References: <4mJmd.1242$Tq6.565@newsread3.news.pas.earthlink.net> <301m1mF2ptcjrU1@uni-berlin.de> <303c4qF2q6ibpU1@uni-berlin.de> Message-ID: <533e1e03.0411180953.1f73dec3@posting.google.com> The following solution is far better (based on a generator): def xpermutations(objects): """A generator that returns the complete set of permutations of a list of objects""" if objects==[]: yield [] else: l=len(objects) for i in xrange(l): for cc in xpermutations(objects[:i]+objects[i+1:]): yield [objects[i]]+cc >>> for p in xpermutations(['A','B','C']): ... print p ... ['A', 'B', 'C'] ['A', 'C', 'B'] ['B', 'A', 'C'] ['B', 'C', 'A'] ['C', 'A', 'B'] ['C', 'B', 'A'] Derived from Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 Arthur From Python at IvoNet.nl Thu Nov 11 13:02:51 2004 From: Python at IvoNet.nl (Ivo Woltring) Date: Thu, 11 Nov 2004 19:02:51 +0100 Subject: ConfigParser References: <35t4p0lou2lmcigaj2ic1fv9b253d5nq6k@4ax.com> Message-ID: <37a7p09upup9ltsthd601l2cl8garmbdr1@4ax.com> On Wed, 10 Nov 2004 21:18:20 GMT, "Paul McGuire" wrote: >"Ivo Woltring" wrote in message >news:35t4p0lou2lmcigaj2ic1fv9b253d5nq6k at 4ax.com... >> >> ...the whole question is mute ;-)) >> >> Ivo. > >The word you are looking for is "moot", not "mute" - this is actually a >common word misuse (known as a "malapropism") even for native English >speakers. :) > >Pedantical-ly yours, >-- Paul > Thanks for the English lesson. I am not a native English though. I'm Dutch. From vinay_sajip at red-dove.com Thu Nov 4 06:30:40 2004 From: vinay_sajip at red-dove.com (Vinay Sajip) Date: Thu, 04 Nov 2004 11:30:40 +0000 Subject: ANN: New configuration module released In-Reply-To: <8ef9bea6.0411040059.664631bc@posting.google.com> References: <2e37dc1.0411030650.ff44840@posting.google.com> <8ef9bea6.0411040059.664631bc@posting.google.com> Message-ID: <418A12E0.8000607@red-dove.com> Hung Jung Lu wrote: > I know you probably want a lot of features, but then different people > want different things. What a person considers necessary, others may > find them unnecessary, and vice versa. I'm not sure what you mean by 'lots of features'. Primarily, I wanted better ease of use than ConfigParser gives me for medium-complexity configurations. > > Microsoft went from .INI files to Windows registry, and now to > XML-based app.config files in the .NET world. I know app.config files > are not the best thing with the cleanest format, but, why re-invent > the wheel? Microsoft did. You may remember, when the registry first appeared in Windows, many viewed it as some kind of panacea - it's the same thing now with .NET configuration files. Do you really believe that they are the last word in application configuration? I don't. Of course, they are quite usable, and have a lot of momentum since anything done by Microsoft does, but that's hardly a reason for people to stop trying alternative approaches. > Microsoft's XML-based app.config is guaranteed to be widely used. For > something as minor as configuration files, for people that juggle > between many programming languages, I guess it's an OK solution. > I know many people may not like the XML overhead, I know many people > don't like Microsoft. But when you have to use hierarchical > configuration files across many programming languages, I don't know > any format out there that can compete with app.config. To me, the war > is already over. Which war would that be? Horses for courses, of course. XML is technically suitable, and the .NET System.Configuration format will seem like a de facto standard for many people. I've used it myself on many a .NET project. (Normally, end users are not expected to edit these configuration files, as they are XML tyros and moreover, cannot be expected to understand the System.Configuration schema.) If you'd rather use the .NET format for your Python application configuration, fine! Best wishes, Vinay Sajip From steven.bethard at gmail.com Mon Nov 22 13:37:44 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 Nov 2004 18:37:44 GMT Subject: [Beginner] delete items of [] also from memory In-Reply-To: <41a1e794$0$29887$626a14ce@news.free.fr> References: <41a1a1da$0$8190$8fcfb975@news.wanadoo.fr> <41a1e794$0$29887$626a14ce@news.free.fr> Message-ID: F. Petitjean wrote: > What about A[:] = None ? I don't think that does what you want it to: >>> a = [None]*100 >>> a[:] = None Traceback (most recent call last): File "", line 1, in ? TypeError: can only assign an iterable Steve From jhujsak at neotopica.com Tue Nov 16 18:13:53 2004 From: jhujsak at neotopica.com (Jon) Date: 16 Nov 2004 15:13:53 -0800 Subject: Yet Another BLT/TkInter Install Question Message-ID: <51e59f27.0411161513.1afffa2e@posting.google.com> Hi All, I'm running ActiveState Python 2.3.4 and I'm trying to figure out how to install BLT so that I can add PMW widgets. No matter how or where I try to install it I still get: Traceback (most recent call last): File "", line 1, in ? File "HelloUser.py", line 225, in ? g = Pmw.Blt.Graph(master) File "/usr/local/python/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBlt.py" , line 260, in __init__ Tkinter.Widget.__init__(self, master, _graphCommand, cnf, kw) File "/usr/local/python/lib/python2.3/lib-tk/Tkinter.py", line 1835, in __init on trying to run the HelloUser.py PMW example. From a past post I gather this indicates BLT is not installed correctly. Does anyone know what the required BLT configure options are for an ActiveState install? Thanks! --Jon From aleaxit at yahoo.com Sat Nov 6 02:12:10 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 Nov 2004 08:12:10 +0100 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> Message-ID: <1gmtkpc.1h26kkr1rd529sN%aleaxit@yahoo.com> Hans Nowak wrote: > John Machin wrote: > > > Or is this a joke/troll?? I can't believe the "unimelb.edu.au"; surely > > a forgery. > > Is it just me, or is the climate in c.l.py getting less friendly to > newbies? In any case, Interestingly enough, I sort of share your perception -- and I have noticed the same thing, and seen it remarked upon by others, in other, completely unrelated newsgroups as well, such as it.comp.macintosh. It's not, I think, about newbies in general: people who come and post help requests, without giving the information that's quite obviously indispensabile to let us help them, keep getting treated with unreasonable amounts of friendliness and courtesy even after many requests for more info go unheeded, for example. However, newbies who are clueless enough to come blasting in with the usual whines we've heard a zillion times -- Macs cost too much, Python is too slow, there's no apps for Macs, Python must absolutely add feature X or it will die, Apple's gonna go broke tomorrow, etc, etc -- do appear to get on our collective nerves worse than their essentially indistinguishable precursors did last year, two years ago, &c. The accusation of being a troll often follows, breaking the old advice to "Never attribute to malice what can be adequately explained by incompetence". Maybe it's a case of the corollary to that old advice, "Sufficiently advanced cluelessness is indistinguishable from malice". But why that should be so this year more than last year, say, is not clear to me... Alex From zach at cs.uni-bonn.de Tue Nov 2 04:51:53 2004 From: zach at cs.uni-bonn.de (Gabriel Zachmann) Date: 2 Nov 2004 09:51:53 GMT Subject: strong/weak typing and pointers References: Message-ID: > You didn't mention C++. Try this ... > > std::string s = "Wow"; > s += 3.141592654; // Perfectly valid > s = 3.141592654; // Also valid ah, good example. So, would it be valid to say: the more coercion (or automatic conversion) rules a language has, the weaker the typing? Best regards, Gabriel. -- /-------------------------------------------------------------------------\ | There are works which wait, | | and which one does not understand for a long time; [...] | | for the question often arrives a terribly long time after the answer. | | (Oscar Wilde) | +-------------------------------------------------------------------------+ | zach at cs.uni-bonn.de __@/' www.gabrielzachmann.org | \-------------------------------------------------------------------------/ From dochtman at cs.vu.nl Wed Nov 3 03:41:11 2004 From: dochtman at cs.vu.nl (Dirkjan Ochtman) Date: Wed, 03 Nov 2004 09:41:11 +0100 Subject: Should I learn Python? In-Reply-To: <624a388a.0411021328.5ac41f4c@posting.google.com> References: <624a388a.0411021328.5ac41f4c@posting.google.com> Message-ID: > 1. What can I do with Python that I can't do with php? Python is a much cleaner. Its design was well thought-out, with very good support of OOP (something which has been problematic in PHP 4). Also, several features in Python make sure you write clean code with it, something that is very much lacking in PHP. Finally, the library in Python is cleanly separated and easily extensible. > 2. Do you use both PHP and Python in conjunction with each other? I've used PHP a lot, but I'm currently moving all development effort to Python. For some projects, I think combined use could be useful (e.g. to setup a web service of which one side is easier to do in Python, while the other side would be easier to do in PHP). > 3. In what way could I utilize Python to compliment existing sites or > apps built with PHP? This depends on the way your applications are written. My PHP applications are always embedded in a framework I wrote myself, and this would make it hard to effectively extend the application in Python. Regards, Dirkjan From nhodgson at bigpond.net.au Tue Nov 9 05:24:01 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 09 Nov 2004 10:24:01 GMT Subject: generic way to access C++ libs? References: Message-ID: <5V0kd.30218$K7.5461@news-server.bigpond.net.au> Gabriel Zachmann: > > The layout is also modified by various compiler options. > > really? that would mean that c++ libs themselves are > not binary compatible among each other? I was thinking in terms of Microsoft C++ options like the vtordisp setting used to handle virtual inheritance (/vd0 or /vd1), pointer to member representation (/vm*), and the old favourite struct alignment (/Zp*). Borland adds options for allowing small enumerations to take only one byte (-b-), zero size empty base classes (-Ve), zero size empty members (-Vx), and a layout compatible with old compiler versions (-Vl). Much of the time C++ code only has to be compatible with the other modules it is delivered with. So long as all the modules use the same compiler flags, this will be achieved. Neil From michele.simionato at gmail.com Sat Nov 6 10:51:28 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Nov 2004 07:51:28 -0800 Subject: CGIs and file exclusion References: <2uvedvF2g1pv3U1@uni-berlin.de> <6f402501.0411050228.aea8068@posting.google.com> <4edc17eb.0411052049.7df47379@posting.google.com> Message-ID: <4edc17eb.0411060751.280dbdf6@posting.google.com> Tim Peters wrote in message news:... > What you got above is > a "write conflict error", and is normal behavior. What happens: > > - Process A loads revision n of some particular object O. > - Process B loads the same revision n of O. > - Process A modifies O, creating revision n+1. > - Process A commits its change to O. Revsion n+1 is then current. > - Process B modifies O, creating revision n+2. > - Process B *tries* to commit its change to O. > > The implementation of commit() investigates, and effectively says > "Hmm. Process B started with revision n of O, but revision n+1 is > currently committed. That means B didn't *start* with the currently > committed revision of O, so B has no idea what might have happened in > revision n+1 -- B may be trying to commit an insane change as a > result. Can't let that happen, so I'll raise ConflictError". That > line of argument makes a lot more sense if more than one object is > involved, but maybe it's enough to hint at the possible problems. > > Anyway, since your store() method always picks on the root object, > you're going to get ConflictErrors frequently. It's bad application > design for a ZODB/ZEO app to have a "hot spot" like that. > > In real life, all ZEO apps, and all multithreaded ZODB apps, always do > their work inside try/except structures. When a conflict error > occurs, the except clause catches it, and generally tries the > transaction again. In your code above, that isn't going to work well, > because there's a single object that's modified by every transaction > -- it will be rare for a commit() attempt not to give up with a > conflict error. > > Perhaps paradoxically, it can be easier to get a real ZEO app working > well than one's first overly simple attempts -- ZODB effectively > *wants* you to scribble all over the database. Ok, I understand what you are saying, but I do not understand how would I solve the problem. This is interesting to me since it has to do with a real application I am working on. Maybe I should give the framework. We have an application where the users can interact with the system via a Web interface (developed in Zope/Plone by other people) and via email. I am doing the email part. We want the email part to be independent from the Zope part, since it must act also as a safety belt (i.e. even if the Zope server is down for any reason the email part must continue to work). Moreover, people with slow connections can prefer the email interface over the Zope/Plone interface which is pretty heavyweight. So, it must be there. We do expect to have few emails coming in (<100 per hour) so I just modified /etc/aliases and each mail is piped to a simple Python script which parses it and stores the relevant information (who sent the email, the date, the content, etc.). Input coming via email or via the web interface should go into the same database. Since we are using Zope anyway and there is no much writing to do, we thought to use the ZODB and actually ZEO to keep it independent from the main Zope instance. We could use another database if needed, but we would prefer to avoid additional dependencies and installation issues. The problem is that occasionally two emails (or an email and a web submission) can arrive at the same time. At the moment I just catch the error and send back an email saying "Sorry, there was an internal error. Please retry later". This is rare but it happened during the testing phase. I would rather avoid that. I thought about catching the exception and waiting a bit before retrying, but I am not completely happy with that; I also tried a hand-coded solution involving a lock file but if was not 100% reliable. So I ask here if the ZODB has some smart way to solve that, or if it is possible to change the design in such a way to avoid those concurrency issues as much as possible. Another concern of mine is security. What happens if a maliciuous user sends 10000 emails at the same time? Does the mail server (can be postfix or exim4) spawn tons of processes until we run out of memory and the server crashes? How would I avoid that? I can think of various hackish solutions but I would like something reliable. Any hints? Suggestions? Thanks, Michele Simionato From __peter__ at web.de Tue Nov 16 13:55:20 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Nov 2004 19:55:20 +0100 Subject: determining the number of output arguments References: Message-ID: Jeremy Bowers wrote: > On Tue, 16 Nov 2004 17:58:52 +0100, Peter Otten wrote: >> You could yield Indent/Dedent (possibly the same class) instances >> whenever the level changes - provided that the length of sequences of >> nodes with the same depth does not approach one. > > In this case, the depth of the node is multiplied by some indentation > parameter, or some similar operation, and it occurs in three or places, so > the duplication of the > > if token == INDENT: > depth += 1 > elif token == DEDENT: > depth -= 1 > if depth == 0: > abort or something > > three or four times was starting to smell itself. I guess I don't understand, so I wrote a simple example: DEDENT = object() INDENT = object() def _walk(items): for item in items: if isinstance(item, list): yield INDENT for child in _walk(item): yield child yield DEDENT else: yield item class Tree(object): def __init__(self, data): self.data = data def __iter__(self): for item in _walk(self.data): yield item class WalkBase(object): def __call__(self, tree): dispatch = { DEDENT: self.dedent, INDENT: self.indent } default = self.default for item in tree: dispatch.get(item, default)(item) class PrintIndent(WalkBase): def __init__(self): self._indent = "" def indent(self, node): self._indent += " " def dedent(self, node): self._indent = self._indent[:-4] def default(self, node): print self._indent, node class PrintXml(WalkBase): def indent(self, node): print "" def dedent(self, node): print "" def default(self, node): print "%s" % node def __call__(self, tree): print "" super(PrintXml, self).__call__(tree) print "" if __name__ == "__main__": tree = Tree([ 0, [1, 2, 3], [4, [5, 6, 7], [8, [9, 10]]], [11], 12 ]) for i, Class in enumerate([PrintIndent, PrintXml]): print "%d " % i * 5 Class()(tree) I think taking actions on indent/dedent "events" is easier and simpler than keeping track of a numerical depth value, and at least the PrintXml example would become more complicated if you wanted to infer the beginning/end of a level from the change in the depth. I do check the depth level twice (isinstance(item, list) and dispatch.get()), but I think the looser coupling is worth it. If you are looking for the cool version of such a dispatch mechanism, Phillip J. Eby's article http://peak.telecommunity.com/DevCenter/VisitorRevisited (found in the Daily Python URL) might be interesting. Peter From joshway_without_spam at myway.com Wed Nov 17 14:21:31 2004 From: joshway_without_spam at myway.com (JCM) Date: Wed, 17 Nov 2004 19:21:31 +0000 (UTC) Subject: thread, threading; how to kill a thread? References: Message-ID: Jerry Sievers wrote: > Greetings Pythonists; > I have limited experience with threaded apps and plenty with old style > forked heavyweight multi-processing apps. > Using Python 2.3.3 on a Redhat 7.x machine. > Wondering if there is a simple way from a main python program to kill > a running thread? Sort of. You can send a unix signal to the main thread (it causes an exception which you can catch). But as others have and will surely point out, it's usually better to have your thread occasionally check whether it should die, so it doesn't leave anything in a bad state. From drlinux at columbus.rr.com Mon Nov 29 15:15:29 2004 From: drlinux at columbus.rr.com (Dave Reed) Date: Mon, 29 Nov 2004 15:15:29 -0500 Subject: Protecting Python source In-Reply-To: <41ab74f4$0$85031$a1866201@visi.com> References: <41ab74f4$0$85031$a1866201@visi.com> Message-ID: <200411291515.29610.drlinux@columbus.rr.com> On Monday 29 November 2004 14:13, Grant Edwards wrote: > On 2004-11-29, Peter Maas wrote: > > > If the "reverse engineering" argument boils down to "protecting source > > doesn't make sense" then why does Microsoft try so hard to protect > > its sources? > > To avoid embarassment. +1 QOTW From drew at gremlinhosting.com Sat Nov 20 09:02:02 2004 From: drew at gremlinhosting.com (Andrew James) Date: Sat, 20 Nov 2004 14:02:02 +0000 Subject: Reading Formatted Text File In-Reply-To: <20041120133402.12675.qmail@web14026.mail.yahoo.com> References: <20041120133402.12675.qmail@web14026.mail.yahoo.com> Message-ID: <1100959322.10554.4.camel@odin> Kevin, There was an article on parser generators in this mailing list a couple of days ago - given the relative complexity of the format you've shown below you might try simple regex matching but only if you know all the input is valid. Some places you might want to look: http://christophe.delord.free.fr/soft/tpg/ - Parser generator http://dparser.sourceforge.net/ - Another parser generator (both are excellent) And, of course, diveintopython's most excellent regular expression tutorial: http://www.diveintopython.org/regular_expressions/index.html Hope this helps! Regards, Andrew On Sat, 2004-11-20 at 05:34 -0800, Kevin McBrearty wrote: > Hello All, > > I'm trying to read a formatted text of strings and > floats. I have looked through previous posts and > couldn't deciper a good method. I'm new to python so > any suggestions would be helpful. > > Regards, > Kevin > > solid SIMPLEBLOCK > facet normal 0.000000e+00 0.000000e+00 -1.000000e+00 > outer loop > vertex 1.000000e+00 -1.000000e+00 0.000000e+00 > vertex -1.000000e+00 -1.000000e+00 0.000000e+00 > vertex -1.000000e+00 1.000000e+00 0.000000e+00 > endloop > endfacet > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > -- Andrew James From exarkun at divmod.com Tue Nov 9 22:22:22 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 10 Nov 2004 03:22:22 GMT Subject: property for class objects In-Reply-To: Message-ID: <20041110032222.20649.438868458.divmod.quotient.1190@ohm> On Tue, 09 Nov 2004 21:54:50 -0500, Steve Menard wrote: >As par of JPype, I find that I have to brifge Java static members into > class attributes. > > I am using a metaclass to dynamically create a Python class for every > Java type encountered. Instance variables were handled by adding a > property(get, set) to the class's dictionary. > > Now static members are giving me a headache. I cannot use "property" for > them, because properties are for instances only. > > What I am currently doing is adding a __getattr__ and a __setattr__ > methods to the metaclass, which is called when a class attribute is > requested but not found in the class' dict. > > This works fine exact it does not walk the inheritance tree to find > static members defined in base classes. I am currently adding up all the > names in every class. This "works", however it is misleading when you do > a dir() of the class. > > Does anyone have an idea how to implement "classproperty" ? How about this? exarkun at boson:~$ python Python 2.3.4 (#2, Sep 24 2004, 08:39:09) [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class x(type): ... def get_y(self): ... return 'y on', self ... def set_y(self, value): ... print 'y on', self, 'is now', value ... y = property(get_y, set_y) ... >>> class z(object): ... __metaclass__ = x ... >>> z.y ('y on', ) >>> z.y = 'foo' y on is now foo >>> If not, how is what you are looking for different? Jp From bokr at oz.net Sat Nov 13 10:40:40 2004 From: bokr at oz.net (Bengt Richter) Date: Sat, 13 Nov 2004 15:40:40 GMT Subject: permuting letters and fairy tales References: <67lld8kr76.fsf@aster.homelinux.net> <41957f26.318790786@news.oz.net> <4195b412.332338677@news.oz.net> <41960db9$1_2@newspeer2.tds.net> Message-ID: <419623d3.360947044@news.oz.net> On Sat, 13 Nov 2004 08:40:24 -0500, Kent Johnson wrote: >Bengt Richter wrote: >> But it does bring up a general problem of final logic in an iter loop. ISTM it could >> be useful to have an option not to raise StopIteration, but instead keep returning >> a specified sentinel at the end, something like file.read returns '' repeatedly at EOF. > > From the itertools examples: > >>> def padnone(seq): >... "Returns the sequence elements and then returns None indefinitely" >... return chain(seq, repeat(None)) > Thanks for shaming me into refreshing my acquaintance with the itertools module ;-) It really deserves to be more than an acquaintance. It's surprising that itertools doesn't show up in posted solutions more (Alex's notwithstanding ;-) Regards, Bengt Richter From Scott.Daniels at Acm.Org Fri Nov 26 23:51:26 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Nov 2004 20:51:26 -0800 Subject: I Need a Python Mentor In-Reply-To: References: Message-ID: <41a81a7b$1@nntp0.pdx.net> abhay wrote: > .... I'm seeking for a good programming project to be implemented in > python. Do you have any projects to share, I'm ready to spend my free time > over it to learn the best. Let us know what fascinates or obsesses you; these subjects are fertile sources for projects. It always helps if the subject itself holds the student's interest. --Scott David Daniels Scott.Daniels at Acm.Org From pwatson at redlinepy.com Sat Nov 27 13:01:43 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Sat, 27 Nov 2004 12:01:43 -0600 Subject: ctypes 0.9.2 released References: <1gmeuqj.1p0mkh41y1zvfcN%aleaxit@yahoo.com> Message-ID: <30rtokF349078U1@uni-berlin.de> "Thomas Heller" wrote in message news:mzy58j41.fsf at python.net... > Ian Bicking writes: > >> Just wrote: >>>>One of the perceived strengths of Python is the fact that it >>>>integrates well with the platforms it is running on, so it's not an >>>>insulated box like Java. >>> Another one of Pythons perceived strengths is that if you get a >>> segfault, it's a bug in Python. With ctypes that will no longer be >>> as clear. >> >> It's always been the case that C extensions can cause segfaults. This >> is just a tool for incorporating C extensions, without writing any >> extra C. It even says "c" right in the name, which should cause a >> certain amount of (justified) fear for anyone who knows what that >> means ;) >> >> Having ctypes in the stdlib would be cool, because it would mean that >> many C library extension could be installed with no compilation step, >> since ctypes would already be compiled as part of the default >> install. Assuming the C library was already installed, but typically C >> libraries get packaged for distribution long before the associated >> Python extension is packaged. > > Of course I think that ctypes in the standard lib would be great, but I > won't try to push this myself anymore. I tried several times in the > past, and have failed miserably (at least that's how I feel). > > Thomas The question at hand is "what is the alternative?" Will the user (developer) need to write code and acquire a compiler? Will that reduce the probability of a segfault on the Python project? Also, it is much easier to push an application into an enterprise when everything comes in one kit. Those who do not know and are making the decisions return nothing but "NO WAY" when a developer says that we just need to download something on the Internet... And the discussion ends. What does the developer do then? From carribeiro at gmail.com Wed Nov 24 04:46:47 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 24 Nov 2004 07:46:47 -0200 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: Message-ID: <864d37090411240146489ad69e@mail.gmail.com> On Wed, 24 Nov 2004 07:36:26 +0000, Paul Robson wrote: > On Tue, 23 Nov 2004 18:35:01 +0000, Lenard Lindstrom wrote: > > >> I bought a copy of this in I reckon about 1986ish. Visual Basic debuted in > >> 1991. > > > > I would hope that a rewrite of Claim-2 of the patent is required before the patent > > is accept (if it is not outright rejected). Claim-2 is too vague to be meaningful. > > Proper definitions of "BASIC" and "derived" are missing. I imaging the patent is > > intended to protect Visual Basic.NET rather than restrict unrelated languages > > like Delphi and Python anyways. > > It's blatantly obvious to me that the C# classes, ASP.NET etc. are knock > offs of the Delphi design. They also bear little resemblance beyond the > most basic syntactic stuff to VB6.0 let alone VB1.0 I think that Delphi is *so* underated when it comes to language & framework design... Delphi suffered from a couple of problems; first, it was Pascal's child, and not C; also, because it was a proprietary project, owned by a single company. For some reason, being a Pascal descendant was regarded as a big "no" by a huge part of the industry, not to mention academia, that was at that time fascinated with the prospect of C++. I wonder what could have happened if Delphi (maybe with another name -- P++ anyone?) was widely adopted instead of C++ for big projects... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From sjmaster at gmail.com Mon Nov 15 18:55:35 2004 From: sjmaster at gmail.com (SM) Date: 15 Nov 2004 15:55:35 -0800 Subject: How to load new class definitions at runtime? References: <1gn8ja3.7d3sbhuk94khN%aleaxit@yahoo.com> Message-ID: <6542462a.0411151555.5fe41de4@posting.google.com> aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gn8ja3.7d3sbhuk94khN%aleaxit at yahoo.com>... > If you need [classes] to be _updatable_ at runtime, look at a recipe by > Michael Hudson in the cookbook -- I've updated it for the printed > version 2nd ed (since we do have __subclasses__ now, yay!) but that's > not done yet. My vote for most useful custom metaclasses ever... That recipe is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Is it correct that this metaclass solution does not handle changes to __init__, including new attributes that are bound there? I.e., it basically only deals with modification or addition or deletion of methods; if you need to add new attributes or have any other new code in __init__, you'll have to make new instances for all the old instances, or deal with it some other way. In which case would you be better off just using that other way from the start? From mfuhr at fuhr.org Thu Nov 18 10:02:36 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 18 Nov 2004 08:02:36 -0700 Subject: Python client lib for PostgreSQL8 References: Message-ID: <419cb98c$1_3@omega.dimensional.com> Peter Maas writes: > I just tried to connect to a PostgreSQL8 beta2 database server with > pyPgSQL 2.4 and got a libpq.DatabaseError telling "Ivalid format for > PgVersion construction". This bug was reported over three months ago: http://sourceforge.net/tracker/index.php?func=detail&aid=1006782&group_id=16528&atid=116528 > Is there already a PyPgSQL version in CVS or another client library > that handles PostgreSQL 8? A lot of people like psycopg. http://initd.org/software/initd/psycopg -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From foo at bar.com Tue Nov 9 21:54:50 2004 From: foo at bar.com (Steve Menard) Date: Tue, 09 Nov 2004 21:54:50 -0500 Subject: property for class objects Message-ID: As par of JPype, I find that I have to brifge Java static members into class attributes. I am using a metaclass to dynamically create a Python class for every Java type encountered. Instance variables were handled by adding a property(get, set) to the class's dictionary. Now static members are giving me a headache. I cannot use "property" for them, because properties are for instances only. What I am currently doing is adding a __getattr__ and a __setattr__ methods to the metaclass, which is called when a class attribute is requested but not found in the class' dict. This works fine exact it does not walk the inheritance tree to find static members defined in base classes. I am currently adding up all the names in every class. This "works", however it is misleading when you do a dir() of the class. Does anyone have an idea how to implement "classproperty" ? Thanks in advance for any help, Steve From steven.bethard at gmail.com Tue Nov 30 02:41:47 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 30 Nov 2004 07:41:47 GMT Subject: Python code and C code in the same module? Message-ID: <%uVqd.112242$V41.104378@attbi_s52> I'd like to merge a module written in C with a module written in Python so that the user can access objects from either module by importing the single, merged module. Specifically, I'm looking at the collections module, which is written in C, and my Bunch object, which is written in Python. I'd like the Bunch object to appear in the collections module so that you can do: from collections import Bunch without, of course, removing the ability to do: from collections import deque There's no need for the code to reside in the same file or anything of course -- I just want the different objects to appear in the same module. Thanks, Steve From mwm at mired.org Fri Nov 19 12:03:46 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 19 Nov 2004 11:03:46 -0600 Subject: distutils setup.cfg question. References: <419d906c$0$143$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > Mike Meyer wrote: >> Ok, I give up. I searched the CVS code, and can't find the place that >> turns an include_dirs option in setup.cfg into a list of >> directories. The reason I was looking for it is that I can't figure >> out how to make include_dirs include multiple directories from >> setup.cfg. Everything I try winds up putting >> -I. I couldn't even find the place where the >> string value that is returned by ConfigParser is enclosed in a list. > > % grep include_dirs *.py */*.py > > This gives a long list. However, in two places, include_dirs is split: > command/config.py: self.include_dirs = > string.split(self.include_dirs, os.pathsep) > command/build_ext.py: self.include_dirs = > string.split(self.include_dirs, os.pathsep) That's the code I was missing. And I missed it because I wasn't looking in subdirectories (duh). > Both places have similar code: > > if self.include_dirs is None: > self.include_dirs = self.distribution.include_dirs or [] > elif type(self.include_dirs) is StringType: > self.include_dirs = string.split(self.include_dirs, os.pathsep) That helps immensely. But it seems to make setup.cfg non-portable, in that you have to change the path separator in it to the one for the platform you are on. I guess that since editing setup.cfg is expected, that's not to bad. Next question: I'd like to submit a bug report and patch for the documentation of distutils. Where do I get copies of the source to work on? Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Mon Nov 1 15:36:06 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 01 Nov 2004 20:36:06 GMT Subject: List problem References: <1gmjqh9.oialil1r1xwffN%aleaxit@yahoo.com> <41858eaa.1299498379@news.oz.net> Message-ID: <41860f36.1328806672@news.oz.net> On Mon, 01 Nov 2004 00:13:18 -0700, Josiah Carlson wrote: > >bokr at oz.net (Bengt Richter) wrote: > >> delsome_br >> 3.39048024526 >> 3.63548729364 >> 3.6326486655 >> delsome_am >> 6.40547292869 >> 6.32403355062 >> 6.21752171923 > >FYI: list comprehensions in 2.4 are significantly faster than list >comprehensions in 2.3, which is likely where a large portion of your >difference is coming from. > Sounds reasonable. >I wasn't sure that I believed your statements in regards to Python's >cache performance, so I thought I'd give it a look... I'm not sure which statements you are referring to, but if it's about bad jobsharing between multiple processors, I don't think that's what's causing the result you get below. I get a similar slowdown after shuffling. I would guess only one of your processors is really doing the work of the interpreter, and the other mostly idling and taking care of i/o and interrupts. So why would a single processor slow down? The low level in for i in a: pass must be to bind i to successive integers, however laid out. Meaning incrementing and decrementing ref counts on the integer objects, and doing that either in linear memory order or shuffled order, with the integer objects themselves not moving at all, even with the shuffle of references to them in a. So how big an L2 cache? 512k bytes? How big is an int object? Even if type info is shared for an arena, it must be a value,refcount pair each at least, or 8 bytes. I guess I'd bet on no tricks for type info, so that's a pointer for that -> 12 bytes. so 512k/12 is about 43k integer objects in L2 cache. But we have a million, so if they are laid out linearly, we should have 1e6*12/512k or about 22.89 int objects modulo sharing each cache space that can span an integer. Ok, but L2 cache communicates with CPU cache which is much smaller, maybe 16 or 32k. 8k 32-bit values in 2k 128-bit chunks. Maybe ;-) or about 2700 12-byte int objects. But cache lines probably go back and forth to L2 memory 128 bits wide or 16 bytes. Which doesn't match 12 bytes, so what happens when you walk orderly through type,refount,value triplets presumably reading type and reading and writing refount twice, and ignoring the value since were doing pass? Anyway, I'm not sure how smart L2 cache is with communicating to slower DRAM, which might be interleaved in some cases, and have narrower data path. So many factors. But you can see reading 3*16 will get you 4*12 where randomly you might have to read 4*16 or even more to get your 4*12, depending on the overlaps. If that is what's doing it, going to a different int representation, where only refcount and value are stored, and the type info is separate, then the 8 byte lineup with cache chunks ought to make noticeable speedup for int ops. Of course, I don't know what percentage of all ops that is. I guess someone instruments the interpreter for that kind of statistics? Timbot? > >Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on wi= >n32 >Type "help", "copyright", "credits" or "license" for more information. >>>> a =3D range(1000000) >>>> import time >>>> def f(a): >=2E.. t =3D time.time() >=2E.. for i in a: >=2E.. pass >=2E.. return time.time()-t >=2E.. >>>> for i in xrange(10): >=2E.. print f(a), >=2E.. >0.421999931335 0.421000003815 0.421999931335 0.422000169754 0.421999931335 = >0.437 >99996376 0.421000003815 0.421999931335 0.43799996376 0.406000137329 >>>> import random >>>> random.shuffle(a) >>>> for i in xrange(10): >=2E.. print f(a), >=2E.. >0.594000101089 0.59299993515 0.610000133514 0.608999967575 0.608999967575 0.= >5940 >00101089 0.593999862671 0.608999967575 0.594000101089 0.593999862671 >>>> a.sort() >>>> for i in xrange(10): >=2E.. print f(a), >=2E.. >0.421999931335 0.421999931335 0.421999931335 0.422000169754 0.43700003624 0.= >4219 >99931335 0.421999931335 0.421999931335 0.422000169754 0.43700003624 > > >Looks to be an almost 50% slowdown on my dual celeron 400mhz machine >(128kb cache). Very interesting, I would have never have expected as >much (due to the amount of overhead of Python data structures, I >believed it was generally a wash). > Regards, Bengt Richter From bokr at oz.net Mon Nov 22 01:53:26 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 22 Nov 2004 06:53:26 GMT Subject: generic object implementation References: <8W9od.373195$wV.310530@attbi_s54> Message-ID: <41a17599.693692997@news.oz.net> On Sun, 21 Nov 2004 23:55:48 GMT, Steven Bethard wrote: >So I'm trying to get a prototype implementation of the 'generic object' >type. (I'm currently calling it 'bunch', but only because I can't >really think of anything better.) I'd like some feedback on what >methods it needs to support. Ideally I'd keep this as minimal as >possible... UIAM 'bunch' already has a related meaning from c.l.py past (approx the first three lines of your class), so how about 'gob' ? ;-) > >Remember that the goal of the 'generic object' type is to allow the >programmer to make the design decision that attribute-style access is >more appropriate than []-style access. Given that, my feeling is that >the 'generic object' type should *not* support __(get|set|del)item__ , >though I'm still undecided on __len__, __iter__, __contains__, items, >keys, values, etc. > >Here's what I have currently: > >import operator as _operator > >class bunch(object): > def __init__(self, **kwds): > self.__dict__.update(kwds) > > def __eq__(self, other): > if not isinstance(other, bunch): > return False > attrs = set(self.__dict__) > if attrs != set(other.__dict__): > return False > for attr in attrs: > if not getattr(self, attr) == getattr(other, attr): > return False > return True > > def __repr__(self): > return '%s(%s)' % (self.__class__.__name__, > ', '.join('%s=%r' % (k, v) > for k, v in self.__dict__.items())) > > def update(self, other): > self.__dict__.update(other.__dict__) > > @classmethod > def frommapping(cls, mapping, > getkeys=iter, getitem=_operator.getitem): > result = bunch() > for key in getkeys(mapping): > value = getitem(mapping, key) > try: > value = bunch.frommapping(value) > except TypeError: > pass > setattr(result, key, value) > return result I dunno, begins to look more like a dict with getattr access substituted for __getitem__ than a primitive generic object... >>> class dbunch(dict): ... def __metaclass__(name, bases, cdict): ... cdict.update(dict.__dict__) ... cdict['__getattr__'] = cdict['__getitem__'] ... cdict['__setattr__'] = cdict['__setitem__'] ... cdict['__delattr__'] = cdict['__delitem__'] ... def raiseunsub(*ignore): raise TypeError, 'unsubscriptable object' ... cdict['__getitem__'] = raiseunsub ... cdict['__setitem__'] = raiseunsub ... cdict['__delitem__'] = raiseunsub ... return type(name, bases, cdict) ... >>> db = dbunch(x=123) >>> db {'x': 123} >>> db.x 123 >>> db['x'] Traceback (most recent call last): File "", line 1, in ? File "", line 7, in raiseunsub TypeError: unsubscriptable object >>> db.y = 456 >>> db {'y': 456, 'x': 123} >>> db.x = 789 >>> db {'y': 456, 'x': 789} >>> del db.x >>> db {'y': 456} >>> db.x = 101112 >>> db.z = 131415 >>> db {'y': 456, 'x': 101112, 'z': 131415} >>> db.keys() ['y', 'x', 'z'] >>> db.values() [456, 101112, 131415] >>> db.items() [('y', 456), ('x', 101112), ('z', 131415)] >>> for k in db: print k, ... y x z ... and etc. methods from dict, so should it be a restricted builtin subclass of dict or derive from object directly? It the hope for a lean representation for small numbers of items? Regards, Bengt Richter From __peter__ at web.de Fri Nov 19 07:35:11 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Nov 2004 13:35:11 +0100 Subject: Identifying exceptions that can be raised References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: dkcpub wrote: > Brian van den Broek wrote: >> If you mean you want a list of exceptions that a given function could >> raise, well, never mind :-) > > Yeah, that is what I mean. I write foo(), which calls a half-dozen > library functions. What exceptions is a caller of foo() going to have > to handle? It there an automated way of discovering that? > > /Dan None that I know of. You just have to feed the function the typical data and any corner cases that you can think of and handle all failures that appear in the process. The unittest module can help you automate this. Hoping to ever get a comprehensive set of exceptions a function can raise is a vain effort in Python. A little example may illustrate this: >>> def add(a, b): ... return a + b ... >>> add(1, 2) 3 >>> add(1, "2") Traceback (most recent call last): File "", line 1, in ? File "", line 2, in add TypeError: unsupported operand type(s) for +: 'int' and 'str' The above calls should cover the typical usage of our trivial function. Does it make sense then, to document/report that add() may raise a TypeError? I think that would be misleading: >>> class Int(int): ... def __add__(self, other): ... return self/other ... >>> add(Int(1), 0) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in add File "", line 3, in __add__ ZeroDivisionError: integer division or modulo by zero This may seem contrived, but for any non-trivial function the number of exceptions is open-ended, and trying to achieve reliability by handling a fixed set of exceptions is essentially asking for type declarations for a small portion of a function's signature - and a portion where its usefulness is debated even for statically typed languages (I think Java has it, but C sharp doesn't). Put your time to a better use and write a good test suite. Peter From jacek.generowicz at cern.ch Wed Nov 10 03:57:21 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Nov 2004 09:57:21 +0100 Subject: generic way to access C++ libs? References: <1gmxizh.3rip5na92f0nN%aleaxit@yahoo.com> <1gmxn7d.19o8q51jt2gu5N%aleaxit@yahoo.com> <2vbunuF2kakbcU1@uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: > > I don't think so. Given that the _definition_ of the function is in > > the header, and the header is needed to compile any code which might > > want to link with the library, the compiler has all it needs, without > > a need for a corresponding function to exist in the library. > > It has been a while, but I think what happened when including such a header > on several locations that produced .o-files was that a duplicate symbol > problem arised on linking time. I find this hard to believe, unless we are talking about a buggy compiler or linker. Remember that in the case of templates (until the EDG people implemented the mythical "export" keyword, relatively recently) the _only_ way to use templates in more than one translation unit was to include the full _definitions_ of everything in the template, in the header. That's why C++ has the One Definition Rule (ODR). Here's what Stroustrup has to say about the ODR in _The C++ Programming Language_ 3rd edition (p203): A given class, enumeration, and template, etc., must be defined exactly once in a program. From a practical point of view, this means that there must be exactly one definition of, say, a class ersiding in a single file somewhere. Unfortunately, the language rule cannot be that simple. [...] Consequently the rule in the standard that says that there must be a unique definition of a class, template, etc., is phrased in a somewhat more compliated and subtle manner. This rule is commonly referred to as "the one-definiton rule," the ODR. That is, two definitions of a class, template, or inline function are accepted as examples of the same unique definition if and only if [1] they appear in different translation units [2] they are token-for-token identical [3] the meanings of those tokens are the same in both translation units. [...] The intent of the ODR is to allow inclusion of a class definiton in different tranlation units from a common source file. > Why would there be a symbol at all, when the code got "pasted" into > the callee's code? Remember that "inline" (and the implicit inline you generate by _defining_ the method in the class itself) is merely a hint to the compiler, which the compiler is perfectly entitled to ignore. One situation in which the compiler is _guaranteed_ to ignore it is if you also declare the method to be virtual, for example. In general, it may choose to inlne some of the calls while not others. I don't think that declaring a function to be inline makes any guarantess about whether you will find a symbol for that function in the object code. But the ODR guarantees that sorting this mess out is the compiler's problem, not yours. From rkern at ucsd.edu Wed Nov 10 20:28:39 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 10 Nov 2004 17:28:39 -0800 Subject: distutils and Debian In-Reply-To: References: <4192AD69.5040707@sympatico.ca> Message-ID: Istvan Albert wrote: > Sam Holden wrote: [Colin J. Williams wrote:] >>> Should this be reported as a Debian bug? > > >> No. > > > I would say yes ... there is no logic in crippling > a standard python distribution. What else is missing? It's a matter of Debian policy to split things into runtime packages and development packages. A Debian package that needs Python to run need only depend on the main python package. Most packages that need Python *don't* need distutils or the C headers or the static library. Debian users know, or ought to, that if they want to compile extra-Debian software that needs Python (or whatever) they need to install the appropriate *-dev packages. This is a pretty standard split thats followed by several free UN*X distributions (I'm tempted to say "most" but I don't have personal experience with enough to do that). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From caroundw5h at yahoo.com Wed Nov 24 13:47:11 2004 From: caroundw5h at yahoo.com (caroundw5h) Date: 24 Nov 2004 10:47:11 -0800 Subject: Python's annoyance. Message-ID: [code] PEP 292 adds a Template class to the string module that uses "$" to indicate a substitution. Template is a subclass of the built-in Unicode type, so the result is always a Unicode string: >>> import string >>> t = string.Template('$page: $title') >>> t.substitute({'page':2, 'title': 'The Best of Times'}) u'2: The Best of Times' If a key is missing from the dictionary, the substitute method will raise a KeyError. There's also a safe_substitute method that ignores missing keys: >>> t = string.SafeTemplate('$page: $title') >>> t.safe_substitute({'page':3}) u'3: $title' [/code] [code]As a slightly more realistic example, the following decorator checks that the supplied argument is an integer: def require_int (func): def wrapper (arg): assert isinstance(arg, int) return func(arg) return wrapper @require_int def p1 (arg): print arg @require_int def p2(arg): print arg*2 [/code] Serioulsy, one of python's main selling points is its elegant syntax, non perl like, non C like. If it can't live up to it. I guess i might as well use perl or ruby or server side javascript. how annoying. From peter at engcorp.com Sun Nov 28 09:21:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 28 Nov 2004 09:21:29 -0500 Subject: futue feature division not found (embedded) In-Reply-To: References: <41a925d5.1197560430@news.oz.net> Message-ID: Jive wrote: > "Bengt Richter" wrote in message >>HTH. On to the next bug ;-) > > What's HTH? http://www.google.ca/search?q=acronym+hth -Peter From vincent at visualtrans.de Fri Nov 19 16:05:13 2004 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 19 Nov 2004 22:05:13 +0100 Subject: using the bsddb from Python (missing docs!) In-Reply-To: <4edc17eb.0411191042.64ee3c7@posting.google.com> References: <4edc17eb.0411180549.33719f1e@posting.google.com> <4edc17eb.0411191042.64ee3c7@posting.google.com> Message-ID: Michele Simionato wrote: > vincent wehren wrote in message news:... > >>The bsddb3 package has become part of the standard library as of 2.3, I >>believe. The docs for this "full blown" bsddb package are not (yet) part >>of Python docs, but off-site on http://pybsddb.sourceforge.net/bsddb3.html. > > > I am a bit confused about pybsddb; is pybsddb exactly the same as the module > bsddb in Python 2.3+ ? Originally I thought that pybsddb had more stuff in it, > but now I tend to believe that they are the same. It is confusing since the > docs are not in the standard distribution, so it is not clear if they are the > same package (as optik and optparse, for instance) or not. Also, the docs > of pybsddb are kind of terse: there is the API but there are no examples, so > they are not very suitable for people without previous experience with the > sleepycat database. This is the reason why I asked is somebody is aware of > some journal article, or tutorial, or other useful stuff. > > > Michele Simionato My guess is that it is the same thing, but that the release schedule varies. Using the print_version() function from test_all.py in the test directory with Python 2.3.4 gives: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Sleepycat Software: Berkeley DB 4.1.25: (December 19, 2002) bsddb.db.version(): (4, 1, 25) bsddb.db.__version__: 4.2.0.2 bsddb.db.cvsid: $Id: _bsddb.c,v 1.17.6.4 2004/03/16 07:47:45 greg Exp $ python version: 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] My pid: 1056 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= The version of pybsddb on Sourceforge is at 4.2.4. I don't know any documentation besides the API stuff. So I guess that inference from what happens in the test modules probably does give you the most mileage ;). -- Vincent Wehren From jfouhy at paradise.net.nz Wed Nov 10 22:35:29 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 10 Nov 2004 19:35:29 -0800 Subject: Floating point -> string conversions References: Message-ID: I have another related question... >>> pow(2, 31) 2147483648L >>> '%d' % 2147483647.0 # python will convert to int '2147483647' >>> '%d' % 2147483648.0 # too big for an int, so error. Traceback (most recent call last): File "", line 1, in ? TypeError: int argument required >>> '%d' % long(2147483648.0) # but yet, no trouble accepting a long. '2147483648' >>> '%d' % int(2147483648.0) # and int() converts to long anyway '2147483648' Is this a bug? (python 2.3.4) -- John. From mwh at python.net Mon Nov 22 18:08:47 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Nov 2004 23:08:47 GMT Subject: Will python ever have signalhandlers in threads? References: <4195419b.303035081@news.oz.net> Message-ID: I'm not really reading comp.lang.python at the moment, but found this thread via the Python-URL... Tim Peters writes: > The only currently active contributor I can think of who cares about > signals enough to actually work on them is Michael Hudson, but his > interest seems limited to keeping the interactions been Python's GNU > readline wrapper and signals working across incompatible details of > signal semantics on Unixish boxes. It's possible I'm wrong, and he'd > really love to work much more on signals, but feels inhibited by > Guido's well-known dislike of the beasts. I think you're more or less right. A couple of years ago I got pretty badly discouraged attempting to support sigprocmask and friends from Python, and came to conclusion that noone who cares about portability -- not just no Python programmers, but *noone at all* -- mixes threads and signals, because the cross platform behaviour is a total mess, and in many cases is just plain buggy (I believe the FreeBSD version of libc_r for 5.something contains a fix that is a direct consequence of my efforts, for example). Even linking with the threading libraries was enough to stuff things up mightily in some circumstances. We Do Not Want To Go There. Cheers, mwh -- Well, you pretty much need Microsoft stuff to get misbehaviours bad enough to actually tear the time-space continuum. Luckily for you, MS Internet Explorer is available for Solaris. -- Calle Dybedahl, alt.sysadmin.recovery From jcarlson at uci.edu Thu Nov 4 13:20:02 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 04 Nov 2004 10:20:02 -0800 Subject: Modification to asyncore.py to support threaded event loop In-Reply-To: <8548c5f3.0411040053.15644bfe@posting.google.com> References: <8548c5f3.0411040053.15644bfe@posting.google.com> Message-ID: <20041104095512.F80F.JCARLSON@uci.edu> abpillai at gmail.com (Anand Pillai) wrote: > > If you have ever used the asyncore module, you will realize that it's > event loop does not have a programmable exit condition. It keeps > looping till the channels in its socket map (a dictionary) are closed > and don't have any pending reads/writes. With the asyncore that will be included with Python 2.4, loop() has a 'count' argument. Your 'programmable exit condition' is simple... while not exit_condition_satisfied: asyncore.loop(count=1) > If you are using Python threads in your application, by using either > the threading or thread modules, adding asyncore capability on top of > it is a bit tricky. The moment you call asyncore.loop after > initializing your asyncore based client/server, it takes over the main > thread. Hence, if you want to mix threaded classes (derived from > threading.Thread) and asyncore in one program, the only recourse is to > create and initialize all your thread objects first and call > asyncore.loop as the last function in your main thread. > > However, with a small hack it is possible to get asyncore event loop > running in its own thread, as shown below. Here's an easier way to get asyncore running in its own thread, with nearly all the functionality you mention, without having to subclass Thread. def asyncore_loop(exit_condition, timeout=30.0, use_poll=False, map=None): if map is None: map = asyncore.map while map and not exit_condition: asyncore.loop(timeout=30.0, use_poll=False, map=map, count=1) exit_condition = [] threading.Thread(target=asyncore_loop, args=(exit_condition,)).start() #to kill the thread... exit_condition.append(None) > The following is a mixin class, which derives from threading.Thread > and also overrides asyncore.loop in its 'run()' method. [snip unnecessary code] > Now you can initialize your asyncore based clients/servers and instead > of calling 'asyncore.loop', do it as follows, See the snippet I provide above. > Perhaps this is worth a PEP for inclusion in Python 2.4? Module and/or functionality additions do not require a PEP (from what I understand). Changing the behavior of the language, adding a builtin, etc., that requires a PEP. It is not going to make it into Python 2.4. How would I know this? Because "no new functionality after the beta". We're on beta 2, and even small functionality additions that were pre-approved (but not implemented) are not making it into 2.4. What about for Python 2.5? I doubt it would be added there either. The functionality is very simple to implement if you know what you are doing, and doesn't require copying the internals of asyncore.loop to make it happen. - Josiah From peter at semantico.com Fri Nov 19 10:48:37 2004 From: peter at semantico.com (Peter Hickman) Date: Fri, 19 Nov 2004 15:48:37 +0000 Subject: Question about thread In-Reply-To: <1100875373.911763@eng-ser6> References: <1100875373.911763@eng-ser6> Message-ID: <419e164f$0$24802$afc38c87@news.easynet.co.uk> Valkyrie wrote: > Refering to the following codes I found, there is nothing displayed in the > console, may I ask why? > > def thrd(param): # the thread worker function > print "Received",param > > import thread > for i in range(5): # start five threads passing i to each one > thread.start_new_thread(thrd,(i,)) > > Thanks in advance The problem with your script is that it will run too fast before it quits and kills all the threads. if you add a = 0 for i in range(100000): a = a + 1 to the end you will see the output. From peter at engcorp.com Tue Nov 2 08:33:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Nov 2004 08:33:36 -0500 Subject: OT: Ruby programmers use Python (was Re: ruby on rails ... python on ?) In-Reply-To: References: Message-ID: <8vudnfVCkdgyERrcRVn-jA@powergate.ca> Richard Blackwood wrote: > >> To the OP: there are several Python "application frameworks" >> which on the surface appear to be similar in goal to Rails. >> I don't know much about them, and at the moment even their >> names aren't coming to me, so I can't help more than that. >> I think a search for "enterprise application framework Python" >> would probably turn up at least one of them. > > Do you mean Zope? Yikes! I *didn't* mean Zope, as it doesn't qualify for the term 'enterprise application framework' as I used it above, but I *should* have meant Zope, because upon revisiting the rubyonrails.org site, I see that it is a *web* framework. No idea how I missed that key word. Perhaps the MVC part grabbed my eyes and filtered the rest of my reading (which was admittedly brief). Perhaps I was just on drugs. Was that a Saturday? Yes, it was definitely the drugs. Today I'm on *different* drugs, the pretty blue ones, and I'm feeling much furrier, thank you. Down, Shadowfax, down! Oh, the spiders are crawling up my legs! They're coming to take me away, away! to the funny farm, where life is From someone at microsoft.com Sun Nov 28 17:37:35 2004 From: someone at microsoft.com (Jive) Date: Sun, 28 Nov 2004 22:37:35 GMT Subject: A lock that times out but doesn't poll References: Message-ID: Dang. I forgot the line-wrap again. Sorry about that. From gdamjan at gmail.com Tue Nov 23 20:56:02 2004 From: gdamjan at gmail.com (Damjan) Date: Wed, 24 Nov 2004 02:56:02 +0100 Subject: Nagging problem with MySQLdb References: Message-ID: <30i81jF30gipaU1@uni-berlin.de> As much as I can see > VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, > %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""" there's a missing comma here > [data01, data02, data03, data04, data05, data06, data07, data08, > data09, data10, data11, data12, data13, data14, data15, data16, data17, > data18, data19, data20, data21, data22, data23, data24, data25, data26, > data27, data28, data29] > ) -- damjan From michele.petrazzo at TOGLIunipex.it Tue Nov 2 03:22:52 2004 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Tue, 02 Nov 2004 09:22:52 +0100 Subject: [wx] Simple image editor In-Reply-To: References: Message-ID: Cliff Wells wrote: > On Sat, 2004-10-30 at 11:28 +0200, Michele Petrazzo wrote: > >>I want to create a simple image editor (with wxPython) for my application. >>Now I'm able to zoom, draw with a pen, insert a text into the loaded >>image, and undo changes (for this I reload the image and redraw all the >>lines/text, but not the last.) >> >>My problem is how can I move the texts/lines that are insert into Image, >>after placed? How the image editors (like GIMP) are able to move the >>objects? Please don't tell me to read the GIMP's source :). > > > First of all, if you are talking about bitmaps, then there are no such > things as "objects" in that sense, there is only a big bunch of bits. > What programs like the Gimp do is keep several (possibly hundreds) of > separate bitmaps for each of the objects and then composite them > together to give you a unified view of your "bitmap". So the first > thing you'll need is a framework for managing all those objects. Ok. I'll divide all my "objects" into a lot of bitmaps. > This > should be fairly straightforward in Python. Second, you can use the > built-in wxPython image handling tools or take a look at something like > PIL for doing the compositing. I'm using yet both wxPython and PIL. So the work will not be very hard. > > Regards, > Cliff > Thanks. Michele Petrazzo From mpapec at yahoo.com Mon Nov 22 13:18:43 2004 From: mpapec at yahoo.com (Matija Papec) Date: Mon, 22 Nov 2004 19:18:43 +0100 Subject: for(each) element aliasing References: <2844q0l5ccahj6poumolghrcm2u2boo9ka@4ax.com> Message-ID: X-Ftn-To: Jp Calderone Jp Calderone wrote: >> ------- >> 2 4 6 > > No. Integers in Python are immutable. For lists of other things, mutation in-place (similar to the above example) is possible, but for integers and other immutable types, it is not. You may be interested in list comprehensions, though: > > arr = range(1, 4) > arr[:] = [a * 2 for a in arr] > print arr I guess this works like "map" but "for" is more idimatic. Thank you all for so quick responses. :) -- Matija From boisgera at isia.cma.fr Thu Nov 25 13:13:21 2004 From: boisgera at isia.cma.fr (Sebastien Boisgerault) Date: 25 Nov 2004 10:13:21 -0800 Subject: Operator Overloading References: <41a5e084$0$25787$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Nick Coghlan wrote in message news:<41a5e084$0$25787$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>... > Peter Maas wrote: > > What you are wondering about is the opposite direction > > > > IF [] works THEN __getitem__ in dict. > > > > but this is not what the Python Reference Manual says. Im not a > > Numeric expert but AFAIK Numeric arrays are basically C arrays > > having [] intrinsically so there's no need no deliver it via > > __getitem__. > > This is correct, and true of any C extension - classes implemented in C only > need to define the appropriate function pointers in their type structures in > order for Python to find the relevant methods. > > Classes that are being *nice* about it put in the actual magic method names as > well (e.g. try "list.__getitem__"), but it is by no means required. Nick, Pierre, Peter, Thanks for your answers. I guess that in the case of the Numeric package, there was at least the *intent* to support __getitem__ because it is provided at the class level (which is not required, right ?): >> from Numeric import * >> a = array([3.14]) >> Array = type(a) >> a.__getitem__(0) Traceback (most recent call last): File "", line 1, in ? AttributeError: __getitem__ >> Array.__getitem__(a,0) 3.14 I guess that everything would work as expected if __class__ was defined at the instance level ... Regards, SB From noway at sorry.com Wed Nov 24 22:47:26 2004 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 25 Nov 2004 03:47:26 GMT Subject: Python's annoyance. References: Message-ID: caroundw5h wrote: > Serioulsy, one of python's main selling points is its elegant syntax, > non perl like, non C like. If it can't live up to it. I guess i might > as well use perl or ruby or server side javascript. > how annoying. In fact, I find the decorator syntax awful. But I know this was already discussed to a large extent, so there must be a very good reason to use @. Which I totally miss, but hey. -- Giovanni Bajo From DesertLinux at netscape.net Wed Nov 10 17:22:06 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 10 Nov 2004 22:22:06 GMT Subject: web hosting with Python In-Reply-To: <3cccb1d8.0411101416.690960c3@posting.google.com> References: <3cccb1d8.0411101416.690960c3@posting.google.com> Message-ID: Yes, check out: http://www.data393.com/web-hosting/reseller-hosting.asp Byron --- MJR wrote: > Hi, > anybody could recommend web hosting company which offer professional > reseller package with Python, preferable located in Europe? > > Thanks, > Mike From v451v at yahoo.com Mon Nov 29 18:05:37 2004 From: v451v at yahoo.com (Jorl Shefner) Date: Mon, 29 Nov 2004 18:05:37 -0500 Subject: Numeric: 'where' function conditions Message-ID: <311o97F300hdgU1@uni-berlin.de> Could anyone tell me the efficient way to do this? Extracting values from an array for a single condition (say all values greater than 'x') using 'where' and 'compress' is simple enough. >>> from Numeric import arange,where,compress >>> data= arange(10) >>> data= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> mask= where((data > 3),1,0) >>> result= compress(mask,data) >>> result array([4, 5, 6, 7, 8, 9]) But, 'where' doesn't appear to allow for multiple conditions in one statement. For instance, I'd like to do something like: mask= where((3 < data <= 7),1,0) but, this won't work. So, the best I could come up with was this more complicated process that requires 2 separate masks and an extra temporary array. >>> mask1= where((data > 3),data,0) >>> mask1 array([0, 0, 0, 0, 4, 5, 6, 7, 8, 9]) >>> mask2= where((mask1<= 7),mask1,0) >>> mask2 array([0, 0, 0, 0, 4, 5, 6, 7, 0, 0]) >>> r= compress(mask2,data) >>> r array([4, 5, 6, 7]) Is there a more concise way? Thanks, J.S. From mwm at mired.org Tue Nov 9 11:36:32 2004 From: mwm at mired.org (Mike Meyer) Date: Tue, 09 Nov 2004 10:36:32 -0600 Subject: possible to pass python objects into java without jython? References: Message-ID: Maurice Ling writes: > Hi, > > I have read that this had been asked before but there's no > satisfactory replies then. > > I have a module (pA) written in python, which originally is called by > another python module (pB), and passes a python object (pO) to pB. Now > I require pA to be called in a java class (jC) and pass pO into jC. As > pA uses non-python modules, I am not able to use Jython on this. > > Are there any way out in this? CORBA. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steven.bethard at gmail.com Wed Nov 24 01:35:20 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 24 Nov 2004 06:35:20 GMT Subject: protocols, inheritance and polymorphism In-Reply-To: References: <1101180636.399043.199740@z14g2000cwz.googlegroups.com> <1101192010.421806.51240@f14g2000cwb.googlegroups.com> Message-ID: Donn Cave wrote: > Rather than embrace > subtype polymorphism through inheritance, however, I see it > as evidence that no one has figured out how to make static > typing really work with OOP. I'm not sure I follow your argument here. Java interfaces provide the same sort of protocol-based typing as Python does (though of course you have do declare interfaces everywhere to make them work this way). Going back to my earlier Python example: >>> def process_rules(rules): ... for rule in rules: ... print rule.name ... the corresponding Java might look something like: public interface Rule { public Object getName(); } public class RuleProcessor { public void processRules(Iterable rules){ for (Rule rule: rules) { System.out.println(rule.getName()) } } } Note that because Java is statically typed, you have to declare all the appropriate interfaces: Iterable is in java.lang, and Rule is declared above. In Python, the interfaces are implied by the use, and left undeclared. Of course, you have to declare your interfaces in a suitably generic manner. I could have written this replacing Iterable with Collection or List, but Iterable is the type that makes the fewest commitments about the parameter and still allows me to iterate over the Rule objects. Similarly, I could have written getName to return a String, but by declaring getName with Object as a return type, I make only the necessary commitment that getName returns a value. The annoying thing, of course, is what you do when suddenly *one* use of a Rule does require, say, a String result of getName: public class OtherRuleProcessor { public void processRules(Iterable rules){ for (Rule rule: rules) { String[] s = rule.getName().split('\\s') } } } Do I now declare a new interface for this Rule and add another implements clause to all my classes that implement the original Rule as well? Do I make the original Rule interface less general by changing the return type from Object to String? It can get nasty rather quickly... Python, of course, avoids this by not declaring types. =) Steve From arkham at gmail.com Wed Nov 24 09:57:44 2004 From: arkham at gmail.com (Rob Snyder) Date: Wed, 24 Nov 2004 14:57:44 GMT Subject: asynchat and threading Message-ID: Greetings - I've embarked on a small learning project, trying to get a better grasp of the asyncore and asynchat modules. The project involves building a simple instant messenger application for use on our LAN - nothing heavy duty, as 99% of my reason for doing this is just to learn. I got my server portion working well, and I think I understand the basics. Where I'm getting stuck is on the client side, where I'm trying to involve both the asyncore / asynchat stuff in a multithreaded app. Assume for this that I have a window open with an active chat session, and an open connection to the server. At any moment in time, a message coule be received on the connection from the server, or the user could start typing their own message (and ultimately press enter to send it). Or, for that matter, the user could close the window or resize it, etc. I've got to be listening for incoming messages while also letting the UI run to handle events, while checking the event queue for things I care about (such as the enter key). I may also, in theory, still be in the process of sending a prior message out. I noticed early on that once I call asyncore.loop(), I surrender control to the asyncore library. I don't want to get into a polling situation, so I like that asyncore has taken over and is effectively waiting on incoming or outgoing data. Since I still need to run my UI, though, started a seperate thread for the asyncore stuff. I figured I would establish a queue that the asyncore could use to deliver messages to the UI, and I would just have the UI call the "push" method to get messages sent. Then, of course, the ugliness ensued. First, I can't have the UI wait on both the UI's event queue and the queue I established for communication, so I'd have to go back to polling between the two. Second, after I read through the asynchat module, I realized that the producer fifo is just a list, and when I call push, not only is there no inherent synchronization, I would actually invoking the code to deliver the message in the UI thread (so now I have two threads running through the same instance of my async_chat object, which seems dangerous). There *must* be some way to use this asyncore stuff on the client side, but I'm not seeing it. I'm about to bail on it for the client, but I thought I'd put this out there to see if anyone can help me see a different approach to this stuff. Thanks for the help! Rob From noway at sorry.com Thu Nov 25 18:10:07 2004 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 25 Nov 2004 23:10:07 GMT Subject: Python's annoyance. References: <4edc17eb.0411242359.6f32199e@posting.google.com> Message-ID: Michele Simionato wrote: >> In fact, I find the decorator syntax awful. But I know this was >> already >> discussed to a large extent, so there must be a very good reason to >> use @. >> Which I totally miss, but hey. > > Well, there is very good reason: Guido likes it! > > Right. Giovanni Bajo From tjreedy at udel.edu Sat Nov 13 19:24:12 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Nov 2004 19:24:12 -0500 Subject: Python 2.4: Why only assignments to None are forbiden? References: <4195190f@pfaff2.ethz.ch> Message-ID: "Andrew Dalke" wrote in message news:eivld.25773$KJ6.22637 at newsread1.news.pas.earthlink.net... > Peter Hansen wrote: >> One perfectly good reason to assign to builtins (and there are others, >> I'm sure) is to provide a "mock" function to replace a standard >> one, for use during automated testing. > > That's understandable, but it doesn't work for None. Peter was not suggesting that replacement of None be allowed but that replacement of things like file() should continued to be allowed and not prohibited as someone (I believe other than the OP) suggested. Terry J. Reedy From jemfinch at gmail.com Wed Nov 3 02:53:17 2004 From: jemfinch at gmail.com (Jeremy Fincher) Date: 2 Nov 2004 23:53:17 -0800 Subject: sh: test: argument expected References: Message-ID: <600ac2cf.0411022353.6e071999@posting.google.com> Iv?n Cabria wrote in message news:... > Hi, > > I am a new user of python. I ran > a python script and I got the > following message: > > sh: test: argument expected > > The first line of the python script is: > #!/usr/bin/env python Check that again, I suspect it's wrong. The error you're getting is the exact error I get when that line isn't correct or isn't present in my python scripts. Run your script as "python