Re: injecting set into 2.3's builtins?
Skip Montanaro wrote: I use sets a lot in my Python 2.3 code at work and have been using this hideous import to make the future move to 2.4's set type transparent: try: x = set (Surely just 'set' on its own is sufficient? This avoids the ugly else clause.) __builtin__.set = sets.Set I'm wondering if others have tried it. If so, did it cause any problems? I don't know of any specific case where it would cause problems but I'd be very wary of this; certainly doing the same with True and False has caused problems in the past. A module might sniff for 'set' and assume it is running on 2.4 if it sees it, with unpredictable results if it relies on any other 2.4 behaviour. I'd personally put this at the top of local scripts: from siteglobals import * Then put compatibility hacks like set and bool in siteglobals.py. Then any modules or other non-site scripts could continue without the polluted builtin scope. -- Andrew Clover mailto:[EMAIL PROTECTED] http://www.doxdesk.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4, distutils, and pure python packages
Thomas Heller wrote: [CC to python-dev] Fuzzyman [EMAIL PROTECTED] writes: Python 2.4 is built with Microsoft Visiual C++ 7. This means that it uses msvcr7.dll, which *isn't* a standard part of the windows operating system. Nitpicking - it's MSVC 7.1, aka MS Visual Studio .NET 2003, and it's msvcr71.dll. Sorry - my mistake ! This means that if you build a windows installer using distutils - it *requires* msvcr7.dll in order to run. This is true even if your package is a pure python package. This means that when someone tries to use a windows installer created with Python 2.4, on a machine with only python 2.3 - it will fail. Bummer. It's likely that nothing can be done about this (although for a pure python package there's no reason not to use the 'source distribution' and the setup.py). It does mean that I have to build my windows installer on a machine with python 2.3. There's a workaround, although ugly. [snip..] Yuck ! Distributing different versions of a pure python package :-) As I maintain a 2.3 machine as well, it's not too bad for me. I posted this mainly for the reference of others. Thanks for your reply Thomas. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: PyAsm
Won't docstrings be removed in optimised bytecode ? that would stuff things up. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python- xxxxxxxxxxxxxx Dev] RELEASED Python 2.4.1, release candidate 1
[Martin] I'd like to encourage feedback on whether the Windows installer works for people. It worked fine for me, upgrading from 2.4 on XPsp2. The only glitch was that it hung for 30 seconds between hitting Next on the directory-choosing page and the feature-choosing page. -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
Well, my concern here was mostly about SSL support. It seems it's not supported natively. Anyway, I'm looking at all those frameworks by a 'pre-evaluation' point of you. so I'm fully trusting what I can read on their websites... -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
[Martin] I'd like to encourage feedback on whether the Windows installer works for people. [Me] It worked fine for me, upgrading from 2.4 on XPsp2. Gah! I didn't mean to send that. It *didn't* work, as it turns out. It didn't overwrite python24.dll. It's possible that there was a process running at the time that was using python24.dll (I have a bunch of scheduled jobs that run in the background), but the installer didn't say anything about being unable to write the file. I could try again, but maybe there's some useful information you can get from the partially upgraded environment. Here's how the \python24 directory looks: C:\Python24dir /od Volume in drive C has no label. Volume Serial Number is E031-65A3 Directory of C:\Python24 26/11/1997 06:14 766 py.ico 11/04/2002 06:40 766 pyc.ico 24/03/2003 22:33 633 python.exe.manifest 24/03/2003 22:33 633 pythonw.exe.manifest 03/11/2004 15:3713,499 LICENSE.txt 09/11/2004 16:2761,440 Removepywin32.exe 09/11/2004 16:2899,601 pywin32-wininst.log 30/11/2004 11:49 1,867,776 python24.dll 21/01/2005 14:2120,992 Removeelementtree.exe 21/01/2005 14:21 3,191 elementtree-wininst.log 31/01/2005 14:4661,440 Removectypes.exe 31/01/2005 14:4625,371 ctypes-wininst.log 15/02/2005 14:3061,440 Removepy2exe.exe 15/02/2005 14:30DIR Scripts 15/02/2005 14:30 5,621 py2exe-wininst.log 18/02/2005 16:5950,963 README.txt 10/03/2005 10:13 228,444 NEWS.txt 10/03/2005 10:36 4,608 w9xpopen.exe 10/03/2005 10:46 4,608 python.exe 10/03/2005 10:46 5,120 pythonw.exe 11/03/2005 08:55DIR DLLs 11/03/2005 08:55DIR include 11/03/2005 08:55DIR libs 11/03/2005 08:55DIR tcl 11/03/2005 08:55DIR Tools 11/03/2005 08:55DIR .. 11/03/2005 08:55DIR . 11/03/2005 08:55DIR Doc 11/03/2005 08:56DIR Lib 19 File(s) 2,516,912 bytes 10 Dir(s) 14,520,340,480 bytes free And here's what Python thinks it is: C:\Python24python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch pdf viewer on Mac?
Paul McNett wrote: On Windows, os.startfile() does what I want: os.startfile(myDocument.pdf) But on Mac, what do I do? os.system(open myDocument.pdf) HTH has -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a short-circuiting dictionary get method?
Terry Reedy wrote: Skip Montanaro [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] value = d.get('x') or bsf() Of course, this bsf() will get called if d['x'] evaluates to false, not just None, value = (d.get('x') is not None) or bsf() #?? Unfortunately this will set value to True for all non-None values of d['x']. Suppose d['x'] == 3: 3 is not None True regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Setting sizes of widgets (PyGTK)
I have the following code and I would like to know how to set the length and width of widgets like Buttons. When the window opens the button fills up the space even though I have told it not to. Anyone know how I can accomplish this? : import pygtk, gtk class Greeter: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.box = gtk.VBox() self.window.add(self.box) self.label = gtk.Label(Please enter your name in the box below:) self.namebox = gtk.Entry(12) self.button = gtk.Button(Greet Me!) self.output = gtk.Label(Your output will appear here.) self.box.pack_start(self.label, False, False, 2) self.box.pack_start(self.namebox, False, False, 2) self.box.pack_start(self.button, False, False, 2) self.box.pack_start(self.output, False, False, 2) self.label.show() self.namebox.show() self.button.show() self.output.show() self.box.show() self.window.show() def main(self): gtk.main() a = Greeter() a.main() -- http://mail.python.org/mailman/listinfo/python-list
Re: shuffle the lines of a large file
On Fri, 11 Mar 2005 06:59:33 +0100, Heiko Wundram [EMAIL PROTECTED] wrote: On Tuesday 08 March 2005 15:55, Simon Brunning wrote: Ah, but that's the clever bit; it *doesn't* store the whole list - only the selected lines. But that means that it'll only read several lines from the file, never do a shuffle of the whole file content... Err, thing is, it *does* pick a random selection from the whole file, without holding the whole file in memory. (It does hold all the selected items in memory - I don't see any way to avoid that.) Why not try it and see? When you'd want to shuffle the file content, you'd have to set lines=1 and throw away repeating lines in subsequent runs, or you'd have to set lines higher, and deal with the resulting lines too in some way (throw away repeating ones... :-). Eliminating duplicates is left as an exercise for the reader. ;-) Doesn't matter how, you'd have to store which lines you've already read (selected_lines). And in any case you'd need a line cache of 10^9 entries for this amount of data... Nope, you don't. -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk(entire filesystem)
On Thu, 10 Mar 2005 20:11:10 +0100, Uwe Becher [EMAIL PROTECTED] wrote: You would need a wrapper to retrieve all logical drives using win32api.GetLogicalDriveStrings(),check the drive type with win32file.GetDriveType() and then os.walk() those local fixed drives. http://groups-beta.google.com/group/comp.lang.python/msg/49fc9210007a -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a short-circuiting dictionary get method?
On Fri, 11 Mar 2005 04:12:19 -0500, Steve Holden [EMAIL PROTECTED] wrote: Terry Reedy wrote: Skip Montanaro [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] value = d.get('x') or bsf() Of course, this bsf() will get called if d['x'] evaluates to false, not just None, value = (d.get('x') is not None) or bsf() #?? Unfortunately this will set value to True for all non-None values of d['x']. Suppose d['x'] == 3: 3 is not None True maybe (untested) value = ('x' in d and [d['x']] or [bsf()])[0] then there's always if 'x' in d: value = d['x'] else: value = bsf() or try: value = d['x'] except KeyError: value = bsf() Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: modifiable config files in compiled code?
Stephen Thorne [EMAIL PROTECTED] writes: On 10 Mar 2005 06:02:22 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi All, I've been trying to come up with an elegant solution to this problem, but can't seem to think of anything better than my solution below. I have a Python program that needs to be converted into an executable. The problem is that I have a config template file that I've been using to modify initialization constants such as paths, global variables, structures, etc. Obviously, once I convert my code into an executable I can no longer read/write to my configuration file. My solution was to convert this config file into a standard ASCII text document and have Python parse it for user set variables. This doesn't seem like the most elegant of solutions; however, and I thought others must have implemented a better way than this. Anyone have a better solution for this problem? Package config.py outside the zipfile containing all the python bytecode. 1) Remove config.pyc from dist\Library.zip as the last thing you do in your setup.py. You can save this step by using the exclude module option of py2exe. 2) As the first thing you do in main.py (or whatever your main is), do: import sys, os try: import config except ImportError: # We're in a py2exe, so we'll append an element to the (one element) # sys.path which points to Library.zip, to the directory that contains # Library.zip, allowing us to import config.py sys.path.append(os.path.split(sys.path[0])) import config 3) Put in your setup.py setug( data=[('.', ['config.py'])]# Package config.py seperately. ) Regards, Stephen Thorne -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n: looking for expertise
klappnase wrote: On my box (mandrake-10.1) sys.getfilesystemencoding() returns 'ISO-8859-15', however : locale.nl_langinfo(locale.CODESET) 'ANSI_X3.4-1968' In the locale API, you have to do locale.setlocale(locale.LC_ALL, ) to activate the user's preferences. Python does that on startup, but then restores it to the C locale, since that is the specified locale for the beginning of the (Python) program. Try that before invoking nl_langinfo. Anyway, my app currently runs with python-2.2 and I would like to keep it that way if possible, so I wonder which is the preferred replacement for sys.getfilesystemencoding() on versions 2.3 , or in particular, will the method I use to determine sysencoding I described in my original post be safe or are there any traps I missed (it's supposed to run on linux only)? I would put an nl_langinfo call in-between, since this is more reliable than getdefaultlocale (which tries to process environment variables themselves and happens to crash if they are not in an expected form). See idlelib/IOBinding.py for the algorithm that I use in IDLE to determine the user's encoding. On most systems, this encoding is good for usage on the file system API, except for MacOS X, which uses UTF-8 to encode file names regardless of user or system settings. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.4.1, release candidate 1
Sorry, but I don't know what you mean with 'workaround for the crash'... The interpreter no longer crashes when trying to compile this file. In Python2.4.0 I never saw any syntax error, there was just crash. Now there is a syntax error, and I when I look at the code I don't spot it. regards, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n: looking for expertise
klappnase wrote: Oh, from the reading docs I had thought XP would use unicode: It depends on the API that the application uses. Windows has the ANSI (*) API (e.g. CreateFileExA) and the Unicode API (CreateFileExW). The ANSI API uses what Python calls the mbcs encoding; Windows calls it the ANSI code page (CP_ANSI). The Unicode API expects WCHAR pointers. Python uses the *W APIs since Python 2.3 (I believe), except that maybe os.access was overlooked in 2.3 as well, so it uses the *W API for access only in 2.4. At run-time, it dynamically decides which API to use, and uses *W on NT+ (i.e. NT, W2k, WXP, W2k3, ...). * On Windows 9x, the encoding is ``mbcs''. Correct. * On Mac OS X, the encoding is ``utf-8''. Correct. * On Unix, the encoding is the user's preference according to the result of nl_langinfo(CODESET), or None if the nl_langinfo(CODESET) failed. Correct. In the latter case, it falls back to sys.getdefaultencoding(). When on windows the filesystemencoding differs from what I get in UnicodeHandler.sysencoding That could happen on OS X. Tk seems to be pretty smart on handling unicode, so using unicode for everything that's displayed on tk widgets should be ok (I hope). So do I. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
Richie Hindle wrote: Gah! I didn't mean to send that. It *didn't* work, as it turns out. It didn't overwrite python24.dll. It's possible that there was a process running at the time that was using python24.dll (I have a bunch of scheduled jobs that run in the background), but the installer didn't say anything about being unable to write the file. Ah, ok. I'll see whether I can reproduce this. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: modifiable config files in compiled code?
In article [EMAIL PROTECTED], [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Since this utility will also be ported to the linux world, does anyone know what the linux/unix counterpart of a Windows .INI configuration file is? ConfigParser works on Linux and Mac as well. Configuration files on Linux/Unix have a high 'roll your own' value: the format basically depends on the needs of the program. I suppose I could get away with using XML for my config files and avoid having two different tools altogether. I think you could do worse than adopt the Apple .plist format. There is already a pure python module for these: http://sarwat.net/opensource/ The advantage of the plist module is that the type of the variables is stored as well, and that you can store complex variables (lists, dictionaries) without mangling. Maarten -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a short-circuiting dictionary get method?
Bengt Richter wrote: then there's always if 'x' in d: value = d['x'] else: value = bsf() or try: value = d['x'] except KeyError: value = bsf() Its worth remembering that the first of those two suggestions is also faster than using get, so you aren't losing on speed if you write the code out in full: choose whichever seems clearest and uses the least contorted code. (The second is the fastest of all if the value is found, but a lot slower if the exception gets thrown.) C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k value = d.get('x45', 'notfound') 100 loops, best of 3: 0.427 usec per loop C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k value = d.get('z45', 'notfound') 100 loops, best of 3: 0.389 usec per loop C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k if 'x45' in d: value=d['x45'] else: value='notfound' 100 loops, best of 3: 0.259 usec per loop C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k if 'z45' in d: value=d['z45'] else: value='notfound' 100 loops, best of 3: 0.131 usec per loop C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k try: value=d['x45'] except: value='notfound' 100 loops, best of 3: 0.158 usec per loop C:\Python24\Libtimeit.py -s d={} -s for k in range(1000): d['x%s'%k]=k try: value=d['z45'] except: value='notfound' 10 loops, best of 3: 2.71 usec per loop -- http://mail.python.org/mailman/listinfo/python-list
Re: HC Library and *attributes parameter
Efrat Regev wrote: Hello, I'm a really new (and quite bad) Python programmer. While trying to use the HC HTML-Generating library, I couldn't figure out how to set a table's width to some given width. Moreover, the constructors interface is def __init__(self, object = None, align = None, border = None, cellspacing = None, cellpaddding = None, *attributes) So, what does *attribute stand for (being a C++ programmer, it looks like a pointer, probably not the case). Is it like the C++ ellipsis? If so, how can I use it? The notation *attribute in the function signature denotes a variable number of positional arguments, which are provided to the function body as a tuple named attribute. def f1(a, b, *c): ... print a:, a ... print b:, b ... print c:, c ... f1(1, 2, 3, 4, 5) a: 1 b: 2 c: (3, 4, 5) f1('one', 'two') a: one b: two c: () Much easier than varargs in C! The notation **kw similarly denotes a variable number of keyword arguments, which are provided to the function body as a dictionary named kw. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: HC Library and *attributes parameter
Efrat Regev wrote: def __init__(self, object = None, align = None, border = None, cellspacing = None, cellpaddding = None, *attributes) So, what does *attribute stand for (being a C++ programmer, it looks like a pointer, probably not the case). Is it like the C++ ellipsis? If so, how can I use it? Your guess is pretty close. See here for details: http://docs.python.org/ref/calls.html#calls -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Working on a log in script to my webpage
Hi all. Unfortunaly it looks like I dont have to skill to make a secure log in, cant figure out how the code has to look like, so guess my webpage has to live with a security issue. Thanks for the effort you put into teaching me the use of cookies. Best wishes Pete Pete. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Thanks. But I would really like to do this from scratch, so that I can learn it, I dont think I need that much more, before it works. I found an example with asp, where the save the session if the password is correct. It isnt that long a code, so was wondering if it isnt possible to make something like that in python. Cause when this code is applied to the loginform, CODE2 will only have to be applied to every following page and everything is good. code is from: http://tutorialized.com/tutorial/Creating-a-Members-Area-in-ASP/2234 CODE1 Set objRS = objConn.Execute (strSQL) '// see if there are any records returned If objRS.EOF Then 'no username found strError = - Invalid username or passwordbr vbNewLine Else 'check password If objRS(password)=Request.Form(password) Then 'username/password valid 'save session data Session(loggedin) = True Session(userid) = objRS(id) 'redirect to members area Response.Redirect (default.asp) Response.End Else 'invalid password strError = - Invalid username or passwordbr vbNewLine CODE2% If Session(loggedin) True Then Response.Redirect login.asp % html head titleMembers Area/title /head body h1Members Area/h1 pWelcome to our members area!/p/body /html In my code I have allready tested if the username and password is correct, so I just need to do the cookie thing :D Thanks all, hope all my questions dosnt make you tired, I just really wanna figure this out, and I am doing this as a little hobby of mine, so I dont have anyone else to ask, hope that is okay... Kent Johnson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Pete. wrote: Hi all I am working on a log in script for my webpage. I have the username and the password stored in a PostgreSQL database. You might want to look at Snakelets and CherryPy. Snakelets is a very simple-to-use Python web application server. One of the features is Easy user authentication and user login handling. http://snakelets.sourceforge.net/ CherryPy is a pythonic, object-oriented web development framework that seems to be popular. A recipe for password-protected pages in CherryPy is here: http://www.cherrypy.org/wiki/PasswordProtectedPages Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: modifiable config files in compiled code?
Tom Willis wrote: ConfigParser works on linux I'm pretty sure. I just ran Ipython imported it and loaded a config file. I don't remember anything in the docs that said otherwise. ConfigParser is pure python - so it's cross platform. ConfigObj is nicer though :-) http://www.voidspace.org.uk/python/configobj.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml [snip..] -- http://mail.python.org/mailman/listinfo/python-list
Re: modifiable config files in compiled code?
There are a lot of good options here. Much more than I thought I had. Since my program's configuration file will need to be read/writeable from an existing Java Netbeans GUI, I'll most likely move the Python module to an INI or XML document. The deciding factor will be whichever the other programmer is most comfortable with, of course. Thanks, everyone. -- http://mail.python.org/mailman/listinfo/python-list
Wishlist item: itertools.flatten
For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): [1,2,[3,hello,[[4 - [1, 2, 3, 'hello', 4] One such implementation is at http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2302348 but something like this would be handy in itertools as well. It seems trivial, but I managed to screw up several times when trying to produce my own implementation (infinite recursion). -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
(Newbie) Restricting inherited methods to operate on element from same subclass
Hi all, Sorry if the post's title is confusing... I'll explain: I have a class, called A say, and N1 subclasses of A, called A1, A2, A3, ..., AN say. Instances of each subclass can sensibly be joined together with other instances of the *same subclass*. The syntax of the join method is identical for each of the N subclasses, so it would make sense to implement a *single* method called join in the toplevel class A, and then do: a = A1() b = A1() a.join(b) #I want the join method to be inherited from class A d = A2() e = A2() d.join(e) But I want to raise an exception if my code finds: f = A1() g = A2() f.join(g) #should raise exception, as cannot join an #instance of A1 to an instance of A2. How can I verify in a method defined in class A that the subclasses I am joining are exactly the same? Or is there a design flaw here I haven't spotted that makes this a bad idea? Or do I need to code N join methods? Many thanks, Andy -- http://mail.python.org/mailman/listinfo/python-list
Confused with classmethods
Hi. Suppose this: def foo (x): print x f = classmethod (foo) class A: pass a=A() a.f = f a.f() # TypeError: 'classmethod' object is not callable! ### I understand that this is a very peculiar use of classmethods but is this error intentional? Or did I completely missed the point somewhere? j. -- http://mail.python.org/mailman/listinfo/python-list
Re: (Newbie) Restricting inherited methods to operate on element from same subclass
andy2o wrote: But I want to raise an exception if my code finds: f = A1() g = A2() f.join(g) #should raise exception, as cannot join an #instance of A1 to an instance of A2. How can I verify in a method defined in class A that the subclasses I am joining are exactly the same? Or is there a design flaw here I haven't spotted that makes this a bad idea? Or do I need to code N join methods? Assuming that A is a new-style class then if they have to be exactly the same type compare the types: def join(self, other): if type(self) != type(other): raise whatever if the 'other' value can be a subclass of self: def join(self, other): if not isinstance(other, type(self)): raise whatever If A is an old-style class then you would have to compare the __class__ attribute: self.__class__ != other.__class__ -- http://mail.python.org/mailman/listinfo/python-list
Re: HC Library and *attributes parameter
Efrat Regev [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello, ... Many thanks for the useful replies!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting sizes of widgets (PyGTK)
Harlin Seritt wrote: I have the following code and I would like to know how to set the length and width of widgets like Buttons. When the window opens the button fills up the space even though I have told it not to. Your button is stretched horizontally because there is nothing to put around it in order to fill the space. Try to embed it into a HBox, surrounded by empty labels : import pygtk, gtk class Greeter: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.box = gtk.VBox() self.window.add(self.box) self.label = gtk.Label(Please enter your name in the box below:) self.namebox = gtk.Entry(12) self.button = gtk.Button(Greet Me!) self.output = gtk.Label(Your output will appear here.) hbox = gtk.HBox() self.box.pack_start(self.label, False, False, 2) self.box.pack_start(self.namebox, False, False, 2) hbox.add(gtk.Label()) hbox.pack_start(self.button, False, False, 2) hbox.add(gtk.Label()) self.box.pack_start(hbox, False, False, 2) self.box.pack_start(self.output, False, False, 2) self.window.show_all() def main(self): gtk.main() a = Greeter() a.main() Cheers, Franck -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
I understand that this is a very peculiar use of classmethods but is this error intentional? Or did I completely missed the point somewhere? A little bit: classmethods are defined in a class context. def foo(cls): print cls class A: foo = classmethod(foo) The error you observe seems to be a result of your abuse of classmethod outside a class scope. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Working on a log in script to my webpage
Pete: Don;t give up, load Webware or similar and use that! regards Steve Pete. wrote: Hi all. Unfortunaly it looks like I dont have to skill to make a secure log in, cant figure out how the code has to look like, so guess my webpage has to live with a security issue. Thanks for the effort you put into teaching me the use of cookies. Best wishes Pete Pete. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Thanks. But I would really like to do this from scratch, so that I can learn it, I dont think I need that much more, before it works. I found an example with asp, where the save the session if the password is correct. It isnt that long a code, so was wondering if it isnt possible to make something like that in python. Cause when this code is applied to the loginform, CODE2 will only have to be applied to every following page and everything is good. code is from: http://tutorialized.com/tutorial/Creating-a-Members-Area-in-ASP/2234 CODE1 Set objRS = objConn.Execute (strSQL) '// see if there are any records returned If objRS.EOF Then 'no username found strError = - Invalid username or passwordbr vbNewLine Else 'check password If objRS(password)=Request.Form(password) Then 'username/password valid 'save session data Session(loggedin) = True Session(userid) = objRS(id) 'redirect to members area Response.Redirect (default.asp) Response.End Else 'invalid password strError = - Invalid username or passwordbr vbNewLine CODE2% If Session(loggedin) True Then Response.Redirect login.asp % html head titleMembers Area/title /head body h1Members Area/h1 pWelcome to our members area!/p/body /html In my code I have allready tested if the username and password is correct, so I just need to do the cookie thing :D Thanks all, hope all my questions dosnt make you tired, I just really wanna figure this out, and I am doing this as a little hobby of mine, so I dont have anyone else to ask, hope that is okay... Kent Johnson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Pete. wrote: Hi all I am working on a log in script for my webpage. I have the username and the password stored in a PostgreSQL database. You might want to look at Snakelets and CherryPy. Snakelets is a very simple-to-use Python web application server. One of the features is Easy user authentication and user login handling. http://snakelets.sourceforge.net/ CherryPy is a pythonic, object-oriented web development framework that seems to be popular. A recipe for password-protected pages in CherryPy is here: http://www.cherrypy.org/wiki/PasswordProtectedPages Kent -- http://mail.python.org/mailman/listinfo/python-list
pythonwx with database starting point
Hi, I am looking for some example code or open source project that involves pythonwx and a database. I am wanting to store images and data on the filesystem and transmit thumbnailed images and subsets of records to the web using xmlrpc preferably. I am wanting the application to be able to be run as an exe from a local Windows machine. I would appreciate links to any existing material that could assist me in getting started with some code. Many thanks. Regards, David -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
Diez B. Roggisch wrote: I understand that this is a very peculiar use of classmethods but is this error intentional? Or did I completely missed the point somewhere? A little bit: classmethods are defined in a class context. def foo(cls): print cls class A: foo = classmethod(foo) The error you observe seems to be a result of your abuse of classmethod outside a class scope. Not necessarily: def foo(cls): print cls f=classmethod(foo) class A: pass A.f = f a=A() a.f() This works. Anyway, the confusion starts from the documentation of classmethod(). Since classmethod is a *function* of builtins we can invoke it as such from wherever we want. Moreover the documentation sais that if the first argument is an instance, its class will be used for the classmethod. OTOH, class scope is not a real thing in python. It is just some code which is executed and then we get its locals and use it on Class(localsDict, BasesTuple, ClassName) to make a new class, it seems. So we can create a classmethod in any scope and then just attach it to a class's dictionary. jf -- http://mail.python.org/mailman/listinfo/python-list
Will presentations at PyCon be recorded/streamed?
Howdy, I sure hope so. I don't get around much, so I love to be able to hear what I'm missing. I bet lots of folks would appreciate audio/video download/stream. Though video may be prefered, I've found that listening to a Powerpoint presentation is fine. Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Logging global assignments
I am dealing with an application which reads in configurations by calling (a wrapper around) execfile. Any configuration file may itself execfile other configuration files in the same manner. I would like to create a log containing all global assignments made in these files. Comparing the globals dictionaries before and after is not quite enough, as a) this misses multiple assignments to the same name, within a single file, b) doesn't allow me to pinpoint the line at which the assignment is made. Inspecting the implementation of execfile suggests to me that the assignments are performed by a hard-wired call to PyDict_SetItem, in the opcode implementations, so it looks like ideas based on giving execfile a globals dictionary with an instrumented __setitem__ are probably doomed to failure. Is there any way of injecting some of my code into the process of global name binding, or some other means of capturing global assignments ? -- http://mail.python.org/mailman/listinfo/python-list
Re: injecting set into 2.3's builtins?
Stephen Thorne [EMAIL PROTECTED] wrote: I have: try: set except NameError: from sets import Set as set in my code in a few places. Is there any reason to prefer this over the idiom I have: if sys.version_info (2, 4): from sets import Set as set ? (I've also used the same kind of trick to provide enumerate when a script is being run with pre-2.3.) -- \S -- [EMAIL PROTECTED] -- 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
Not necessarily: def foo(cls): print cls f=classmethod(foo) class A: pass A.f = f a=A() a.f() Ahhh, yes, I see the minor difference - I didn't recognize it before. This works. Anyway, the confusion starts from the documentation of classmethod(). Since classmethod is a *function* of builtins we can invoke it as such from wherever we want. Sure. AFAIK it is actually a descriptor. From what I understand, when calling a descriptor on an instance it will invoke it's __get__ method and pass the instance as first argument. So classmethod just gets the __class__ from that argument and passes it to its callable together with the rest of the arguments. But this magic seems only to work if the descriptor has been fetched from a classes __dict__, not the instance __dict__. Hmm. Nice. Moreover the documentation sais that if the first argument is an instance, its class will be used for the classmethod. OTOH, class scope is not a real thing in python. It is just some code which is executed and then we get its locals and use it on Class(localsDict, BasesTuple, ClassName) to make a new class, it seems. So we can create a classmethod in any scope and then just attach it to a class's dictionary. I'd still call the code executed inside a class statement block a scope - for example in a def-statement the scope is the current frame of execution, so def foo(): bar = baz makes the bar part of the frames local variables. Scopes just exchange or stack the dicts for name lookup. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: (Newbie) Restricting inherited methods to operate on element from same subclass
Assuming that A is a new-style class then if they have to be exactly the same type compare the types Ah-ha! I didn't know that. if the 'other' value can be a subclass of self: def join(self, other): if not isinstance(other, type(self)): raise whatever Simple and neat! If A is an old-style class then you would have to compare the __class__ attribute: self.__class__ != other.__class__ That answered my question perfectly. I'll read up on the new style classes and pick whichever of your solutions fits best. Many thanks, Andy. -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.4.1, release candidate 1
Hi, The new installer worked fine for me (WinXP1), but I wasn't sure if I could install over the old version and have it work properly / remove the old version from the 'Add / remove programs' list. It suggested a default location on the C: drive but the old version was installed on the D: drive (and that's where I want it to be installed). When I pointed it to the old location it didn't complain about the old files, but didn't give me an indication either of going to do an update. So I got confused and uncertain. I decided to remove the old Python2.4 first, then reboot and reinstall. (Is reboot really needed?) And then afterwards it did complain about seeing files still in the D:\Python24 directory. Perhaps nicer if the installer could give feedback like 'Old installation found; will update to new version' or something like that. But that can be for 2.4.2 or a later time. cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
a RegEx puzzle
I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. In each string I want to find the longest continuous stretch of pairs whose first character is 'x' and the second is either mark. So if marks = '/xx/xxx///', the winning stretch begins at position 2 and is 6 characters long ('x/xxx/'), which requires finding a second match that overlaps the first match (which is just 'xx' in position 1). (When there are multiple winning stretches, I might want to adjudicate among them, but that's a separate problem.) I hope this is clear enough. Here's the best I've come up with so far: pat = sre.compile('(x[x/])+') (longest, startlongest) = max([(fnd.end()-fnd.start(), fnd.start()) for i in range(len(marks)) for fnd in pat.finditer(marks,i)]) It seems to work, but it's not very smart. Given the string '//xx//', it returns a list whose first seven tuples are all '(2,6)', followed by a single '(2,7)', which gets returned because of max's secondary attention to the second element in the tuple. In other words this code searches from position 0 and finds (2,6), then searches from position 1 and finds (2,6) . . . Obviously it ought to adjust the second argument to pat.finditer according to what it finds, instead of blindly stepping. (By the way, I can't give 'range' a stepsize of 2 because the winning stretch could begin with an odd-numbered character.) That sounds like a job for a generator. But (1) I haven't been able to work out the details (I'm even shakier on generators than I am on regexes!) and (2) that *seems* likely to be less efficient, maybe by a large enough factor that the obnoxiousness of getting the first search-return seven times is something I should just swallow. What magic am I missing? Charles Hartman Professor of English, Poet in Residence http://cherry.conncoll.edu/cohar http://villex.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Wishlist item: itertools.flatten
On 11 Mar 2005 13:32:45 +0200, rumours say that Ville Vainio [EMAIL PROTECTED] might have written: For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): [1,2,[3,hello,[[4 - [1, 2, 3, 'hello', 4] One such implementation is at http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2302348 but something like this would be handy in itertools as well. It seems trivial, but I managed to screw up several times when trying to produce my own implementation (infinite recursion). See Python Library Reference, 5.16.3 Recipes. Now that all and any (also presented as recipes there) are considered to be included, perhaps flatten gets a chance too. This is just a personal opinion, but I detest restraints on library (itertools module in this case) expansion when talking about such useful *building blocks*. What happened to batteries included? -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
hotshot ??
(I asked this a day or two ago; if there was an answer, I missed it. Anybody using hotshot?) I've used profile before, but wanted to get more information so I thought I'd try hotshot instead. It works fine when used like profile. But when I run it using this line, prof = hotshot.Profile('ScanHot.prof', lineevents=1) though it runs all right, when I try to load the resulting file I get this: hs = hotshot.stats.load(ScanHot.prof) Traceback (most recent call last): File stdin, line 1, in ? File /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/hotshot/stats.py, line 12, in load return StatsLoader(filename).load() File /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/hotshot/stats.py, line 51, in load assert not self._stack AssertionError --which I don't understand. (The program is a GUI one using wxPython 2.5, running from within the WingIDE on a Mac under OS 10.3.8, if any of that makes a difference. Nothing there prevents hotshot from loading a file that's been made without the lineevents=1 argument.) Charles Hartman Professor of English, Poet in Residence http://cherry.conncoll.edu/cohar http://villex.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging global assignments
Jacek Generowicz wrote: I am dealing with an application which reads in configurations by calling (a wrapper around) execfile. Any configuration file may itself execfile other configuration files in the same manner. I would like to create a log containing all global assignments made in these files. Comparing the globals dictionaries before and after is not quite enough, as a) this misses multiple assignments to the same name, within a single file, b) doesn't allow me to pinpoint the line at which the assignment is made. Inspecting the implementation of execfile suggests to me that the assignments are performed by a hard-wired call to PyDict_SetItem, in the opcode implementations, so it looks like ideas based on giving execfile a globals dictionary with an instrumented __setitem__ are probably doomed to failure. Is there any way of injecting some of my code into the process of global name binding, or some other means of capturing global assignments ? Suggestion: Use ConfigParser to set your globals instead and you can track your assignments over each file, section and option in the file. Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging global assignments
Larry Bates [EMAIL PROTECTED] writes: Suggestion: Use ConfigParser to set your globals instead and you can track your assignments over each file, section and option in the file. I would dearly love to go down this sort of route but, unfortunately, they are not _my_ configuration files, and it is not _my_ configuration mechanism ... it's just the one I have to work with. I do not have the freedom to change it; I merely have to try to make some sense out of it :-( -- http://mail.python.org/mailman/listinfo/python-list
Re: Will presentations at PyCon be recorded/streamed?
[EMAIL PROTECTED] wrote: Howdy, I sure hope so. I don't get around much, so I love to be able to hear what I'm missing. I bet lots of folks would appreciate audio/video download/stream. Though video may be prefered, I've found that listening to a Powerpoint presentation is fine. Thanks, Kent A team of volunteers is planning to try and make audio recordings available under a Creative Commons license. Speakers should shortly be receiving an email asking them to agree to this license (though it will NOT be mandatory), and we hope to publish the audio via www.python.org. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging global assignments
Jacek Generowicz wrote: Inspecting the implementation of execfile suggests to me that the assignments are performed by a hard-wired call to PyDict_SetItem, in the opcode implementations, so it looks like ideas based on giving execfile a globals dictionary with an instrumented __setitem__ are probably doomed to failure. For Python 2.4 here is evidence against that assumption: $ cat config.py a = 42 b = so what class Dict(dict): ... def __setitem__(self, k, v): ... print k, -, v ... dict.__setitem__(self, k, v) ... execfile(config.py, Dict()) a - 42 b - so what We are all doomed to succeed, then... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: PyAsm
I haven't checked PyPy out lately. I was under the impression the Pyrex/C backend was still doing static compilation. Guess I'll have to take a look. -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
Charles Hartman [EMAIL PROTECTED] wrote: I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. One possibility is to cheat completely, and depending on memory constraints and how often you need to do this, it might even make sense to do so. There's only two possible values for each character, so you're really dealing with binary numbers. The max length is 12 characters (I'm deliberately being oblivious to where you said about :-)), so there are only 2^12 or 4096 possible strings. You could probably afford to pre-compute all 4096 strings, use them as dictionary keys, and store a (start, end) tuple for each key. Computation then becomes a simple dictionary lookup. In each string I want to find the longest continuous stretch of pairs whose first character is 'x' and the second is either mark. So if marks = '/xx/xxx///', the winning stretch begins at position 2 and is 6 characters long ('x/xxx/'), which requires finding a second match that overlaps the first match (which is just 'xx' in position 1). (When there are multiple winning stretches, I might want to adjudicate among them, but that's a separate problem.) I hope this is clear enough. Unfortunately, no, it's not very clear. In fact, I have no clue what you're trying to do. Could you try explaining it again? Charles Hartman Professor of English, Poet in Residence Hmmm. Are you, by any chance, looking for meter patterns in verse? -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
Diez B. Roggisch wrote: Moreover the documentation sais that if the first argument is an instance, its class will be used for the classmethod. OTOH, class scope is not a real thing in python. It is just some code which is executed and then we get its locals and use it on Class(localsDict, BasesTuple, ClassName) to make a new class, it seems. So we can create a classmethod in any scope and then just attach it to a class's dictionary. I'd still call the code executed inside a class statement block a scope - for example in a def-statement the scope is the current frame of execution, so def foo(): bar = baz Absolutely. In fact here is another interesting case which can lead to nice recipies: class B: print Making class B! if blah: def f(self): print self else def f(self): raise StopIteration print My locals are:,locals(),and I will make a class from them makes the bar part of the frames local variables. Scopes just exchange or stack the dicts for name lookup. Well, actually, to put things right, in python there are only *two* real scopes: global scope and local scope. I remember that when I was a newbie I was confused by this. The thing is that there is no nesting of scopes in reality. Just to help other newbies avoid the confusion, I believe it would be better to say, from the start, that: - There definitelly is no nesting of scopes for if/for/while/try blocks. - There is no nesting of scopes when nested functions reference stuff from the enclosing function. It looks like there is but there isn't because then we should be able to say: exec some code in locals(), cellvars(), globals() which we can't and proves that referencing variables from the enclosing function is indeed a questionable feature. It all happens because the parser detects that there are variables with that name in the enclosing functions and creates special cellvars... - No nesting of scopes for classes because we *have* to use 'self' (which is a good thing IMHO). jf -- http://mail.python.org/mailman/listinfo/python-list
Re: Will presentations at PyCon be recorded/streamed?
Steve Holden wrote: [EMAIL PROTECTED] wrote: Howdy, I sure hope so. I don't get around much, so I love to be able to hear what I'm missing. I bet lots of folks would appreciate audio/video download/stream. Though video may be prefered, I've found that listening to a Powerpoint presentation is fine. Thanks, Kent A team of volunteers is planning to try and make audio recordings available under a Creative Commons license. Speakers should shortly be receiving an email asking them to agree to this license (though it will NOT be mandatory), and we hope to publish the audio via www.python.org. I would not be easily forgiven for failing to point to http://www.python.org/moin/PyConDC2005/TalkRecording which holds the current plans. If anyone else is interested in getting involved I'm sure the existing team would welcome additional help. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging global assignments
In 2.4 at least, it looks like execfile can take an arbirary mapping object for globals, so something like this may work: class LoggedDict(dict): def __setitem__(self, item, val): dict.__setitem__(self, item, val) # Do whatever logging is needed here print Assignment made: %s = %r % (item, val) # When loading your config file use: logged_globals = LoggedDict() execfile(my_config_file, logged_globals) Note that this covers all name binding (ie. function and class definitions etc), not just assignments. This might not work with earlier versions of python, since I think these may restrict the globals argument to a real dictionary. -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
On Fri, 11 Mar 2005 01:24:59 +0100, rumours say that Patrick Useldinger [EMAIL PROTECTED] might have written: Have you found any way to test if two files on NTFS are hard linked without opening them first to get a file handle? No. And even then, I wouldn't know how to find out. MSDN is our friend for Windows stuff. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/createhardlink.asp and then http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/getfileinformationbyhandle.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/by_handle_file_information_str.asp The relevant parts from this last page: st_dev - dwVolumeSerialNumber st_ino - (nFileIndexHigh, nFileIndexLow) -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Marcin Ciura wrote: None of the more efficient solutions is particularly straightforward, either: result = [] for x in seq: result.append(fn(x)) print ''.join(result) print ''.join([fn(x) for x in seq]) print ''.join(fn(x) for x in seq) Moreover, all of them require creating one or two temporary objects to hold the entire result. If the programmers use one of them without qualms, it is only because their mind is warped by the limitation of print. I can't say I lose much sleep over this, but you could add my preferred workaround to the list (I don't believe it suffers from the same drawbacks as the options you propose) and say why your comma solution is better than it: import sys def nospace(value, stream=None): '''Suppress output of space before printing value''' stream = stream or sys.stdout stream.softspace = 0 return str(value) print a, nospace(b) ab def fn(x): return %s % x for i in range(10): print nospace(fn(i)), 0123456789 -- http://mail.python.org/mailman/listinfo/python-list
Re: help with warning formatting
import warnings warnings.warn('foo') % python t.py t.py:2: UserWarning: foo warnings.warn('foo') Is there a way to just issue the warning message itself, or to at least suppress printing the line where the warning occurred ( warnings.warn('foo') in the example)? In case anyone else is searching for a solution to this the following sort of works in Python 2.1: warnings.warn_explicit('foo', UserWarning, '', '') :: UserWarning: foo I'm new to Python so if there is a better way to do this please let me know. Jasmin -- http://mail.python.org/mailman/listinfo/python-list
executing non-Python conde
I need to repeatedly execute an .exe program, changing the command line arguments, and log the output. My search of Python documentation and O'Reilly texts hasn't uncovered how I do this. Both exec and execfile seem to only run Python code. Also, neither seem to be able to pass parameters. (Although there is a reference to global and local dictionaries that I don't understand.) Surely there is a way to do this! Earl Eiland -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
On Fri, 11 Mar 2005 01:12:14 +0100, rumours say that Patrick Useldinger [EMAIL PROTECTED] might have written: On POSIX filesystems, one has also to avoid comparing files having same (st_dev, st_inum), because you know that they are the same file. I then have a bug here - I consider all files with the same inode equal, but according to what you say I need to consider the tuple (st_dev,ST_ium). I'll have to fix that for 0.13. I have a bug here too-- I wrote st_inum meaning st_ino, but that would be quick to find! Thanks ;-) You are very welcome. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
wxPtyhon 2.4 non trivial problems :D
Hi to everybody :) I use Boa-constructor 0.3.1, wx 2.4 and python 2.3. I'have 2 big problems in my application : 1. My EVT_KEY_UP on wxTextCtrl works only when mouse pointer is on the active window. If i'll move it outside the window (with no clicking) it doesn't work. And if i move mouse pointer back on the window - it works. Anyone know why??? 2. My application is divided into few sections. I want to create each window only once - on first visit, because creating a window takes a 80% of time needed to open it (about 6 seconds on a middle-sized window). I did a construction which allows to do this and which destroys all windows on exiting to another section of program. Here is my solution : from wxPython.wx import * from wxPython.lib.maskededit import * from wxPython.lib.maskednumctrl import * ... window = None // variable which has a object inside (its not destroyed after a closing a window oldparent = None // it helps me to check do i have to recreate a window with new parent def ShowMyWindow(parent): //this function shows my window. And creates it if needed global window,oldparent if oldparentparent: oldparent = parent window = create(parent) window.Inicialize(parent)// it does some things to window - sets accelerator table, sets fonts,loads data and such window.SetTitle(' My window') window.MakeModal(True) window.Show() And i close my window with : def OnMyWindowClose(self, event): self.Hide() self.MakeModal(FALSE) It's destroyed when a parent is destroyed. It looks simple. Now my problem :D I can create a chains of windows. They are all destroyed when the parent of the first of them is being destroyed. I want to create tree : Parent | Child1 | Child2 Where parent is created and destroyed on open/close and children are created once and destroyed with parent. When i open a child1 and close it - it stays created, and if i open it second time it opens faster and works properly. It happens with second child too. Problem appears when i : open first child, open second child and close both. Then they both exist and child1 is parent of child2. After that if i open child1 it works properly, but opening of child2 results with some kind of inactivity of it. It's losing focus on all application and is inactive in strange way. My tests told me that both windows exist. Can anyone can help me? It's really important to me... Thanks for answers Michal -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPRequestHandler handling long lasting requests problem
Sorry for questioning Python :-) - it turned out that this is a problem with Mozilla. For some reason it holds up with opening second connection to given host until the previous one is completed. Interestingly enough, IE works better with Python multi threaded server in that regard. Thx, A. -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
Charles Hartman [EMAIL PROTECTED] wrote: I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. One possibility is to cheat completely, and depending on memory constraints and how often you need to do this, it might even make sense to do so. Interesting -- I hadn't thought of that. It would, realistically, probably be 2 ** 14 or so, but what the hell. Trouble is, this would require me to pick out by hand/eye -- once only, admittedly -- something like 16,384 longests, which I do not care to do. If I can compute them, instead, there's no reason not to do it on the fly; it doesn 't take *that* long. There's only two possible values for each character, so you're really dealing with binary numbers. The max length is 12 characters (I'm deliberately being oblivious to where you said about :-)), so there are only 2^12 or 4096 possible strings. You could probably afford to pre-compute all 4096 strings, use them as dictionary keys, and store a (start, end) tuple for each key. Computation then becomes a simple dictionary lookup. In each string I want to find the longest continuous stretch of pairs whose first character is 'x' and the second is either mark. So if marks = '/xx/xxx///', the winning stretch begins at position 2 and is 6 characters long ('x/xxx/'), which requires finding a second match that overlaps the first match (which is just 'xx' in position 1). (When there are multiple winning stretches, I might want to adjudicate among them, but that's a separate problem.) I hope this is clear enough. Unfortunately, no, it's not very clear. In fact, I have no clue what you're trying to do. Could you try explaining it again? See below. Charles Hartman Professor of English, Poet in Residence Hmmm. Are you, by any chance, looking for meter patterns in verse? Yes, of course. My program that scans iambic pentameters (Scandroid, ver. 0.2a) is available (GPL) on the Programs page of my site listed below. It pretty much works, which is interesting. (People who know how to do this generally don't believe a program can do it.) I'm a week or two (knock on wood) from version 1.0, which handles anapestic meters as well, and non-pentameter lengths, and do other stuff. I'm not sure which part of my explanation wasn't clear. The string ('/' and 'x' only) will ultimately be divided into groups of one, two, three, or four marks, by many complex operations. One approach to the whole task (an approach I just discovered a month or two ago, which supplements a more chunk-by-chunk method) is to look for the longest substring within that string of (perhaps) 10 or twelve mrks, of which the following is true: if the substring is divided into pairs, each pair consists of a 'x' followed by either a 'x' or a '/'. The general problem is to the find the longest possible substring matching an sre specfication -- and a general solution to that doesn't seem to be obvious, though the need for it must arise often enough. What I want is code (a line, a function . . .) that returns the beginning-point and length of that longest substring. (I could ask for the substring itself; it doesn't matter; the information sought will be some subset of the information supplied with every sre match object.) For my current best solution, see previous message. Hope this is any clearer. Charles Hartman Professor of English, Poet in Residence http://cherry.conncoll.edu/cohar http://villex.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Duncan Booth wrote: import sys def nospace(value, stream=None): '''Suppress output of space before printing value''' stream = stream or sys.stdout stream.softspace = 0 return str(value) I'm teaching Python as the first programming language to non-computer scientists. Many of the toy programs would be simpler with the double comma syntax. Presently, having a choice whether to teach my students the result += fn(x) way or your way, I would still opt for the former. Best regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: executing non-Python conde
On Fri, 11 Mar 2005 07:36:03 -0700, Earl Eiland [EMAIL PROTECTED] wrote: I need to repeatedly execute an .exe program, changing the command line arguments, and log the output. http://docs.python.org/lib/module-subprocess.html -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
PEP 309 (Partial Function Application) Idea
Random idea of the day: How about having syntax support for currying/partial function application, like this: func(..., a, b) func(a, ..., b) func(a, b, ...) That is: 1) Make an Ellipsis literal legal syntax in an argument list. 2) Have the compiler recognize the Ellipsis literal and transform the function call into a curried/parially applied function. So the compiler would essentially do something like this: func(a, ...) == curry(func, a) func(..., a) == rightcurry(func, a) func(a, ..., b) == rightcurry(curry(func,a), b) I haven't though this through much, and I'm sure there are issues, but I do like the way it looks. The ... really stands out as saying something is omitted here. Chris Perkins -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Marcin Ciura wrote: Here is a pre-PEP about print that I wrote recently. Please let me know what is the community's opinion on it. Cheers, Marcin PEP: XXX Title: Print Without Intervening Space Version: $Revision: 0.0 $ Author: Marcin Ciura marcin.ciura at polsl.pl Status: Draft Type: Standards Track Created: 11-Mar-2005 Post-History: 11-Mar-2005 Abstract This PEP proposes to extend the syntax of the print statement so that its space-insertion mechanism can be selectively disabled by using double instead of single commas. Rationale The print statement can write several expressions in one line, but presently always separates them with spaces. While this behaviour is often desirable, not uncommon are situations, where programmers have to use workarounds to achieve a non-spaced display. This has been recognized as one of Python Gotchas [1]. Even the simplest workaround results in an unnecessarily complicated code (for the sake of simplicity let us assume that fn() returns strings): result = '' for x in seq: result += fn(x) print result Not to mention it also has a terrible algorithmic complexity. None of the more efficient solutions is particularly straightforward, either: result = [] for x in seq: result.append(fn(x)) print ''.join(result) print ''.join([fn(x) for x in seq]) print ''.join(fn(x) for x in seq) Moreover, all of them require creating one or two temporary objects to hold the entire result. If the programmers use one of them without qualms, it is only because their mind is warped by the limitation of print. Using write() is not especially appealing either, especially if the print statements are used elsewhere in the code: import sys for x in seq: sys.stdout.write(fn(x)) print # or sys.stdout.write('\n') The proposed extension to the print statement is to use two commas to signal that no space should be written after an expression: for x in seq: print fn(x),, print To quote The Zen of Python [2]: Beautiful is better than ugly. Simple is better than complex. Readability counts. The proposal applies also to the expressions in the middle of the print statement. Thus it provides an alternative to string concatenation and string interpolation, either with the '%'-based specifiers, or with the '$'-based ones introduced by PEP 292 [3], not requiring creating a temporary string object: print 'The phone number is (',,extension,,')', number,,'.' Note that I do not claim that the above version is any more readable than print 'The phone number is (%s) %s.' % (extension, number) Specification It is proposed to allow separating the expressions to be printed by single or double commas, and to allow single or double commas at the end of the print statement. The two commas shall be consecutive, i.e. there shall be no whitespace between them. Non-consecutive commas or any sequence of more than two commas constitute a syntax error. In the print chevron form of the statement, the name of the file object shall be separated from the next expression only by a single comma, as it is now. Formally, the proposed syntax of the extended print statement is print_stmt: print ( [expression ((, | ,,) expression)* [, | ,,]] | expression [(, expression ((, | ,,) expression)* [, | ,,]] Implementing the proposed syntax may require introducing a new type of token: double comma, or a hack in the parser to recognize two consecutive commas in the context of the print statement. Two new byte codes, parallel to PRINT_ITEM and PRINT_ITEM_TO, are needed to implement the semantics of the proposal. Discussion Pros: - The proposed semantics allows avoiding temporary string objects during the execution of the print statement and often makes for more readable and explicit source code. - The proposed syntax is easy to learn for the beginners. - It breaks no existing Python code. - Mistakes are unlikely to happen with the proposed syntax, unless someone has problems with his typing or his keyboard, in which case any programming is difficult, anyway. Cons: - Wrapper functions around print will be unable to mimic its syntax. It is, however, impossible even now, due to trailing commas. - In PEP 259 [4], the BDFL has pronounced that he wants to avoid any more tinkering with print. - PEP 3000 [5] and Python Regrets [6] state that the print statement is to be replaced with a function
Re: executing non-Python conde
Earl Eiland wrote: I need to repeatedly execute an .exe program, changing the command line arguments, and log the output. My search of Python documentation and O'Reilly texts hasn't uncovered how I do this. Both exec and execfile seem to only run Python code. Also, neither seem to be able to pass parameters. (Although there is a reference to global and local dictionaries that I don't understand.) Surely there is a way to do this! Earl Eiland os.system() or win32process.CreateProcess() depending on how much control you want and/or if it is a Windows GUI .exe. Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: executing non-Python conde
Earl Eiland wrote: I need to repeatedly execute an .exe program, changing the command line arguments, and log the output. My search of Python documentation and O'Reilly texts hasn't uncovered how I do this. Both exec and execfile seem to only run Python code. Also, neither seem to be able to pass parameters. (Although there is a reference to global and local dictionaries that I don't understand.) Surely there is a way to do this! Earl Eiland Yes. os.popen, popen.popen{2,3,4}, os.system, ... take your pick! regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Larry Bates wrote: I fail to see why your proposed solution of: for x in seq: print fn(x),, print is clearer than: print ''.join([fn(x) for x in seq]) Thank you for your input. The latter form is fine with me personally, but you just can't explain it to complete novices. My proposal aims at making programming easier for them. Also your statement: print 'The phone number is (',,extension,,')', number,,'.' requires three double commas and can already be written more clearly as: print 'The phone number is ('+extension+') '+number'.' I agree with you in this point (if extension and number are strings). Best regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
smtplib / solaris (newbie problem?)
I've good luck with this on a Linux system (foolproof), and now I'm trying to get the same thing to run on a Solaris box. pythonpath, or env or..? Any help much appreciated. Thanks Chuck Python 2.3.2 (#1, Oct 17 2003, 19:06:15) [C] on sunos5 Type help, copyright, credits or license for more information. import smtplib host=localhost server = smtplib.SMTP(host) Traceback (most recent call last): File stdin, line 1, in ? File /usr/local/lib/python2.3/smtplib.py, line 240, in __init__ (code, msg) = self.connect(host, port) File /usr/local/lib/python2.3/smtplib.py, line 302, in connect raise socket.error, msg socket.error: (146, 'Connection refused') -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
Christos TZOTZIOY Georgiou wrote: The relevant parts from this last page: st_dev - dwVolumeSerialNumber st_ino - (nFileIndexHigh, nFileIndexLow) I see. But if I am not mistaken, that would mean that I (1) had to detect NTFS volumes (2) use non-standard libraries to find these information (like the Python Win extentions). I am not seriously motivated to do so, but if somebody is interested to help, I am open to it. -pu -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
David Eppstein wrote: You need do no comparisons between files. Just use a sufficiently strong hash algorithm (SHA-256 maybe?) and compare the hashes. That's not very efficient. IMO, it only makes sense in network-based operations such as rsync. -pu -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
On Fri, 11 Mar 2005 10:00:03 -0600, Larry Bates [EMAIL PROTECTED] wrote: I also don't miss a no-space option on print. I've always believed that print statements with commas in them were for simple output with little or no regard for formatting (like for debugging statements). If I want precisely formatted output I use '%' formats or I build the output line manually with joins or some other mechanism. The ''.join(seq) or ''.join([fn(x) for x in seq]) says exactly what is being done to create the output string. I agree with everything said here. Furthermore, I don't like this PEP because it introduces magic. When reading code, you just need to magically know what the double-comma does in a print statement. Yes, there are bits of magic involved in the solutions that already exist, but I am opposed to the introduction of more. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
Charles Hartman wrote: pat = sre.compile('(x[x/])+') (longest, startlongest) = max([(fnd.end()-fnd.start(), fnd.start()) for i in range(len(marks)) for fnd in pat.finditer(marks,i)]) If I'm understanding that correctly, the only way for you to get different best matches are at offsets 0 and 1; offset 2 will yield the same matches as 0, with the possibility of excluding the first two characters -- i. e. any different matches should be guaranteed to be shorter. Therefore ... for i in range(2) ... instead of ... for i in range(len(marks)) ... should be sufficient. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: shuffle the lines of a large file
Simon Brunning wrote: I couldn't resist. ;-) Me neither... import random def randomLines(filename, lines=1): selected_lines = list(None for line_no in xrange(lines)) for line_index, line in enumerate(open(filename)): for selected_line_index in xrange(lines): if random.uniform(0, line_index) 1: selected_lines[selected_line_index] = line return selected_lines This has the advantage that every line had the same chance of being picked regardless of its length. There is the chance that it'll pick the same line more than once, though. The idea is simple: have a chain of pickers that pass all items that are not picked on to the next picker. The current implementation, however, may hit the recursion limit for large samples. import random class PickOne(object): Pick a random item from an iterable and store it in the 'picked' attribute. As an iterator, yield all items that are not picked. Helper for the pick() function. def __init__(self, iterable): self.iterable = iterable def __iter__(self): it = enumerate(self.iterable) index, self.picked = it.next() for index, item in it: if random.uniform(0, index) 1: yield self.picked self.picked = item else: yield item def pick(iterable, N, accept_less=False): Pick N random items from an iterable. # Set up the PickOne(PickOne( ... PickOne(iterable) ... )) chain keepers = [] for i in xrange(N): iterable = PickOne(iterable) keepers.append(iterable) # We are interested in the side effects, i. e. the PickOne instances # picking random items from the initial iterable for item in iterable: pass # The following could be # return [k.picked for k in keepers] # but we want to handle the case len(iterable) N, too result = [] for keeper in keepers: try: picked = keeper.picked except AttributeError: if accept_less: return result raise ValueError(sequence contains less items than shall be picked) result.append(picked) return result def demo(): Pick random lines from a set of files. import optparse from itertools import chain, izip, repeat, count parser = optparse.OptionParser() parser.usage = (%prog [nl] file1 file2 ... fileN\n\n Choose random lines from files given on the command line.) parser.add_option(-n, --count, type=int, default=10, help=number of lines that shall be picked (default=10)) parser.add_option(-l, --less, action=store_true, help=accept less picked lines than specified, if there are less total lines in the file(s)) options, args = parser.parse_args() index_name_line = chain(*[izip(count(), repeat(fn), file(fn)) for fn in args]) try: picked = pick(index_name_line, options.count, options.less) except ValueError: raise SystemExit(Cannot pick more lines than found in the file(s)) print .join([(%3d %s %s % ifl) for ifl in picked]) if __name__ == __main__: demo() -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
jfj schreef: Diez B. Roggisch wrote: I understand that this is a very peculiar use of classmethods but is this error intentional? Or did I completely missed the point somewhere? Note that this is not really related to classmethods. A similar problem exists if you want to use an ordinary function as a method: def g(self): print argument: + str(self) class A(object): pass a=A() a.x = g a.x function g at 0x00B9F070 Here you see that none of the class magic has been performed; a.x is *not* a method, but an ordinary function. It has absolutely no relation to / knowledge of the class that a belongs to. Calling a.x() leads to an exception: a.x() Traceback (most recent call last): File pyshell#53, line 1, in -toplevel- a.x() TypeError: g() takes exactly 1 argument (0 given) And of course, if you supply an argument, everything works fine: a.x(1) argument: 1 To get the method behaviour the function needs to be associated with the class: del a.x A.x = g a.x bound method A.g of __main__.A object at 0x00B93B90 a.x() argument: __main__.A object at 0x00B93B90 The mechanism is basically as follows (with thanks to Alex Martelli's execellent Python in a Nutshell, Chapter 5). When a.x is being resolved, first a.__dict__['x'] is tried. In the first case x was indeed defined in a.__dict__, and its value was returned (the function also known as g). No class magic at all. The same happened with your classmethod foo: you get a bare classmethod, and apparently these are not callable. In the second case, a.__dict__ did not have a key 'x'. The lookup then continues in a's class: A.__dict__['x']. Again it finds the function. But when a class __dict__ lookup returns a function, the result is first wrapped into a bound or unbound method object (depending on whether you arrived there via a.x or A.x). So far for *how* it works. As to *why* it works like this, I don't know for sure. But my guess is that the reasoning was something as follows: if you define a function (regular or something special like a classmethod) only for an instance of a class, you obviously don't want to use it in a class context: it is -by definition- invisible to the class, or to other instances of the same class. One possible use case would be to store a callback function. And in that case you definitely don't want the class magic to happen when you reference the function. Just my 2 cents Regards, Ruud -- '@'.join('.'.join(s) for s in (['ruud','de','jong'],['tiscali','nl'])) -- http://mail.python.org/mailman/listinfo/python-list
Re: executing non-Python conde
So where do I find win32process. It's not a builtin (at least import win32process fails) A search of python.org fails. A search of sourceforge fails. A google search brings up lots of stuff, but I didn't find the module. Earl Eiland On Fri, 2005-03-11 at 09:02, Larry Bates wrote: Earl Eiland wrote: I need to repeatedly execute an .exe program, changing the command line arguments, and log the output. My search of Python documentation and O'Reilly texts hasn't uncovered how I do this. Both exec and execfile seem to only run Python code. Also, neither seem to be able to pass parameters. (Although there is a reference to global and local dictionaries that I don't understand.) Surely there is a way to do this! Earl Eiland os.system() or win32process.CreateProcess() depending on how much control you want and/or if it is a Windows GUI .exe. Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
Christos TZOTZIOY Georgiou wrote: A minor nit-pick: `fdups.py -r .` does nothing (at least on Linux). Changed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4, distutils, and pure python packages
Martin v. Löwis [EMAIL PROTECTED] writes: Thomas Heller wrote: This means that if you build a windows installer using distutils - it *requires* msvcr7.dll in order to run. This is true even if your package is a pure python package. This means that when someone tries to use a windows installer created with Python 2.4, on a machine with only python 2.3 - it will fail. Bummer. I wonder whether it would be better to continue linking wininst.exe with mscvrt40.dll, and use that regardless of the version used to build Python. Alternatively, we could try to get rid of the C library altogether for wininst.exe. For install.c, this should be possible: it primarily uses *printf, which can be replaced with FormatMessage. The challenge, of course, is zlib. This could be replaced with lz32, but I doubt this would improve anything. Alternatively, we could load zlib.pyd from the target system, but that would be tedious, I guess. OTOH, it might to replace extract.c largely with Python source code, and run this in an interpreter... I had something similar in my mind for quite some time. zlib.pyd would be used automatically if the extraction is done in Python code - when bdist_wininst was written, Python didn't have the zipfile module. It would be for 2.5, anyway, and I have hoped that bdist_wininst would be replaced by bdist_msi then ;-). What are your plans for that? Although I'm wondering if it would be possible to run bdist_msi on linux systems for pure Python distributions - some people are doing that with bdist_wininst afaik. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
On Fri, 11 Mar 2005 08:38:36 -0500, Charles Hartman wrote: I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. In each string I want to find the longest continuous stretch of pairs whose first character is 'x' and the second is either mark. So if marks = '/xx/xxx///', the winning stretch begins at position 2 and is 6 characters long ('x/xxx/') I don't think regexes are a good match for this task. They just aren't optimized for this very well. Here's what I have, though I don't know if it's *exactly* what you want: def xCounter(s, initialOffset): offset = initialOffset count = 0 slen = len(s) while s[offset] == 'x': count = count + 1 offset += 2 if offset slen: break return count, s[initialOffset:offset] def longestRun(s): return max([xCounter(s, i) for i in range(len(s))])[1] In other words, start at all the positions and find the max, sort of by hand. (In particular, I don't know how this will handle two runs of equal size, if it will prefer the first or the last. I don't know how *you* handle that, either, so I'm not sweating it for now. If you clarify this I can help, the easiest way is to add another number into the tuple that xCounter generates for max to work on.) This is not optimized, and if you're processing millions of these, this may be too slow. What I'd suggest is that if this isn't fast enough, memoize the function, i.e., with this: longestRunResults = {} def memoizedLongestRun(s): try: return longestRunResults[s] except KeyError: pass result = longestRun(s) longestRunResults[s] = result return result You'll probably want to change the names of things to better fit. This will get you the benefits of pre-computation without paying the up-front costs (you only compute what you need, not all possible combinations), and this ought to be plenty fast to process a whole lotta data really quickly. (This is a great example of why readable code can be more important than fast code; the speedup can be added later, it's more important that you can satisfy yourself that the code is correct, and a clever algorithm might make that hard.) -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPRequestHandler handling long lasting requests problem
Andy Leszczynski wrote: Sorry for questioning Python :-) - it turned out that this is a problem with Mozilla. For some reason it holds up with opening second connection to given host until the previous one is completed. Interestingly enough, IE works better with Python multi threaded server in that regard. Thx, A. Try switching keepalives off, or falling back to HTTP 1.0 - ironically it may be the attempt to use the same connection for both pieces of content that holds things up. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
Charles Hartman wrote: I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. In each string I want to find the longest continuous stretch of pairs whose first character is 'x' and the second is either mark. So if marks = '/xx/xxx///', the winning stretch begins at position 2 and is 6 characters long ('x/xxx/'), which requires finding a second match that overlaps the first match (which is just 'xx' in position 1). (When there are multiple winning stretches, I might want to adjudicate among them, but that's a separate problem.) I hope this is clear enough. Here's the best I've come up with so far: pat = sre.compile('(x[x/])+') (longest, startlongest) = max([(fnd.end()-fnd.start(), fnd.start()) for i in range(len(marks)) for fnd in pat.finditer(marks,i)]) It's pretty simple to put re.search() into a loop where subsequent searches start from the character after where the previous one matched. Here is a solution that uses a general-purpose longest match function: import re # RE solution def longestMatch(rx, s): ''' Find the longest match for rx in s. Returns (start, length) for the match or (None, None) if no match found. ''' start = length = current = 0 while True: m = rx.search(s, current) if not m: break mStart, mEnd = m.span() current = mStart + 1 if (mEnd - mStart) length: start = mStart length = mEnd - mStart if length: return start, length return None, None pairsRe = re.compile(r'(x[x/])+') for s in [ '/xx/xxx///', '//xx//' ]: print s, longestMatch(pairsRe, s) -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
Martin v. Löwis wrote: 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.1 (release candidate 1). Python 2.4.1 is a bug-fix release. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the bugs squished in this release. I'd like to encourage feedback on whether the Windows installer works for people. It replaces the VBScript part in the MSI package with native code, which ought to drop the dependency on VBScript, but might introduce new incompatibilities. Regards, Martin Hi Martin, is there a reason why msiexec iterates through what looks like all (?) files and directories in/under the destination directory? There is massive file I/O going on there (OK, by now you know I didn't de-install 2.4 before trying ;-)) which explains the 100% CPU usage and the time it takes for the Next button to respond. -- Vincent Wehren -- http://mail.python.org/mailman/listinfo/python-list
pyparsing: parseString confusion
My understanding of parseString seems flawed: I thought the grammar must match the string in its entirety, based on the following from the howto: scanString allows you to scan through the input source string for random matches, instead of exhaustively defining the grammar for the entire source text (as would be required with parseString) However: from pyparsing import * alphas 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' word=Word(alphas) word.parseString(foo888) (['foo'], {}) I'd expect this to raise an exception. What am I missing here? -- Peter Fein [EMAIL PROTECTED] 773-575-0694 Basically, if you're not a utopianist, you're a schmuck. -J. Feldman -- http://mail.python.org/mailman/listinfo/python-list
Re: a RegEx puzzle
If I'm understand you right, then I still didn't explain clearly. (Surprise!) If the string is '//xx//' then possible matches are at position 6 and 7 (both length 2, so longest doesn't even come into it). My code searches from position 0, then 1, then 2, and so on, to catch every possible pattern and then compare them for length. You seem to be suggesting a different approach, one I hadn't thought of: explicitly test series of pairs, rather than the whole remaining string at each point, and do this just once starting at 0, and once starting at 1. That sounds as though it would work, though the regex would have to be called in a different way so as to seek non-overlapping patterns (rather than the elaborate precautions I've taken to seek overlapping ones) -- I'm not yet sure quite how, and I'm not yet clear that it's any more efficient and/or elegant than what I've got now. Hm -- lots to think about here. Thank you. Charles Hartman Professor of English, Poet in Residence http://cherry.conncoll.edu/cohar http://villex.blogspot.com pat = sre.compile('(x[x/])+') (longest, startlongest) = max([(fnd.end()-fnd.start(), fnd.start()) for i in range(len(marks)) for fnd in pat.finditer(marks,i)]) If I'm understanding that correctly, the only way for you to get different best matches are at offsets 0 and 1; offset 2 will yield the same matches as 0, with the possibility of excluding the first two characters -- i. e. any different matches should be guaranteed to be shorter. Therefore ... for i in range(2) ... instead of ... for i in range(len(marks)) ... should be sufficient. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with classmethods
jfj wrote: Diez B. Roggisch wrote: Moreover the documentation sais that if the first argument is an instance, its class will be used for the classmethod. OTOH, class scope is not a real thing in python. It is just some code which is executed and then we get its locals and use it on Class(localsDict, BasesTuple, ClassName) to make a new class, it seems. So we can create a classmethod in any scope and then just attach it to a class's dictionary. I'd still call the code executed inside a class statement block a scope - for example in a def-statement the scope is the current frame of execution, so def foo(): bar = baz Absolutely. In fact here is another interesting case which can lead to nice recipies: class B: print Making class B! if blah: def f(self): print self else def f(self): raise StopIteration print My locals are:,locals(),and I will make a class from them makes the bar part of the frames local variables. Scopes just exchange or stack the dicts for name lookup. Well, actually, to put things right, in python there are only *two* real scopes: global scope and local scope. Not strictly true. There's builtins right at the back, and nowadays inside a nested function you have a nested set of local scopes. [EMAIL PROTECTED] ~ $ cat test88.py # # Namespace testing # x = 33 y = 44 def f1(): def f2(): y = 33 print f2, x, y x = 22 print f1, x, y f2() print f1, x, y print main, x, y f1() print main, x, y [EMAIL PROTECTED] ~ $ python test88.py main 33 44 f1 22 44 f2 22 33 f1 22 44 main 33 44 [EMAIL PROTECTED] ~ I remember that when I was a newbie I was confused by this. The thing is that there is no nesting of scopes in reality. Really? Just to help other newbies avoid the confusion, I believe it would be better to say, from the start, that: - There definitelly is no nesting of scopes for if/for/while/try blocks. Correct. - There is no nesting of scopes when nested functions reference stuff from the enclosing function. It looks like there is but there isn't because then we should be able to say: exec some code in locals(), cellvars(), globals() which we can't and proves that referencing variables from the enclosing function is indeed a questionable feature. It all happens because the parser detects that there are variables with that name in the enclosing functions and creates special cellvars... I believe you are coinfusing restrictions on exec syntax with restrictions on namespace nexting. - No nesting of scopes for classes because we *have* to use 'self' (which is a good thing IMHO). regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing: parseString confusion
I've notice the same thing. It seems that it will return as much as it can that matches the grammar and just stop when it encounters something it doesn't recognize. -- http://mail.python.org/mailman/listinfo/python-list
Re: executing non-Python conde
Earl Eiland wrote: So where do I find win32process. It's not a builtin (at least import win32process fails) A search of python.org fails. A search of sourceforge fails. A google search brings up lots of stuff, but I didn't find the module. Earl Eiland [...] http://starship.python.net/crew/mhammond/ google-is-your-friend-ly y'rs - steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Will presentations at PyCon be recorded/streamed?
Is there an official procedure for signing up for presenting a Lightning Talk, except for editing the PyCon05 Wiki page? Grig -- http://mail.python.org/mailman/listinfo/python-list
Pygame - jerky motion
Hi- just installed pygame, not sure where to go for some help. I am on Fedora 3 running an ATI card but without the GL drivers installed. When I run any of the examples they work fine but they are very jerky. The animation is smooth for a few seconds and then the entire thing pauses for a heartbeat and then it goes on, pause, move, pause, move etc. Any ideas about what's up? (This is the same in fullscreen or running as a window) -- http://mail.python.org/mailman/listinfo/python-list
RE: Will presentations at PyCon be recorded/streamed?
Title: RE: Will presentations at PyCon be recorded/streamed? [Grig Gheorghiu] #- Is there an official procedure for signing up for presenting a #- Lightning Talk, except for editing the PyCon05 Wiki page? Don't know. I just edited it today and a mail was generated automatically to some people... . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
RE: hotshot ??
Charles Hartman wrote: (I asked this a day or two ago; if there was an answer, I missed it. Anybody using hotshot?) I've used profile before, but wanted to get more information so I thought I'd try hotshot instead. It works fine when used like profile. But when I run it using this line, prof = hotshot.Profile('ScanHot.prof', lineevents=1) though it runs all right, when I try to load the resulting file I get this: hs = hotshot.stats.load(ScanHot.prof) Traceback (most recent call last): File stdin, line 1, in ? File /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/hotshot/stats.py, line 12, in load return StatsLoader(filename).load() File /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/hotshot/stats.py, line 51, in load assert not self._stack AssertionError --which I don't understand. (The program is a GUI one using wxPython 2.5, running from within the WingIDE on a Mac under OS 10.3.8, if any of that makes a difference. Nothing there prevents hotshot from loading a file that's been made without the lineevents=1 argument.) Sounds like you're hitting a known bug: http://sourceforge.net/tracker/index.php?func=detailaid=900092group_id =5470atid=105470 Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Pygame - jerky motion
donn wrote: Hi- just installed pygame, not sure where to go for some help. I am on Fedora 3 running an ATI card but without the GL drivers installed. When I run any of the examples they work fine but they are very jerky. The animation is smooth for a few seconds and then the entire thing pauses for a heartbeat and then it goes on, pause, move, pause, move etc. Any ideas about what's up? (This is the same in fullscreen or running as a window) Well, I have since compiled and run some SDL demos (not Python, but c) and they also jerk and pause, so I'm guessing it's an SDL/Fedora/my card thing and not Pygame at all. F.I.Y I suppose :) -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] a program to delete duplicate files
In article [EMAIL PROTECTED], Patrick Useldinger [EMAIL PROTECTED] wrote: You need do no comparisons between files. Just use a sufficiently strong hash algorithm (SHA-256 maybe?) and compare the hashes. That's not very efficient. IMO, it only makes sense in network-based operations such as rsync. Well, but the spec didn't say efficiency was the primary criterion, it said minimizing the number of comparisons was. More seriously, the best I can think of that doesn't use a strong slow hash would be to group files by (file size, cheap hash) then compare each file in a group with a representative of each distinct file found among earlier files in the same group -- that leads to an average of about three reads per duplicated file copy: one to hash it, and two for the comparison between it and its representative (almost all of the comparisons will turn out equal but you still need to check unless you use a strong hash). I'm assuming of course that there are too many files and/or they're too large just to keep them all in core. Anyone have any data on whether reading files and SHA-256'ing them (or whatever other cryptographic hash you think is strong enough) is I/O-bound or CPU-bound? That is, is three reads with very little CPU overhead really cheaper than one read with a strong hash? I guess it also depends on the number of files you expect to have duplicates of. If most of the files exist in only one copy, it's clear that the cheap hash will find them more cheaply than the expensive hash. In that case you could combine the (file size, cheap hash) filtering with the expensive hash and get only two reads per copy rather than three. -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ -- http://mail.python.org/mailman/listinfo/python-list
Help Installing Python 2.3.5
I've been running python for years and have never had trouble installing until today. I am trying to install Python 2.3.5 from python.org on my windows 2000 box. I uninstalled everything from the previous Python, downloaded and ran the exe and everything appeared to run correctly (even got the Python installed correctly screen). Reboot. When I open a dos window and type python I am told it doesn't know that that is! The file association with seems to work. Do I need to map the PATH myself? Everything's in the default directory (C:\Python23). Thanks for your help, --greg -- Greg Lindstrom 501 975.4859 Computer Programmer [EMAIL PROTECTED] NovaSys Health Little Rock, Arkansas We are the music makers, and we are the dreamers of dreams. W.W. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to turn a variable name into a string?
Any given Python object may be bound to multiple names or none at all, so trying to find the symbol(s) which reference an object is sort of quixotic. In fact, you've got None referenced by both my and c in this example, and in a more complicated program None will be referenced by dozens symbols because it's unique [e.g. (a == None, b == None) necessitates (a is b) == True] You could try using is to match it with something in the namespace, though. This might do what you want. def names(thing): return [name for name,ref in globals().iteritems() if ref is thing] a = 1; b = 2; c = None mylist = [a,b,c] for my in mylist: if my is None: print 'you have a problem with %s' % names(my) - Although it would be much simpler to rewrite your code like this: a = 1; b = 2; c = None mylist = ['a','b','c'] for my_name in mylist: my = eval(my_name) if my is None: print 'you have a problem with %s' % my_name -- http://mail.python.org/mailman/listinfo/python-list
storing large amounts of data in a list/dictionary
Hi, Basically, what I'm trying to do is store large amounts of data in a list or dictionary and then convert that to a custom formatted xml file. My list looks roughly like this: (d[],r[c[d[p[],p[R,C,I) My question is, would it be faster to use a dictionary if the elements of the lists have to be put in alphebetical order, or just use lists as above(since hashes are faster supposedly)? {d;d[],r;name[{d;d[{p;p[]}],c;name[{d;d[{p;p[]}]}]}]} Please consider the amount of code necessary to create/decode this (and sorry if this doesn't make any sense..) -thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple buffers management
Bengt Richter wrote: On 10 Mar 2005 15:18:08 -0800, [EMAIL PROTECTED] wrote: Hello, I need to create 6 buffers in python and keep track of it. I need to pass this buffer, say buffer 1 as an index to a test app. Has Take a look at Blocks Views: http://members.dsl-only.net/~daniels/Block.html For some versions of buffers, this might work. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
I'm against further tinkering with Print on a number of grounds, not least of which is that it's going away in Python 3.0. It seems like wasted effort. I don't see much difficulty with the current behavior: if you want to get rid of the spaces, there are alternatives. I don't buy the novice arguement. If you want, you can always implement your own print function with a variable number of arguements and just about any semantics you want. John Roth Marcin Ciura [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Here is a pre-PEP about print that I wrote recently. Please let me know what is the community's opinion on it. Cheers, Marcin PEP: XXX Title: Print Without Intervening Space Version: $Revision: 0.0 $ Author: Marcin Ciura marcin.ciura at polsl.pl Status: Draft Type: Standards Track Created: 11-Mar-2005 Post-History: 11-Mar-2005 Abstract This PEP proposes to extend the syntax of the print statement so that its space-insertion mechanism can be selectively disabled by using double instead of single commas. Rationale The print statement can write several expressions in one line, but presently always separates them with spaces. While this behaviour is often desirable, not uncommon are situations, where programmers have to use workarounds to achieve a non-spaced display. This has been recognized as one of Python Gotchas [1]. Even the simplest workaround results in an unnecessarily complicated code (for the sake of simplicity let us assume that fn() returns strings): result = '' for x in seq: result += fn(x) print result Not to mention it also has a terrible algorithmic complexity. None of the more efficient solutions is particularly straightforward, either: result = [] for x in seq: result.append(fn(x)) print ''.join(result) print ''.join([fn(x) for x in seq]) print ''.join(fn(x) for x in seq) Moreover, all of them require creating one or two temporary objects to hold the entire result. If the programmers use one of them without qualms, it is only because their mind is warped by the limitation of print. Using write() is not especially appealing either, especially if the print statements are used elsewhere in the code: import sys for x in seq: sys.stdout.write(fn(x)) print # or sys.stdout.write('\n') The proposed extension to the print statement is to use two commas to signal that no space should be written after an expression: for x in seq: print fn(x),, print To quote The Zen of Python [2]: Beautiful is better than ugly. Simple is better than complex. Readability counts. The proposal applies also to the expressions in the middle of the print statement. Thus it provides an alternative to string concatenation and string interpolation, either with the '%'-based specifiers, or with the '$'-based ones introduced by PEP 292 [3], not requiring creating a temporary string object: print 'The phone number is (',,extension,,')', number,,'.' Note that I do not claim that the above version is any more readable than print 'The phone number is (%s) %s.' % (extension, number) Specification It is proposed to allow separating the expressions to be printed by single or double commas, and to allow single or double commas at the end of the print statement. The two commas shall be consecutive, i.e. there shall be no whitespace between them. Non-consecutive commas or any sequence of more than two commas constitute a syntax error. In the print chevron form of the statement, the name of the file object shall be separated from the next expression only by a single comma, as it is now. Formally, the proposed syntax of the extended print statement is print_stmt: print ( [expression ((, | ,,) expression)* [, | ,,]] | expression [(, expression ((, | ,,) expression)* [, | ,,]] Implementing the proposed syntax may require introducing a new type of token: double comma, or a hack in the parser to recognize two consecutive commas in the context of the print statement. Two new byte codes, parallel to PRINT_ITEM and PRINT_ITEM_TO, are needed to implement the semantics of the proposal. Discussion Pros: - The proposed semantics allows avoiding temporary string objects during the execution of the print statement and often makes for more readable and explicit source code. - The proposed syntax is easy to learn for the beginners. - It breaks no existing Python code. - Mistakes are unlikely to happen with the proposed syntax, unless someone has problems with his typing or his keyboard, in which case any programming is difficult, anyway. Cons: - Wrapper functions around print will be
Re: pre-PEP: Print Without Intervening Space
Marcin Ciura wrote: Duncan Booth wrote: import sys def nospace(value, stream=None): '''Suppress output of space before printing value''' stream = stream or sys.stdout stream.softspace = 0 return str(value) I'm teaching Python as the first programming language to non-computer scientists. Many of the toy programs would be simpler with the double comma syntax. Presently, having a choice whether to teach my students the result += fn(x) way or your way, I would still opt for the former. Best regards, Marcin You could think about teaching them the linelist.append(fn(x)) way, which then gives you the choice of .join(linelist) - no gaps \n.join(lienlist) - one item per line .join(linelist) - spaces between items. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
In view of Duncan's response, which invalidates the premises of my proposal, I announce the end of its short life. I will add Duncan's solution to my bag of tricks - thank you! Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to turn a variable name into a string?
Hi Stewart, what about the other way, string - var and not var - string? My suggestion: mylist = [a, b, c] for my in mylist: if locals()[my] == None: print you have a problem with %s % my Paolo Stewart Midwinter wrote: I'd like to do something like the following: a = 1; b = 2; c = None mylist = [a, b, c] for my in mylist: if my is None: print 'you have a problem with %s' % my #this line is problematic You have a problem with None What I want to see in the output is: You have a problem with c How do I convert a variable name into a string? thanks! -- http://mail.python.org/mailman/listinfo/python-list