From g.franzkowiak at onlinehome.de Fri Sep 30 12:44:10 2005 From: g.franzkowiak at onlinehome.de (g.franzkowiak) Date: Fri, 30 Sep 2005 18:44:10 +0200 Subject: PyWin SendMessage In-Reply-To: References: <7jczvrb5.fsf@python.net> Message-ID: Gonzalo Monz?n schrieb: > g.franzkowiak escribi?: > >> Thomas Heller schrieb: >> >> >>> "g.franzkowiak" writes: >>> >>> >>> >>> >>>> Thomas Heller schrieb: >>>> >>>> >>>> >>>>> "g.franzkowiak" writes: >>>>> >>>>> >>>>> >>>>> >>>>> >>>>>> Hello everybody, >>>>>> >>>>>> I've tryed to use an interprocess communication via >>>>>> SendMessage on Windows. >>>>>> Unfortunately, nothing goes on >>>>>> >>>>>> ######################################################################### >>>>>> >>>>>> #! /usr/bin/env python >>>>>> >>>>>> import win32api, win32ui, win32con >>>>>> import struct, array >>>>>> >>>>>> """ >>>>>> typedef struct tagCOPYDATASTRUCT { // cds >>>>>> DWORD dwData; >>>>>> DWORD cbData; >>>>>> PVOID lpData; >>>>>> } COPYDATASTRUCT; >>>>>> """ >>>>>> >>>>>> def packCopyData(nNum, sString): >>>>>> int_buffer = array.array("L",[nNum]) >>>>>> char_buffer = array.array('c', sString) >>>>>> int_buffer_address = int_buffer.buffer_info()[0] >>>>>> char_buffer_address = char_buffer.buffer_info()[0] >>>>>> char_buffer_size = char_buffer.buffer_info()[1] >>>>>> copy_struct = struct.pack("pLp", # dword*, dword, char* >>>>>> int_buffer_address, >>>>>> char_buffer_size, >>>>>> char_buffer) >>>>>> return copy_struct >>>>>> >>>>> >>>>> After packCopyData(...) returns, the arrays are destroyed, which will >>>>> probably void their contents. You must keep them alive until you >>>>> don't >>>>> need the COPYDATASTRUCT instance any longer. For this kind of stuff, >>>>> ctypes may be easier to use than pywin32. >>>>> >>>>> Thomas >>>>> >>>> >>>> Hmm, have read something in <> >>>> and the script changed to this: >>>> >>>> #--------------------------------------------------------- >>>> #! /usr/bin/env python >>>> >>>> import win32api, win32ui, win32con, win32gui >>>> import struct, array >>>> >>>> from ctypes import * >>> >>> >>> >>>> """ >>>> typedef struct tagCOPYDATASTRUCT { // cds >>>> DWORD dwData; >>>> DWORD cbData; >>>> PVOID lpData; >>>> } COPYDATASTRUCT; >>>> """ >>>> >>>> class COPYDATATYPE(Structure): >>>> _fields_ = [("nNum", c_ulong), >>>> ("szData", c_char_p)] >>>> >>>> class COPYDATASTRUCT(Structure): >>>> _fields_ = [("dwData", c_ulong), >>>> ("cbData", c_ulong), >>>> ("lpData", POINTER(COPYDATATYPE))] >>>> >>>> # get the window handle >>>> hwnd = win32ui.FindWindow(None, "target window") >>>> >>>> # print just for fun >>>> # ##print hwnd >>>> >>>> # prepare copydata structure for sending data >>>> cpyData = COPYDATATYPE(1, '1') >>>> cds = COPYDATASTRUCT(c_ulong(1), >>>> c_ulong(sizeof(cpyData)), >>>> pointer(cpyData)) >>>> >>>> # try to send a message >>>> win32api.SendMessage(hwnd, >>>> win32con.WM_COPYDATA, >>>> 0, >>>> pointer(cds)) >>>> >>>> #--------------------------------------------------------- >>>> and the message for the last line is: >>>> ==> TypeError: an integer is required" >>>> >>>> This message comes with "pointer(cds)" and with "addressof(cds)" >>>> >>> >>> That error refers to the first argument - win32ui.FindWindow returns a >>> PyCWnd object, which is not accepted by win32api.SendMessage. >>> Changing this brings you one step further. win32api.SendMessage accepts >>> an integer for the last element, so addressof(cds) should work now. >>> >>> win32gui.SendMessage is more tolerant in what it accepts as 4th >>> argument, according to the error message you get when you try it it >>> expects a string, a buffer, or an integer. So you could use addressof() >>> or pointer(), what you like best. >>> >>> Thomas >>> >> >> >> Super, operates :-)) >> >> My last answer must be in the Nirvana, strange ? >> >> Ok, only the version with 'addressof' generates a message and I must >> play with the data types. The receiver becomes a wrong data formate. >> Expect (int=1, char[256]='1\00'), but the int is 0x31 and the string >> somewhat. Must play with my data. >> >> Thanks >> gerd >> >> > > Hi Gerd, > > I'm not really sure of, but I think you must use a message value in > range of WM_USER or WM_APP so this fact maybe let the receiver window > getting bad data... have a look to this: > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/messagesandmessagequeues/messagesandmessagequeuesreference/messagesandmessagequeuesmessages/wm_user.asp > > > 0 through WM_USER > > 0x0400 > Messages reserved for use by the system. > *WM_USER* through 0x7FFF Integer messages for use by private window > classes. > *WM_APP* through 0xBFFF Messages available for use by applications. > 0xC000 through 0xFFFF String messages for use by applications. > Greater than 0xFFFF Reserved by the system. > > > > I've done the same with PHP GTK and achieved random results sending low > Msg values... until used WM_USER and above. Also, in my case only > PostMessage work fine... try using both... but expect this doesn't > happen with python, > > Hope it helps. > > Gonzalo Hi Gonzalo, thank you for your interest and for your tips. With your links was it possible to learn something over messages in user applications. I'm not the windows guru, like the open source scene. My problem was not the message type and I think the WM_COPYDATA is the right thing for interprocess communication between python and C++. I've changed in my script the COPYDATATYPE field szData from c_char_p to c_char * 256 and the memory is correct initialized. The first situation was according to **data and in consequence the wrong content on the receiver side. Now is it a good thing :-) gerd From pink at odahoda.de Fri Sep 9 16:41:45 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 09 Sep 2005 22:41:45 +0200 Subject: how to get the return value of a thread? References: Message-ID: Leo Jay wrote: > Dear all, > > i would like to get the return value of all threads > > e.g. > def foo(num): > if num>10: > return 1 > elif num>50: > return 2 > else > return 0 > > > after i invoked > t = thread.start_new_thread(foo,(12,)) > how to get the return value of `foo'? Take a look at the Queue module. Create a queue instance at let the 'foo thread' put() its result into it: fooResult = Queue.Queue() def foo(num): result = 0 if num>10: result = 1 elif num>50: result = 2 fooResult.put(result) t = thread.start_new_thread(foo,(12,)) # do other stuff, foo is running in background r = fooResult.get() # guaranteed to block until result is available print r -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From tjreedy at udel.edu Sat Sep 10 21:26:21 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2005 21:26:21 -0400 Subject: Python versus Perl References: Message-ID: "Roy Smith" wrote in message news:roy-A55323.15113410092005 at reader1.panix.com... > Dieter Vanderelst wrote: >> 1 - How does the speed of execution of Perl compares to that of Python? > To a first-order approximation, Perl and Python run at the same speed. 'Speed of execution' is a feature of an inplementation, not of languages themselves. Different implementations of Python (for instance, CPython versus CPython+Psyco) can vary in speed by more than a factor of 10 for particular blocks of Python code. (Yes, I know you are comparing the stock standard implementations, but my point still stands.) > They are both interpreted languages. To be useful, every language has to be interpreted sometime by something. In the narrow technical sense that I presume you mean, 'interpretation' versus 'compilation' is again an implementation feature, not a language feature. As far as I know, neither Perl nor Python has an implementation that directly interprets in the way that Basic or tokenized Basic once was. I am being picky because various people have claimed that Python suffers in popularity because it is known as an 'interpreted language'. So maybe advocates should be more careful than we have been to not reinforce the misunderstanding. Terry J. Reedy From csubich.spamblock at subich.spam.com.block Wed Sep 21 14:46:23 2005 From: csubich.spamblock at subich.spam.com.block (Christopher Subich) Date: Wed, 21 Sep 2005 14:46:23 -0400 Subject: Writing a parser the right way? In-Reply-To: <1127323058.667034.43540@g49g2000cwa.googlegroups.com> References: <1127300661.440587.287950@g47g2000cwa.googlegroups.com> <1127306797.658461.264950@g44g2000cwa.googlegroups.com> <1127323058.667034.43540@g49g2000cwa.googlegroups.com> Message-ID: beza1e1 wrote: > Well, a declarative sentence is essentially subject-predicate-object, > while a question is predicate-subject-object. This is important in > further processing. So perhaps i should code this order into the > classes? I need to think a little bit more about this. A question is subject-predicate-object? That was unknown by me. Honestly, if you're trying a general English parser, good luck. From timr at probo.com Fri Sep 30 02:41:39 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 30 Sep 2005 06:41:39 GMT Subject: Straight line detection References: <1127939495.032208.272230@z14g2000cwz.googlegroups.com> Message-ID: <7enpj1paiadd4ourjttchtrrpdkq0krivg@4ax.com> "PyPK" wrote: > >Does anyone know of a simple implementation of a straight line >detection algorithm something like hough or anything simpler.So >something like if we have a 2D arary of pixel elements representing a >particular Image. How can we identify lines in this Image. >for example: > >ary = >[[1,1,1,1,1], > [1,1,0,0,0], > [1,0,1,0,0], > [1,0,0,1,0], > [1,0,0,0,1]] >So if 'ary' represents pxl of an image which has a horizontal line(row >0),a vertical line(col 0) and a diagonal line(diagonal of ary). then >basically I want identify any horizontal or vertical or diagonal line >anywhere in the pxl array. If all you want is horizontal, vertical, or 45 degree diagonal, it's pretty easy to do that just be checking all of the possibilities. But what if your array is: [[1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1]] Would you say there were 12 lines there? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Wed Sep 7 13:02:38 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Sep 2005 13:02:38 -0400 Subject: anaconda.real in RH7.1 In-Reply-To: References: Message-ID: Allan Adler wrote: > Allan Adler writes: > > >>I'm trying to reinstall RedHat 7.1 Linux on a PC that was disabled when >>I tried to upgrade from RH7.1 [....] >>The file anaconda.real is invoked with the line >>exec /usr/bin/anaconda.real -T "$@" >>I don't know what effect the -T "$@" has. > > > Tiny progress on this: in a shell script, "$@" apparently lets you refer > to the output of a previous command. I don't know what output would be > relevant, since the last few lines of the shell script anaconda that > invokes anaconda.real are: > > cd /usr/sbin > uncpio < sbin.cgz > rm sbin.cgz > cd /lib > uncpio < libs.cgz > rm libs.cgz > cd / > exec /usr/bin/anaconda.real -T "$@" > $@ doesn't refer to the output of a previous command. It refers to a list of quoted arguments of the script it's a part of. It's supposed, IIRC, to be equivalent to exec /usr/bin/anaconda.real -T "$1" "$2" "$2" ... as opposed to $*, which would be equivalent to exec /usr/bin/anaconda.real -T $1 $2 $3 ... > As for exec itself, the command line > exec -T > leads to a complaint that -T is an illegal option for exec, while > python -T > leads to a usage statement that doesn't list -T among the options for python. > So, I still don't understand the statement that is used to call the python > script anaconda.real. > What's supposed to happen is that anaconda.real is supposed to be processed by the Python interpreter. You will probably find a "shebang" line at the start of anaconda.real that reads something like #!/usr/bin/python1.5.2 The -T argument is, I suspect, intended for anaconda.real - you could check the source and verify that it looks at sys.argv. > I also tried to execute in interactive session some of the commands in the > file anaconda.real. E.g. the first command signal.signal(SIGINT,SIG_DFL) > > Python 1.5.2 (#1, Mar 3 2001, 01:35:43) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>>>signal.signal(SIGINT,SIG_DFL) > > Traceback (innermost last): > File "", line 1, in ? > NameError: signal > >>>>import signal >>>>signal.signal(SIGINT,SIG_DFL) > > Traceback (innermost last): > File "", line 1, in ? > NameError: SIGINT > >>>>import SIGINT > > Traceback (innermost last): > File "", line 1, in ? > ImportError: No module named SIGINT > > On the other hand, while looking at Kernighan and Pike, "The Unix programming > environment" (1984), I fortuitously ran across a discussion of signals and > interrupts on p.225, including the example > > #include > signal(SIGINT,SIG_DFL) > > which restores default action for process termination. The resemblance to the > first command in anaconda.real is so close that I think the intention in > both must be the same. What is the right way to get python to do this? > SIGINT is defined in the signal module so you probably want signal.signal(signal.SIGINT, signal.SIG_DFL) > The file anaconda.real doesn't explicitly execute > import signal > but it still somehow knows what signal means (my example session above shows > that it stops complaining about not knowing what signal means after I import > signal). Presumably there is some way of invoking python that causes signal > and other stuff to be imported automatically. What is it? On that one you have me stumped. It's possible it imports some other module that plays with the namespace in a magical way. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From peter at engcorp.com Thu Sep 8 08:23:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Sep 2005 08:23:06 -0400 Subject: Distutils question In-Reply-To: References: Message-ID: <4tqdnchig9Qysb3eRVn-pw@powergate.ca> Laszlo Zsolt Nagy wrote: > How how can I install my .mo files from a distutil script into its > default location? > > sys.prefix + os.sep + 'share' + os.sep + 'locale' I can't answer the first question, but the latter should be written this way instead os.path.join(sys.prefix, 'share', 'locale') for greater portability and maintainability. -Peter From lidenalex at yahoo.se Wed Sep 7 03:42:34 2005 From: lidenalex at yahoo.se (Alex) Date: 7 Sep 2005 00:42:34 -0700 Subject: dict and __cmp__() question Message-ID: <1126078954.485637.172070@g47g2000cwa.googlegroups.com> Entering >>> help(dict) Help on class dict in module __builtin__: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs. | dict(seq) -> new dictionary initialized as if via: | d = {} | for k, v in seq: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) | | Methods defined here: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __contains__(...) | D.__contains__(k) -> True if D has a key k, else False snip | update(...) | D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k] | (if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k] | | values(...) | D.values() -> list of D's values Now I understand methods like update(...) and values(...), for instance >>> D={'a':1, 'b':2} >>> D.values() [1, 2] >>> But what are those with double underscore? For instance __cmp__(...)? I tried >>> D.cmp('a','b') Traceback (most recent call last): File "", line 1, in -toplevel- D.cmp('a','b') AttributeError: 'dict' object has no attribute 'cmp' >>> Alex From iddw at hotmail.com Wed Sep 14 17:04:42 2005 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 14 Sep 2005 21:04:42 GMT Subject: Unexpected Behavior Iterating over a Mutating Object References: <432740ae.1301867062@news.ispnetbilling.com> Message-ID: <432823e0.1360028812@news.ispnetbilling.com> On Tue, 13 Sep 2005 21:28:21 GMT, iddw at hotmail.com (Dave Hansen) wrote: >OK, first, I don't often have the time to read this group, so >apologies if this is a FAQ, though I couldn't find anything at >python.org. > Thanks to everyone who responded. All is clear now. And I know I need to look deeper into list comprehensions... Regards, -=Dave -- Change is inevitable, progress is not. From max at alcyone.com Tue Sep 6 06:05:16 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 Sep 2005 03:05:16 -0700 Subject: Job Offer in Paris, France : R&D Engineer (Plone) In-Reply-To: <7x4q8y35lx.fsf@ruckus.brouhaha.com> References: <7xbr37u8ut.fsf@ruckus.brouhaha.com> <7xpsrn3100.fsf@ruckus.brouhaha.com> <7x4q8y35lx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > If you still think this, I'd be interested in chatting a little > further. Does the email address in the pdf go to you? If not, should > I write you directly? Can I call on the phone (you can leave me a > number at http://paulrubin.com)? Thanks. Do you even realize you're having this conversation over the Python mailing list/newsgroup, rather than by private email? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Defeat is a school in which truth always grows strong. -- Henry Ward Beecher From markus_REMOVEwankusALL_CAPS at hotmail.com Fri Sep 30 08:53:00 2005 From: markus_REMOVEwankusALL_CAPS at hotmail.com (Markus Wankus) Date: Fri, 30 Sep 2005 08:53:00 -0400 Subject: Zope3 Examples? In-Reply-To: References: Message-ID: Jean-Fran?ois Doyon wrote: > Markus, > > Zope 3 is mature as a framework, but does not provide much "out of the > box". It's a basis upon which to build applications like Plone ... If > you are looking for something that provides Plone-like features on top > of Zope 3, it doesn't exist (yet). > > Personally, I'm waiting for this: http://www.z3lab.org/ > But it'll be a while yet! > Yes - I was watching the screencasts (well, animations) on this and it looks incredible! I can't wait to play with something like this. > Zope 3 is brilliant, but complex, and quite the departure from Zope 2, > so it'll take a while for the take up to occur. > > What might work better for you is to use Zope 2 + the CMF, without > Plone. Plone can be fairly heavy and rigid, the CMF alone might give > you the tools you need. I use Zope 2 with success and good performance > on a hig traffic website, I wouldn't discount it just because of your > first impression ... There are many tweaks available that will > considerably improve performance for production systems. > > Cheers, > J.F. > Thanks for the reply - maybe I'll give it another shot. I'm currently demoing Snakelets. Quite a turn in the opposite direction, but small and super-easy to get going with. I think once this project gets a few good webapps under its belt (and maybe I can contribute there!) this could be a nice solution for many people. At least a good starting point for someone like me who knows a good deal about Python and nothing about web frameworks. Markus. From steven.bethard at gmail.com Sun Sep 4 15:08:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 04 Sep 2005 13:08:36 -0600 Subject: regular expression unicode character class trouble In-Reply-To: <3o0n4bF3hmbaU1@uni-berlin.de> References: <3o0n4bF3hmbaU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Hi, > > I need in a unicode-environment the character-class > > set("\w") - set("[0-9]") > > or aplha w/o num. Any ideas how to create that? I'd use something like r"[^_\d\W]", that is, all things that are neither underscores, digits or non-alphas. In action: py> re.findall(r'[^_\d\W]+', '42badger100x__xxA1BC') ['badger', 'x', 'xxA', 'BC'] HTH, STeVe From eurleif at ecritters.biz Tue Sep 27 19:34:27 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 27 Sep 2005 23:34:27 GMT Subject: __call__ in module? In-Reply-To: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> References: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> Message-ID: <7Gk_e.28$PA1.5188@monger.newsread.com> ncf wrote: > I have a feeling that this is highly unlikely, but does anyone in here > know if it's possible to directly call a module, or will I have to wrap > it up in a class? You could use trickery with sys.modules to automatically wrap it in a class: import sys from types import ModuleType class CallableModule(ModuleType): def __call__(self): print "You called me!" mod = FooModule(__name__, __doc__) mod.__dict__.update(globals()) sys.modules[__name__] = mod From mensanator at aol.com Wed Sep 21 16:17:08 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 21 Sep 2005 13:17:08 -0700 Subject: unusual exponential formatting puzzle In-Reply-To: <1127333251.055532.278540@g49g2000cwa.googlegroups.com> References: <1127333251.055532.278540@g49g2000cwa.googlegroups.com> Message-ID: <1127333828.538525.235630@o13g2000cwo.googlegroups.com> mensanator at aol.com wrote: > Neal Becker wrote: > > Like a puzzle? I need to interface python output to some strange old > > program. It wants to see numbers formatted as: > > > > e.g.: 0.23456789E01 > > > > That is, the leading digit is always 0, instead of the first significant > > digit. It is fixed width. I can almost get it with '% 16.9E', but not > > quite. > > > > My solution is to print to a string with the '% 16.9E' format, then parse it > > with re to pick off the pieces and fix it up. Pretty ugly. Any better > > ideas? > > If you have gmpy available... > > >>> import gmpy > > ...and your floats are mpf's... > > >>> s = gmpy.pi(64) > >>> s > mpf('3.14159265358979323846e0',64) > > ...you can use the fdigits function > > >>> t = gmpy.fdigits(s,10,8,0,0,2) > > ...to create a seperate digit string and exponent... > > >>> print t > ('31415927', 1, 64) > > ...which can then be printed in the desired format. > > >>> print "0.%sE%02d" % (t[0],t[1]) > 0.31415927E01 Unless your numbers are negative. >>> print "0.%sE%02d" % (t[0],t[1]) 0.-31415927E03 Drat. Needs work. And does the format permit large negative exponents (2 digits + sign)? >>> print "0.%sE%02d" % (t[0],t[1]) 0.31415927E-13 From trentm at ActiveState.com Thu Sep 29 22:05:55 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 29 Sep 2005 19:05:55 -0700 Subject: RELEASED Python 2.4.2 (final) In-Reply-To: References: Message-ID: <20050930020555.GA7371@ActiveState.com> [Bugs wrote] > I downloaded the 2.4.2 Windows Binary Installer from python.org but when > I try to run python.exe I get the following in the console: > -------------------- > ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on > Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> > -------------------- > It says ActivePython 2.4.1 but I downloaded the 2.4.2 binary installer > from python.org and the python.exe executable I'm running is timestamped > 9/28/2005 12:41PM... Any ideas what I'm doing wrong? It is possible that the python.org installer didn't overwrite the "python24.dll" in the system directory (C:\WINDOWS\system32). Try doing this: - manually delete C:\WINDOWS\system32\python24.dll - run the "repair" functionality of the python.org installer (you can either do this from "Start | Settings | Control Panel | Add/Remove Programs" or by just running the .msi file again Then try running python again. Trent -- Trent Mick TrentM at ActiveState.com From donald.welch at hp.com Fri Sep 9 12:23:22 2005 From: donald.welch at hp.com (djw) Date: Fri, 09 Sep 2005 09:23:22 -0700 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: <4321b75f$1@usenet01.boi.hp.com> Stefano Masini wrote: > I don't know what's the ultimate problem, but I think there are 3 main reasons: > 1) poor communication inside the community (mhm... arguable) > 2) lack of a rich standard library (I heard this more than once) > 3) python is such an easy language that the "I'll do it myself" evil > side lying hidden inside each one of us comes up a little too often, > and prevents from spending more time on research of what's available. > I think, for me, this most important reason is that the stdlib version of a module doesn't always completely fill the requirements of the project being worked on. That's certainly why I wrote my own, much simpler, logging module. In this case, its obvious that the original author of the stdlib logging module had different ideas about how straightforward and simple a logging module should be. To me, this just demonstrates how difficult it is to write good library code - it has to try and be everything to everybody without becoming overly general, abstract, or bloated. -Don From g.horvath at gmx.at Thu Sep 29 02:15:11 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 29 Sep 2005 08:15:11 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xd5mstqab.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > > Huh? If my car has a "feature" that lets someone blow it to > smithereens from hundreds of miles away without even intending to, > that's somehow an advantage? I would not accept a car that does constraint my driving directions. I want to drive for myself, because its fun. > > No problem, but any decision like that should be expressed in > "writing", by re-declaring the variable so it's no longer private. Remember, its Python not Java. Tastes are different and so are programming languages, but please do not make Python to a Java Clone. I love python because of its simplicity, freedom, power and because its fun to program. One reason is that it does not restrict the programer to tight und has genuine simple solutions, like the one with "private" instance variables. -- Greg From steve at holdenweb.com Sat Sep 3 02:09:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Sep 2005 01:09:35 -0500 Subject: urllib.urlopen doesn't work In-Reply-To: <004701c5b00b$06db4790$ce0221d5@familygroup> References: <004701c5b00b$06db4790$ce0221d5@familygroup> Message-ID: Josef Cihal wrote: > Hallo, > > i need a help with module URLLIB. > > I am trying to open url via: > - urllib.urlopen > ('http://brokerjet.ecetra.com/at/markets/stocks/indices.phtml?notation=92866') > > > Problem is, that I am always redirecting to > - LOGIN page (www.brokerjet.at ), > and cannot get my page with "news", which I want to download. > > Can it be, that I forgot to pass all (hidden too) parameters to form by > submit? > > Is it possible to get (ask) for all existing valid parameters, which I > need to pass to form > for getting requested page? > Is action submit correct in my case? > > > Thank you very much for all your help or ideas > I suspect that the problem is you are attempting to access a web application in which every page checks for a valid login and, if this isn't present, redirects you to the login page. You might try a URL for the form http://username:password at server/path/resource as this is the easiest way to achieve basic authentication. Otherwise there are other ways, which you can get back to us about. Also you might try just starting a new browser session an entering the URL that gave you problems in your code. If the browser displays the page correctly then *either* it has cookies set that you aren't setting when you call urllib.urlopen() *or* I'm wrong. :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From billiejoex at fastwebnet.it Sat Sep 10 13:06:52 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Sat, 10 Sep 2005 19:06:52 +0200 Subject: execute commands and return output References: Message-ID: Thanks for suggestions. I'll try one of these solutions soon. From lycka at carmen.se Fri Sep 16 06:06:17 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 16 Sep 2005 12:06:17 +0200 Subject: MySQLdb UPDATE does nothing In-Reply-To: References: <4329633F.7060609@jmsd.co.uk> Message-ID: Steve Horsley wrote: > Or, as I found out yesterday, cursor.execute('commit') afterwards. The correct way to do it is to close the cursor object, and then do "db.commit()". Don't rely on a cursor object to work across transaction boundries! See e.g. www.thinkware.se/epc2004db/epc04_mly_db.pdf and http://www.thinkware.se/epc2004db/dbapitest.py From tzot at sil-tec.gr Fri Sep 30 03:51:59 2005 From: tzot at sil-tec.gr (Christos Georgiou) Date: Fri, 30 Sep 2005 10:51:59 +0300 Subject: 1 Million users.. I can't Scale!! References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> <17210.62571.387969.713030@montanaro.dyndns.org> <433B0B38.7040406@bellsouth.net> Message-ID: On Wed, 28 Sep 2005 21:58:15 -0400, rumours say that Jeff Schwab might have written: >For many (most?) applications in need of >serious scalability, multi-processor servers are preferable. IBM has >eServers available with up to 64 processors each, and Sun sells E25Ks >with 72 processors apiece. SGI offers modular single-image Itanium2 servers of up to 512 CPU at the moment: http://www.sgi.com/products/servers/altix/configs.html And NASA have clustered 20 of these machines to create a 10240 CPU cluster... >I like to work on those sorts of machine >when possible. Of course, they're not right for every application, >especially since they're so expensive. And expensive they are :) -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From abo at google.com Tue Sep 27 13:57:59 2005 From: abo at google.com (ABO) Date: 27 Sep 2005 10:57:59 -0700 Subject: Self reordering list in Python References: <200509161058.48155.hancock@anansispaceworks.com> <1127810493.378770.282050@z14g2000cwz.googlegroups.com> Message-ID: <1127843879.245154.22300@g44g2000cwa.googlegroups.com> Actually, after posting this I did some more work on the PQueue modules I had, implementing both bisect and heapq versions. It turns out the bisect version is heaps faster if you ever delete or re-set values in the queue. The problem is heapq is O(N) for finding a particular entry in the Queue, and any time you change or remove something from it you need to heapify it again, which is also O(N). Andew Snare has a C PQueue extension module that is heaps faster from all angles. It uses a fibonacci heap and gets O(lg N) deletes and re-sets. I think it does this by using the dict to speed finding entries it in the heap, and uses some properties of the heap to "assign lower" efficiently. The queue used in the lrucache will also suffer from the O(N) problem when deleting or reseting values in the cache. From fredrik at pythonware.com Wed Sep 14 12:57:23 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 14 Sep 2005 18:57:23 +0200 Subject: Python Search Engine app References: <1126708775.608076.106850@g43g2000cwa.googlegroups.com> Message-ID: Harlin Seritt wrote: > Is anyone aware of an available open-source/free search engine app > (something similar to HTDig) written in Python that is out there? > Googling has turned up nothing. Thought maybe I'd mine some of you > guys' minds on this. http://divmod.org/ has a couple of alternatives: http://divmod.org/projects/lupy http://divmod.org/projects/pyndex http://divmod.org/projects/xapwrap From gnb at itga.com.au Wed Sep 7 02:06:27 2005 From: gnb at itga.com.au (Gregory Bond) Date: Wed, 07 Sep 2005 16:06:27 +1000 Subject: Ode to python In-Reply-To: <1126062515.460542.95260@f14g2000cwb.googlegroups.com> References: <1126062515.460542.95260@f14g2000cwb.googlegroups.com> Message-ID: <510mfd.n08.ln@lightning.itga.com.au> Hmmm... OK... you forced me into it. Python uses whitespace Where C++ uses a brace New users fret, But old pros forget - it quickly all falls into place. I could go on...... From theller at python.net Tue Sep 13 04:13:12 2005 From: theller at python.net (Thomas Heller) Date: Tue, 13 Sep 2005 10:13:12 +0200 Subject: Using Python with COM to communicate with proprietary Windows software References: <5bMhQyygYQbAxWGqorX8DcbkrRte@4ax.com> Message-ID: Andrew MacIntyre writes: > On Fri, 09 Sep 2005 08:36:00 +0200, Thomas Heller > wrote: > > {...} > >>(I have released and announced this 3 weeks ago, but haven't got a >>single feedback. So it seems the need to access custom interfaces is >>very low.) > > I have downloaded it and am trying to find the time to play with it > (unsuccessfully so far). > > As someone working with a large, complex, COM library with minimal > IDispatch support, I'm really looking forward to this. > > However, at the moment I'm limited to Python 2.2 and ctypes 0.6.3 > (which is allowing me to get the job done!!). > > Regardless, I thank you for what you have released! I knew there are fans out there ;-) Thomas From fredrik at pythonware.com Thu Sep 15 03:49:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Sep 2005 09:49:47 +0200 Subject: new in python References: Message-ID: "blackfox505" wrote: > I'm new in python and I would like to know what is the capabilleties > of this language.Please let me know and how I can make a program in > python exe if you want to know how to make programs in python, start here: http://wiki.python.org/moin/BeginnersGuide if you want to know how to turn python program into exe files, this page might help: http://effbot.org/zone/python-compile.htm From deets at nospam.web.de Mon Sep 26 08:45:09 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Sep 2005 14:45:09 +0200 Subject: What is "self"? In-Reply-To: References: <43335c5f$1_4@alt.athenanews.com> Message-ID: <3pq8qlFbncaaU1@uni-berlin.de> > This still seems not quite right to me... Or more likely seems to be > missing something still. > > (But it could be this migraine I've had the last couple of days > preventing me from being able to concentrate on things with more than a > few levels of complexity.) > > Playing around with the shell a bit gives the impression that calling a > method in a instance gives the following (approximate) result... > > try: > leader.__dict__["set_name"]("John") > except: > type(leader).__dict__["set_name"].__get__(leader, "John") > # which results in... > # Person.set_name(leader, "John") > except: > raise( AttributeError, > "%s object has no attribute %s" \ > % (leader, "set_name") ) > > > Of course this wouldn't use the object names directly... I guess I'll > need to look in the C object code to see exactly how it works. But the > links you gave help. I guess you mean to indent the whole part after the first except and put a try beforehand? Apart from that you seem to be right - there can very well be values in the class dict that don't follow the descriptor-protocol. However my playing around with this stuff indicates that the creation of bound methods relies on the method being wrapped in a descriptor - otherwise, you get the notorious TypeError set_name() takes exactly 1 argument (0 given) as the binding doesn't occur. Regards, Diez From ptmcg at austin.rr._bogus_.com Thu Sep 22 16:20:01 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 22 Sep 2005 20:20:01 GMT Subject: Newbie regular expression and whitespace question References: <1127419129.027712.252910@g47g2000cwa.googlegroups.com> Message-ID: "googleboy" wrote in message news:1127419129.027712.252910 at g47g2000cwa.googlegroups.com... > Hi. > > I am trying to collapse an html table into a single line. Basically, > anytime I see ">" & "<" with nothing but whitespace between them, I'd > like to remove all the whitespace, including newlines. I've read the > how-to and I have tried a bunch of things, but nothing seems to work > for me: > > -- > > table = open(r'D:\path\to\tabletest.txt', 'rb') > strTable = table.read() > > #Below find the different sort of things I have tried, one at a time: > > strTable = strTable.replace(">\s<", "><") #I got this from the module > docs > > strTable = strTable.replace(">.<", "><") > > strTable = ">\s+<".join(strTable) > > strTable = ">\s<".join(strTable) > > print strTable > > -- > > The table in question looks like this: > > > > > > > > > > > > > > > >
 Introduction
3
 
ONEChildraising for Parrots
11
> > > > For extra kudos (and I confess I have been so stuck on the above > problem I haven't put much thought into how to do this one) I'd like to > be able to measure the number of characters between the

&

> tags, and then insert a newline character at the end of the next word > after an arbitrary number of characters..... I am reading in to a > script a bunch of paragraphs formatted for a webpage, but they're all > on one big long line and I would like to split them for readability. > > TIA > > Googleboy > If you're absolutely stuck on using RE's, then others will have to step forward. Meanwhile, here's a pyparsing solution (get pyparsing at http://pyparsing.sourceforge.net): --------------- from pyparsing import * LT = Literal("<") GT = Literal(">") collapsableSpace = GT + LT # matches with or without intervening whitespace collapsableSpace.setParseAction( replaceWith("><") ) print collapsableSpace.transformString(data) --------------- The reason this works is that pyparsing implicitly skips over whitespace while looking for matches of collapsable space (a '>' followed by a '<'). When found, the parse action is triggered, which in this case, replaces whatever was matched with the string "><". Finally, the input data (in this case your HTML table, stored in the string variable, data) is passed to transformString, which scans for matches of the collapsableSpace expression, runs the parse action when they are found, and returns the final transformed string. As for word wrapping within

...

tags, there are at least two recipes in the Python Cookbook for word wrapping. Be careful, though, as many HTML pages are very bad about omitting the trailing

tags. -- Paul From iddw at hotmail.com Fri Sep 30 18:04:29 2005 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 30 Sep 2005 22:04:29 GMT Subject: New Python chess module References: <433c066c$0$21931$db0fefd9@news.zen.co.uk> <433d7fa0$0$4177$da0feed9@news.zen.co.uk> Message-ID: <1128117924.237ac3772a24648083f429d57da23b12@teranews> On Sat, 01 Oct 2005 06:27:01 +1000, Tim Churches wrote: >Will McGugan wrote: >> There is a new version if anyone is interested... >> >> http://www.willmcgugan.com/chess.py >> >> It contains optimizations and bugfixes. >> >> Can anyone suggest a name for this module? pyChess is already taken... > >Pyawn??? As a play on "pawn?" that wasn't the way I first took it (ho-hum...) How about pyTurk, after the first chess automaton? It seems to be available. Regards, -=Dave -- Change is inevitable, progress is not. From salvatore.didio at wanadoo.fr Wed Sep 28 16:55:55 2005 From: salvatore.didio at wanadoo.fr (salvatore.didio at wanadoo.fr) Date: 28 Sep 2005 13:55:55 -0700 Subject: Nufox : Simple Tree Message-ID: <1127940955.116568.285180@g49g2000cwa.googlegroups.com> Nufox allow XUL developement like you could do with any other GUI library If you want to see an example : http://www.google.com/url?sa=D&q=http://www.freezope.org/Members/artyprog/programmation/lienspython/nufox/examples/sortedcolumns Regards Salvatore From nil at dev.nul Wed Sep 14 10:10:57 2005 From: nil at dev.nul (Christian Stapfer) Date: Wed, 14 Sep 2005 16:10:57 +0200 Subject: Removing duplicates from a list References: <1126697915.879705.300450@g44g2000cwa.googlegroups.com> <1126706415.609072.92570@o13g2000cwo.googlegroups.com> Message-ID: wrote in message news:1126706415.609072.92570 at o13g2000cwo.googlegroups.com... >I do this: > > def unique(keys): > unique = [] > for i in keys: > if i not in unique:unique.append(i) > return unique > > I don't know what is faster at the moment. This is quadratic, O(n^2), in the length n of the list if all keys are unique. Conversion to a set just might use a better sorting algorithm than this (i.e. n*log(n)) and throwing out duplicates (which, after sorting, are positioned next to each other) is O(n). If conversion to a set should turn out to be slower than O(n*log(n)) [depending on the implementation], then you are well advised to sort the list first (n*log(n)) and then throw out the duplicate keys with a single walk over the list. In this case you know at least what to expect for large n... Regards, Christian From fredrik at pythonware.com Thu Sep 29 01:11:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 07:11:10 +0200 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com><8c7f10c605092804053a6eadf4@mail.gmail.com><813D949A-554B-4801-BE07-13F652A218AD@ihug.co.nz><8c7f10c605092804552f1dac9@mail.gmail.com><00C39639-DDD6-41A7-BEA9-F78EFA3288A5@ihug.co.nz> <0669A0A3-A514-4A58-A8C0-80594B56399E@ihug.co.nz> Message-ID: Tony Meyer wrote: > That elaborates on the intent, it doesn't change it. The sentence > clearly says that the intent is to easily define private variables, > whereas Simon said that it the intent was not to provide a mechanism > for making variables private. Are you aware of the fact that computer terms might have slightly different meanings in different languages, due to differences in language details and semantics? Of course they're "private variables", but they're "private" in the Python sense, and they were added to Python to solve problems that were observed in Python, not because someone thought it was important to cater to confused C++ or Java programmers. And as Simon said, and the original thread showed, the problem they were (and are) intended to address is accidental namespace collisions when sub- classing. If we'd really needed "true" private variables, don't you think we would have been able to come up with a design that provided that? It just wasn't important, because Python is Python. From lasse at vkarlsen.no Tue Sep 27 14:07:58 2005 From: lasse at vkarlsen.no (=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?=) Date: Tue, 27 Sep 2005 20:07:58 +0200 Subject: Documenting properties Message-ID: I notice that if I use this syntax: def classname: ... ## # closes the database connection and releases the resources. def close(self): .... ## # Returns a list of fields fields = property(....) then doing: help (classname) then the text is listed for the property and the method, whereas if I do this: classname.close.__doc__ then nothing is listed, and to get that I have to use the """..""" syntax to document: def close(self): """closes the datab...""" .... then classname.close.__doc__ shows the text. So, my question is, is there a way to get __doc__ support for properties, in effect, use the """xxx""" syntax for documenting properties. Is the preferred way to use """xxx""" or # to document ? Whatever is preferred, what's the upside/downsides of the two beyond what I just explained? -- Lasse V?gs?ther Karlsen http://usinglvkblog.blogspot.com/ mailto:lasse at vkarlsen.no PGP KeyID: 0x2A42A1C2 From llothar at web.de Fri Sep 23 15:28:31 2005 From: llothar at web.de (llothar) Date: 23 Sep 2005 12:28:31 -0700 Subject: Python Source Code for a HTTP Proxy Message-ID: <1127503711.400381.259530@z14g2000cwz.googlegroups.com> Hello, i'm looking for a simple http proxy in python. Does anybody know about something like this ? From andreas.zwinkau at googlemail.com Wed Sep 21 07:04:21 2005 From: andreas.zwinkau at googlemail.com (beza1e1) Date: 21 Sep 2005 04:04:21 -0700 Subject: Writing a parser the right way? Message-ID: <1127300661.440587.287950@g47g2000cwa.googlegroups.com> I'm writing a parser for english language. This is a simple function to identify, what kind of sentence we have. Do you think, this class wrapping is right to represent the result of the function? Further parsing then checks isinstance(text, Declarative). ------------------- class Sentence(str): pass class Declarative(Sentence): pass class Question(Sentence): pass class Command(Sentence): pass def identify_sentence(text): text = text.strip() if text[-1] == '.': return Declarative(text) elif text[-1] == '!': return Command(text) elif text[-1] == '?': return Question(text) return text ------------------- At first i just returned the class, then i decided to derive Sentence from str, so i can insert the text as well. From this.address.is.fake at realh.co.uk Thu Sep 22 19:50:42 2005 From: this.address.is.fake at realh.co.uk (Tony Houghton) Date: 22 Sep 2005 23:50:42 GMT Subject: Finding where to store application data portably References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> <4332985d$0$15046$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: In , Ron Adam wrote: > Tony Houghton wrote: > >> > This works on Win XP. Not sure if it will work on Linux. >> > >> > import os >> > >> > parent = os.path.split(os.path.abspath(os.sys.argv[0]))[0] >> > file = parent + os.sep + '.bombz' >> >> Ooh, no, I don't want saved data to go in the installation directory. In >> general that practice encourages people to run with Admin access, and >> it's about time Windows users were discouraged from that. > > Yes, it occurred to me you didn't want to do that after I posted. > > Looks like maybe the correct place would be as you suggested, but maybe > doing it this way would be better. > > import os > user = os.path.join( os.environ["USERPROFILE"], > 'Application Data', > 'Bombz' ) I like that, it's nice and simple. It doesn't look like it's supported on Win 9x though, but on 9x using the installation directory would be acceptable. -- The address in the Reply-To is genuine and should not be edited. See for more reliable contact addresses. From fredrik at pythonware.com Fri Sep 9 12:13:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 9 Sep 2005 18:13:06 +0200 Subject: Where do .pyc files come from? References: <1126279989.004437.270950@g49g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: >I noticed in a python distribution there were 5 python files (.py) and > 5 other files with the same name, but with the extension .pyc . Is > this some kind of compiled version of the .py files. Thanks, http://www.python.org/doc/2.4.1/tut/node8.html#SECTION008120000000000000000 From python at rcn.com Tue Sep 13 19:42:39 2005 From: python at rcn.com (Raymond Hettinger) Date: 13 Sep 2005 16:42:39 -0700 Subject: Unexpected Behavior Iterating over a Mutating Object References: <432740ae.1301867062@news.ispnetbilling.com> Message-ID: <1126654959.843540.165630@g47g2000cwa.googlegroups.com> [Dave Hansen] > It seems when an item is 'remove'd from data, the rest of the list > 'shifts' over one, so what was 'next' now occupies the slot of the > 'remove'd item. When the next 'item' is selected from 'data', the > _desired_ 'next' item is skipped. So when 'data' has several > consecutive items to be deleted, only every other one is 'remove'd. Your analysis is dead-on. Instead of being the "desired" item, the iterator fetches a[0], a[1], a[2], ... as determined by the state of the list when the index is retrieved. > Again, iterating over an item that is mutating seems like a Bad > Idea(tm) to me. Right. > But I was curious: is this the intended behavior, or > does this fall under what C programmers would call 'undefined > behavior.' It is intended. The behavior is defined as above (a series of indexed lookups). BTW, the usual ways to deal with this are to: 1. iterating from the right using: for item in reversed(data) 2. making a copy of the original list before iterating 3. creating a new result list: data = [x for x in data if 'DEL' not in x] Raymond From fredrik at pythonware.com Thu Sep 8 14:39:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 8 Sep 2005 20:39:01 +0200 Subject: Help! Python either hangs or core dumps when calling C malloc References: <1126198290.288644.247510@o13g2000cwo.googlegroups.com><1126199525.752904.254930@z14g2000cwz.googlegroups.com> <1126203439.152057.78210@o13g2000cwo.googlegroups.com> Message-ID: Lil wrote:' >I already double checked my C code. It runs perfectly fine in C without > any errors. So in my python program, I added a pdb.set_trace() > and step through the program and it did not dump. But when i took out > the tracing, the core dump came back. "sigh" so triple-check it. if your code overwrites the malloc buffer, it's perfectly possible that it appears to run fine when you run it standalone or under the debugger, but that doesn't mean that your code is fine. From jpopl at interia.pl Thu Sep 8 10:50:32 2005 From: jpopl at interia.pl (=?UTF-8?B?SmFjZWsgUG9wxYJhd3NraQ==?=) Date: Thu, 08 Sep 2005 16:50:32 +0200 Subject: popen in thread on QNX In-Reply-To: References: Message-ID: Laszlo Zsolt Nagy wrote: > - one of your worker threads wants to run a command > - it creates the argument list and puts it into a message queue > - woker thread starts to sleep > - main thread processes the message queue -> it will run popen, put back > the file descriptors into the message and wake up the worker thread > - the worker thread starts to work with the files Just like I wrote in previous thread ("killing thread after timeout") - I am writting application which read command from socket and run it. I need to be sure, that this command will not take too much time, so I need some kind of timeout, and I need to see its stdout and stderr. So I run command on separate thread, this thread calls os.system(command), main thread takes care about timeout. popen or fork/execve would be much better than os.system, but they both fail on QNX, because os.fork() is not implemented in thread From tismer at stackless.com Wed Sep 28 21:12:33 2005 From: tismer at stackless.com (Christian Tismer) Date: Thu, 29 Sep 2005 03:12:33 +0200 Subject: Alternatives to Stackless Python? In-Reply-To: <4333c642$0$25699$626a14ce@news.free.fr> References: <1127231444.643628.197920@g49g2000cwa.googlegroups.com> <1127438841.532386.73410@g44g2000cwa.googlegroups.com> <4333c642$0$25699$626a14ce@news.free.fr> Message-ID: <433B3F81.2080706@stackless.com> Christophe wrote: ... > Not sure if greenlets support pickling yet. There are no info on that > point and my tests weren't succesful. Greenlets refine a concept of Stackless 2.0 which was orthogonal to the Python implementation in a sense that they did not conflict at all. This is less efficient than collaborative task switching, but allows greenlets to exist without any maintenance. A Stackless subset based upon Greenlets is in discussion. Platform independent Pickling support of running tasklets is almost impossible without support from the Python implementation. I see this as an entry point for people to try these ideas. The switching speed is several times slower by principle. ciao - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From russandheather at gmail.com Tue Sep 27 18:40:22 2005 From: russandheather at gmail.com (Qopit) Date: 27 Sep 2005 15:40:22 -0700 Subject: __call__ in module? In-Reply-To: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> References: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> Message-ID: <1127860822.419544.248190@g44g2000cwa.googlegroups.com> Nope - you can't even force it by binding a __call__ method to the module. For future reference, you can check to see what things *are* callable with the built-in function 'callable'. eg (with sys instead of MyApp): >>> import sys >>> callable(sys) False Also - a thing you can do to sort of do what you want (?) is wrap the code to be executed by the module in a main() function. eg: #-- Start of MyApp.py -- def main(foo): print "My cat loves", foo if __name__ == "__main__": import sys main(" ".join(sys.argv[1:])) #-- EOF -- The main function then lets you either run your module from the command line (MyApp.py Meow Mix) or have another module use it with: import MyApp MyApp.main("Meow Mix") From apardon at forel.vub.ac.be Mon Sep 19 03:12:54 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Sep 2005 07:12:54 GMT Subject: Brute force sudoku cracker References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> <1126909078.589245.253390@g47g2000cwa.googlegroups.com> Message-ID: Op 2005-09-16, my.correo.basura at gmail.com schreef : > > Bas ha escrito: > >> Hi group, >> >> I came across some of these online sudoku games and thought after >> playing a game or two that I'd better waste my time writing a solver >> than play the game itself any longer. I managed to write a pretty dumb >> brute force solver that can at least solve the easy cases pretty fast. >> >> It basically works by listing all 9 possible numbers for all 81 fields >> and keeps on striking out possibilities until it is done. >> [snip] > > This problem is desperately begging for backtracking. I don't think so. I regularly solve one and I never needed to try something out, to see if it worked or not except when there were muliple solutions. I think it is a beautifull problem, to make people think of how they could code some of their thought processes, which would be a more fruitfull experience as programming this with backtracking. -- Antoon Pardon From simoninusa2001 at yahoo.co.uk Tue Sep 20 16:25:47 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 20 Sep 2005 13:25:47 -0700 Subject: Getting tired with py2exe In-Reply-To: References: <1127241797.610338.201800@z14g2000cwz.googlegroups.com> Message-ID: <1127247947.066480.219710@f14g2000cwb.googlegroups.com> James Stroud wrote: [snip] > > http://pyinstaller.hpcf.upr.edu/pyinstaller > That's one short "indefinitely": > > Not Found > The requested URL /pyinstaller was not found on this server. > Apache/2.0.53 (Fedora) Server at pyinstaller.hpcf.upr.edu Port 80 It seems that the URL is http://pyinstaller.hpcf.upr.edu >From the website it seems this is a continuation of McMillan Installer, which they claim is "far superior" to py2exe! Personally I gave up on MMI, prefering py2exe on Windows and cx_Freeze on UNIX. And if they want to use UPX, well that's up to them, but I've had some problems with it and don't particularly like the thought of runtime decompression and the two process thing. And when you can compress the distributable using 7zip or whatever, why bother keeping it compressed once downloaded? Ah well, I wish you, whoever takes over py2exe and the PyInstaller guys the best of luck! From mtebeka at qualcomm.com Wed Sep 28 08:22:01 2005 From: mtebeka at qualcomm.com (Miki Tebeka) Date: Wed, 28 Sep 2005 15:22:01 +0300 Subject: Telephony project In-Reply-To: <1127758835.527555.217870@g47g2000cwa.googlegroups.com> References: <1127758835.527555.217870@g47g2000cwa.googlegroups.com> Message-ID: <20050928122201.GD2056@qualcomm.com> Hello Roger, > 1. Fetch phone number from my ASCII data. Trivial in Python. > 2. Dial (always a local number) phone (through USRobotics 56K? ). Can't recall that. > 3. Ask @3 questions to called phone number. Y/N Y/N Y/N You can use flite (http://www.speech.cs.cmu.edu/flite/) for Text-To-Speech. (e.g. system("flite -t 'how are you?'")) > 4. Save answers to ASCII file. You need to get the audio, maybe you can use portaudio (http://www.portaudio.com/) > 5. Say 'Thanks', hang up. flit again. > Repeat till eof() Trivial. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From sybrenUSE at YOURthirdtower.com.imagination Sat Sep 10 04:23:15 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 10 Sep 2005 10:23:15 +0200 Subject: Create new instance of Python class in C References: Message-ID: phil hunt enlightened us with: > Why do you need to maske lots of copies? The puzzles are stored in a NxN list of strings. The strings contain all the numerals that that block can contain. So a 9x9 puzzle contains 81 strings "123456789" when it's "empty". My creation function picks a block that isn't a given, and fixes it to one of it's possible values. It then tries to solve the puzzle. If it works, it's done creating the puzzle. If it doesn't work, it starts over again in a recursive manner. The solver solves the puzzle in-place. That means that if I want to keep the original puzzle (the one that could be solved), I have to make a copy. > And when you say "lots of" what numbers do you mean? 100? 1000000? That depends a lot. The parts "picks a block that isn't a given" and "fixes it to one if it's possible values" are both randomized. Sometimes it's 100, sometimes it's 50000. > The reason I ask is I recently wrote a program to solve Sudoku > puzzles, and IIRC it didn't make copies at all. My solver doesn't create copies either. The creator does. I think I'll change my algorithm to just solve the puzzle and don't care about the original minimal puzzle that could be solved. I'll create a fully solved puzzle, and then use another routine to remove givens at random until the required number of givens is left. Of course, still maintaining solvability. That last part would require copying, but not as much as in the current situation. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From olivier.dormond at hispeed.ch Fri Sep 23 08:07:42 2005 From: olivier.dormond at hispeed.ch (Olivier Dormond) Date: Fri, 23 Sep 2005 14:07:42 +0200 Subject: Alternatives to Stackless Python? In-Reply-To: <4333c642$0$25699$626a14ce@news.free.fr> References: <1127231444.643628.197920@g49g2000cwa.googlegroups.com> <1127438841.532386.73410@g44g2000cwa.googlegroups.com> <4333c642$0$25699$626a14ce@news.free.fr> Message-ID: <4333F00E.8010709@hispeed.ch> Christophe wrote: > simonwittber at gmail.com a ?crit : > >>> I found LGT http://lgt.berlios.de/ but it didn't seem as if the >>> NanoThreads module had the same capabilites as stackless. >> >> What specific capabilities of Stackless are you looking for, that are >> missing from NanoThreads? > > Capabilities of the different "threadlike" systems are somewhat muddy. > What myself I like in stackless is : > - you can put context switching instuctions anywhere in the callstack > without having to explicitely chain the operation > - pickle support > > Not sure if greenlets support pickling yet. There are no info on that > point and my tests weren't succesful. The greenlets play with the underlying CPU stack directly so I don't think they could ever be pickled. From jepler at unpythonic.net Thu Sep 15 12:23:27 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 15 Sep 2005 11:23:27 -0500 Subject: Tkinter add_cascade option_add In-Reply-To: References: <8sCdnf5Vq94_1bXenZ2dnUVZ_sudnZ2d@nmt.edu> Message-ID: <20050915162327.GD2861@unpythonic.net> On Thu, Sep 15, 2005 at 06:11:18PM +0200, Mikael Olofsson wrote: > Is this simply a Windows-issue that cannot easily be solved? Or is it > possibly so that this just happens to be a problem on a few > ill-configured computers? Or am I possibly blind? Here's a section from the menu(n) manpage for Tcl. It would appear that the font for the menubar is one of the things which happens 'according to the interface guidelines of their platforms' on win32-family systems. MENUBARS Any menu can be set as a menubar for a toplevel window (see toplevel command for syntax). On the Macintosh, whenever the toplevel is in front, this menu's cascade items will appear in the menubar across the top of the main monitor. On Windows and Unix, this menu's items will be displayed in a menubar accross the top of the window. These menus will behave according to the interface guidelines of their platforms. For every menu set as a menubar, a clone menu is made. See the CLONES sec- tion for more information. As noted, menubars may behave differently on different platforms. One example of this concerns the handling of checkbuttons and radiobuttons within the menu. While it is permitted to put these menu elements on menubars, they may not be drawn with indicators on some platforms, due to system restrictions. On Windows, the font used for the menu can be ajusted by the user for all applications (except those which go out of their way to ignore the user's preferences) using the Display item in Control Panel. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Tue Sep 27 13:37:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Sep 2005 19:37:10 +0200 Subject: Memory stats References: <43386FE3.7060606@v.loewis.de> <43396704.1030700@nuxeo.com> Message-ID: Tarek Ziad? wrote: > > If you want a list of all objects (container or not), you have to > > compile a debug build of Python. > > I am amazed not to find an existing implementation for this. the debug build is an existing implementation, of course. From sybrenUSE at YOURthirdtower.com.imagination Fri Sep 23 02:26:50 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 23 Sep 2005 08:26:50 +0200 Subject: How to use a timer in Python? References: Message-ID: Nico Grubert enlightened us with: > How can I use a timer that waits e.g. 10 seconds if 'transfer.lock' > is present and then checks again if 'transfer.lock' is still there? Make a while loop in which you sleep. Or use the threading module if you want to go multi-threading. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From steve at holdenweb.com Wed Sep 7 13:10:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Sep 2005 13:10:54 -0400 Subject: Question about concatenation error In-Reply-To: References: Message-ID: colonel wrote: > On Wed, 07 Sep 2005 16:34:25 GMT, colonel > wrote: > > >>I am new to python and I am confused as to why when I try to >>concatenate 3 strings, it isn't working properly. >> >>Here is the code: >> >>------------------------------------------------------------------------------------------ >>import string >>import sys >>import re >>import urllib >> >>linkArray = [] >>srcArray = [] >>website = sys.argv[1] >> >>urllib.urlretrieve(website, 'getfile.txt') >> >>filename = "getfile.txt" >>input = open(filename, 'r') >>reg1 = re.compile('href=".*"') >>reg3 = re.compile('".*?"') >>reg4 = re.compile('http') >>Line = input.readline() >> >>while Line: >> searchstring1 = reg1.search(Line) >> if searchstring1: >> rawlink = searchstring1.group() >> link = reg3.search(rawlink).group() >> link2 = link.split('"') >> cleanlink = link2[1:2] >> fullink = reg4.search(str(cleanlink)) >> if fullink: >> linkArray.append(cleanlink) >> else: >> cleanlink2 = str(website) + "/" + str(cleanlink) >> linkArray.append(cleanlink2) >> Line = input.readline() >> >>print linkArray >>----------------------------------------------------------------------------------------------- >> >>I get this: >> >>["http://www.slugnuts.com/['index.html']", >>"http://www.slugnuts.com/['movies.html']", >>"http://www.slugnuts.com/['ramblings.html']", >>"http://www.slugnuts.com/['sluggies.html']", >>"http://www.slugnuts.com/['movies.html']"] >> >>instead of this: >> >>["http://www.slugnuts.com/index.html]", >>"http://www.slugnuts.com/movies.html]", >>"http://www.slugnuts.com/ramblings.html]", >>"http://www.slugnuts.com/sluggies.html]", >>"http://www.slugnuts.com/movies.html]"] >> >>The concatenation isn't working the way I expected it to. I suspect >>that I am screwing up by mixing types, but I can't see where... >> >>I would appreciate any advice or pointers. >> >>Thanks. > > > > Okay. It works if I change: > > fullink = reg4.search(str(cleanlink)) > if fullink: > linkArray.append(cleanlink) > else: > cleanlink2 = str(website) + "/" + str(cleanlink) > > to > > fullink = reg4.search(cleanlink[0]) > if fullink: > linkArray.append(cleanlink[0]) > else: > cleanlink2 = str(website) + "/" + cleanlink[0] > > > so can anyone tell me why "cleanlink" gets coverted to a list? Is it > during the slicing? > > > Thanks. The statement cleanlink = link2[1:2] results in a list of one element. If you want to accesss element one (the second in the list) then use cleanlink = link2[1] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From en.karpachov at ospaz.ru Fri Sep 30 01:11:26 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Fri, 30 Sep 2005 09:11:26 +0400 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xzmpwuxd0.fsf@ruckus.brouhaha.com> <20050930075313.67b9b6 76.jk@ospaz.ru> Message-ID: <20050930091126.0c81580c.jk@ospaz.ru> On Fri, 30 Sep 2005 06:31:44 +0200 Fredrik Lundh wrote: > en.karpachov at ospaz.ru wrote: > > > Looks like you must know every one of the base classes of the NotSoSecret, > > whether there is some base class named Secret? And, if so, you must also > > know these classes _implementation_ > > that information isn't hidden, so there's nothing "you must know". finding out > is a matter of writing a very small program, or tinkering at the interactive prompt > for a couple of seconds. are you even aware that you're posting to a Python > group ? So you have read every line of the python std library, I guess? (Not to mention libc or kernel32.exe or whatever.) -- jk From roy at panix.com Sat Sep 10 15:11:34 2005 From: roy at panix.com (Roy Smith) Date: Sat, 10 Sep 2005 15:11:34 -0400 Subject: Python versus Perl References: Message-ID: Dieter Vanderelst wrote: > 1 - How does the speed of execution of Perl compares to that of Python? To a first-order approximation, Perl and Python run at the same speed. They are both interpreted languages with roughly the same kind of control flow and data structures. The two have wildly different kinds of syntax, but the underlying machinery is fairly similar. Don't make a decision on which to use based on execution speed. If you feel compelled to ignore this advice, then don't make the decision until you've coded your application in both languages and done careful benchmarking with realistic data for your application domain. > I have noticed that Regular Expressions are executed very fast in > Python. Does anybody know whether Python executes RE faster than Perl > does? Same answer as above -- for a first cut, assume they are the same speed. If you insist on a better answer, do measurements on real data. The big advantage the Python has over Perl is speed of development and ease of maintenance (i.e. a year from now, you can still understand what your own code does). From dimitri.pater at gmail.com Fri Sep 30 19:36:28 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Sat, 1 Oct 2005 01:36:28 +0200 Subject: A Moronicity of Guido van Rossum In-Reply-To: References: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> <1128013745.763757.144280@g44g2000cwa.googlegroups.com> <1128015868.201617.153240@g14g2000cwa.googlegroups.com> <0001HW.BF63479501083049F0407550@news.individual.de> Message-ID: > > > > Yes, it would. Note that the word lunatic is derived from the Latin word > luna, meaning moon. so, he is a just another lunitac barking at the moon? well, err barking at the python list... greetz, dimitri -------------- next part -------------- An HTML attachment was scrubbed... URL: From pink at odahoda.de Thu Sep 1 13:13:37 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Thu, 01 Sep 2005 19:13:37 +0200 Subject: is there a better way to check an array? References: <1125593752.264254.172970@g44g2000cwa.googlegroups.com> Message-ID: jdonnell wrote: > I want to check if a value is in an array. I'm currently doing it as > follows, but I just don't like this way of doing it. It seems > unpythonic. > > fieldIsRequired = true > try: > notRequiredAry.index(k) > fieldIsRequired = false > except ValueError: > pass > > # throw expception if field is required and is empty > if(product[k] == '' and fieldIsRequired): > raise GMError(k + ' is required') if product[k] == '' and k in fieldIsRequired: raise GMError(k + ' is required') -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From bearophileHUGS at lycos.com Sat Sep 17 09:50:56 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Sep 2005 06:50:56 -0700 Subject: sorting tuples... In-Reply-To: <1126964468.444025.181180@g49g2000cwa.googlegroups.com> References: <1126964468.444025.181180@g49g2000cwa.googlegroups.com> Message-ID: <1126965056.689482.294690@g44g2000cwa.googlegroups.com> Uhm, if the file is clean you can use something like this: data = """\ 200501221530 John *** long string here *** 200504151625 Clyde *** clyde's long string here *** 200503130935 Jeremy *** jeremy string here ****""" records = [rec.split("\n") for rec in data.split("\n\n")] records.sort() print records If it's not clean, you have to put some more cheeks/cleanings. Bye, bearophile From crankycoder at gmail.com Sun Sep 25 23:30:21 2005 From: crankycoder at gmail.com (Victor Ng) Date: Sun, 25 Sep 2005 23:30:21 -0400 Subject: Metaclasses, decorators, and synchronization In-Reply-To: <9c195fe6cc1bc873d9a90483f592e1f2@scl.ameslab.gov> References: <9c195fe6cc1bc873d9a90483f592e1f2@scl.ameslab.gov> Message-ID: You could do it with a metaclass, but I think that's probably overkill. It's not really efficient as it's doing test/set of an RLock all the time, but hey - you didn't ask for efficient. :) 1 import threading 2 3 def synchronized(func): 4 def innerMethod(self, *args, **kwargs): 5 if not hasattr(self, '_sync_lock'): 6 self._sync_lock = threading.RLock() 7 self._sync_lock.acquire() 8 print 'acquired %r' % self._sync_lock 9 try: 10 return func(self, *args, **kwargs) 11 finally: 12 self._sync_lock.release() 13 print 'released %r' % self._sync_lock 14 return innerMethod 15 16 class Foo(object): 17 @synchronized 18 def mySyncMethod(self): 19 print "blah" 20 21 22 f = Foo() 23 f.mySyncMethod() If you used a metaclass, you could save yourself the hassle of adding a sync_lock in each instance, but you could also do that by just using a plain old base class and making sure you call the base class's __init__ to add in the sync lock. vic On 9/24/05, Michael Ekstrand wrote: > I've been googling around for a bit trying to find some mechanism for > doing in Python something like Java's synchronized methods. In the > decorators PEP, I see examples using a hypothetical synchronized > decorator, but haven't stumbled across any actual implementation of > such a decorator. I've also found Synch.py, but that seems to use > pre-2.2 metaclasses from what I have read. > > Basically, what I want to do is something like this: > > class MyClass: > __metaclass__ = SynchronizedMeta > @synchronized > def my_sync_method(): > pass > > where SychronizedMeta is some metaclass that implements synchronization > logic for classes bearing some synchronized decorator (probably also > defined by the module defining SynchronizedMeta). > > After looking in the Cheeseshop, the Python source distribution, and > Google, I have not been able to find anything that implements this > functionality. If there isn't anything, that's fine, I'll just write it > myself (and hopefully be able to put it in the cheeseshop), but I'd > rather avoid duplicating effort solving previously solved problems... > So, does anyone know of anything that alreaady does this? (or are there > some serious problems with my design?) > > TIA, > Michael > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Never attribute to malice that which can be adequately explained by stupidity." - Hanlon's Razor From theller at python.net Tue Sep 20 05:51:14 2005 From: theller at python.net (Thomas Heller) Date: Tue, 20 Sep 2005 11:51:14 +0200 Subject: py2exe 0.6.2 version resources References: <1127201535.064565.91670@g14g2000cwa.googlegroups.com> Message-ID: klaus.roedel at vipco.de writes: > Hi @all, > > I've implementet a simple setup script for my application with py2exe. > The setup.py works fine, but now I want to add version resources to my > *.exe-file. But how can I do it? > I've tested it with the setup.cfg, but that doesn't work. I alwayse > became the errormessage: > error: error in setup.cfg: command 'py2exe' has no such option > 'version_legalcopyright' > until I've deleted all options. > I'm using python 2.4.1 and py2exe 0.6.2 on Windows XP SP2. > Thanks for any help. In py2exe 0.5 and 0.6 you can no longer specify the versionresource in setup.cfg. The advanced sample in lib\site-packages\py2exe\samples\advanced demonstrated how to do it. > Greets, > Klaus Thomas From steve at holdenweb.com Sun Sep 4 01:45:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 04 Sep 2005 00:45:58 -0500 Subject: how to do this? In-Reply-To: <9cvSe.3820$3R1.2590@fe06.lga> References: <9cvSe.3820$3R1.2590@fe06.lga> Message-ID: Justin Straube wrote: > Greetings Pythonistas. > Im looking for a way to write this but not sure where or how to begin. > As the user enters or removes characters into/from sEnt I would like > for set_info() to set infVar with the correct value. The same as how > IDLE shows the line and column in the lower right corner. > First of all, it might have been better to provide a more meaningful title like "Update display as text entry changes", but not to worry - this is a matter of experience. > #### Code Example #### > from time import localtime > from Tkinter import * > > def set_info(): > x = len(strVar.get()) > infVar.set('Length: %i' % (x)) > > ROOT = Tk() > strVar = StringVar() > infVar = StringVar() > > sLab = Label(ROOT, text='String') > sLab.grid(row=0, column=0) > sEnt = Entry(ROOT, textvariable=strVar, width=15) > sEnt.grid(row=0, column=1, columnspan=2) > qBut = Button(ROOT, text='Quit', command=ROOT.quit) > qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E) > iLab = Label(ROOT, textvariable=infVar, width=21, > relief=SUNKEN, anchor=W) > iLab.grid(row=2, column=0, columnspan=3) > > set_info() # example to show what will be displayed. > ROOT.mainloop() > #### End Example #### > > Can anyone point me in the right direction for how to do this? > The key here is to bind keystroke events to the routine to change the display. The following program uses your set_info() function to update the display every time a key is released (I chose this event because by the time it is raised the keystroke has been processed by the Entry widget. I don;t guarantee this code will work across several Entry widgets without your keeping track of which one has focus when the event is raised (it's late, and I'm about to turn in for the night), but at least it will give you something to play with. You'll note that set_info() has acquired an argument - Tkinter provides an event as an argument when a callback is called. So the manual call gets a bogus event of "None" just to avoid exceptions. Hope this gets you started. #### Code Example #### from time import localtime from Tkinter import * def set_info(event): x = len(strVar.get()) infVar.set('Length: %i' % (x)) ROOT = Tk() strVar = StringVar() infVar = StringVar() sLab = Label(ROOT, text='String') sLab.grid(row=0, column=0) sEnt = Entry(ROOT, textvariable=strVar, width=15) sEnt.grid(row=0, column=1, columnspan=2) sEnt.bind("", set_info) qBut = Button(ROOT, text='Quit', command=ROOT.quit) qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E) iLab = Label(ROOT, textvariable=infVar, width=21, relief=SUNKEN, anchor=W) iLab.grid(row=2, column=0, columnspan=3) set_info(None) # example to show what will be displayed. ROOT.mainloop() #### End Example #### regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From renting at astron.nl Fri Sep 16 03:02:59 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 16 Sep 2005 09:02:59 +0200 Subject: read stdout/stderr without blocking Message-ID: Great reply, I had just mixed Pexpect and subProcess code until I'd got something that worked, you can actually explain my code better a I can myself. I find it quite cumbersome to read stdout/strerr separately, and to be able to write to stdin in reaction to either of them, but at least on Linux you can get it to work. My NON_BLOCKing command might be unnecesary, I'll try without it. The OP seemed interested on how to do this on Windows, but I've yet to see an answer on that one I think. Thank you for the reply. Adriaan Renting |>>>Donn Cave 09/15/05 6:19 pm >>> |In article , |Peter Hansen wrote: | |>Jacek Pop?awski wrote: |>>Grant Edwards wrote: |>> |>>>On 2005-09-12, Jacek Pop?awski wrote: |>>> |>>>>> ready = select.select(tocheck, [], [], 0.25) ##continues |>>>>>after 0.25s |>>>>> for file in ready[0]: |>>>>> try: |>>>>> text = os.read(file, 1024) |>>>> |>>>> |>>>>How do you know here, that you should read 1024 characters? |>>>>What will happen when output is shorter? |>>> |>>>It will return however much data is available. |>> |>>My tests showed, that it will block. |> |>Not if you use non-blocking sockets, as I believe you are expected to |>when using select(). | |On the contrary, you need non-blocking sockets only if |you don't use select. select waits until a read [write] |would not block - it's like "if dict.has_key(x):" instead of |"try: val = dict[x] ; except KeyError:". I suppose you |knew that, but have read some obscure line of reasoning |that makes non-blocking out to be necessary anyway. |Who knows, but it certainly isn't in this case. | |I don't recall the beginning of this thread, so I'm not sure |if this is the usual wretched exercise of trying to make this |work on both UNIX and Windows, but there are strong signs |of the usual confusion over os.read (a.k.a. posix.read), and |file object read. Let's hopefully forget about Windows for |the moment. | |The above program looks fine to me, but it will not work |reliably if file object read() is substituted for os.read(). |In this case, C library buffering will read more than 1024 |bytes if it can, and then that data will not be visible to |select(), so there's no guarantee it will return in a timely |manner even though the next read() would return right |away. Reading one byte at a time won't resolve this problem, |obviously it will only make it worse. The only reason to |read one byte at a time is for data-terminated read semantics, |specifically readline(), in an unbuffered file. That's what |happens -- at the system call level, where it's expensive -- |when you turn off stdio buffering and then call readline(). | |In the C vs. Python example, read() is os.read(), and file |object read() is fread(); so of course, C read() works |where file object read() doesn't. | |Use select, and os.read (and UNIX) and you can avoid blocking |on a pipe. That's essential if as I am reading it there are supposed |to be two separate pipes from the same process, since if one is |allowed to fill up, that process will block, causing a deadlock if |the reading process blocks on the other pipe. | |Hope I'm not missing anything here. I just follow this group |to answer this question over and over, so after a while it |gets sort of automatic. | | Donn Cave, donn at u.washington.edu From NutJob at gmx.net Mon Sep 19 07:46:10 2005 From: NutJob at gmx.net (antred) Date: 19 Sep 2005 04:46:10 -0700 Subject: threads/sockets quick question. In-Reply-To: <1127103181.088804.173820@g14g2000cwa.googlegroups.com> References: <1127103181.088804.173820@g14g2000cwa.googlegroups.com> Message-ID: <1127130369.929039.8380@z14g2000cwz.googlegroups.com> This may be a really stupid question, but are you actually CALLING your scan() function anywhere? From fakeaddress at nowhere.org Wed Sep 7 04:29:52 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 07 Sep 2005 08:29:52 GMT Subject: dict and __cmp__() question In-Reply-To: <1126078954.485637.172070@g47g2000cwa.googlegroups.com> References: <1126078954.485637.172070@g47g2000cwa.googlegroups.com> Message-ID: <4yxTe.892$JN5.336@newssvr13.news.prodigy.com> Alex wrote: > But what are those with double underscore? For instance __cmp__(...)? Those are these: http://docs.python.org/ref/specialnames.html -- --Bryan From n00m at narod.ru Sun Sep 4 09:41:53 2005 From: n00m at narod.ru (n00m) Date: 4 Sep 2005 06:41:53 -0700 Subject: Sockets: code works locally but fails over LAN In-Reply-To: References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> <1125681663.710557.320340@f14g2000cwb.googlegroups.com> <3m6ih1taaeo7kndnbuvfl5geed053ivunl@4ax.com> <1125774529.074965.269720@g44g2000cwa.googlegroups.com> <1125790986.012636.40050@o13g2000cwo.googlegroups.com> Message-ID: <1125841313.297294.304690@o13g2000cwo.googlegroups.com> Bryan Olson wrote: > Ah, yes, I see. (In my defense, I had already fixed that bug in > my second version.) 1. Yes! I myself noticed that, but your 2nd version looks a bit more verbose. 2. This all means... what? ONLY send() vs sendall() matters? Sometimes send() really sends ALL and my version works too! I must give it a thorough testing! 3. See how it looks in SQL Server Profiler (it's its utility for tracing client/server events) WHEN I started 5 copies of .vbs. http://free.7host02.com/n00b/SQL_Profiler.gif Btw, without s2.shutdown(1) those vbs' do NOT disconnect from the server (see DISCONNECT events on the gif). The latest python version: ============================== import socket, thread sqls_host, sqls_port = '127.0.0.1', 1433 proxy_host, proxy_port = '127.0.0.1', 1434 # How I tested it: # sqls_host, sqls_port = 'www.google.com', 80 def VB_SCRIPT(s2, cn): while 1: data = cn.recv(4096) if not data: s2.shutdown(1) return s2.sendall(data) print 'VB_SCRIPT:' + data + '\n' def SQL_SERVER(s2, cn): while 1: data = s2.recv(4096) if not data: return cn.sendall(data) print 'SQL_SERVER:' + data + '\n' s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((proxy_host, proxy_port)) s1.listen(5) while 1: cn, addr = s1.accept() s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.connect((sqls_host, sqls_port)) thread.start_new_thread(VB_SCRIPT,(s2, cn)) thread.start_new_thread(SQL_SERVER,(s2, cn)) The vbs text: ============== Set cn = CreateObject("ADODB.Connection") cn.Open _ "Provider=sqloledb;Data Source=127.0.0.1,1434;" & _ "Network Library=DBMSSOCN;Initial Catalog=pubs;" & _ "User ID=qwe;Password=asdasd;" cn.Execute _ "select 'AAAAAAAAAAAAAAA';" & _ "waitfor delay '00:00:02'; raiserror('XXX',10,1) with nowait;" & _ "waitfor delay '00:00:02'; raiserror('YYY',10,1) with nowait;" & _ "waitfor delay '00:00:02'; raiserror('ZZZ',10,1) with nowait;" & _ "select 'BBBBBBBBBBBBBBB';" cn.Close Set cn = Nothing From jstroud at mbi.ucla.edu Mon Sep 19 17:46:15 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 19 Sep 2005 14:46:15 -0700 Subject: Best Encryption for Python Client/Server In-Reply-To: References: Message-ID: <200509191446.15240.jstroud@mbi.ucla.edu> SSH can be used for functionality like this, through tunneling. You can even tunnel interprocess communication through SSH. Its not exceptionally complicated. On Sunday 18 September 2005 13:36, Ed Hotchkiss wrote: > Let us say that I am trying to create a very small and simple private > network/connection between several scripts on different machines, to > communicate instructions/data/files etc. to each other over the net. Is SSL > the best method? Any recommendations of something to get started with? > Thanks in advance. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From deets at nospam.web.de Fri Sep 2 09:38:13 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 02 Sep 2005 15:38:13 +0200 Subject: How to handle video & alpha channel In-Reply-To: References: Message-ID: <3nr2u5F2sm47U1@uni-berlin.de> Mic wrote: > I'm looking for a way to build a little player (if possibile with > python ) that could handle common video file formats (mpeg or other) > with above an image with alpha channel (png or other) > > Is there a way to make this with python and available libs (PIL etc)? Check out pymedia. Regards, Diez From http Sat Sep 10 19:30:47 2005 From: http (Paul Rubin) Date: 10 Sep 2005 16:30:47 -0700 Subject: encryption with python References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <87k6hok51e.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <7xhdcsfql4.fsf@ruckus.brouhaha.com> James Stroud writes: > Yes and no. Yes, you are theoretically correct. No, I don't think > you have the OP's original needs in mind (though I am mostly > guessing here). The OP was obviously a TA who needed to assign > students a number so that they could "anonymously" check their > publicly posted grades and also so that he could do some internal > record keeping. If that's all it's about, it's not a big deal. If it's for some central administrative database that's more of a target, more care is warranted. > The idea of combining ID information and encrypting it to create The info to be combined was the student's birthdate. Why would the TA have access to either that or the SSN? > import sha > def encrypt(x,y, password): > def _dosha(v): return sha.new(str(v)+str(password)).hexdigest() > return int(_dosha(_dosha(x)+_dosha(y))[5:13],16) > > So now what is the criticism? That its still a "secret algorithm" > because the password is "secret"? That's sort of reasonable as long as the password really is secret and you don't mind a small chance of two students getting the same ID number once in a while. If the password is something that a TA types into a laptop when entering grades and which goes away after the course ends, it's not such a big deal. If it's a long-term key that has to stay resident in a 24/7 server through the students' entire time at the university and beyond, then the algorithm is the trivial part and keeping the key secret is a specialized problem in its own right. For example, financial institutions use special, tamper resistant hardware modules for the purpose. Could the OP please say what the exact application is? That might get more useful responses if the question still matters. From tdelaney at avaya.com Thu Sep 29 21:12:37 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 30 Sep 2005 11:12:37 +1000 Subject: A Moronicity of Guido van Rossum Message-ID: <2773CAC687FD5F4689F526998C7E4E5F4DB685@au3010avexu1.global.avaya.com> Tony Meyer wrote: > I expect that if you look at the clues for such messages, you'll find > that any 'Xah Lee' clues are swamped by lots of 'c.l.p message' > clues. A big problem with filtering mailing lists at the user end > (rather than before the post is accepted) is that the mailing > software adds so many strongly-correlated clues. It's made worse > because he uses so many words that you'd expect to find in legitimate > c.l.p messages. It's this last bit that's the problem. I've got no problems filtering other types of spam messages to the list, but XL adds so many non-spam terms that the from field gets declared a statistical anomaly :( Tim Delaney From hancock at anansispaceworks.com Thu Sep 22 18:08:17 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 22 Sep 2005 17:08:17 -0500 Subject: Question About Logic In Python In-Reply-To: <0PBYe.109568$p_1.45988@tornado.tampabay.rr.com> References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> <0PBYe.109568$p_1.45988@tornado.tampabay.rr.com> Message-ID: <200509221708.17917.hancock@anansispaceworks.com> On Thursday 22 September 2005 12:26 pm, Ron Adam wrote: > Steve Holden wrote: > > Ron Adam wrote: > >> >>> True * True > >> 1 # Why not return True here as well? > >> > > Why not return 42? Why not return a picture of a banana? > > My question still stands. Could it be helpful if bools were preserved > in more cases than they are now? No. "*" is "multiplication". The multiplication operator is undefined for boolean values. It only makes sense if they are interpreted as numbers. As it happens, both can be coerced to 1, so the result is 1*1. This makes perfect sense to me. >>> True and True True Also makes sense (and this is indeed what happens). Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ajikoe at gmail.com Wed Sep 21 05:03:09 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 21 Sep 2005 02:03:09 -0700 Subject: spe stani collapse all method? Message-ID: <1127293388.964632.303960@z14g2000cwz.googlegroups.com> hello, I wonder if anyone used spe stani, I'm looking for how to collapse all code fold, but can't find. pujo From peter at engcorp.com Fri Sep 30 07:33:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Sep 2005 07:33:23 -0400 Subject: RELEASED Python 2.4.2 (final) In-Reply-To: <433CCF02.6060005@v.loewis.de> References: <433CCF02.6060005@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Trent Mick wrote: > >>It is possible that the python.org installer didn't overwrite the >>"python24.dll" in the system directory (C:\WINDOWS\system32). Try doing >>this: > > > Even though this is apparently what happened, I'm puzzled as to why it > happened: shouldn't the version number of python24.dll in the pydotorg > installer be higher than the one in the ActivePython installer, and > shouldn't then Windows Installer overwrite the DLL? Couldn't it also happen if the first time someone did an "admin" install which (I believe) puts the DLLs in the system folder, and the next time did just a non-admin install which doesn't do that? (Or am I misunderstanding the conditions under which c:\windows\system32 has files written to it?) -Peter From http Wed Sep 28 18:23:07 2005 From: http (Paul Rubin) Date: 28 Sep 2005 15:23:07 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> Message-ID: <7x64skzvas.fsf@ruckus.brouhaha.com> Gregor Horvath writes: > If its your code this is possible, but if not and the maintainer is > not willing or able to change it, then you have a problem. Perhaps the maintainer has good reason for not wanting to change it. After all, he's maintaining the code and you're not. In the course of that maintenance he might change the internal usage of the private variable that messes up the way you use it. He's supposed to be allowed to do that--that's why the variable is private. Is he supposed to get your permission every time he wants to change how the private variables in his class work? > The fact that in other languages there are wired tricks to get to > private instance variables is a strong indicator that there is a need > for that. Java has some JVM switches that open ways to get at private variables so things like debuggers can work. In production code you'd turn that stuff off. And it's certainly not intended for normal classes in an application to get at the private variables of other classes. > Guided freedom is better than enforced authority. The obvious way to provide that guidance is to declare variables to be private if other classes shouldn't mess with the variables. There is still the freedom to change the declaration if necessary. Unless of course you don't have the source code. Where there is no source code, there is no freedom, no matter what features the language has. From darkpaladin79 at hotmail.com Thu Sep 29 20:29:37 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 29 Sep 2005 20:29:37 -0400 Subject: Turning off syntax warnings? Message-ID: Here's a noob question for everyone which i can't seem to find the answer to on google. . .Is there a way to turn off syntax warnings? -Ivan _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From jeffrey.schwab at rcn.com Thu Sep 29 09:22:12 2005 From: jeffrey.schwab at rcn.com (Jeff Schwab) Date: Thu, 29 Sep 2005 09:22:12 -0400 Subject: A rather unpythonic way of doing things In-Reply-To: <37ll1gci8v.fsf@chiark.greenend.org.uk> References: <37ll1gci8v.fsf@chiark.greenend.org.uk> Message-ID: Peter Corbett wrote: > One of my friends has recently taken up Python, and was griping a bit > about the language (it's too "prescriptive" for his tastes). In > particular, he didn't like the way that Python expressions were a bit > crippled. So I delved a bit into the language, and found some sources > of syntactic sugar that I could use, and this is the result: > > http://www.pick.ucam.org/~ptc24/yvfc.html Yuma Valley Agricultural Center? Yaak Valley Forest Council? From email at christoph-haas.de Sun Sep 25 17:24:04 2005 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 25 Sep 2005 23:24:04 +0200 Subject: Best practices for dynamically loading plugins at startup Message-ID: <20050925212404.GA6934@torf.workaround.org> Dear coders... I'm working on an application that is supposed to support "plugins". The idea is to use the plugins as packages like this: Plugins/ __init__.py Plugin1.py Plugin2.py Plugin3.py When the application starts up I want to have these modules loaded dynamically. Users can put their own plugin modules into the Plugins/ directory and the application should know about it. Since I don't know which plugins have been put into that directory I cannot just "import Plugin1, Plugin2, Plugin3" in the "__init__.py". So I need to find out the *.py there and load them during startup. I could do that with a "walk" over that directory. Each plugin is supposed to be a class derived from a general "Plugin" superclass. I just don't know how to 'register' every plugin. The main application needs to know which plugin classes there are. On IRC I was recommended walking through all objects and finding out if the class is a subclass of "Plugin". Another person recommended using metaclasses to automatically register the plugin in a global list. Since I have only little real-life Python knowledge I wonder what the best practice for this kind of problem is. I looked at the "supybot" IRC bot to get an idea how plugins are handled there. Unfortunately it was still a bit over my (python) head. Regards Christoph -- ~ ~ ~ ".signature" [Modified] 3 lines --100%-- 3,41 All From grante at visi.com Thu Sep 15 18:13:52 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Sep 2005 22:13:52 -0000 Subject: 2.3 -> 2.4: long int too large to convert to int Message-ID: <11ijsh0h2dec0ed@corp.supernews.com> I give up, how do I make this not fail under 2.4? fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00)) I get an OverflowError: long int too large to convert to int ioctl() is expecting a 32-bit integer value, and 0xc0047a80 has the high-order bit set. I'm assuming Python thinks it's a signed value. How do I tell Python that 0xc0047a80 is an unsigned 32-bit value? -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com From eghost at flashmail.com Sat Sep 24 15:32:37 2005 From: eghost at flashmail.com (Sam L.) Date: 24 Sep 2005 12:32:37 -0700 Subject: Could this C extension be leaking memory? Message-ID: <1127590357.126298.280260@g49g2000cwa.googlegroups.com> I am trying this out, parts of it are direct from the Python 2.4 manual. //----------- icallbk.c #include "Python.h" PyObject *fcallback = NULL; static PyObject* call_func(PyObject* self, PyObject* args) { PyObject *result; PyObject *arglist; int arg = 123; arglist = Py_BuildValue("(i)", arg); result = PyEval_CallObject(fcallback, arglist); Py_DECREF(arglist); Py_DECREF(result); Py_RETURN_NONE; } static PyObject * set_callback(PyObject *self, PyObject *args) { PyObject *result = NULL; PyObject *temp; if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { if (!PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); return NULL; } Py_XINCREF(temp); /* Add a reference to new callback */ Py_XDECREF(fcallback); /* Dispose of previous callback */ fcallback = temp; /* Remember new callback */ /* Boilerplate to return "None" */ Py_INCREF(Py_None); result = Py_None; } return result; } static PyMethodDef icallbk_methods[] = { { "call_func", call_func, METH_VARARGS, "call_func" }, { "set_callback", set_callback, METH_VARARGS, "set_callback" }, { 0,0,0,0 } }; PyMODINIT_FUNC initicallbk(void) { (void) Py_InitModule("icallbk", icallbk_methods); } """ I use the following code to run the extension above. """ # cb.py: Code to run the extension above. import icallbk as c def f(a): print a c.set_callback(f) c.call_func() """ But when I run that for a hundred times, I think the system is losing 100KB or thereabouts that is no longer re-claimed. Can someone confirm this, and if it so, kindly inform me what is wrong with the code? Thanks From rkern at ucsd.edu Wed Sep 7 18:33:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 07 Sep 2005 15:33:25 -0700 Subject: Construct raw strings? In-Reply-To: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> References: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> Message-ID: Thomas W wrote: > I got a stupid problem; on my WinXP-box I want to scan the filesystem > and enter a path to scan like this : > > path_to_scan = 'd:\test_images' path_to_scan = r'd:\test_images' > This is used in a larger context and joined like > > real_path_after_scanning = os.path.join(path_to_scan, somepart, 'foo', > 'bar', filename) > > Using os.path.exists(real_path_after_scanning) returns false. The > problem is that some of the parts being joined contains escape > characters, like \. If I take the seperate parts and join them using > the interpreter, like : > >>>>f = r'd:\test_images\something\foo\bar\test.jpg' > > it works ok and os.path.exists(f) returns True, but I cannot the that > r' in front using the os.path.join-method in my code. There is no such thing as a "raw string." There are "raw string literals" which, when evaluated as Python source, are interpreted with slightly different rules than regular "string literals." After the literal has been interpreted to yield a string object, there is no difference between the two; they're both just string objects. If you can, please post a small but complete example script that causes errors (and the actual output of the error itself). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dale at riverhall.nospam.co.uk Fri Sep 23 11:44:17 2005 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Fri, 23 Sep 2005 16:44:17 +0100 Subject: Config parser module References: <1127489369.091513.206040@g49g2000cwa.googlegroups.com> Message-ID: <8pVYe.60117$a86.1519@fe04.usenetserver.com> The Config Parser module is for extracting data from and writing to a specific format of file, generally known as a config file. As explained in the documentation, a config file is in the same format as .ini files frequently found on windows - especially used by older software. It is a very handy file format for all sorts of jobs, more so on Linux these days than Windows, probably. However, it isn't much use for your particular need as described here. qqcq6s59 at gmail.com wrote: > Hi all > I am a newbie and I just saw a ongoing thread on Fileprocessing which > talks abt config parser. > I have writen many pyhton program to parse many kind of text files by > using string module and regex. But after reading that config parser > thread I feel stunned. > > Can somebody tell me some intro info how to parse huge data (most of > them are input data to application softwares like nastran, abaqus etc) > > Recently I saw a great work by John on Nastran file parser (i am still > trying to understand the program, > http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ > > An example of dat may be like this, (part of) > (say point id coordinateSysNo x,y,z ...) > GRID 1 12478.0 0.0 256.75 1 > GRID 2 12357.25 0.0 256.75 1 > GRID 3 12357.25 0.0 199.0 1 > (say Elementtype id property point1 point 2 point3 point4 etc) > CQUAD4 7231 21 5691 5700 5701 56920.0 > > CQUAD4 7232 21 5692 5701 5702 56930.0 > > CQUAD4 7233 21 5693 5702 5703 56940.0 > > the data file is very complex if i consider all complexities) > > Is is possible to use config parser module insome way for this. I also > have few perl parser (for some part for some particular tasks) and now > changing them to python. (I feel perl regex combination is very easy to > learn and very powerfull) > > Any information will be appreciated. > > -jiro -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk We're recruiting Python programmers. See web site. From miki.tebeka at zoran.com Thu Sep 1 04:01:55 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 1 Sep 2005 11:01:55 +0300 Subject: Epydoc - Documenting class members? In-Reply-To: <200508311702.04363.hancock@anansispaceworks.com> References: <20050831141106.GG2656@zoran.com> <200508311702.04363.hancock@anansispaceworks.com> Message-ID: <20050901080153.GJ2656@zoran.com> Hello Terry, [Miki] >> Is there a way to document class members in Epydoc? [Terry] > Yes. See additions below: > > > Something like: > > > > class Point: > """ > @ivar x: This is where you document x. > @ivar y: This is where you document y. > """ I don't like this, I want to document where I declare the variable below. Doxygen (www.doxygen.org), for one example, knows how to do this. > > def __init__(self, x, y): > > '''Create new point > > @param x: X coord > > @param y: Y coord > > ''' > > self.x = x # How do I document here? > > self.y = y # How do I document here? > All of the fields are documented on the http://epydoc.sf.net > website, by the way. I know. Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From mfranklin1 at gatwick.westerngeco.slb.com Thu Sep 8 05:29:19 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 08 Sep 2005 10:29:19 +0100 Subject: reading the last line of a file In-Reply-To: References: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> <1126168591.395956.118840@z14g2000cwz.googlegroups.com> Message-ID: <4320046F.1040606@gatwick.westerngeco.slb.com> Martin Franklin wrote: > Xah Lee wrote: > >>Martin Franklin wrote: >> >> >>>import gzip >>>log_file = gzip.open("access_log.4.gz") >>>last_line = log_file.readlines()[-1] >>>log_file.close() >> >> >>does the >>log_file.readlines()[-1] >>actually read all the lines first? > > > > Yes I'm afraid it does. > > > >>i switched to system call with tail because originally i was using a >>pure Python solution >> >> inF = gzip.GzipFile(ff, 'rb'); >> s=inF.readlines() >> inF.close() >> last_line=s[-1] >> >>and since the log file is 100 megabytes it takes a long time and hogs >>massive memory. >> > > > Ok, in that case stick to your shell based solution, although 100 > megabytes does not sound that large to me I guess it is relative > to the system you are running on :) (I have over a gig of memory here) > And just a few minutes after I sent that... this... import gzip logfile = gzip.open("access_log.4.BIG.gz") ## seek relative to the end of the file logfile.seek(-500) last_line = logfile.readlines()[-1] logfile.close() print last_line Works quite fast on my machine... Regards Martin From steven.bethard at gmail.com Mon Sep 19 11:50:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 19 Sep 2005 09:50:43 -0600 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Consider this: > > def func(some_tuple): > > How many items should you pass in the tuple? If it takes variable > arguments, then that works, but if you always expect a fixed number, then > > def func((x, y)) > > is more explicit. > > The only problem I have is that once you unroll the tuple like that, it is > hardly necessary to pass the argument as a tuple. Why not just pass x and > y as two arguments? > > def func(x, y) I generally agree with this (and follow the same guideline in my own APIs), but sometimes you don't have this option. If I have a class that I'd like to support an indexing operation like: obj[x, y] then the natural __getitem__ signature will look like: def __getitem__(self, (x, y)): ... STeVe From bill.mill at gmail.com Mon Sep 19 15:40:44 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 19 Sep 2005 15:40:44 -0400 Subject: C#3.0 and lambdas In-Reply-To: <3p85r3F91u2eU1@uni-berlin.de> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <3p85r3F91u2eU1@uni-berlin.de> Message-ID: <797fe3d405091912402a8cf1d6@mail.gmail.com> On 9/19/05, Diez B. Roggisch wrote: > > meanwhile, over in python-dev land: > > > > "Is anyone truly attached to nested tuple function parameters; 'def > > fxn((a,b)): print a,b'? /.../ > > > > Would anyone really throw a huge fit if they went away? I am willing > > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > > people are up for it." > > I am - I think that feature is sort of an orthogonality which should be > preserved. No doubt its not one of the most important ones - but if I > can write > > a, (b ,c) = 1, (2,3) > > I'd like to write > > def foo(a, (b,c)): > ... > > foo(1, (2,3)) > Agreed. I discovered them when I wondered "wouldn't it be neat if functions unpacked tuples just like regular code does?" And was pleasantly surprised to find that they did. +1 on keeping them. Peace Bill Mill bill.mill at gmail.com From http Fri Sep 30 06:09:33 2005 From: http (Paul Rubin) Date: 30 Sep 2005 03:09:33 -0700 Subject: Self reordering list in Python References: <1128074048.552398.151950@z14g2000cwz.googlegroups.com> Message-ID: <7xfyrmc1eq.fsf@ruckus.brouhaha.com> "zooko" writes: > I haven't benchmarked it against Evan Podromou's heap implementation > yet, but obviously inserting and removing things from a heapq heap is > O(N). Good heavens, I should hope not. The whole point of heaps is that those operations are O(log(N)). From bokr at oz.net Thu Sep 15 00:23:00 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 15 Sep 2005 04:23:00 GMT Subject: Property and "fset" in Python 2.4 References: Message-ID: <4328f635.1502254417@news.oz.net> On Wed, 14 Sep 2005 18:12:44 -0700, "Rob Pawsner" wrote: >With this setup -- > > PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] >on win32. > >-- I'm seeing the old bug which made "fset" methods unusable with declared >properties of a class. Even worse, this is happening with a >fourth-generation descendent of the Object class, not an old-style class as >in "python-Bugs-1207379", >http://www.mail-archive.com/python-bugs-list at python.org/msg03434.html. > >Before I clog up the digest with details and code snippets, does this sound >familiar to anyone? > A snippet demonstrating a real bug would be helpful. A snippet demonstrating a misunderstanding could be helpful. What's the problem? ;-) Regards, Bengt Richter From bektek at gmail.com Fri Sep 30 14:09:00 2005 From: bektek at gmail.com (kimes) Date: 30 Sep 2005 11:09:00 -0700 Subject: Duplicating Modules In-Reply-To: References: Message-ID: <1128103740.931794.136610@o13g2000cwo.googlegroups.com> Why don't you do like this.. import module import mudule as module2 From sam at email-scan.com Wed Sep 21 19:23:33 2005 From: sam at email-scan.com (Sam) Date: Wed, 21 Sep 2005 18:23:33 -0500 Subject: Threading, real or simulated? Message-ID: I'm using Python 2.3.5 with pygtk 2.4.1, and I'm using the second threading approach from pygtk's FAQ 20.6 - invoking "gtk.gdk.threads_init()", and wrapping all gtk/gdk function calls with gtk.threads_enter()/gtk.threads_leave() I start a thread, via thread.Threading.start(). The thread then calls a particularly time consuming C function, from an extension module. I find that when the thread is running the C code, the GUI hangs even though I'm not inside the threads_enter/threads_leave territory. It looks like thread.Threading() only simulates threading, by having the python interpreter multiplex between running threads. Is real threading possible, so that I do something time-consuming in the thread, without hanging the GUI? -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jpopl at interia.pl Thu Sep 8 05:04:30 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Thu, 08 Sep 2005 11:04:30 +0200 Subject: popen in thread on QNX Message-ID: I am still in the process of creating my script which will run command received from socket. My scripts works perfectly on Linux, but doesn't work on QNX! File "/usr/lib/python2.4/popen2.py", line 108, in __init__ self.pid = os.fork() OSError: [Errno 89] Function not implemented When I try to use os.popen3 - it works. But when I try to use it in new thread - I see that error message. Do you see any solution? This script must work on QNX, command must be on thread, because I need to stop it after timeout. I need popen to see stdout and stderr. Any ideas? From rodwellm at REMOVEME.gmail.com Tue Sep 13 01:21:59 2005 From: rodwellm at REMOVEME.gmail.com (Rod W) Date: Tue, 13 Sep 2005 05:21:59 GMT Subject: PyGTK or wXPython? Message-ID: I'm just starting out on Python but my primary goal is to provide applications with some user interface (GUI). Can someone point me to a good comparison of whether I should use wxPython (with wxGlade I assume) or PyGTK (with Glade I assume)? I'd prefer open source (not necessarily GPL though) tools. Rod From ml.sven at subscience.de Mon Sep 12 14:14:18 2005 From: ml.sven at subscience.de (sven) Date: Mon, 12 Sep 2005 20:14:18 +0200 Subject: defining __repr__ In-Reply-To: <1126546229.628365.242310@g49g2000cwa.googlegroups.com> References: <3olkhcF6g6vaU1@individual.net> <1126546229.628365.242310@g49g2000cwa.googlegroups.com> Message-ID: <6.2.3.4.2.20050912200323.02800f68@post.strato.de> hi list, i'd like to define __repr__ in a class to return the standardrepr a la "<__main__.A instance at 0x015B3DA0>" plus additional information. how would i have to do that? how to get the standardrepr after i've defined __repr__? sven. From steve at REMOVETHIScyber.com.au Wed Sep 14 11:26:54 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 15 Sep 2005 01:26:54 +1000 Subject: Removing duplicates from a list References: <1126697915.879705.300450@g44g2000cwa.googlegroups.com> <4328178b$0$21147$db0fefd9@news.zen.co.uk> Message-ID: On Wed, 14 Sep 2005 13:28:58 +0100, Will McGugan wrote: > Rubinho wrote: >> I can't imagine one being much faster than the other except in the case >> of a huge list and mine's going to typically have less than 1000 >> elements. > > I would imagine that 2 would be significantly faster. Don't imagine, measure. Resist the temptation to guess. Write some test functions and time the two different methods. But first test that the functions do what you expect: there is no point having a blindingly fast bug. > Method 1 uses > 'count' which must make a pass through every element of the list, which > would be slower than the efficient hashing that set does. But count passes through the list in C and is also very fast. Is that faster or slower than the hashing code used by sets? I don't know, and I'll bet you don't either. -- Steven. From g.franzkowiak at onlinehome.de Thu Sep 29 15:58:30 2005 From: g.franzkowiak at onlinehome.de (g.franzkowiak) Date: Thu, 29 Sep 2005 21:58:30 +0200 Subject: PyWin SendMessage In-Reply-To: References: <7jczvrb5.fsf@python.net> Message-ID: Thomas Heller schrieb: > "g.franzkowiak" writes: > > >>Thomas Heller schrieb: >> >>>"g.franzkowiak" writes: >>> >>> >>> >>>>Hello everybody, >>>> >>>>I've tryed to use an interprocess communication via >>>>SendMessage on Windows. >>>>Unfortunately, nothing goes on >>>> >>>>######################################################################### >>>>#! /usr/bin/env python >>>> >>>>import win32api, win32ui, win32con >>>>import struct, array >>>> >>>>""" >>>>typedef struct tagCOPYDATASTRUCT { // cds >>>> DWORD dwData; >>>> DWORD cbData; >>>> PVOID lpData; >>>>} COPYDATASTRUCT; >>>>""" >>>> >>>>def packCopyData(nNum, sString): >>>> int_buffer = array.array("L",[nNum]) >>>> char_buffer = array.array('c', sString) >>>> int_buffer_address = int_buffer.buffer_info()[0] >>>> char_buffer_address = char_buffer.buffer_info()[0] >>>> char_buffer_size = char_buffer.buffer_info()[1] >>>> copy_struct = struct.pack("pLp", # dword*, dword, char* >>>> int_buffer_address, >>>> char_buffer_size, >>>> char_buffer) >>>> return copy_struct >>> >>> >>>After packCopyData(...) returns, the arrays are destroyed, which will >>>probably void their contents. You must keep them alive until you don't >>>need the COPYDATASTRUCT instance any longer. For this kind of stuff, >>>ctypes may be easier to use than pywin32. >>> >>>Thomas >> >>Hmm, have read something in <> >>and the script changed to this: >> >>#--------------------------------------------------------- >>#! /usr/bin/env python >> >>import win32api, win32ui, win32con, win32gui >>import struct, array >>from ctypes import * >> >>""" >>typedef struct tagCOPYDATASTRUCT { // cds >> DWORD dwData; >> DWORD cbData; >> PVOID lpData; >>} COPYDATASTRUCT; >>""" >> >>class COPYDATATYPE(Structure): >> _fields_ = [("nNum", c_ulong), >> ("szData", c_char_p)] >> >>class COPYDATASTRUCT(Structure): >> _fields_ = [("dwData", c_ulong), >> ("cbData", c_ulong), >> ("lpData", POINTER(COPYDATATYPE))] >> >># get the window handle >>hwnd = win32ui.FindWindow(None, "target window") >> >># print just for fun >># ##print hwnd >> >># prepare copydata structure for sending data >>cpyData = COPYDATATYPE(1, '1') >>cds = COPYDATASTRUCT(c_ulong(1), >> c_ulong(sizeof(cpyData)), >> pointer(cpyData)) >> >># try to send a message >>win32api.SendMessage(hwnd, >> win32con.WM_COPYDATA, >> 0, >> pointer(cds)) >> >>#--------------------------------------------------------- >>and the message for the last line is: >>==> TypeError: an integer is required" >> >>This message comes with "pointer(cds)" and with "addressof(cds)" > > > That error refers to the first argument - win32ui.FindWindow returns a > PyCWnd object, which is not accepted by win32api.SendMessage. > Changing this brings you one step further. win32api.SendMessage accepts > an integer for the last element, so addressof(cds) should work now. > > win32gui.SendMessage is more tolerant in what it accepts as 4th > argument, according to the error message you get when you try it it > expects a string, a buffer, or an integer. So you could use addressof() > or pointer(), what you like best. > > Thomas Super, operates :-)) My last answer must be in the Nirvana, strange ? Ok, only the version with 'addressof' generates a message and I must play with the data types. The receiver becomes a wrong data formate. Expect (int=1, char[256]='1\00'), but the int is 0x31 and the string somewhat. Must play with my data. Thanks gerd From mwm at mired.org Thu Sep 8 01:54:57 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 08 Sep 2005 01:54:57 -0400 Subject: Manging multiple Python installation References: <-YydnR5-VKJlPILeRVn-sw@comcast.com> Message-ID: <86vf1ct87i.fsf@bhuda.mired.org> Andy Leszczynski writes: > Robert Kern wrote: >> Andy Leszczynski wrote: >> >>>Jeremy Jones wrote: >>> >>> >>>>Andy Leszczynski wrote: >>>> >>>>Download the source, untar, cd to the new directory, run: >>>> >>>>./configure --prefix=/opt/mypython >>>>make >>>>make install >>> >>>Is there any way to pass the prefix to the "make install"? >> Is passing it to the configure script a problem? > > not really but seems to be a bit illogical to me that the build (set > of executables and libraries) depends on the destination installation > path. It's not clear that the build depends on the destination. The install does, though. The Makefile does the install, so it needs the prefix. config builds the makefile, so it also needs the prefix. > Under M$ Windows I was able to install Python in let's say C:\Program > Files\python and then move/copy it frelly to whatever location I > need. Only thing was the resetting PATH to the new location. I miss > that under Linux. Are you sure it doesn't work well enough for you to use on Linux? A quick grep on the python binary and library files reveal that only pydoc knows the prefix - and that points to files that don't exist on my system. That leaves five things to worry about: unix avoids making the user muck with the path by installing the binary in the path, so you have to move the binaries and the libraries separately. The pydoc executable uses the path to the python binary in it's #! line. If you use the shared binary, you may have to muck with the load library state information (not sure what to use to do this on your Linux). Third party libraries may break. Oh yeah - tracebacks on .pyc and .pyo files may be confused because the source files aren't where they where when the file was generated, but that should be the same as it is on Windows. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Wed Sep 28 05:16:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 28 Sep 2005 02:16:51 -0700 Subject: Human readable number formatting In-Reply-To: <7xirwlbnvw.fsf@ruckus.brouhaha.com> References: <1127862406.11827.2.camel@localhost.localdomain> <1127895464.345142.171030@g43g2000cwa.googlegroups.com> <7xirwlbnvw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "MrJean1" writes: > >> Ocha O + 54 - o otro >> Nena N + 57 - nk nekto >> MInga MI + 60 - mk mikto >> Luma L + 63 - l lunto > > Please tell me you're making this up. No, but someone else is. http://jimvb.home.mindspring.com/unitsystem.htm -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From n00m at narod.ru Fri Sep 2 05:12:33 2005 From: n00m at narod.ru (n00m) Date: 2 Sep 2005 02:12:33 -0700 Subject: Code run from IDLE but not via double-clicking on its *.py In-Reply-To: References: <1125478316.530781.315540@g44g2000cwa.googlegroups.com> <1125490472.670850.247240@g49g2000cwa.googlegroups.com> <1125509322.964828.27510@o13g2000cwo.googlegroups.com> <1125579678.705228.172970@f14g2000cwb.googlegroups.com> <1125592608.894215.186670@g43g2000cwa.googlegroups.com> Message-ID: <1125652353.850367.198180@g43g2000cwa.googlegroups.com> LOL... seems it disappears only in Win98. In Win2k it goes like this: C:\>d: D:\>python23\python d:\python23\socket6.py D:\> > C:\> d: > D:\> cd \python23 > D:\> python d:\python23\socket6.py > out.txt 2> err.txt > Does anything appear in d:\python23\out.txt or d:\python23\err.txt? NOTHING APPEARED IN THEM. > n00m, can you post the vbs? Set cn = CreateObject("ADODB.Connection") cn.Open _ "Provider=sqloledb;Data Source=192.168.0.3,1434;" & _ "Network Library=DBMSSOCN;Initial Catalog=pubs;" & _ "User ID=qwe;Password=asdasd;" cn.Execute "select top 1 * from authors;" cn.Close Set cn = Nothing From gandalf at designaproduct.biz Tue Sep 27 08:19:22 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Tue, 27 Sep 2005 14:19:22 +0200 Subject: @staticmethod, backward compatibility? In-Reply-To: References: Message-ID: <433938CA.3040305@designaproduct.biz> Neal Becker wrote: >How can I write code to take advantage of new decorator syntax, while >allowing backward compatibility? > >I almost want a preprocessor. > >#if PYTHON_VERSION >= 2.4 >@staticmethod >... > > >Since python < 2.4 will just choke on @staticmethod, how can I do this? > > Decorators are there because class MyClass: @staticmethod def my_method(arg1, arg2, ...): whatever is nicer than class MyClass: def my_method(arg1, arg2, ...): whatever my_method = staticmethod(my_method) I'm affraid, if you need to be 2.3 compatible then you need to use the later form. Les From NutJob at gmx.net Thu Sep 1 04:43:31 2005 From: NutJob at gmx.net (NutJob at gmx.net) Date: 1 Sep 2005 01:43:31 -0700 Subject: Well, Python is hard to learn... In-Reply-To: References: Message-ID: <1125564211.750923.189790@g14g2000cwa.googlegroups.com> Well, I reckon it all depends on how much experience you have with programming languages in general. If you're completely new to programming it's probably going to take a while to get to grips with it all, regardless of which language you're picking up, although I'd wager that Python is still one of the most intuitive and easiest to learn languages around. Personally I learnt to code in C++ Python, and Perl with a little bit of Java, Tcl and C# thrown in there as well and I like Python and C++ the most. Just be patient, mate, you'll get the hang of it before long. From skip at pobox.com Wed Sep 7 23:32:28 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 7 Sep 2005 22:32:28 -0500 Subject: improvements for the logging package In-Reply-To: <20050907171420.GB31649@ActiveState.com> References: <1125935246.425351.260880@z14g2000cwz.googlegroups.com> <20050906172418.GL4377@ActiveState.com> <17182.22978.718108.100126@montanaro.dyndns.org> <20050907171420.GB31649@ActiveState.com> Message-ID: <17183.45260.647117.513372@montanaro.dyndns.org> >> - It's a package, but contrary to any other package I've ever seen, >> most of its functionality is implemented in __init__.py. Trent> I'm not defending the implementation, but does this cause any Trent> particular problems? No, it just seems symptomatic of some potential organizational problems. >> import logging >> logging.info('hello world') >> >> ought to just work (implicitly add a stream handler connected to >> stderr to the root logger). Trent> Maybe. Unless that causes troubles for real use. Maybe there's a bug then (or maybe the docs still need work). When I executed (all of these examples were typed at an interactive prompt): import logging logging.info('hello world') I get no output. Looking at the doc for the basicConfig() function, I see: The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. If I read that right, my "hello world" example ought to work. I tried: import logging logging.getLogger("main") logging.info("hello world") and import logging logging.basicConfig() logging.info("hello world") and import logging logging.basicConfig() log = logging.getLogger("main") log.info("hello world") Shouldn't one of these have emitted a "hello world" to stderr? (Maybe not. Maybe I need to explicitly add handlers to non-root loggers.) Trent> Having lazy configuration like this means that it can be a subtle Trent> thing for top-level application code to setup the proper logging Trent> configuration. Again, based on my reading of the basicConfig doc, it seems like the logging package is supposed to already do that. Trent> I think the usability of the logging module could be much Trent> improved with a nicer introduction to it (i.e. docs). It's not Trent> really a "hello world" type of tool. Its usefulness only really Trent> shows in larger use cases. I agree about the docs. Whatever the "hello world" example is (I clearly haven't figured it out yet), it ought to be right at the top of the docs. If logging isn't trivial to use, then many simple apps won't use logging. Consequently, when they grow, logging has to be retrofitted. >> - Its functionality is partitioned in sometimes odd ways. For >> example, it has a handlers module, but what I presume would be the >> most commonly used handler (StreamHandler) is not defined there. >> >> - It doesn't use PEP 8 style as far as naming is concerned, instead >> doing some sort of Java or C++ or Perl camelCase thing. Trent> Perhaps Vijay (who did all the implementation) can comment on Trent> these. Unfortunately backwards-compat might restrict some Trent> cleanups to the package, but perhaps not too much. I did a poor Trent> job of keeping up with the package after I laid out an initial Trent> design, er copied an initial design from Java's log4j package Trent> (and I'm not even a Java guy). :( It was probably the log4j roots that provided the non-PEP 8 naming. I suspect the naming could be improved while providing backward compatibility aliases and deprecating those names. From nospam at jollans.com Thu Sep 15 15:39:46 2005 From: nospam at jollans.com (Thomas Jollans) Date: Thu, 15 Sep 2005 21:39:46 +0200 Subject: IDE, widget library Message-ID: I guess questions like this come all the time here ... well: I a looking for a python IDE for gnu/linux that : - has decent sytax highlighting (based on scintilla would be neat) - has basic name completition, at least for system-wide modules - has an integrated debugger - is open source, or at least free of charge an integrated GUI designer would of course be cool, but cannot be counted as a requirement. With that I come to the second question: What cross-platform GUI libraries are there ? cross-platform meaning functional and free on (at least) X11 and Win32 PyQT obviously doesn't count because qt3 is not free on windows. Tk is ugly. (how well) is Tile supported with python ? does PyGTK/Glade work on win32 ? From grante at visi.com Fri Sep 16 16:03:49 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 16 Sep 2005 20:03:49 -0000 Subject: 2.3 -> 2.4: long int too large to convert to int References: <11ijsh0h2dec0ed@corp.supernews.com> <11ilnab5b5vsue0@corp.supernews.com> Message-ID: <11im995j4dcd72@corp.supernews.com> On 2005-09-16, Terry Reedy wrote: >> One of the nasty bits in a pure-python approach is that there's >> no way to write a literal with a fixed length. For example, >> instead of writing 0xf7 to get an 8-bit value and 0x12345789 to >> get a 32-bit value, you have to instantiate a class like >> Word8(0xf7) and Word32(0x12345678). >> >> That starts to make things pretty hard to read. > > This is no worse than having to write decimal(.53489384) or > whatever to get a decimal float rather than a binary float, or > indeed, than writing cname(init_data) to get an instance of > all types/classes. There are many more possible classes than > sensible literal formats. A few basic and general types have > been blessed with literals that translate into inplicit type > constructor calls. Indeed, some literals seem necessary to > start the object construction process. However, most types > and classes, including your particular special-use classes, do > not have corresponding literals and never will in the general > release. Oh, I realize that. I was just fantasizing about features that would make it easier to write the narrow set of applications that I tend to write. I didn't mean that I thought the need was widespread enough to seriously consider adding it to the language. -- Grant Edwards grante Yow! I'd like MY data-base at JULIENNED and stir-fried! visi.com From peter at engcorp.com Fri Sep 23 08:22:37 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Sep 2005 08:22:37 -0400 Subject: File processing In-Reply-To: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> References: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> Message-ID: <0r6dnTXXqccRbq7eRVn-iQ@powergate.ca> Gopal wrote: > Hello, > > I'm Gopal. I'm looking for a solution to the following problem: > > I need to create a text file config.txt having some parameters. I'm > thinking of going with this format by having "Param Name - value". Note > that the value is a string/number; something like this: > > PROJECT_ID = "E4208506" > SW_VERSION = "18d" > HW_VERSION = "2" > > In my script, I need to parse this config file and extract the Values > of the parameters. > > I'm very new to python as you can understand from the problem. However, > I've some project dealines. So I need your help in arriving at a simple > and ready-made solution. Luckily, you're already done! Just make sure the above file has a .py extension, say maybe "config.py", and then in code where you need to "parse" it and extract the values you can just do this: import config print 'Project Id is', config.PROJECT_ID -Peter From jgrahn-nntq at algonet.se Tue Sep 6 13:56:37 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 6 Sep 2005 17:56:37 GMT Subject: execute commands independantly References: <1126012345.854708.314210@g14g2000cwa.googlegroups.com> <1126015149.066715.107340@f14g2000cwb.googlegroups.com> <1126019232.931087.23800@g43g2000cwa.googlegroups.com> Message-ID: On 6 Sep 2005 08:07:12 -0700, Eric McGraw wrote: > > If you want it to return when the program is finished then use > os.system('app') but if you just want to start it and return right > away, use os.startfile('app') That one is Windows-only, though -- at least in 2.3 where I live. The os.spawn* family of calls are more portable, but I'm not sure it's a good idea to just spawn-and-forget a process. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From rrr at ronadam.com Wed Sep 7 13:12:30 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 07 Sep 2005 17:12:30 GMT Subject: Possible improvement to slice opperations. In-Reply-To: <431e28c8.794365627@news.oz.net> References: <0BZSe.13427$xl6.12703@tornado.tampabay.rr.com> <9eeTe.14166$xl6.13552@tornado.tampabay.rr.com> <431e28c8.794365627@news.oz.net> Message-ID: <2cFTe.14786$p_1.473@tornado.tampabay.rr.com> Bengt Richter wrote: > Then the question is, do we need sugar for reversed(x.[a:b]) > or list(reversed(x.[a:b])) for the right hand side of a statement, > and do we want to to use both kinds of intervals in slice assignment? > (maybe and yes ;-) Yes, I think this is the better way to do it, as this address's the underlying causes instead of treating the symptoms. > The reason for yes is that it solves the which-gap problem in assigning to [a:a] > if you define [a, a) as an empty interval to the left of a and (a, a] as an empty > interval to the right of a, sort of like +0 and -0 in half-open intervals ;-) > Replacing the empty interval does the insertion on the side you want ;-) > > I am choosing the convention to stay compatible with python's current behaviour, > even though I'm not sure what the math world says about a different-in-some-sense intervals. I guess the intervals as point sets are the same, > but the interval definitions are different... Not sure either. I think intervals is an important concept and enabling python to work with them would be good if it could be done in a simple and consistent way. This extends a lot further than just slice operations because of the relationship between ... for x in range() -> slice(range) So defining an interval object that can be used as an iterator in a for loop might be the beginning, and then finally slice with an alternate syntax to an abbreviated form. So then you would have the relationship of... for x in interval() -> slice(interval) > Other than the a:a distinction, in terms of integers and UIAM > .[a:b] > is just sugar for > [a+1:b+1] > but the sugar is nice, and the slice assignment to either side is nicer. Wouldn't that be [a:b+1] ? As sugar the index's are translated at compile time, it may run into the current edge case indexing problems. So it will most likely need to be an actual interval object, with an alternative syntax to use it. > I'll deal with the subsetting another time ... No hurry, this isn't a hack it out because "the boss wants it on his desk Monday" situation. ;-) > Regards, > Bengt Richter Cheers, Ron From tjreedy at udel.edu Sat Sep 3 17:37:52 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 3 Sep 2005 17:37:52 -0400 Subject: Submitting doc bug reports without SF registration Message-ID: In response to posts about the overhead of registering as SourceForge to submit quick doc typo/bug reports, I sent an email to docs AT python.org (== Fred Drake) about submitting via that address instead. He responded that he really does not want specific action items sent there because such email only goes to him and can get lost or not read for awhile. Tracker reports, on the other hand, give immediate feedback of reception and are immediately readable and possibly acted on by anyone who reviews tracker items. Indeed, fixes sometimes happen within a day or two. On the other hand, he can see that registration could be just enough barrier to stop someone and does not want that either. He knows that the docs 'need more attention and fresh eyes!' So he suggested two possibilities: 1. A DocImprovement wiki. People could optionally sign up for update reports on specific wiki pages. 2. A new SF tracker, only for doc bugs, that would accept anonymous submissions. The other trackers require login because most items need additional feedback from requestors. But reports like "On page x.y.x, 'seperate' should be 'separate'" do not require feedback unless the requestor wants the 'fixed, thank you' comment emailed. As an item reviewer, I prefer the second, but we are both curious as to the preference of potential no-login reporters. Terry J. Reedy From news at NOwillmcguganSPAM.com Fri Sep 16 10:53:39 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 16 Sep 2005 15:53:39 +0100 Subject: Creating Pie Chart from Python In-Reply-To: References: <1126797017.338319.215400@z14g2000cwz.googlegroups.com> <432990f9$0$21365$db0fefd9@news.zen.co.uk> Message-ID: <432adc74$0$14348$db0fefd9@news.zen.co.uk> Markus Weihs wrote: > Hi! > > I tried your script and got the following error: > > Traceback (most recent call last): > File "pie_chart.py", line 302, in OnPaint > self.OnDraw() > File "pie_chart.py", line 336, in OnDraw > segment.Draw(self.angle, self.rot, self.explode) > File "pie_chart.py", line 46, in Draw > glPopMatrix() > OpenGL.GL.GLerror: [Errno 1281] invalid value > > What am I doing wrong? I'm not sure. Thats a strange place for it to fail. Do you have the latest version of pyOpenGL / wxPython? Its only been tested on Windows, but it just uses basic OpenGL so there is not that much to go wrong.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From larry.bates at websafe.com Thu Sep 15 12:05:34 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 15 Sep 2005 11:05:34 -0500 Subject: Python CSV writer confusion. In-Reply-To: <1126781787.649249.301330@o13g2000cwo.googlegroups.com> References: <1126781787.649249.301330@o13g2000cwo.googlegroups.com> Message-ID: The someiterable should be something that has a .next method. That would be a list or any object with such a method. In your case it would be the images list. The writer method will iterate over the list and write everything out for you. Don't put it inside a loop yourself. More like (not tested): import csv . . . outfile=open(r'D:\path\to\filename_sort1.csv', 'w') CSVwriter=csv.writer(outfile, dialect='excel', delimiter='|') CSVwriter.writerows(images) Larry Bates > > > if __name__ == '__main__': > images = read_images(r"D:\path\to\imagespipe.csv") > > def get_key(*attr_names): > def key(image): > return [getattr(image, name) for name in attr_names] > return key > > images.sort(key = get_key("filename")) > > t = open(r'D:\path\to\filename_sort1.csv', 'w') > > for image in images: > print book > #t.write('%s\n' % book) %Before I needed | delimited, this > worked > #csv.writer(t, dialect='excel', delimiter='|') > output = csv.writer(t, dialect='excel', delimiter='|') > output.writerows() > #output.writerows(image) > #output.writerow(image) > > t.close() -Larry Bates googleboy wrote: > Hi. I am trying to write out a csv file with | instead of comma, > because I have a field that may have many commas in it. I read in a > csv file, sort it, and want to write it out again. > > I read the example that says: > > import csv > writer = csv.writer(open("some.csv", "wb")) > writer.writerows(someiterable) > > The "someiterable" is what is confusing me. > > > > class Image(object): > def __init__(self, title, date, genre, data, value, filename): > params = locals() > del params['self'] > self.__dict__.update(params) > def __repr__(self): > all_items = self.__dict__.items() > return '%s,%s,%s,%s,%s, %s' % (self.title, self.date, > self.genre, self.data, self.value, self.filename) > > def read_images(filename): > csv_file = open(filename, "rb") > reader = csv.reader(csv_file, dialect='excel', delimiter='|') > images = [Image(*[field.strip() for field in row]) for row in > reader] > csv_file.close() > return books > > def sort_images(filename, *attr_names): > csv_file = open(filename, "rb") > reader = csv.reader(csv_file, dialect='excel', delimiter='|') > > > if __name__ == '__main__': > images = read_images(r"D:\path\to\imagespipe.csv") > > def get_key(*attr_names): > def key(image): > return [getattr(image, name) for name in attr_names] > return key > > images.sort(key = get_key("filename")) > > t = open(r'D:\path\to\filename_sort1.csv', 'w') > > for image in images: > print book > #t.write('%s\n' % book) %Before I needed | delimited, this > worked > #csv.writer(t, dialect='excel', delimiter='|') > output = csv.writer(t, dialect='excel', delimiter='|') > output.writerows() > #output.writerows(image) > #output.writerow(image) > > t.close() > > > > This returns an error that says "Error: sequence expected" > > My understanding of this is that I am creating a list of lists and I am > iterating over it (for image in images), and that image is a list, and > is therefore iterable...? > > I am a bit new at this, and would greatly appreciate any assistance. > > TIA > > googleboy > From zanesdad at bellsouth.net Wed Sep 28 18:55:35 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 28 Sep 2005 18:55:35 -0400 Subject: 1 Million users.. I can't Scale!! In-Reply-To: <17211.6223.874504.573767@montanaro.dyndns.org> References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> <17210.62571.387969.713030@montanaro.dyndns.org> <433B0B38.7040406@bellsouth.net> <17211.6223.874504.573767@montanaro.dyndns.org> Message-ID: <433B1F67.4070208@bellsouth.net> skip at pobox.com wrote: > Damjan> Is there some python module that provides a multi process Queue? > > Skip> Not as cleanly encapsulated as Queue, but writing a class that > Skip> does that shouldn't be all that difficult using a socket and the > Skip> pickle module. > > Jeremy> What about bsddb? The example code below creates a multiprocess > Jeremy> queue. > >I tend to think "multiple computers" when someone says "multi-process". I >realize that's not always the case, but I think you need to consider that >case (it's the only practical way for a multi-process application to scale >beyond a few processors). > >Skip > > Doh! I'll buy that. When I hear "multi-process", I tend to think of folks overcoming the scaling issues that accompany the GIL. This, of course, won't scale across computers without a networking interface. - JMJ From fredrik at pythonware.com Wed Sep 7 04:05:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 7 Sep 2005 10:05:01 +0200 Subject: ~ after script filename? References: <1126065469.212137.264680@g49g2000cwa.googlegroups.com> <1126067512.772173.141580@g47g2000cwa.googlegroups.com> Message-ID: "presentt" wrote: > Huh, no ~ on other files when I edit them, but at least I don't have to > worry about it. Thanks Aldo. according to http://www.gnome.org/projects/gedit/ gedit supports backup files, so to figure out how and when they're created, and how to control their creation, you probably just have to read the documentation (which doesn't seem to exist on the web; look in the "help" menu for the bundled version) From rschroev_nospam_ml at fastmail.fm Fri Sep 30 07:50:48 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 30 Sep 2005 11:50:48 GMT Subject: Help with syntax warnings In-Reply-To: References: Message-ID: Ivan Shevanski schreef: > Here's a noob question for everyone (I'm not sure if my first message > got through, is had a "suspicious header" so sorry for double post is > so), is there a way to turn off syntax warnings or just make them not > visible? Those warnings are something I have never seen and even have never heard about, even though I now found out there's a section in the library reference about them. It seems you can define filters to specify what you want to do with the warnings; you can read all about it at http://docs.python.org/lib/module-warnings.html -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fredrik at pythonware.com Fri Sep 23 14:41:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Sep 2005 20:41:51 +0200 Subject: batch mkdir using a file list References: <1127500054.273772.112470@g14g2000cwa.googlegroups.com> Message-ID: DataSmash wrote > I think I've tried everything now and can't figure out how to do it. > I want to read in a text list from the current directory, > and for each line in the list, make a system directory for that name. > > My text file would look something like this: > 1144 > 1145 > 1146 > 1147 > > I simply want to create these 4 directories. > It seems like something like the following > code should work, but it doesn't. > > import os > > file = open("list.txt", "r") > read = file.read() > print "Creating directory " + str(read) > os.mkdir(str(read)) read() returns *all* text in the file as a single string, but you really want to process each line for itself. try this: for name in open("list.txt"): name = name.strip() # get rid of extra whitespace os.mkdir(name) From mwm at mired.org Thu Sep 22 11:42:28 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 22 Sep 2005 11:42:28 -0400 Subject: Open PDF References: <36141C39871E4D4DAE92F79D1838543601B176C8@itcnt14.itc.nl> Message-ID: <8664sthzx7.fsf@bhuda.mired.org> Dan writes: > Under Linux you can probably use xpdf or gpdf: > > os.system("xpdf /path/to/file.pdf") > > Note that you should check the return code of "system" to see if the > execution was successful. For example, the user might not have xpdf > installed. This is the problem that the "open" package was designed to solve. The API for Python apps is still under development, but if you do 'os.system("open /path/to/file.pdf")', open will use the users preferred pdf viewer, and interact with the user to select one if they don't have a prefernce on record. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From xah at xahlee.org Thu Sep 1 04:56:03 2005 From: xah at xahlee.org (Xah Lee) Date: 1 Sep 2005 01:56:03 -0700 Subject: OpenSource documentation problems In-Reply-To: References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> Message-ID: <1125564963.289130.307560@o13g2000cwo.googlegroups.com> By the way, i have sent my criticisms to the proper python doc maintainer or mailing list several months ago. ------------- i'm very sorry to say, that the Python doc is one of the worst possible in the industry. I'm very sick of Perl and its intentional obfuscation and juvenile drivel style of its docs. I always wanted to learn Python as a replacement of Perl, and this year i did. I thought Python is much better. But now i know, that although the language is better, but its documentation is effectively worse than Perl's. The Perl docs, although lousy in the outset because its people immerse in drivel. It is part of their unix culture. Nevertheless, one thing Perl doc is not, is that it in particular do not presume a superficial Computer Science stance. In fact, its culture sneer computer science establishment. (which i caused major harm in the industry) There are quite a lot things wrong with Perl docs. But at least it is not shy to use examples, lots of them. Now, i have thought that Python doc is entirely different. The Python community in many ways are antithesis of Perl community. Python doesn't start with a hacking mentality, and i presume it to have a community who care about correctness and quality. Unfortunately, as i now know, its doc is the worst and almost useless piece of shit. Several problems lies at the core: * its technical writing is extremely poor. * its technical content clearly shows that the writers can't or didn't think clearly. (one confused ball) * its organization exhibits the worst abstruse insensibilities of tech geekers. ------------ as i have expressed before (see http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html ), the python doc has huge number of problems. To remedy them, it needs major overhaul if not complete rewrite. Just about the only worthwhile part of the official doc set is the Tutorial section. The ?Language Reference? section, Library Reference, and The Global Module Index are totally crap and need to be deleted entirely. (i haven't read much of the other sections, but i don't assume they are much better) ------------- I would like to see the Python doc gets a complete rewrite. First of all, the doc system LaTex needs to go. (TeX itself is a OpenSource crime, see this unedited rant http://xahlee.org/Periodic_dosage_dir/t2/TeX_pestilence.html ) Then, the doc needs to be written with a few principles. * to communicate to programers how to use it. (as opposed to being a compiling specification or inline with some computer sciency model) * write with the goal of effective communication. In the writing, avoid big Engish words, long sentences, and focus on precision. In content, avoid philosophical outlook, jargon population, author masturbation, arcane technicalities, gratuitous cautions, geek tips, juvenile coolness ... etc.) * document with consideration of tasks to be performed. * document orient with the language's exhibited functionalities, concrete behaviors. (as opposed to in some milieu of software engineering methodology) * give ample examples. (for detail, study several of my Python criticisms from the link mentioned above) -------------- I have not been in the Python community long and have not delved into it. Is there other documentation that can be a basis of a new python doc? The one i know is the Quick Reference by Richard Gruet. However, it is just a Quick Reference but can be a basis if we lack anything else. Also, i have happened to read the O'Reilly Python book years ago. That book is crap. I have also read parts of the Python Cookbook. Probably half of this book is also crap. Of course, the other major hurdle in progress (for a new doc) is a political one. It is, alas, always the biggest problem. ----------- the python doc wiki given at http://pydoc.amk.ca/frame.html is a great idea. For this to work, there are two things needs to be done, both are equally important: 1. for the official python site Python.org to point to the wiki as THE official python doc. 2. given a authoritarian guide in the wiki on how to write the doc. (the guide based on the principles i gave above. Of course, it needs to be clarified and elaborated with many cases in point.) Without (1), the wiki will never be prominent. Without (2), it will remain a geek drivel. (in this respect, similar to how wikipedia's texts drift into a form of academic esoterica whose educational value are greatly reduced to the general public.) -------- this post is archived at http://xahlee.org/UnixResource_dir/writ/python_doc.html Xah xah at xahlee.org ? http://xahlee.org/ From vimakefile at yahoo.com Tue Sep 27 11:50:36 2005 From: vimakefile at yahoo.com (Mike) Date: Tue, 27 Sep 2005 08:50:36 -0700 Subject: Telephony project References: <1127758835.527555.217870@g47g2000cwa.googlegroups.com> <7x64snbr0l.fsf@ruckus.brouhaha.com> <1127816655.712927.289850@g14g2000cwa.googlegroups.com> Message-ID: I was able to do something like this in Python a while back. You'll need one of: (a) A telephone line dialer/monitor & DTMF I/O board that works through the serial port, and a phone audio tap that mixes the soundcard I/O to the phone (b) A TAPI-compliant modem that does everything you need (c) A digital POTS phone that is controllable through serial, USB or your LAN, or a TAPI interface. (d) VOIP software and service than uses SIP, etc. (I found this I found this: http://softphones.globaliptel.com/(c50kru45yksjek55xr2b5g45)/_Pages/NoFrames/PageBuilder.aspx?content=4214134c0c4f416982e844bcd86b2955, but am in no way endorsing it. Also check out http://www.sipfoundry.org/) I used method (a) -- (b) tends to be a pain (as most OEM TAPI modems have some fatal flaw or three...) and (c/d) may be more possible now that before. I used voice reco on the input side rather then DTMF, but I was doing it from local phone exensions on the same loop, not for outside calls, and not for the elderly, so DTMF is probably better anyway. (If you need to know the exact hardware I used, I can find out.) The other option is to not have your own hardware at all and use a service -- there are companies provide web services that let you write/generate markup (VoiceXML or other) to make the calls, wait for DTMF or voice input, etc. (Though I had trouble Googling one at the moment - there were more a few years ago...) m "Roger" wrote in message news:1127816655.712927.289850 at g14g2000cwa.googlegroups.com... > "CheckOn" is the working name for my project. Our church > community has many elderly who are at home but close to assisted living > placements. Many do not have family and rely on volunteer caretakers > and lunch providers for their socialization. We are trying to make > phone contact with these members to check on their needs, wellbeing, > and ability to take care of themselves. In sharing that information > with other denominations in our city, we discovered that others were > having identical issues. The numbers are larger than we anticipated. > Thus the project. Thanks for your interest. > From merman at o2online.de Fri Sep 23 04:43:45 2005 From: merman at o2online.de (TK) Date: Fri, 23 Sep 2005 10:43:45 +0200 Subject: idle In-Reply-To: References: <4332a386$0$13014$9b622d9e@news.freenet.de> Message-ID: <4333bfae$0$15069$9b622d9e@news.freenet.de> Hi Franz, >>is there no IDLE in Python2.4? > > Sure, > on Windows: > > C:\Python24\Lib\idlelib\idle.pyw > You should have a shortcuts in your StartMenu > und Python 2.4 What about with Suse 9.3 und Python 2.4? o-o Thomas From randy at psg.com Thu Sep 1 13:01:05 2005 From: randy at psg.com (Randy Bush) Date: Thu, 1 Sep 2005 07:01:05 -1000 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> <1125571915.715672.178840@g44g2000cwa.googlegroups.com> Message-ID: <17175.13265.841555.117527@roam.psg.com> > I'm very sorry to say, that the Python doc is one of the worst possible > in the industry. you are entitled to a full refund From Make More With GreenZap (Better than PayPal)get $25.00/signing up + Sat Sep 10 17:30:29 2005 From: Make More With GreenZap (Better than PayPal)get $25.00/signing up + (Make More With GreenZap (Better than PayPal)get $25.00/signing up +) Date: 10 Sep 2005 14:30:29 -0700 Subject: Make Even More $$$$$ with! GreenZap! Get $25.00 for signing up/$5 for thoose u refer Message-ID: <1126387829.256507.261420@g49g2000cwa.googlegroups.com> Make $10,000 in 30 days with GreenZap|Get Paid $25.00/signin up! & get paid $5.00/thoose you refer!!! Pay Automated!!! This really does work and is also totally legal and free for anyone to join. Sign up now for free and get $25 instantly into your new account. Why this works Unlike the PayPal $5 programs, this doesn't even cost you $5 to join in, just 2 minutes of your time. Sign up at this link www.greenzap.com/peso4sho $25 will be put into your account for free. Great, you've made $25 in just 2 minutes, not a bad start. Why not turn it into $10,000 or more in just 30 days. Believe me that's a very realistic target. If you're still not convinced try it for the sole reason of proving yourself right for thinking it won't work. But I warn you now, don't start complaining to me with all the money you're making to why I didn't let you know about this sooner. Here's the reason why the're doing this. Pay Pal is their biggest competitor worth $6-8 billion dollars. Pay Pal has between 60-80 million members. In other words, each of those members is worth about $100 to Pay Pal. GreenZap understands this and is willing to pay for its members in advance. That's where the initial $25 comes in as well as the community rewards of anywhere from $5-30 more dollars. This is an ingenious way to quickly build a loyal community of GreenZap members. But remember the're not going to give out the $25 forever. It's only for their pre-registration campaign, so act quickly. They are cheaper to use than PayPal too. $1.00 per transaction fee Compare $1.00 to PayPal's [1.9%-2.9% + $0.30] transaction fees and its easy to see who's focusing on offering value to their community and who's not. Is GreenZap Really Giving Away FREE Money? Yes. Think of it this way; at $1.00/transaction, GreenZap will eventually get their money back once you use your GreenZap account to transact 25 times. How Can You Profit From The Battle Of GreenZap and PayPal? Get started now 1. GET AN EMAIL ACCOUNT....I ASSUME YOU ALREADY HAVE ONE... 2.GO TO www.greenzap.com/peso4sho 3. SIGN UP FOR AN ACCOUNT. IT'S TOTALLY FREE AND THEY WILL FUND YOU $25 INSTANTLY INTO YOUR ACCOUNT JUST FOR SIGNING UP. 4. TAKE THAT $25 AND USE IT AS FOLLOWS: CLICK ON THE SEND MONEY TAB. 5.ENTER THE EMAIL ADDRESS IN THE NUMBER ONE POSITION. Here's the current list: 1. eternally at winning.com 2. jon8421r at yahoo.co.uk 3. peso4sho at yahoo.com SEND THE $25 DOLLARS TO THE FIRST NAME WITH A NOTE SAYING "ADD ME TO YOUR MAILING LIST". THEN SEND AN EMAIL TO THE NUMBER THREE POSITION SAYING "THANKS I'VE JOINED." THIS SECTION IS IMPORTANT SINCE THIS IS WHAT MAKES THIS LEGAL. YOU CAN SIGN UP FROM ANYWHERE IN THE WORLD AND ONLY ONE ACCOUNT PER PERSON CAN BE OPENED WITH THE GREENZAP SYSTEM SO NO ONE IS ABLE TO SIGN UP FOR LOADS OF ACCOUNTS AND SEND THE $25 TO THEMSELVES. 6. COPY/ PASTE THIS LETTER INTO A WORD PROCESSOR. TAKE THE #1 EMAIL OFF AND PUT YOUR EMAIL YOU SIGNED UP WITH INTO THE #3 POSITION. 7. LOG ON TO GOOGLE OR YAHOO AND TYPE IN MONEY MAKING MESSAGE BOARD OR BUSINESS OPPORTUNITY... ETC. POST THE NEW COPY OF THE LETTER WITH YOUR NAME IN THE 3 SPOT TO LOADS OF MESSAGING BOARDS. THE MORE THE BETTER. YOU CAN ALSO EMAIL THIS LETTER TO ANYONE YOU KNOW, HOW ABOUT SENDING IT TO THE EMAIL ADDRESSES THAT SEND YOU OFFERS. IT'S SIMPLE....THE MORE YOU SEND OUT THE MORE MONEY YOU WILL MAKE. AIM TO SEND IT TO AT LEAST 40 PEOPLE. PLEASE DO NOT TRY AND CHEAT BY PUTTING YOUR EMAIL AT THE TOP BECAUSE YOU WILL NOT MAKE A LOT OF MONEY LIKE THAT. REMEMBER YOUR EMAIL ADDRESS WILL BE DELETED FROM THE TOP BY THE NEXT PERSON WHO RECEIVES THIS LETTER. BY STARING AT THE BOTTOM AND BEING MOVED UP WHEN IT'S EMAILED TO OTHERS YOUR EMAIL ADDRESS IT'S EXPOSED TO MANY THOUSANDS MORE AT THE TOP THAN IF YOU CHEAT. That the response rate to this is VERY HIGH goes without saying, really Who else would give you $25 for free and let you use it to make thousands of dollars. You can maybe use the money you make from this program to start you own business or spend this weekend down at your local auto showroom and test drive some cars. Have fun however you spend it! www.greenzap.com/peso4sho Enjoy making lots and lots and lots of money! If you don't try it you will never know. Good fortunes to you and yours. Peso, success & wealth! peso4sho at yahoo.com *PLEASE ADD ME TO YOUR GreenZap LISTS* GZAccepted_Badge2.gif From dan at cellectivity.com Fri Sep 16 10:28:00 2005 From: dan at cellectivity.com (Dan) Date: Fri, 16 Sep 2005 15:28:00 +0100 Subject: strptime() doesn't recognize BST as a valid timezone Message-ID: <1126880880.7089.21.camel@localhost.localdomain> > I get: "ValueError: time data did not match format: ..." I'm running Linux in London, and I don't get that error. Python 2.3.5 (#2, May 29 2005, 00:34:43) [GCC 3.3.6 (Debian 1:3.3.6-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> date_str = "Wed Sep 14, 2005 5:07 PM BST" >>> format = "%a %b %d, %Y %I:%M %p %Z" >>> time.strptime(date_str, format) (2005, 9, 14, 17, 7, 0, 2, 257, 1) However, when I used another timezone (I tried EST and PST), I got the same error you did. I really don't know enough about how Python handles dates to tell you anything more. -- Diplomacy is saying "nice doggy" until you find a rock. - submitted by Nancy Greer to the CleanStuff mailing list From ndbecker2 at gmail.com Wed Sep 21 15:27:23 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 21 Sep 2005 15:27:23 -0400 Subject: unusual exponential formatting puzzle Message-ID: Like a puzzle? I need to interface python output to some strange old program. It wants to see numbers formatted as: e.g.: 0.23456789E01 That is, the leading digit is always 0, instead of the first significant digit. It is fixed width. I can almost get it with '% 16.9E', but not quite. My solution is to print to a string with the '% 16.9E' format, then parse it with re to pick off the pieces and fix it up. Pretty ugly. Any better ideas? From steve at holdenweb.com Tue Sep 20 17:25:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 20 Sep 2005 22:25:28 +0100 Subject: are variables local only to try/except blocks? In-Reply-To: References: Message-ID: <43307E48.4080001@holdenweb.com> Barry Searle wrote: > > in the case of nested try/except code generation, > your suggestion could cause a problem: > # 1) this is fine: > doInitialStuff # With no exceptions > excp = 0 > try: > doLotsHere() > except aParticularSetOfExceptions: > excp = 1 > if excp: > handleException() > doLotsMoreStuff() > > # 2) nested code generation has problem: > doInitialStuff # With no exceptions > excp = 0 > try: > > doMOREInitialStuff # With no exceptions > excp = 0 > try: > doMORELotsHere() > except aParticularSetOfExceptions: > excp = 1 #### this causes the problem > if excp: > handleException() > doMORELotsMoreStuff() > > doLotsHere() > except aParticularSetOfExceptions: > excp = 1 > #### excp=1 from inner nested code generation > if excp: > handleException() > doLotsMoreStuff() > > # 3) Hence I return to my planned template code generation: > excp = 0 #### Probaly need to do ONCE, to "bind" variable ? Yes, but I am bothered that you appear to feel there is a need to 1) record whether an exception occurred and then 2) handle the exception only when you have finished recording whether exceptions occurred and under what conditions. > doInitialStuff # With no exceptions > try: > > doMOREInitialStuff # With no exceptions In which case you might as well put the excp =0 here. > try: > doMORELotsHere() > excp = 0 ##### always reset excp as last action That doesn't make sense to me. If an exception isn't raised then excp will have the value it's always had, which is to say zero, so I don't see why you feel the need for this "resetting" to take place (unless there's a chance that doMORELotsHere() changes excp's value). > except aParticularSetOfExceptions: > excp = 1 > if excp: > handleException() > doMORELotsMoreStuff() > > doLotsHere() > excp = 0 ##### always reset excp as last action > except aParticularSetOfExceptions: > excp = 1 > if excp: #### should be fine > handleException() > doLotsMoreStuff() > > [previous insanities deleted] I don't believe there isn't a simpler way to do what you appear to want to do. Since you are talking about machine-generated code we can agree not to care about ugly in terms of source, but I think we should be careful no to throw the baby out with the bath water here. Rather than casting your question as code it may prove helpful simply to describe the problem in English, and then see if others on the group can't help you structure your code better. Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From mwm at mired.org Mon Sep 26 14:39:29 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 26 Sep 2005 14:39:29 -0400 Subject: ncurses programming References: <1127754862.781184.224480@z14g2000cwz.googlegroups.com> <874q87pw5f.fsf@wilson.rwth-aachen.de> Message-ID: <86wtl3wu5a.fsf@bhuda.mired.org> Torsten Bronger writes: > Hall?chen! > > "ncf" writes: > >> [...] >> >> Py Docs: http://docs.python.org/lib/module-curses.html > > This document suggests that Python+ncurses won't work on windows. > What's the reason for this? Could it be that ncurses doesn't work on Windows? At least, it didn't last time I looked. There was a curses library for Windows, but you'll have to google for it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From keithlackey at deegroup.com Wed Sep 21 02:12:12 2005 From: keithlackey at deegroup.com (keithlackey) Date: Wed, 21 Sep 2005 14:12:12 +0800 Subject: What am I doing wrong? In-Reply-To: Message-ID: I'm relatively new to python and I've run into this problem. DECLARING CLASS class structure: def __init__(self, folders = []): self.folders = folders def add_folder(self, folder): self.folders.append(tuple(folder)) Now I try to make an instance of this class structure1 = structure() structure1.add_folder([('foo'),]) print structure1.folders This returns: [('foo',)] This works fine. But when I try to make another instance of that class... structure2 = structure() print structure2.folders This now also returns: [('foo',)] Even though I haven't added any folders to this new instance What am I doing wrong? From theller at python.net Tue Sep 6 02:23:24 2005 From: theller at python.net (Thomas Heller) Date: Tue, 06 Sep 2005 08:23:24 +0200 Subject: py2exe 0.6.1 released References: <431cf3eb.715296532@news.oz.net> Message-ID: <3boisoir.fsf@python.net> bokr at oz.net (Bengt Richter) writes: > On Mon, 05 Sep 2005 21:55:19 +0200, Thomas Heller wrote: > >> * py2exe can now bundle binary extensions and dlls into the >> library-archive or the executable itself. This allows to >> finally build real single-file executables. >> >> The bundled dlls and pyds are loaded at runtime by some special >> code that emulates the Windows LoadLibrary function - they are >> never unpacked to the file system. > > So py2exe is windows-only (like exe ;-) or is there a py2elf or > py2coff or such? py2exe is windows only. But, there are also (in no particular order) PyInstaller, cx_Freeze, py2app, exemaker, freeze. > >> >> This part of the code is distributed under the MPL 1.1, so this >> license is now pulled in by py2exe. > Mozilla? Has nothing to do with Mozilla directly, it is just that parts of the code are licensed under the Mozilla Public License Version 1.1. I'm not too happy with this, but I have other things to do than to rewrite software relased under the MPL just to release it under a more liberal license (although I have considered that, and I certainly would not reject a contribution ;-). Thomas From gg63551 at hotmail.com Sun Sep 4 01:29:43 2005 From: gg63551 at hotmail.com (gerald gillespie) Date: Sun, 04 Sep 2005 00:29:43 -0500 Subject: gmail access Message-ID: how do I access my new Gmail account gg63551 at hotmail.com _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rbt at athop1.ath.vt.edu Tue Sep 20 10:50:50 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 20 Sep 2005 10:50:50 -0400 Subject: win32 service and time.sleep() In-Reply-To: <1126711859.13054.8.camel@athop1.ath.vt.edu> References: <86zmqgxrps.fsf@bhuda.mired.org> <1126711859.13054.8.camel@athop1.ath.vt.edu> Message-ID: <1127227850.11591.14.camel@athop1.ath.vt.edu> I have a win32 service written in Python. It works well. It sends a report of the status of the machine via email periodically. The one problem I have is this... while trying to send an email, the script loops until a send happens and then it breaks. Should it be unable to send, it sleeps for 10 minutes with time.sleep(600) and then wakes and tries again. This is when the problem occurs. I can't stop the service while the program is sleeping. When I try, it just hangs until a reboot. Can some suggest how to fix this? Thanks, rbt From jhu at metrigenix.com Mon Sep 26 11:11:45 2005 From: jhu at metrigenix.com (James Hu) Date: Mon, 26 Sep 2005 11:11:45 -0400 Subject: how to implement propertyPage using wxPyhton? Message-ID: <90DEA7ED93F71A4580CEDF76A02682EA03AC91@torexch.metrigenix.com> Hi, gurus, I would like to implement something like propertyPage (VC++ term) Ie. There are a few tabs in the top, clicking any tab will display a different panel. I searched on the Internet, couldn't get any clue. Thanks in advance. James -------------- next part -------------- An HTML attachment was scrubbed... URL: From sklass at pointcircle.com Tue Sep 20 19:56:58 2005 From: sklass at pointcircle.com (rh0dium) Date: 20 Sep 2005 16:56:58 -0700 Subject: re.search experts needed on fqdn stripping.. Message-ID: <1127260618.929425.175440@g14g2000cwa.googlegroups.com> Hi all, Ok I have a list hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "loghost", "scorpian", "localhost", "lan", "lan.fpdn.com" ] Assumptions: scorpian.fqdn.com == scorpian lan == lan.fqdn.com I want pear this list down based on the following: 1. ignore loghost, localhost, timehost, mailhost 2. Use the first found name used reguardless if it is the fqdn or not So what you would get back out is this.. hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "lan" ] Now here is my code - and I have a problem with the splitting. I am really looking for a cool ( but understandable ) way to simplify this.. e =[] for host in hosts: sn = re.split( "\.", host) ig = 1 ignore = [ "localhost", "loghost", "timehost", "mailhost" ] for i in ignore: if i == sn[0]: ig = 0 if ig: print "%s not ignored" % sn[0] found = 0 for n in e: sm = re.split( "\.", n) print "checking %s to %s" % (sm[0], sn[0]) if sm[0] == sn[0]: print "match"; found = 1 if found == 0: print "appending %s " % host e.append(host) print e Which kicks out.. poundcake not ignored appending poundcake.nsc.com scorpion not ignored checking poundcake to scorpion appending scorpion.nsc.com scorpian not ignored checking poundcake to scorpian checking scorpion to scorpian appending scorpian lan not ignored checking poundcake to lan checking scorpion to lan checking scorpian to lan appending lan ['poundcake.fpdn.com', 'scorpion.fpdn.com', 'scorpian', 'lan'] Crap still wrong.. From kbk at shore.net Thu Sep 8 00:31:14 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 8 Sep 2005 00:31:14 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200509080431.j884VEHG028517@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 342 open ( +3) / 2923 closed ( +1) / 3265 total ( +4) Bugs : 908 open ( +5) / 5232 closed (+10) / 6140 total (+15) RFE : 188 open ( +1) / 185 closed ( +1) / 373 total ( +2) New / Reopened Patches ______________________ String formatting character for str.join (2005-09-04) CLOSED http://python.org/sf/1281573 opened by Nick Coghlan Speed up gzip.readline (~40%) (2005-09-04) http://python.org/sf/1281707 opened by April King Enable SSL for smtplib (2005-09-05) http://python.org/sf/1282340 opened by Phil Underwood AIX port from Elemental Security (2005-09-07) http://python.org/sf/1284289 opened by Guido van Rossum Patches Closed ______________ String formatting character for str.join (2005-09-04) http://python.org/sf/1281573 closed by ncoghlan New / Reopened Bugs ___________________ time.strptime() fails with unicode date string, de_DE locale (2005-09-01) CLOSED http://python.org/sf/1280061 opened by Adam Monsen tokenize module does not detect inconsistent dedents (2005-06-21) http://python.org/sf/1224621 reopened by arigo PyDateTime_Check references static object (2005-09-02) CLOSED http://python.org/sf/1280924 opened by Skip Montanaro xml.sax.expatreader doesn't pass encoding to ParserCreate (2005-09-02) http://python.org/sf/1281032 opened by Samuel Bayer Erroneous \url command in python.sty (2005-09-03) http://python.org/sf/1281291 opened by Rory Yorke array.arrays are not unpickleable (2005-09-03) CLOSED http://python.org/sf/1281383 opened by Reinhold Birkenfeld Py_BuildValue k format units don't work with big values (2005-09-04) http://python.org/sf/1281408 opened by Adal Chiriliuc exception when unpickling array.array objects (2005-09-04) http://python.org/sf/1281556 opened by John Machin urllib violates rfc 959 (2005-09-04) http://python.org/sf/1281692 opened by Matthias Klose logging.shutdown() not correct for chained handlers (2005-09-05) http://python.org/sf/1282539 opened by Fons Dijkstra socket.getaddrinfo() bug for IPv6 enabled platforms (2005-09-06) http://python.org/sf/1282647 opened by Ganesan Rajagopal PyArg_ParseTupleAndKeywords gives misleading error message (2005-09-06) http://python.org/sf/1283289 opened by japierro nit for builtin sum doc (2005-09-07) http://python.org/sf/1283491 opened by daishi harada os.path.abspath() / os.chdir() buggy with unicode paths (2005-09-07) http://python.org/sf/1283895 opened by Antoine Pitrou re nested conditional matching (?()) doesn't work (2005-09-07) http://python.org/sf/1284341 opened by Erik Demaine Bugs Closed ___________ codecs.StreamRecoder.next doesn't encode (2005-07-10) http://python.org/sf/1235646 closed by doerwalter time.strptime() fails with unicode date string, de_DE locale (2005-09-01) http://python.org/sf/1280061 closed by bcannon crash recursive __getattr__ (2005-08-24) http://python.org/sf/1267884 closed by tjreedy Lambda and deepcopy (2005-08-31) http://python.org/sf/1277718 closed by tjreedy logging module broken for multiple threads? (2005-09-01) http://python.org/sf/1277903 closed by vsajip PyDateTime_Check references static object (2005-09-02) http://python.org/sf/1280924 closed by montanaro bz2module.c compiler warning (2005-08-26) http://python.org/sf/1274069 closed by birkenfeld discrepancy between str.__cmp__ and unicode.__cmp__ (2005-08-29) http://python.org/sf/1275719 closed by rhettinger array.arrays are not unpickleable (2005-09-03) http://python.org/sf/1281383 closed by rhettinger SyntaxError raised on win32 for correct files (2005-05-12) http://python.org/sf/1200686 closed by tim_one New / Reopened RFE __________________ non-sequence map() arguments for optimization (2005-09-02) CLOSED http://python.org/sf/1281053 opened by Ecnassianer of the Green Storm Give __len__() advice for "don't know" (2005-09-06) http://python.org/sf/1283110 opened by Tim Peters RFE Closed __________ non-sequence map() arguments for optimization (2005-09-03) http://python.org/sf/1281053 closed by birkenfeld From amk at amk.ca Thu Sep 1 18:54:09 2005 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 01 Sep 2005 17:54:09 -0500 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> Message-ID: On Thu, 1 Sep 2005 17:09:27 +0200, Fredrik Lundh wrote: > the useredit approach I'm using over at the librarybook site works > pretty well. for example, if you go to That looks pleasantly simple. I don't consider the pydoc.amk.ca experiment to have been really successful. It was a half-hour hack that's usable with some pain, but the JavaScript and frame display needs quite a bit of polishing to be usable by a random newbie. There's a Firefox extension (http://www.wikalong.org/) that allows wiki annotation, but a browser-specific annotation tool doesn't solve the general problem. I suspect the best solution is something Python-doc-specific that runs the generated HTML for the docs through a preprocessor that inserts comments and an editing form. It would be a great topic for a user group sprint or weekend project. (If someone volunteers to do this: if you decide to use an RDBMS, please use PostgreSQL, because it's already installed on one of the python.org servers.) --amk From sybrenUSE at YOURthirdtower.com.imagination Tue Sep 13 09:57:03 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 13 Sep 2005 15:57:03 +0200 Subject: Python for ARM7? References: Message-ID: Ken Seehart enlightened us with: > 1. How do I know whether to use sharprom or modern? If it works, use it. > 2. What do I do with ipk files? I surfed around and found that in > one example, the command is "ipkg install foo.ipk", but ipkg doesn't > seem to exist on my hardware. ipkg doesn't have anything to do with your hardware. It's just a shell script. Anyway, an ipkg file is nothing more than a tarball with a certain content. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rubbishemail at web.de Thu Sep 8 07:37:33 2005 From: rubbishemail at web.de (rubbishemail at web.de) Date: 8 Sep 2005 04:37:33 -0700 Subject: record sound to numarray/list Message-ID: <1126179453.007330.116070@o13g2000cwo.googlegroups.com> Hello, do you know any way to record a sound from the soundcard on winXP to a numarray? many thanks Daniel From cmkleffner at gmx.de Wed Sep 7 10:55:17 2005 From: cmkleffner at gmx.de (cmkl) Date: 7 Sep 2005 07:55:17 -0700 Subject: py2exe 0.6.1 released References: <1126021854.581774.261940@g43g2000cwa.googlegroups.com> Message-ID: <1126104917.246314.231250@f14g2000cwb.googlegroups.com> I removed conditional imports from visual and after that I works like a charm. Now I've got a VPython application within a single 3 Mbyte exe-file (Python-2.3). That is really cool. Thanks Carl From timo.linna at gmail.com Fri Sep 9 06:04:45 2005 From: timo.linna at gmail.com (Timo) Date: 9 Sep 2005 03:04:45 -0700 Subject: Inconsistent reaction to extend In-Reply-To: References: Message-ID: <1126260285.349597.274070@f14g2000cwb.googlegroups.com> Jerzy Karczmarczuk kirjoitti: > On the other hand, try > > p=range(4).extend([1,2]) > > Then, p HAS NO VALUE (NoneType). > > With append the behaviour is similar. I didn't try other methods, but > I suspect that it won't improve. > > > WHY? range(4) returns a list and Python's list.extend() returns None. Extend is a in-place operation. -- timo From xah at xahlee.org Thu Sep 8 01:07:08 2005 From: xah at xahlee.org (Xah Lee) Date: 7 Sep 2005 22:07:08 -0700 Subject: determine if os.system() is done In-Reply-To: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> References: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> Message-ID: <1126156028.500117.323200@z14g2000cwz.googlegroups.com> Thanks all. I found the answer, rather easily. To make a system call and wait for it, do: subprocess.Popen([r"/sw/bin/gzip","-d","access_log.4.gz"]).wait(); ------ this post is archived at: http://xahlee.org/perl-python/system_calls.html Xah xah at xahlee.org ? http://xahlee.org/ Xah Lee wrote: > suppose i'm calling two system processes, one to unzip, and one to > ?tail? to get the last line. How can i determine when the first > process is done? > > Example: > > subprocess.Popen([r"/sw/bin/gzip","-d","access_log.4.gz"]); > > last_line=subprocess.Popen([r"/usr/bin/tail","-n 1","access_log.4"], > stdout=subprocess.PIPE).communicate()[0] > > of course, i can try workarounds something like os.system("gzip -d > thiss.gz && tail thiss"), but i wish to know if there's non-hack way to > determine when a system process is done. > > Xah > xah at xahlee.org > ? http://xahlee.org/ From jaydonnell at gmail.com Thu Sep 1 16:59:40 2005 From: jaydonnell at gmail.com (jdonnell) Date: 1 Sep 2005 13:59:40 -0700 Subject: is there a better way to check an array? In-Reply-To: <1125595376.858041.112430@g43g2000cwa.googlegroups.com> References: <1125593752.264254.172970@g44g2000cwa.googlegroups.com> <1125595376.858041.112430@g43g2000cwa.googlegroups.com> Message-ID: <1125608380.573439.317040@g49g2000cwa.googlegroups.com> Thanks for all the help everyone. Steve, sets are perfect. I didn't even realize they existed. Somehow I completely missed that part of the tutorial. Thanks :) From tores at stud.cs.uit.no Wed Sep 21 10:58:47 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Wed, 21 Sep 2005 16:58:47 +0200 Subject: using variable-value Message-ID: Hi In php I can assign a value to a variable and use this varaible to access a property in some object: $var = 'property'; $object->{$var} This will transelate to $object->property... Is this possible in Python? # Prints help on methods in Canvas-instance for method in dir(self.canvas): print method print help(self.canvas.method) gives me " AttributeError: Canvas instance has no attribute 'method' "... regards tores From rtconner at gmail.com Fri Sep 9 15:04:06 2005 From: rtconner at gmail.com (Rob Conner) Date: 9 Sep 2005 12:04:06 -0700 Subject: Redundant code in multiple methods Message-ID: <1126292646.472895.259480@g44g2000cwa.googlegroups.com> No you don't need to know Zope to help me. The whole reason I'd even want to do this is because of Zope though. I made a Zope product, and now want to perfect it. some simple example code... class User: def View(self): # play with data here myHtmlDoc = "pretend this is a uper profile" return myHtmlDoc index_html = View def Edit(self): # play with data here myHtmlDoc = "editing the user" return myHtmlDoc So when visiting "website.com/User" zope will call User.index_html() or when you visit "website.com/User/View" zope will call User.View() In all of the testing/learning I've done on Zope I'm pretty sure that last item (index_html or View) must be a method, but possible it only needs to have an __doc__ attribute (otherwise Zope will Error) The problem comes when I want to have code put into every method. Perhaps a counter I want to increment on every visit to a User page. I can do this.. def View(self): incrementCounter() # play with data here myHtmlDoc = "pretend this is a uper profile" return myHtmlDoc index_html = View def Edit(self): incrementCounter() # play with data here myHtmlDoc = "editing the user" return myHtmlDoc ... but in reality in my real code that one counter increment line ends up being 20 lines long. An al lot of that "counter code" is actaully setting up variables I'd like to access within the scope of the given method. So if you follow me so far, I was wondering how I might change things to only have one place where I have to maintain the "setup my method" code, which is pretty much a lot of the same code typed over and over into all of the methods. (for a more real life example of things) - def View(self): REQUEST = self.REQUEST SESSION = REQUEST.SESSION dbConnection = self.getDBConnection() logger = self.getLogger() trackStatsHere() # set up some local variables here # change some global variables here try: myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc except: raise "handle the error here" finally: dbConnection.close() index_html = View def Edit(self): REQUEST = self.REQUEST SESSION = REQUEST.SESSION dbConnection = self.getDBConnection() logger = self.getLogger() trackStatsHere() # set up some local variables here # change some global variables here try: myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc except: raise "handle the error here" finally: dbConnection.close() I would ideally like to do something such as this this, or something where I don't have all of that redundant code. def __allmethods__(self, methodname): "gets called when all methods are called" REQUEST = self.REQUEST SESSION = REQUEST.SESSION dbConnection = self.getDBConnection() logger = self.getLogger() trackStatsHere() # set up some local variables here # change some global variables here try: methodname(localvariables) except: raise "handle the error here" finally: dbConnection.close() def View(self, localvariables): myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc index_html = View def Edit(self): myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc __getattr__ almost does the trick but not quite. So any suggestions on how to streamline my code here and make it slightly more maintainable. From andrea.valle at unito.it Sat Sep 17 09:50:20 2005 From: andrea.valle at unito.it (andrea valle) Date: Sat, 17 Sep 2005 15:50:20 +0200 Subject: problem with setup.py In-Reply-To: References: <20050607150658.GB5985@ActiveState.com> Message-ID: <856e627deed3989260ca9846ed603946@unito.it> Thanks a lot. I have bash as shell but I ignore what > your ~/.bashrc means. Have I to edit a file? Where should it be? Thanks again -a- On 17 Sep 2005, at 12:46, Robert Kern wrote: > andrea valle wrote: >> Hi to all, >> and sorry for cross-posting. >> >> I'm having troubles with installing packages. >> I'm on macosx 10.3.8 and I have activestate python 2.4 >> >> For example, pyrtf an pyx. >> it is the first time I install packages so pardon me if it's obvious. >> >> I call python from terminal, I pass the absolute path of the setup.py >> with command install, and results are always: >> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during >> configure >> >> For example with pyrtf: >> >> apples-Computer:~ apple$ python >> /Users/apple/Desktop/PyRTF-0.45/setup.py installrunning install >> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during >> configure >> >> What should I do? I guess I have to hack some configuration, but don't >> know which. > > Add the following line to your ~/.bashrc (assuming that you are using > bash as your shell): > > export MACOSX_DEPLOYMENT_TARGET=10.3 > > Then start a new Terminal.app window (the change doesn't take effect > until a new shell is started). > > I haven't needed to do this with the official 2.4.1 build, so you > should > complain to ActiveState. Or use the official build. > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > -- > http://mail.python.org/mailman/listinfo/python-list > > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From steve at REMOVETHIScyber.com.au Mon Sep 19 10:13:20 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 20 Sep 2005 00:13:20 +1000 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: On Mon, 19 Sep 2005 10:31:48 +0200, Fredrik Lundh wrote: > meanwhile, over in python-dev land: > > "Is anyone truly attached to nested tuple function parameters; 'def > fxn((a,b)): print a,b'? /.../ > > Would anyone really throw a huge fit if they went away? I am willing > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > people are up for it." Consider this: def func(some_tuple): How many items should you pass in the tuple? If it takes variable arguments, then that works, but if you always expect a fixed number, then def func((x, y)) is more explicit. The only problem I have is that once you unroll the tuple like that, it is hardly necessary to pass the argument as a tuple. Why not just pass x and y as two arguments? def func(x, y) I think tuple unrolling would work better if there was a way to refer to the argument as both a tuple and by the components. Eg, making up a hypothetical syntax for it: def func(pt?(x,y)): print "Tuple", pt print "Items", x, y Calling func((2,3)) prints: "Tuple" (2, 3) "Items" 2 3 Of course, this opens a can of worms, what happens if you pass a mutable object like a list instead of a tuple or string? Still, if Python is eventually to get something static types, it probably makes sense to keep the def func((x,y)) idiom, because it will come in handy for ensuring that your sequence arguments have the right number of items. -- Steven. From larry.bates at websafe.com Thu Sep 8 13:01:24 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 08 Sep 2005 12:01:24 -0500 Subject: job scheduling framework? In-Reply-To: <1126194711.728965.86630@g43g2000cwa.googlegroups.com> References: <1126194711.728965.86630@g43g2000cwa.googlegroups.com> Message-ID: <5cOdnfriiORj8L3eRVn-vA@comcast.com> Google turned up these links that might be of interest: http://www.foretec.com/python/workshops/1998-11/demosession/hoegl/ http://www.webwareforpython.org/Webware/TaskKit/Docs/QuickStart.html http://www.slac.stanford.edu/BFROOT/www/Computing/Distributed/Bookkeeping/SJM/SJMMain.htm Larry Bates Chris Curvey wrote: > Has anyone seen a simple open source job-scheduling framework written > in Python? I don't really want to reinvent the wheel. All I need is > the ability to set up a series of atomic "jobs" as a "stream", then > have the system execute the jobs in the stream one-at-a-time until all > the jobs in the stream are complete or one of them reports an error. > > (If it tied into a really simple grid-style computing farm, that would > be worth double points!) > > -Chris > From cmkleffner at gmx.de Tue Sep 6 11:50:54 2005 From: cmkleffner at gmx.de (cmkl) Date: 6 Sep 2005 08:50:54 -0700 Subject: py2exe 0.6.1 released References: Message-ID: <1126021854.581774.261940@g43g2000cwa.googlegroups.com> Hi, I didnt succeed to bundle vpython-3.2.3 with py2exe-0.6.1 - regardless if its build as single file or not: "This application has requested the Runtime to terminate it in an unusual way" and so on... This error message seems not generated by py2exe. At least I could not find a reference to it in the sources of py2exe. Regards Carl From smadim2 at grads.ece.mcmaster.ca Tue Sep 20 13:15:55 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Tue, 20 Sep 2005 13:15:55 -0400 Subject: mailing from with python Message-ID: <433043CB.8010608@grads.ece.mcmaster.ca> hi; if i want to send a mail message using the "mail" client on a machine that has smtp protocol is there an easy way (i.e. like bash where you would just type mail -s SUBJECT message RECIPIENT) to do it from a python script? thanks moe smadi From fredrik at pythonware.com Sun Sep 25 15:18:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 25 Sep 2005 21:18:38 +0200 Subject: cElementTree clear semantics References: Message-ID: Igor V. Rafienko wrote: > Finally, I thought about keeping track of when to clear and when not > to by subscribing to start and end elements (so that I would collect > the entire -subtree in memory and only than release it): > > from cElementTree import iterparse > clear_flag = True > for event, elem in iterparse("data.xml", ("start", "end")): > if event == "start" and elem.tag == "schnappi": > # start collecting elements > clear_flag = False > if event == "end" and elem.tag == "schnappi": > clear_flag = True > # do something with elem > # unless we are collecting elements, clear() > if clear_flag: > elem.clear() > > This gave me the desired behaviour, but: > > * It looks *very* ugly > * It's twice as slow as version which sees 'end'-events only. > > Now, there *has* to be a better way. What am I missing? the iterparse/clear approach works best if your XML file has a record-like structure. if you have toplevel records with lots of schnappi records in them, iterate over the records and use find (etc) to locate the subrecords you're interested in: for event, elem in iterparse("data.xml"): if event.tag == "record": # deal with schnappi subrecords for schappi in elem.findall(".//schnappi"): process(schnappi) elem.clear() the collect flag approach isn't that bad ("twice as slow" doesn't really say much: "raw" cElementTree is extremely fast compared to the Python interpreter, so everything you end up doing in Python will slow things down quite a bit). to make your application code look a bit less convoluted, put the logic in a generator function: # in library def process(filename, annoying_animal): clear = True start = "start"; end = "end" for event, elem in iterparse(filename, (start, end)): if elem.tag == annoying_animal: if event is start: clear = False else: yield elem clear = True if clear: elem.clear() # in application for subelem in process(filename, "schnappi"): # do something with subelem (I've reorganized the code a bit to cut down on the operations. also note the "is" trick; iterparse returns the event strings you pass in, so comparing on object identities is safe) an alternative is to use the lower-level XMLParser class (which is similar to SAX, but faster), but that will most likely result in more and tricker Python code... From steve at holdenweb.com Fri Sep 30 06:37:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 30 Sep 2005 11:37:40 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> Message-ID: Antoon Pardon wrote: > Op 2005-09-30, Steve Holden schreef : > >>Antoon Pardon wrote: >> >>>Op 2005-09-29, Bill Mill schreef : >>> >>> >>>>But, if your users can't figure out that they shouldn't be changing >>>>the variable called t._test__i without expecting side effects, what do >>>>you think of the users of your class? >>>> >>>>Python is for consenting adults. >>> >>> >>>No it is not. Consenting means you had the choice. Python doesn't >>>give you the choice not to consent. Unless of course you write >>>it as a C-extension, then you can hide all you want. >>> >> >>Good grief, the ultimate choice is to use Python because you like it, or >>not to use it because you don't. Enough with the picking every available >>nit, please. Consent or stop complaining :-) > > > This is IMO not a nit. IMO people are redefining words. We are also > talking within a certain context. When people use this slogan, they > don't mean that people have the choice to not use python. > Quite true, but people do none the less have that choice. Some days I wish a few more would exercise it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From peter at engcorp.com Thu Sep 15 06:06:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Sep 2005 06:06:56 -0400 Subject: Newbie - instanciating classes from other files In-Reply-To: <1126752450.458728.59050@g44g2000cwa.googlegroups.com> References: <1126752450.458728.59050@g44g2000cwa.googlegroups.com> Message-ID: comanighttrain at gmail.com wrote: > Hey guys, i just started learning python (i usually use java/C). > > this has got me stumped as its not mentioned in the documentation > (unless im skimming it every time). > > How does one instanciate a class from another file > > i thought it would be > -----------------------------------code--------------------------- > import file.py > > thisFile = ClassName() > -------------------------------not code--------------------------- It's clear you haven't worked through the tutorial. It's short, easy, and educational, so why not save yourself from embarrassment and whip through it rather than trying to learn Python by guess-and-error? -Peter From fredrik at pythonware.com Fri Sep 30 10:17:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 16:17:46 +0200 Subject: Overloading __init__ & Function overloading References: <433D4714.9050808@websafe.com> Message-ID: Larry Bates wrote: >I may be reading this question different than Fredrik. it looks like you're using a non-standard definition of the word "overloading". here are the usual definitions (quoting from a random google page): "Overloading a method refers to having two methods which share the same name but have different signatures." "Overriding a method refers to having a new implementation of a method with the same signature in a subclass." From lycka at carmen.se Wed Sep 28 05:20:57 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 28 Sep 2005 11:20:57 +0200 Subject: number of python users In-Reply-To: <4337f0a5$1@nntp0.pdx.net> References: <4337f0a5$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > * 2.3 was called Python-in-a-tie; Nope, that's 2.2. See e.g. http://lists.debian.org/debian-python/2002/08/msg00025.html Sadly, it seems the Python Business Forum has died, or at least fallen into some kind of coma, so I don't know if that's an issue. In corporate installations, there are still a lot of Red Hat Enterprise Linux 3 installations, and they have 2.2. RH EL4 comes with 2.3. From max at alcyone.com Fri Sep 30 16:53:19 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 30 Sep 2005 13:53:19 -0700 Subject: Google Not Universal Panacea [was: Re: Where to find python c-sources] In-Reply-To: References: Message-ID: Steve Holden wrote: > While a snappish "go and look it up on Google" might suffice for a > mouthy apprentice who's just asked their thirteenth question in the last > half hour, it's (shall we say) a little on the brusque side for someone > who only appears on the group last February, and has a history of asking > reasonably pertinent though sometimes beginner-level questions. I told him exactly where it was. I just also pointed out that he could have trivially found out the answer on his own by using Google for fifteen seconds. It would be one thing if I (and nobody else) answered his question and just rudely pointed him to Google. But since I actually answered his question, looks to me like someone just wanted to stand on his soapbox today. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Let he who does not know what war is go to war. -- (a Spanish proverb) From steve at holdenweb.com Sat Sep 3 01:45:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Sep 2005 00:45:19 -0500 Subject: 'isa' keyword In-Reply-To: References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> Message-ID: phil hunt wrote: > On Thu, 01 Sep 2005 20:39:14 -0500, Steve Holden wrote: > >>phil hunt wrote: >> >>>It could be argued of course, that an OOPL should allow methods to >>>be sent with a grammar: >>> >>> receiver selector argument >>> >>>(which is almost what Smalltalk does), but you're not arguing for >>>that (and I'm not sure it would work with the rest of python's >>>grammar). >>> >> >>Even if it did it might mangle operator precedence in the same way >>SmallTalk did, which I always felt was one of the least attractive >>features" of the language. > > > That's certainly a point of view; another is that Smalltalk > simplified things by making all operators the saem priority. For > those that don't know smalltalk, in that language: > > a + b * c > > means: > > (a + b) * c > > >>I don't think a change to a message-passing paradigm > > > I'm not talking about a change in *paradigm* merely a change in > *syntax*; this: > > receiver selector argument > > would mean the same as the current Python: > > receiver.selector(argument) > Aah, I see. I had assumed that "selector" was always going to be an operator. 3 . (+ 4) does indeed seem very "SmallTalkative". I don't think that Python method (or attribute) selection bears any relationship to SmallTalk message-passing, but I hope you will feel free to enlighten me. > so it is purely a matter of aesthetics which is preferred. Havcing > said that, I don't see a big benefit in changing Python's syntax in > this way. > Me neither. And I can see positive disbenefits, like it would confuse the hell out of most people :-) > >>would necessarily >>benefit Python at this stage. Some people are still under the >>misapprehension that message-passing is a fundamental of object-oriented >>programming because of Smalltalk, but they are wrong. > > > I don't see how it can reasonably said that STK has > "message-passing" but other OOPLs don't. Consider these code > fragments: > > Smalltalk: > receiver selector: argument > > C++ or Java: > receiver.selector(argument); > > Python: > receiver.selector(argument) > > PHP: > $receiver->selector($argument) > > (I'm not sure if the last one is right since I've not done much OO > stuff in PHP) > > These all mean essentially the same thing so how can one be "message > passing" and the others not? > Sorry, they don't all mean "essentially the same thing" at all. It seems to me you are looking at SmallTalk in entirely too superficial a light. In SmallTalk, control structures aren't syntactic primitives, they are also examples of message-passing, so code blocks are sent as messages to objects. Python eschews such obscurity and (IMHO) gains clarity by so doing. But that is, of course, a matter of opinion. Also, remember that just because two expressions in different languages "mean the same thing "doesn't mean they are implemented using the same techniques. I would contend (if backed into a corner) that there is a significant difference between passing the arguments 3 and 4 to a "+" operator (which is what Python and most other languages implementing standard ideas of operator precedence do) and sending the message "+ 4" to the integer 3 (which is effectively what SmallTalk does). Of course, I realise that you can argue that the two are equivalent in the sense that they perform the same computation. But SmallTalk's choice led to the loss of operator precedence, which is something that is pretty fundamental to mathematics. Also Python allows much more flexibility by hard-wiring operators and allowing alternatives to be considered (if the left operand doesn't have an "__add__" method then try to use the right operand's "__radd__" method). SmallTalk doesn't have any parallel to this that I can think of. Also, try seeing what the mathematicians have to say about a language where a + b * c means (a + b) * c Of course it isn't only mathematicians who are taught to us the precedence rules, so I contend that SmallTalk would seem counter-intuitive in a "Programming for Everyone" context as well. It seems to me that Guido's primary achievement with Python's design is to provide a language that allows the expression of object-oriented paradigms in a way that seems natural even to people who are new to object-oriented concepts. I'm glad you haven't done much object-oriented stuff in PHP, because its object-oriented paradigm is about as sensible as Perl's (which is to say it was a bolt-on extension that resulted in an extremely unnatural mode of expression). The fact that people can write object-oriented code in these languages is a testament to the flexibility of human thought rather than a benefit of the languages' design. I speak as one who was partly, and in a minor way, responsible for implementing the SmallTalk system on the Perq architecture back in the 1980's. (Mario Wolczko did the real work). So it's not that I've just looked at SmallTalk and find it odd. It's just that it treats expressions in a way which ultimately appear to seem counter-intuitive in contexts like arithmetic expressions. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From andreas.lobinger at netsurf.de Wed Sep 7 10:28:37 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Wed, 07 Sep 2005 16:28:37 +0200 Subject: encryption with python In-Reply-To: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> Message-ID: Aloha, jlocc at fau.edu wrote: > I was wondering if someone can recommend a good encryption algorithm > written in python. > It would be great if there exists a library already written to do this, > and if there is, can somebody please point me to it?? M2Crypto, interface to OpenSSL http://sandbox.rulemaker.net/ngps/m2 Wishing a happy day LOBI From sjmaster at gmail.com Mon Sep 12 14:22:06 2005 From: sjmaster at gmail.com (Steve M) Date: 12 Sep 2005 11:22:06 -0700 Subject: How to protect Python source from modification In-Reply-To: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Message-ID: <1126549326.710649.42210@g44g2000cwa.googlegroups.com> This is a heck of a can of worms. I've been thinking about these sorts of things for awhile now. I can't write out a broad, well-structured advice at the moment, but here are some things that come to mind. 1. Based on your description, don't trust the client. Therefore, "security", whatever that amounts to, basically has to happen on the server. The server should be designed with the expectation that any input is possible, from slightly tweaked variants of the normal messages to a robotic client that spews the most horrible ill-formed junk frequently and in large volumes. It is the server's job to decide what it should do. For example, consider a website that has a form for users to fill out. The form has javascript, which executes on the client, that helps to validate the data by refusing to submit the form unless the user has filled in required fields, etc. This is client-side validation (analagous to authentication). It is trivial for an attacker to force the form to submit without filling in required fields. Now if the server didn't bother to do its own validation but just inserted a new record into the database with whatever came in from the form submission, on the assumption that the client-side validation was sufficient, this would constitute a serious flaw. (If you wonder then why bother putting in client-side validation at all - two reasons are that it enhances the user experience and that it reduces the average load on the server.) 2. If you're moving security and business logic to the server you have to decide how to implement that. It is possible to rely solely on the RDBMS e.g., PostgreSQL. This has many consequences for deployment as well as development. FOr example, if you need to restrict actions based on user, you will have a different PgSQL user for every business user, and who is allowed to modify what will be a matter of PgSQL configuration. The PgSQL is mature and robust and well developed so you can rely on things to work as you tell them to. On the other hand, you (and your clients?) must be very knowledgeable about the database system to control your application. You have to be able to describe permissions in terms of the database. They have to be able to add new users to PgSQL for every new business user, and be able to adjust permissions if those change. You have to write code in the RDBMS procedural language which, well, I don't know a lot about it but I'm not to thrilled about the idea. Far more appealing is to write code in Python. Lots of other stuff. Imagine in contrast that user authentication is done in Python. In this scenario, you can have just a single PgSQL user for the application that has all access, and the Python always uses that database user but decides internally whether a given action is permitted based on the business user. Of course in this case you have to come up with your own security model which I'd imagine isn't trivial. You could also improve security by combining the approaches, e.g. have 3 database users for 3 different business "roles" with different database permissions, and then in Python you can decide which role applies to a business user and use the corresponding database user to send commands to the database. That could help to mitigate the risks of a flaw in the Python code. 3. You should therefore have a layer of Python that runs on the server and mediates between client and database. Here you can put authentication, validation and other security. You can also put all business logic. It receives all input with the utmost suspicion and only if everything is in order will it query the database and send information to the client. There is little or no UI stuff in this layer. To this end, you should check out Dabo at www.dabodev.com. This is an exciting Python project that I haven't used much but am really looking forward to when I have the chance, and as it becomes more developed. My impression is that it is useable right now. They basically provide a framework for a lot of stuff you seem to have done by hand, and it can give you some great ideas about how to structure your program. You may even decide to port it to Dabo. From i_vincent at hotmail.com Wed Sep 28 03:00:57 2005 From: i_vincent at hotmail.com (Ian Vincent) Date: 28 Sep 2005 08:00:57 +0100 Subject: Spoiler to Python Challenge (help!!!) References: Message-ID: Terry Hancock wrote in news:mailman.1044.1127862510.509.python-list at python.org: > > Took me a long time to figure out what you meant. ;-) > > So the string actually contains the backslashes, not the escaped > characters. > > This works: > >>>> bz2.decompress(eval(repr(user))) > 'huge' Unfortunately, it doesn't. Get the same error. From ksenia.marasanova at gmail.com Thu Sep 15 18:03:44 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Fri, 16 Sep 2005 00:03:44 +0200 Subject: Postgres PL/Python Message-ID: <130df19305091515032288e40e@mail.gmail.com> Hi, I wonder if anyone on this list is using Python as Postgres procedural language. I can't find a place for it i my mind. How would a typical MVC web application benefit from it (besides performance)? I understand from the docs that Postgres 7.4 has PL/PythonU - unlimited functionality. It sounds like I have the whole Python available in Postgres. That means big parts of application logic can be moved to stored procedures, and dummy SQL layer becomes something else... sounds scary. Any opinions on this? Thanks. -- Ksenia From ICG04984 at nifty.com Fri Sep 23 04:46:31 2005 From: ICG04984 at nifty.com (=?ISO-2022-JP?B?GyRCQ11CPBsoQiAbJEIybUc3GyhC?= ( Takemura Masayuki )) Date: Fri, 23 Sep 2005 17:46:31 +0900 Subject: re.split() problem In-Reply-To: References: Message-ID: Thanks for your reply. >>> In Re: re.split() problem >>> [Fredrik] = "Fredrik Lundh" wrote Fredrik> >>> s = "foo\nbar\n\nbaz" Fredrik> >>> re.findall("(?s).*\n\n|.+$", s) Fredrik> ['foo\nbar\n\n', 'baz'] Fredrik> (this also lets you use finditer so you can process huge texts without Fredrik> having to hold everything in memory) Thanks. This sovles my problem. > Will it be fixed in Python 2.4.2? Fredrik> 2.4.2 is a bug fix release. "doesn't work as you intend" doesn't really Fredrik> count as a bug I'm sorry for my expression. I should have written "Will those features which were discussed in these threads be released in Python 2.4.2 ?" From mwm at mired.org Fri Sep 9 16:27:22 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 09 Sep 2005 16:27:22 -0400 Subject: Question about consistency in python language References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> <86y867yqna.fsf@bhuda.mired.org> Message-ID: <86psri2dhx.fsf@bhuda.mired.org> Dave Benjamin writes: > Mike Meyer wrote: >> Dave Benjamin writes: >>>Python is actually quite consistent in this regard: methods that >>>modify an object in-place return None; >> Um, no. list.pop comes to mind as an immediate counterexample. It may >> be the only one... > I've never had to look up the return type of "pop" though. The only > thing even remotely ambigious about that term (at least, if you've > learned what a stack is) is whether it mutates the object, but I don't > think I've ever seen a "pop" that didn't (aside from toy examples in > formal methods / ADT related classes). Eiffel STACK class has a pop that dosn't return a value - at least in SmartEiffel. On the other hand, Eiffel makes a *big* deal about the difference between command features - which change the state - and query features - which report on the state. That distinction even shows up in the threading model for Eiffel. > "os.system" might be a better example, since the return value could be > one of two obvious things: the status code, or the program's output. To me, os.system obviously returns the status code. Then again, I know it's just the unix system() routine, which I've know *much* longer than there's been a Python. The point is that what's "obvious" depends on where you're coming from. If your background is as a Unix developer, the result of os.system is obvious. If your background is Eiffel or some other strong ADT area, that pop has a result at all may surprise you. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From sjmaster at gmail.com Thu Sep 22 01:37:16 2005 From: sjmaster at gmail.com (Steve M) Date: 21 Sep 2005 22:37:16 -0700 Subject: Windows paths, Java, and command-line arguments, oh my! In-Reply-To: <3p8rpkF9a8o3U1@uni-berlin.de> References: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> <3p8rpkF9a8o3U1@uni-berlin.de> Message-ID: <1127367436.954536.92020@o13g2000cwo.googlegroups.com> Thank you. I was able to fix it by putting the '-Dwhatever=x' bit before the '-jar y.jar' bit. I had no idea this could matter. Thanks all for the help. From chris.cavalaria at free.fr Mon Sep 19 05:01:05 2005 From: chris.cavalaria at free.fr (Christophe) Date: Mon, 19 Sep 2005 11:01:05 +0200 Subject: IDE, widget library In-Reply-To: References: Message-ID: <432e7cbf$0$31015$626a14ce@news.free.fr> Alessandro Bottoni a ?crit : > Try wxPython (Based on wxWidgets). Really "free" (LGPL'ed = MIT license) on > all platforms, well-engineered, documented and supported, native look&feel > on all platform. Need anything else? ;-) Some people have that weird notion that GTK is native look and feel on all Linux platforms. Unfortunately for you, I have no GTK applications running on *my* system and all wxPython apps look so outlandish :) From aahz at pythoncraft.com Wed Sep 7 15:01:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2005 12:01:45 -0700 Subject: Improving Python docs (was Re: OpenSource documentation problems) References: Message-ID: In article , Steve Holden wrote: >Aahz wrote: >> In article , >> Steve Holden wrote: >.> >>>Bear in mind that the PSF made its very first grants last year. The >>>reason none of those grants was awarded to a documentation project was >>>that the (volunteer) Grants Committee and helpers didn't see any >>>documentation projects worthy of support. >> >> Really? And what exactly is "Software Engineering with Python for >> Scientist and Engineers" if not a documentation project? It may not be >> the kind of documentation people are talking about in this thread, but it >> certainly is documentation. > >Sigh. Fine. Any more nits you'd like to pick? Why are you calling this a nit? It is direct proof that the PSF is prepared to allocate financial resources to improve the Python documentation. We only await people to take up the challenge. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From http Thu Sep 8 16:06:45 2005 From: http (Paul Rubin) Date: 08 Sep 2005 13:06:45 -0700 Subject: Python Jabber client? Message-ID: <7x1x3zmii2.fsf_-_@ruckus.brouhaha.com> Is there such a thing as a general purpose Python Jabber client? I'm imagining one that uses tkinter. A little Googling finds a couple of Jabber protocol libraries written in Python, a few half-finished projects, and a client for the Sharp Zaurus, but I didn't spot any simple portable ones that are finished and ready to use. If there's more than one, does anyone have a favorite? Thanks. From steve at holdenweb.com Wed Sep 21 10:33:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Sep 2005 15:33:19 +0100 Subject: Finding where to store application data portably In-Reply-To: References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Steven D'Aprano wrote: > On Tue, 20 Sep 2005 23:03:52 +0100, Tony Houghton wrote: > > >>I'm using pygame to write a game called Bombz which needs to save some >>data in a directory associated with it. In Unix/Linux I'd probably use >>"~/.bombz", in Windows something like >>"C:\Documents And Settings\\Applicacation Data\Bombz". > > > In Windows, you shouldn't hard-code the drive letter. I don't know how you > find out what the correct value is, but hard-coding it is just Bad. > > As a Linux user, I really am sick of every damn application, script and > program under the sun filling the top level of my home directory with > dot-files. > > I wish the Linux Standard Base folks would specify that settings files > should all go into a subdirectory like ~/settings rather than filling up > the home directory with cruft. That was acceptable in the days when people > only looked at their files with ls, but in these days of GUI file > managers, it is ridiculous that there are more than 100 dot files and > directories in my home directory. > > > > Can I ask developers to break with the obsolete and annoying habit of > creating user-specific config files as ~/.app-name and use > ~/settings/app-name instead? > > > > While we're asking for the improbable, perhaps we could make that ~/.settings/app-name Ssh has used the ~/.ssh directory for a long time to avoid the need for lots of little dot files, and this works quite well. Good luck in your campaign! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From you at anywhere.nt Thu Sep 1 11:39:02 2005 From: you at anywhere.nt (Jake Gittes) Date: 1 Sep 2005 10:39:02 -0500 Subject: Extend Python References: <1125576741.165568.22390@g14g2000cwa.googlegroups.com> Message-ID: Try looking at ctypes - http://starship.python.net/crew/theller/ctypes/ On 1 Sep 2005 05:12:21 -0700, Tommy.Ryding at gmail.com wrote: >Hi All I have a problem with extentions of Python. > >Background: >I'm workin within a large industrial control system and I have created >a Port for VxWorks. In the system we have different permissions >depending on which state the controller is in. To perform some actions >in some states may even injure or kill people. Therefor we need >"intelligent" wrappers between Python and C-code. > >My Question: >Swig offers some great features but is to basic for us. Is there >another program that creates more readble code that can be easily >edited? How much work is it to write our own wrappers? > >//T From steve.horsley at gmail.com Mon Sep 12 17:19:55 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Mon, 12 Sep 2005 22:19:55 +0100 Subject: Premature wakeup of time.sleep() In-Reply-To: References: Message-ID: Erich Schreiber wrote: > In the Python Library Reference the explanation of the time.sleep() > function reads amongst others: > > >>The actual suspension time may be less than that requested because >>any caught signal will terminate the sleep() following execution >>of that signal's catching routine. Also, the suspension time may >>be longer than requested by an arbitrary amount because of the >>scheduling of other activity in the system. > > > I don't understand the first part of this passage with the premature > wakeup. What signals would that be? That would be signals from the OS, frinstance, if you type ^C into the python console, or kill the process from another command line. > I've written a script that tries to bench the responsiveness of a > virtual Linux server. My script sleeps for a random time and on waking > up calculates the difference of the proposed and actual wakeup time. > > The essential code fragment is > > while True: > ts = tDelay() > t1 = time.time() > time.sleep(ts) > t2 = time.time() > twu = str(datetime.datetime.utcfromtimestamp(t1 + ts)) > logResults(LOGFILE, twu, ts, int((t2-t1-ts)*1000)) > > Whereas tDelay() returns a (logarithmically) randomly distributed real > number in the range [0.01, 1200] which causes the process to sleep > from 10 ms to 20 minutes. > > In the logs I see a about 1% of the wake-up delays beeing negative > from -1ms to about -20ms somewhat correlated with the duration of the > sleep. 20 minute sleeps tend to wake-up earlier then sub-second > sleeps. Can somebody explain this to me? > I think the sleep times are quantised to the granularity of the system clock, shich varies from os to os. From memory, windows 95 has a 55mS timer, NT is less (19mS?), Linux and solaris 1mS. All this is from memory, and really comes from discussions I have seen about sleep and time in java, but I am guessing that there are similarities. Steve From deets at nospam.web.de Thu Sep 8 04:36:40 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Sep 2005 10:36:40 +0200 Subject: generator object, next method In-Reply-To: <1126167462.278755.287950@g44g2000cwa.googlegroups.com> References: <1126164425.475226.143510@g14g2000cwa.googlegroups.com> <7xll282cz4.fsf@ruckus.brouhaha.com> <1126167462.278755.287950@g44g2000cwa.googlegroups.com> Message-ID: <3oabgpF4uugnU1@uni-berlin.de> simonwittber at gmail.com wrote: >>Why is that? I thought gen.next is a callable and gen.next() actually >>advances the iterator. Why shouldn't gen.next always be the same object? > > > That is, in essence, my question. Because bound methods are generated on the fly - google this group, there have been plenty of discussions about that. Diez From bdesth.quelquechose at free.quelquepart.fr Thu Sep 8 18:39:41 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 09 Sep 2005 00:39:41 +0200 Subject: Django and SQLObject. Why not working together? In-Reply-To: References: <43206FBF.8010105@intercable.ru> Message-ID: <4320b552$0$6548$626a14ce@news.free.fr> Ksenia Marasanova a ?crit : > 2005/9/8, Sokolov Yura : > >>Django Model is wonderfull. But SQLObject more flexible (and powerfull, >>as i think, and has already more db interfaces). >>But Django Model is tied with Django, and using Django with another OO >>mapping is not comfortable. >>Why do not working together? I can't understand. > > (snip) > > BTW, while SQLObject is very advanced, there are/were some other ORM > mappers in python: > http://www.thinkware.se/cgi-bin/thinki.cgi/ObjectRelationalMappersForPython > While not all of them share the same philosophy with SQLObject, some > do. But they are not merging together either. Just like web frameworks > :) > > I guess it's just the joy of creating something that fits you mind and > solves all you problems, instead of picking up something that does it > partially and was created by another person with different views and > philosophy. > Also, there's something like darwinism at play here. Yes, there are a lot of concurrent ORM/Templating/Web Publishing/GUI/Whatnot projects around, but I guess only the best of them will survive - eventually 'absorbing' what's good in the others. I also noticed something like a 'converging evolution' scheme in Python these days. It strikes me that more and more frameworks seems to be based on concepts like intelligent properties assembled in schemas (Zope, Plone, Django, BasicProperties, SQLObjects...), interface adaptation (PEAK, Zope3, ...) and 'configurable polymorphism' (PEAK, Zope3, ...). Strange enough, I was developping a similar solution for a higher-level LDAP api when I noticed this... It seems to me that it has to do with recent evolutions of Python (decriptors, decorators, metaclasses made simple etc) beginning to be widely adopted and taken advantage of by Python programmers. Anyone else on this ? From bbands at gmail.com Thu Sep 1 17:24:00 2005 From: bbands at gmail.com (BBands) Date: 1 Sep 2005 14:24:00 -0700 Subject: Add lists to class? In-Reply-To: <1125605901.380239.210350@z14g2000cwz.googlegroups.com> References: <1125605901.380239.210350@z14g2000cwz.googlegroups.com> Message-ID: <1125609840.221425.37560@g47g2000cwa.googlegroups.com> Thanks to a generous Pyhtonista replied with a pointer to setattr(). jab From peter at engcorp.com Mon Sep 12 10:08:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Sep 2005 10:08:54 -0400 Subject: How to protect Python source from modification In-Reply-To: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Message-ID: Frank Millman wrote: > I am writing a multi-user accounting/business system. Data is stored in > a database (PostgreSQL on Linux, SQL Server on Windows). I have written > a Python program to run on the client, which uses wxPython as a gui, > and connects to the database via TCP/IP. > > The client program contains all the authentication and business logic. > It has dawned on me that anyone can bypass this by modifying the > program. As it is written in Python, with source available, this would > be quite easy. My target market extends well up into the mid-range, but > I do not think that any CFO would contemplate using a program that is > so open to manipulation. > > The only truly secure solution I can think of would involve a radical > reorganisation of my program Please define what "truly secure" means to you. I think you'll find that the only "truly secure" solution is to install the critical authentication and business logic stuff that you want to protect on a server to which the user does not have physical access. People wanting to protect critical algorithms often conclude that they need to have a "black box" server which cannot be physically opened by the user. Or do you think this issue is in some way unique to Python? You might not realize that the only difference from a security point of view between shipping such a program written in Python and one written in, say, C++, is that "modifying the program" is somewhat more tedious with C++. That's no better than security by obscurity; maybe it should be called "security by adiposity". ;-) But the real answer does depend a lot on *exactly* what kind of security you want (or, ultimately, what it turns out you really need, once you've clarified your thinking based on the feedback you do get here). Issues like: are you more concerned about detecting changes, or in preventing them in the first place? (the latter is much harder); what is the nature of software that competes with yours? (is it really any more secure, or only apparently so? maybe this is just a marketing issue); and is there any intellectual property that you are trying to protect here, or are you just interested in avoiding casual disruption of normal operation? -Peter From vincent at visualtrans.de Thu Sep 22 02:39:36 2005 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 22 Sep 2005 08:39:36 +0200 Subject: PyEphem on winXP References: <1127337234.547710.160890@f14g2000cwb.googlegroups.com> Message-ID: schrieb im Newsbeitrag news:1127337234.547710.160890 at f14g2000cwb.googlegroups.com... | Hi, | | I'm a (sort of) newbie to python and would like to install the PyEphem | extension to Python. I'm using Python 2.4 | I obtained PyEphem from: | http://rhodesmill.org/brandon/projects/pyephem.html | | When i ran python setup.py install my error was: | "error: Python was built with version 7.1 of Visual Studio, and | extensions need to be built with the same version of the compiler, but | it isn't installed" | | Browsing this group led me to the following URL where I could get (for | free) the Visual C++ Toolkit 2003: | http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-49FD-9CB0-4BFA122FA91B&displaylang=en | | However I still see the same error when running | python setup.py install. | I know that Visual C++ Toolkit 2003 is the same as version 7.1, but is | this the same as Visual Studio 7.1? It should work. Did you follow the instructions as per http://www.vrplumber.com/programming/mstoolkit/ ? I've had success using that approach... HTH, -- Vincent Wehren | | If so, can Visual Studio 7.1 be obtained for free? | If not, is there a workaround? | | I've seen suggestions in the group that you can recompile Python 2.4 | using MinGW or some other c compiler. I'd be willing to do that, but | do not know how to go about recompiling python. Advice on this would | also be helpful. | | Thanks, | James | From cam.ac.uk at mh391.invalid Fri Sep 2 10:14:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 02 Sep 2005 15:14:42 +0100 Subject: anaconda.real in RH7.1 In-Reply-To: <1125669216.690734.265910@g14g2000cwa.googlegroups.com> References: <1125669216.690734.265910@g14g2000cwa.googlegroups.com> Message-ID: pruebauno at latinmail.com wrote: > If I know the the name of the module > (for example it starts with sys.zz) I use: > http://www.python.org/doc/2.4.1/modindex.html > > If I know what I want but not the name I use: > http://www.python.org/doc/2.4.1/lib/lib.html I have a Firefox Quick Search installed with keyword: pymod and location: http://www.python.org/doc/lib/module-%s.html or on a Windows box where I have the docs installed locally: file:///C:/Documentation/Python-Docs-2.4/lib/module-%s.html -- Michael Hoffman From benji at benjiyork.com Wed Sep 7 18:29:49 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 07 Sep 2005 18:29:49 -0400 Subject: Construct raw strings? In-Reply-To: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> References: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> Message-ID: <431F69DD.7060001@benjiyork.com> Thomas W wrote: > I got a stupid problem; on my WinXP-box I want to scan the filesystem > and enter a path to scan like this : > > path_to_scan = 'd:\test_images' Note the lack of an "r" prefix and the \t sequence above. > The problem is that some of the parts being joined contains escape > characters > If I take the seperate parts and join them using the interpreter, > like : > >>>> f = r'd:\test_images\something\foo\bar\test.jpg' > > it works ok and os.path.exists(f) returns True, but I cannot the that > r' in front using the os.path.join-method in my code. It's not join that's getting you, it's the non-raw string representation in path_to_scan. Use either 'd:\test_images' or 'd:\\test_images' instead. -- Benji York From jgrahn-nntq at algonet.se Sat Sep 17 17:57:30 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 17 Sep 2005 21:57:30 GMT Subject: which is more 'pythonic' / 'better' ? References: Message-ID: On Mon, 12 Sep 2005 12:52:52 +0200, gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? I don't know. Who cares? > === > try: > text = line[n] > except IndexError: > text = 'nothing' > === > > > which is the one you would use? The 'try' version. But I'd also ask myself how I could end up in a state where this part of the code is asked to find a string that doesn't exist, and if I really want it to keep running, with a made-up value. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Nainto at gmail.com Mon Sep 5 14:05:44 2005 From: Nainto at gmail.com (Nainto) Date: 5 Sep 2005 11:05:44 -0700 Subject: Getting the bytes or percent uploaded/downloaded through FTP? In-Reply-To: References: <1125931880.415786.40880@g47g2000cwa.googlegroups.com> Message-ID: <1125943544.670895.308940@f14g2000cwb.googlegroups.com> Thanks guys. I'll try to these things too work. From jeremy+complangpython at jeremysanders.net Wed Sep 14 06:55:41 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 14 Sep 2005 11:55:41 +0100 Subject: round() wrong in Python 2.4? References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Message-ID: Robert Kern wrote: > That's not what he's asking about. He's asking why his Python 2.3 rounds > 0.0225 *up* to 0.023 while his Python 2.4 rounds *down* to 0.022. It's > the change in behavior that he's concerned with and isn't just the usual > floating point problem. You can't rely on either being true, given the nature of the inexact representation of the number, and the fact that python ignores quite a lot of the IEEE stuff. Different optimisations (particularly with the 80 bit floating point registers in x86), will lead to different represenations. Any code which relies on a particular behaviour is broken. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From steve at REMOVETHIScyber.com.au Sun Sep 18 01:27:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 18 Sep 2005 15:27:38 +1000 Subject: complex data types? References: Message-ID: On Sat, 17 Sep 2005 20:49:32 -0500, richard wrote: > I'd like to have an array in which the elements are various data types. > How do I do this in Python? > > For example: > > array[0].artist = 'genesis' > array[0].album = 'foxtrot' > array[0].songs = ['watcher', 'time table', 'friday'] > array[1].artist = 'beatles' > array[1].album = 'abbey road' > array[1].songs = ['come', 'something', 'maxwell'] > > Everything I try generates errors or results in array[0].songs equaling > array[1].songs. I feel I'm missing something obvious. Would you like to tell us what you have already tried, or should we guess? To get good answers, it helps to ask good questions. What have you tried. What errors did you generate? Most importantly, what are you hoping to do with your data structure after you've got it? One hint is to split the problem into two halves, then solve each one. It looks to me like you are trying to store a list of albums. So half the problem is solved: the list of albums is just a list. Each item is an album. Now you just have to decide on how you store each album. Here is one solution: # Create a single album. album = {"artist": "beetles", "title": "abbey road", \ "songlist" = ['come together', 'something', 'maxwell']} # Store it in the album list. albums.append(album) You can change an item like this: # Oops, wrong artist... albums[0]["artist"] = "beatles" albums[0]["songlist"].append("mean mr mustard") Does this solution work for you? If not, what does it not do that you need it to do? -- Steven. From aldo at nullcube.com Wed Sep 7 00:08:57 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 7 Sep 2005 14:08:57 +1000 Subject: ~ after script filename? In-Reply-To: <1126065469.212137.264680@g49g2000cwa.googlegroups.com> References: <1126065469.212137.264680@g49g2000cwa.googlegroups.com> Message-ID: <20050907040857.GA9750@nullcube.com> Thus spake presentt (presentt at gmail.com): > Hello all, > > I just wrote a really simple script and named it > helloworld.py. Inside was only: > > #!/usr/bin/env print "Hello, world" > > I used chmod to set the permissions, and ran it to see > what happened (I just started learning Python, if you > couldn't guess) > > Then, I typed ls in the directory to see what was there, > and I noticed a new file, namely helloworld.py~ . What is > that file (its contents are identicle to helloworld.py)? > Why the ~? > > Thanks a lot. I'm using Ubuntu Linux 5.04 (Hoary), and > wrote the script with gedit. It doesn't have anything to do with Python. I'm pretty sure you'll find that the file is created by your editor as a backup or a running store of some kind. Try just editing a random non-python file with the same editor, and see if you find the same thing... Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From rune.strand at gmail.com Wed Sep 14 21:26:23 2005 From: rune.strand at gmail.com (Rune Strand) Date: 14 Sep 2005 18:26:23 -0700 Subject: Some advice on startingout with python. In-Reply-To: References: Message-ID: <1126747583.709224.294020@g44g2000cwa.googlegroups.com> It's not about GUI, but it's a good book. It's both online and printed: http://diveIntoPython.org From chrisperkins99 at gmail.com Thu Sep 15 19:11:40 2005 From: chrisperkins99 at gmail.com (chrisperkins99 at gmail.com) Date: 15 Sep 2005 16:11:40 -0700 Subject: 2.3 -> 2.4: long int too large to convert to int References: <11ijsh0h2dec0ed@corp.supernews.com> Message-ID: <1126825900.309872.76830@f14g2000cwb.googlegroups.com> Grant Edwards wrote: > I give up, how do I make this not fail under 2.4? > > fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00)) > > I get an OverflowError: long int too large to convert to int > > ioctl() is expecting a 32-bit integer value, and 0xc0047a80 has > the high-order bit set. I'm assuming Python thinks it's a > signed value. How do I tell Python that 0xc0047a80 is an > unsigned 32-bit value? > You could sort-of fake it like this, def unsigned(val): return struct.unpack('i', struct.pack('I', val))[0] fcntl.ioctl(self.dev.fileno(), unsigned(0xc0047a80), ...) but good luck writing a docstring explaining why a function called "unsigned" takes a positive long and returns a negative int... ;) Chris Perkins From steve at REMOVETHIScyber.com.au Wed Sep 14 14:06:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 15 Sep 2005 04:06:04 +1000 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <7xwtlkrs4c.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 14 Sep 2005 11:28:02 -0400, Terry Reedy wrote: > > "Steven D'Aprano" wrote in message > news:pan.2005.09.14.12.05.00.913356 at REMOVETHIScyber.com.au... >> Which works wonderfully as an academic exercise, but doesn't tend to work >> so terribly well in the real world where the performance and >> resource-requirement differences between iteration and recursion can be >> significant. > > I think your comparison is incomplete. Yes, it is incomplete. It seems that I've given the mistaken impression that I am opposed to recursion in principle. I am not. Perhaps I should have qualified my remarks by stating that sometimes recursion can be easier to comprehend than iteration, more efficient and all those other goodies that developers like their programs to be. A good example of a task that is frequently better solved with recursion than with iteration is walking a binary tree. But in the context of my response, I was replying to a paraphrased quote from somebody who apparently believes that recursion is *always* better than iteration. That is clearly not the case. It is a "mere implementation detail" that (for most computer systems, and most programming languages) stack space is at a premium and a deeply recursive function can run out of stack space while the heap still has lots of free memory. But those implementation details in the real world make the difference between an elegant solution that runs like a lame duck and an practical solution that has nothing going for it except the fact that it works. (And then there are the elegant solutions that are also practical. It is a good day when you find yourself writing one of those.) Recursion is frequently extravagant in its use of resources: if nothing else, it takes resources to call a function, and recursion means you call the same function over and over again. There is a reason why functional programming never really took off. Extravagance is not necessarily a bad thing -- if I thought it were, I wouldn't be using a high-level object-oriented language like Python. But it is important to be aware of those factors. > Recursion and iteration are two syntaxes for the same operation: repetition > with variation. Yes, in general anything that can be solved recursively can be solved iteratively. Some classes of problems lend themselves naturally to one or the other solution, but it is always possible (in principle at least) to use either. > Abstractly, these are two algorithms for the same function. One runs in > exponential time because it wastefully calculates and tosses away an > exponential number of subvalues. The other runs in linear time because it > calculates each subvalue once. When one only wants Fib(n), and not the > sequence leading up to it, even this is wasteful, for large enough n, since > there is a third algorithm that caluculates Fib(n) directly by a simple > formula (something like the interger part of the golden ratio to the nth > power). Yes. There are lots of algorithms that could be done, and they all have their pros and cons. Biset's formula, for example, is mathematically correct, but for large enough n, the "mere implementation detail" that floats have a finite precision will cause that algorithm to give incorrect answers. For "large enough", on my system I mean n=71. > Now: I could (and probably someday will) write an iterative version of the > exponential algorithm (using an explicit stack) that calculates each > subvalue exactly as many times as the recursive version of that same > algorithm. And I could compare it to a recursive version of the more > efficient linear algorithm (such as posted by Jerzy Karczmarczuk). And I > could claim that this shows hows iteration can waste time compared to > recursion. Of course it can. But you have to really *work* at getting the iterative version to be as wasteful as the obvious recursive version. > But that, I admit, would be an invalid conclusion. And that, I claim, > is also invalid when 'iteration' and 'recursion' are reversed, no matter > how often repeated in texts and articles. The difference is between the > algorithms, not the differing syntactic expressions thereof. Now you go too far. You are right that a change of algorithm will often make a much bigger difference to performance than merely swapping from one form of repetition to another. But you ignore those "mere implementation details" that lead to exceptions like this one: RuntimeError: maximum recursion depth exceeded (eg calling Jerzy Karczmarczuk's efficiently recursive function with n=1000, while my iterative version works for at least values of n an order of magnitude larger.) Yes, the maximum recursion depth in Python is an artificial limit. But that artificial limit is built into Python specifically to protect you from running into a real recursion limit based on the hardware and architecture of your PC, with painful consequences. -- Steven. From bathing at gmail.com Fri Sep 16 00:18:33 2005 From: bathing at gmail.com (A. L.) Date: 15 Sep 2005 21:18:33 -0700 Subject: How to clear screen in Python interactive shell mode? Message-ID: <1126844313.379059.207200@z14g2000cwz.googlegroups.com> In Python interactive mode, is there some function acting like 'clear' command in bash? Could somebody here give some advice? Thanks in advance. From mekstran at scl.ameslab.gov Thu Sep 29 10:54:42 2005 From: mekstran at scl.ameslab.gov (Michael Ekstrand) Date: Thu, 29 Sep 2005 09:54:42 -0500 Subject: A rather unpythonic way of doing things In-Reply-To: <37ll1gci8v.fsf@chiark.greenend.org.uk> References: <37ll1gci8v.fsf@chiark.greenend.org.uk> Message-ID: <200509290954.43129.mekstran@scl.ameslab.gov> On Thursday 29 September 2005 04:53, Peter Corbett wrote: > One of my friends has recently taken up Python, and was griping a bit > about the language (it's too "prescriptive" for his tastes). In > particular, he didn't like the way that Python expressions were a bit > crippled. So I delved a bit into the language, and found some sources > of syntactic sugar that I could use, and this is the result: > > http://www.pick.ucam.org/~ptc24/yvfc.html Umm, TMTOWTDI? As uniform as Python is, it still is flexible... Brilliant. Simply brilliant. -Michael From tjreedy at udel.edu Sun Sep 4 21:11:30 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Sep 2005 21:11:30 -0400 Subject: Possible improvement to slice opperations. References: Message-ID: <9ZudnU0AAr3ZBobeRVn-ig@comcast.com> "Ron Adam" wrote in message news:FRISe.13089$xl6.6814 at tornado.tampabay.rr.com... > Slicing is one of the best features of Python in my opinion, but > when you try to use negative index's and or negative step increments > it can be tricky and lead to unexpected results. > > This topic has come up fairly often on comp.lang.python, and often times, > the responses include: > * Beginners should avoid negative extended slices. > * Slices with negative step increments are for advanced > python programmers. > * It's not broke if you look at it in a different way. > * You should do it a different way. You omitted the slice-specific response I gave before and repeat here with more detail by quoting from What's New in Python 2.3. http://www.python.org/doc/2.3/whatsnew/section-slices.html " 15 Extended Slices Ever since Python 1.4, the slicing syntax has supported an optional third ``step'' or ``stride'' argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. " Again, extended slices were probably designed by and certainly designed for Numerical Python and for 7 years were used at least mainly by Numerical Python. They were not designed for other users like you. The responses you summarized and distain pretty much all derive from this history. So, I am pretty sure that changes to the core would have to be upwards compatible with current usage. On the other hand, your nxlist subclass of list seems to work pretty well now.The 2.2+ ability to do this sort of thing is what type subclassing was made for. Or one could just write an extended slice function similar to your .normslc method. I might even use such a thing one day. Terry J. Reedy From duncan.booth at invalid.invalid Sun Sep 25 14:55:38 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2005 18:55:38 GMT Subject: Struggling with basics References: Message-ID: Jason wrote: > My first problem (lack of understanding of course) is that if I run the > above, I get an error saying: > > print "%s - %s" % name,score > TypeError: not enough arguments for format string > > Now I understand what it's saying, but I don't understand why. > The problem is precedence. print "%s - %s" % name,score is equivalent to: print ("%s - %s" % name),score not: print "%s - %s" % (name,score) The % operator binds more tightly than the comma, so you need to put parentheses around the argument to % (as in the last line above). From richie at entrian.com Thu Sep 29 11:05:03 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 29 Sep 2005 16:05:03 +0100 Subject: A rather unpythonic way of doing things In-Reply-To: <433bff40$0$13513$626a14ce@news.free.fr> References: <37ll1gci8v.fsf@chiark.greenend.org.uk> <433bff40$0$13513$626a14ce@news.free.fr> Message-ID: [Peter] > http://www.pick.ucam.org/~ptc24/yvfc.html [fraca7] > print ''.join(map(lambda x: chr((((ord(x) - ord('a')) + 13) % 26) + > ord('a')), 'yvfc')) Ah! Or more easily, Edit / Apply ROT13. Thanks! -- Richie Hindle richie at entrian.com From http Wed Sep 7 00:29:20 2005 From: http (Paul Rubin) Date: 06 Sep 2005 21:29:20 -0700 Subject: Function returns a function References: <7x4q8xx5fn.fsf@ruckus.brouhaha.com> <4ajlfd.ok4.ln@lightning.itga.com.au> Message-ID: <7x8xy9lcv3.fsf@ruckus.brouhaha.com> Aldo Cortesi writes: > The lexical scope within which a function is declared is > made available to the function when it is run. This is done > by storing the values of free variables within the declared > function in the func_closure attribute of the created > function object. Actually not quite right: a = [] for i in range(5): a.append(lambda: i) # i is free in the lambda print [f() for f in a] prints [4,4,4,4,4] instead of [0,1,2,3,4]. The value of i has not been copied into the closure. Rather, the closure has a cell bound to the same place that i is bound. So: for i in range(5): def f(): j = i # bind a new variable "j" and assign the value from i return lambda: j # j is free and its value doesn't change a.append(f()) print [f() for f in a] prints [0,1,2,3,4]. There's a Pythonic idiom using default args: a = [] for i in range(5): a.append(lambda i=i: i) # the "inner" i is free in the lambda print [f() for f in a] Closures like may look a little surprising in Python but they're a standard technique in Scheme. The classic textbook "Structure and Interpretation of Computer Programming" explains it all. Full text is online at: http://mitpress.mit.edu/sicp/ From ms at cerenity.org Mon Sep 19 03:29:19 2005 From: ms at cerenity.org (Michael Sparks) Date: Mon, 19 Sep 2005 08:29:19 +0100 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <1126881457.829758.281840@g47g2000cwa.googlegroups.com> Message-ID: <432e68ce$0$1298$ed2619ec@ptn-nntp-reader02.plus.net> Giles Brown wrote: > Michael Sparks wrote: >> The problem that these sorts of approaches don't address is the simple >> fact that simple creating a formal spec and implementing it, even if >> you manage to create a way of automating the test suite from the spec >> *doesn't guarantee that it will do the right thing*. > >> As a result I'd say that the subject "Software bugs aren't inevitable" >> is not true. > > I think you can argue (I would) that any behaviour that is in the > specification this "isn't right" is not a software bug, but a > specification error. To a user there is no difference. If the software doesn't do what they wanted it to do/asked for, then to *them* the person who is accepting the software it's a bug. It doesn't matter to them what caused it - be it a buffer overflow, a misunderstanding of a language feature or an incorrectly written formal spec, it's still a bug to them. I'm actually a big fan of formal specification (specifically VDM), but that doesn't stop me realising that it's not a cure-all, and it's also not an excuse - if code doesn't do what it was asked to do, it's bust. Regards, MIchael. From steve at holdenweb.com Wed Sep 21 10:38:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Sep 2005 15:38:47 +0100 Subject: wxPython Notebook crash when pressing alt key In-Reply-To: <1127311253.582981.277380@z14g2000cwz.googlegroups.com> References: <1127311253.582981.277380@z14g2000cwz.googlegroups.com> Message-ID: Kreedz wrote: > Hi > > I've got some really weird issue with a sizer, a text field and a > notebook. Here's an example: > > import wx > > class A(wx.Panel): > def __init__(self, parent, id): > wx.Panel.__init__(self, parent) > self.noteBook = wx.Notebook(self, -1) > self.panel = wx.Panel(self.noteBook, -1) > self.noteBook.AddPage(self.panel, "Page 1", False) > self.text = wx.TextCtrl(self, -1) > sizerMain = wx.BoxSizer(wx.VERTICAL) > sizerMain.Add(self.text, 0) > sizerMain.Add(self.noteBook, 0, wx.EXPAND) > self.SetSizer(sizerMain) > > class TRL(wx.Frame): > def __init__(self, parent, id, title="App"): > wx.Frame.__init__(self, None, -1, title, size=(640,480)) > self.content = A(self, -1) > > app = wx.App() > app.frame = TRL(None, -1) > app.frame.Show(True) > app.MainLoop() > > Run this, press ALT+F or ALT+(any other key) and try closing the > application (Its totally frozen) Anybody have a solution to this? Or > have an idea whats hapening and what I am doing wrong? > > Thanks > > - Kreedz > This code works fine for me (once I add an "import wx" at the top). Python 2.4.1, wxPython 2..5.3.1 regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From nils.grimsmo at gmail.com Tue Sep 13 09:17:50 2005 From: nils.grimsmo at gmail.com (Nils Grimsmo) Date: 13 Sep 2005 06:17:50 -0700 Subject: round() wrong in Python 2.4? Message-ID: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Why did round() change in Python 2.4? $ python2.3 Python 2.3.5 (#2, Jun 19 2005, 13:28:00) [GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2 >>> round(0.0225, 3) 0.023 >>> "%.3f" % round(0.0225, 3) '0.023' >>> $ python2.4 Python 2.4.1 (#2, Jul 12 2005, 09:22:25) [GCC 4.0.1 (Debian 4.0.1-1)] on linux2 >>> round(0.0225, 3) 0.021999999999999999 >>> "%.3f" % round(0.0225, 3) '0.022' >>> (Is this due to the different GCC used?) How do you correctly output floating-point numbers in 2.4? I do not like the "print number + EPS" solution, as you would need different EPS for different exponent sizes. In C you could get it by taking integer 1, and &-ing in the right exponent, and then casting to double via void*. This would not be very portable, though. Klem fra Nils From frithiof.jensen at die_spammer_die.ericsson.com Tue Sep 20 05:33:31 2005 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 20 Sep 2005 11:33:31 +0200 Subject: ready-made file format for "file pibes"? Message-ID: I am writing an application that does a lot of filtering of much data through a sequence of filters. After some thinking and wasting a lot of time with an object oriented design with GUI and all, I decided that the Real Way to do this is to create the filters as independent programs that take input and produce output in the good, olde UNIX way, using good olde MAKE to track what needs to be done next. Now, I need to simplify even further and leach on even more common knowledge :) so it is obvious to anyone how to extend the collection of filtering methods. Is there a Python library for defining and using a good (i.e. humanly readable), text-based format that one can use for the intermediate files? ZConfig is - as I understand it - read-only and it is difficult (for me) to completely understand what the general principles are because anything appears possible with it. I am unsure of Pyxie mainly because the documentation does not describe the "philosophy" and I would rather not hack up a parser for XML myself for my very-own-xml-format-that-no-one understands. If the experience with ZConfig is good, then maybe one can sidestep this and simply write files that can later be read by ZConfig? I need to save state between filter runs too and I would like to use the same mechanism everywhere. I also need some form of hierachi, i.e. for including information from further up the chain to know what triggered a filter so that downstream tools can get that information. Something as simple as a stansa-format (like .netrc) will probably be servicable with a little work - but if someone has already defined a better, more commonly-used format, I am all game. Any Clues?? mvh, frithiof jensen. From steve at REMOVETHIScyber.com.au Sat Sep 24 14:41:33 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 25 Sep 2005 04:41:33 +1000 Subject: Dynamically adding and removing methods Message-ID: Suppose I create a class with some methods: py> class C: ... def spam(self, x): ... print "spam " * x ... def ham(self, x): ... print "ham * %s" % x ... py> C().spam(3) spam spam spam >>> C().ham(3) ham * 3 To dynamically remove the methods, delete them from the class like you would any other attribute: py> del C.ham py> C().ham(3) Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'ham' That's fairly straight forward -- no major surprises there. How does one dynamically add methods to an instance or class? You might think you can do this: py> def eggs(self, x): ... print "eggs * %s" % x ... py> inst = C() py> inst.eggs = eggs py> inst.eggs(3) Traceback (most recent call last): File "", line 1, in ? TypeError: eggs() takes exactly 2 arguments (1 given) Even though we've added a function to the instance, it hasn't got all the machinery to work as a proper method. A work-around is to explicitly pass an instance: py> inst.eggs(inst, 3) eggs * 3 To create a proper method, we do this: py> import new py> inst.eggs = new.instancemethod(eggs, None, C) py> inst.eggs(3) eggs * 3 You can now delete the top-level function eggs, and the method bound to inst will not be affected. Because eggs is bound to the instance, new instances will not understand it: py> C().eggs(3) Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'eggs' Or you could put the method in the class and have all instances recognise it: py> C.eggs = new.instancemethod(eggs, None, C) py> C().eggs(3) eggs * 3 Instead of passing None as the second argument to instancemethod, you can pass an instance. If you do that, self will automatically be set to that instance instead of the one doing the calling: py> def truffles(self, x): ... print self, x ... py> C.truffles = new.instancemethod(truffles, inst, C) py> inst <__main__.C instance at 0xf6d2d6cc> py> inst.truffles(3) <__main__.C instance at 0xf6d2d6cc> 3 No surprises there. But look what happens when we use a new instance: py> x = C() py> x <__main__.C instance at 0xf6d2ca6c> >>> x.truffles(3) <__main__.C instance at 0xf6d2d6cc> 3 Hope this is useful to some folks. -- Steven. From huron at sopinspace.com Tue Sep 6 04:34:41 2005 From: huron at sopinspace.com (Huron) Date: Tue, 06 Sep 2005 10:34:41 +0200 Subject: Job Offer in Paris, France : R&D Engineer (Plone) References: <7xbr37u8ut.fsf@ruckus.brouhaha.com> <7xpsrn3100.fsf@ruckus.brouhaha.com> Message-ID: > Working remotely hadn't occurred to me ;-). I was wondering > > 1) whether there would be legal or procedural obstacles for a > non-European wanting to work in Paris for a while; and If you are a member of the EU (the netherlands ?), there no such problem on our side. Only _you_ would have some paperwork to do. > 2) whether it was mandatory to be able to speak and write in French (I > can do so, but very badly for now). I would say that it is mandatory to speak a bit and to be willing/able to lean ... but this is not _mandatory_ to speak perfectly. This should not stop you if you're interested. (A test could be : whether or not you understand the position description pdf.) > I'm sure you will get lots of good French-speaking candidates though. Dont be too sure of that ;-) ... and dont hesitate to apply if you are interested. Best, - RB From manuelg at gmail.com Wed Sep 7 17:52:22 2005 From: manuelg at gmail.com (manuelg at gmail.com) Date: 7 Sep 2005 14:52:22 -0700 Subject: List of integers & L.I.S. References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> Message-ID: <1126129942.736374.260770@g44g2000cwa.googlegroups.com> I coded a solution that can compute the ordering numbers for random.shuffle(range(1, 1000001)) in 2.5 seconds (typical, Win 2K Pro, Pentium 4 2.40GHz 785Meg RAM) Are you sure that this is not a homework problem? From erniedude at gmail.com Mon Sep 12 12:23:58 2005 From: erniedude at gmail.com (Ernesto) Date: 12 Sep 2005 09:23:58 -0700 Subject: Ctypes Install in Linux In-Reply-To: <1126541837.832917.172740@g14g2000cwa.googlegroups.com> References: <1126541371.379893.295950@g43g2000cwa.googlegroups.com> <1126541837.832917.172740@g14g2000cwa.googlegroups.com> Message-ID: <1126542238.904285.208470@g14g2000cwa.googlegroups.com> Thanks for the help. I'm kind of new to Linux, but I am the only user of this machine (just installed Red Hat). How do I make myself a "root-user"? For the second method you mentioned, how do I add access the PYTHONPATH environment variable? Thanks again! From removethis.kartic.krishnamurthy at gmail.com Sun Sep 4 14:00:40 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Sun, 04 Sep 2005 18:00:40 GMT Subject: Problems with Python for Windows extensions In-Reply-To: <1125760475.488680.17070@z14g2000cwz.googlegroups.com> References: <1125760475.488680.17070@z14g2000cwz.googlegroups.com> Message-ID: <431B36F7.80206@gmail.com> Hi, Invoking Execute as shown below works.. I have no explanation why your VB to Py converted code did not work. wdFindContinue = 1 objSelection.Find.Execute('Contosa', False, True, False, False, True, True, wdFindContinue, True, 'Fabrikam', wdReplaceAll, False, False, False, False) This finds 'Contosa' and replaces all occurances with 'Fabricam'. For a full explanation about the arguments to Execute, look it up in the VBA Help. Thanks, -Kartic The Great 'KK' uttered these words on 9/3/2005 11:14 AM: > the code below is taken from M$ technet as an example on using vb > script to do a replace all in word: > > Const wdReplaceAll = 2 > > Set objWord = CreateObject("Word.Application") > objWord.Visible = True > > Set objDoc = > objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") > Set objSelection = objWord.Selection > > objSelection.Find.Text = "Contoso" > objSelection.Find.Forward = True > objSelection.Find.MatchWholeWord = True > > objSelection.Find.Replacement.Text = "Fabrikam" > objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll > > > > > I did a rewrite and made it pythonic: > > from win32com.client import * > > wdReplaceAll = 2 > > objWord = Dispatch("Word.Application") > objWord.Visible = True > > objDoc = > objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") > objSelection = objWord.Selection > > objSelection.Find.Text = "Contoso" > objSelection.Find.Forward = True > objSelection.Find.MatchWholeWord = True > > objSelection.Find.Replacement.Text = "Fabrikam" > objSelection.Find.Execute (Replace = wdReplaceAll) > > > However, the document juz loaded up in word but no action was taken. I > am using Word 2003. Any ideas? > From zen19725 at zen.co.uk Fri Sep 16 11:47:12 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Fri, 16 Sep 2005 16:47:12 +0100 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <7xwtlkrs4c.fsf@ruckus.brouhaha.com> <7xpsrb78tn.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 16 Sep 2005 20:36:02 +1000, Steven D'Aprano wrote: >On Thu, 15 Sep 2005 18:07:28 +0100, phil hunt wrote: > >> On Thu, 15 Sep 2005 21:56:06 +1000, Steven D'Aprano wrote: >>> >>>Are you saying that the recursion done by "serious" languages is a fake? >>>That it is actually implemented behind the scenes by iteration? >>> >>>It seems to me that if recursion and iteration produce "the exact same >>>machine code", the argument for preferring recursion over iteration is >>>gutted. >> >> It seems to me that if a high level language and assembler produce >> "the exact same machine code", the argument for preferring high >> level languages is gutted. >> >> Do you see the fallacy in your statement now? > >Ah, yes, you got me on that one. > >But there is a difference: writing assembly is *hard*, which is why we >prefer not to do it. Are you suggesting that functional programming is >significantly easier to do than declarative? No. I'm saying that under some circumstances it might be easier to write code as a recursive routine than a loop. In those circumstances, why should I care if the compiler then re-encodes my recursive routine as a loop, so long as the program gives the correct answer. Compilers/interpreters/runtimes are black boxes: we don't (or shouldn't) care how they do their work as long as they run correctly and aren't too heavy on system resources like CPU time and memory. -- Email: zen19725 at zen dot co dot uk From mitsura at skynet.be Mon Sep 5 09:12:19 2005 From: mitsura at skynet.be (mitsura at skynet.be) Date: 5 Sep 2005 06:12:19 -0700 Subject: newbie Q: mouse clicks don't seem to get trapped Message-ID: <1125925939.370793.78240@z14g2000cwz.googlegroups.com> Hi, I want to display a window containing an image and when I move the mouse over the image and click on the left Mb, I want to get the position of the mouse on the image. I listed the code to view the image below (so far so good) but for some reason the EVT_LEFT_DOWN/UP does not work. Any idea what might be wrong? With kind regards, Kris " class DisplayPicture(wx.Frame): cD = 0 # bmp = stream that contains the picture (not a filename!) # w,h: widht, height of the picture def __init__(self, parent, id, title, bmp, w, h): wxFrame.__init__(self,parent,wxID_ANY, title, size = ( w, h), style=wxDEFAULT_FRAME_STYLE) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick) self.Bind(wx.EVT_LEFT_UP, self.OnLeftClick) Panel=wx.Panel(self) wx.StaticBitmap(Panel, -1, bmp, (5, 5) ) self.Show() def OnLeftClick(self, event): print "ok" " From tjreedy at udel.edu Thu Sep 8 14:05:13 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Sep 2005 14:05:13 -0400 Subject: generator object, next method References: <1126164425.475226.143510@g14g2000cwa.googlegroups.com> <7xll282cz4.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xll282cz4.fsf at ruckus.brouhaha.com... > Duncan Booth writes: >> 1) Every time you access gen.next you create a new method-wrapper >> object. > > Why is that? I thought gen.next is a callable and gen.next() actually > advances the iterator. Why shouldn't gen.next always be the same object? If you explicitly or implicitly (via for loop) calculate gen.next exact once (as I presume for loops do, and as I would for explicit while loop), then it is. When you keep a reference to the wrapper, and call it repeatedly via that wrapper, then all is as you expect. next_x = genfunc(*args).next while True: x = next_x() # same next_x each time Terry J. Reedy From anthony at python.org Wed Sep 28 08:44:15 2005 From: anthony at python.org (Anthony Baxter) Date: Wed, 28 Sep 2005 22:44:15 +1000 Subject: RELEASED Python 2.4.2 (final) Message-ID: <200509282244.26130.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.2 (final). Python 2.4.2 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 more than 60 bugs squished in this release. For more information on Python 2.4.2, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.2 Highlights of this new release include: - Bug fixes. According to the release notes, more than 60 have been fixed, including bugs that prevented Python from working properly on 64 bit HP/UX and AIX systems. Highlights of the previous major Python release (2.4) are available from the Python 2.4 page, at http://www.python.org/2.4/highlights.html Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From forestiero at qwest.net Tue Sep 6 00:31:26 2005 From: forestiero at qwest.net (DogWalker) Date: Mon, 05 Sep 2005 21:31:26 -0700 Subject: Python executable In-Reply-To: <1125978845.080791.14520@g43g2000cwa.googlegroups.com> References: <1125978845.080791.14520@g43g2000cwa.googlegroups.com> Message-ID: <20050906042632.1986.57786@linux.local> "presentt" said: >Hello, > >I'm running Ubuntu Linux 5.04. > >I just started teaching myself Python today, and have been reading a >few things to get started. I came across something in one (namely >http://docs.python.org/tut/node4.html#SECTION004220000000000000000) >that confused me a little. > >It says: > >------------ > >On BSD'ish Unix systems, Python scripts can be made directly >executable, like shell scripts, by putting the line > >#! /usr/bin/env python > >(assuming that the interpreter is on the user's PATH) at the beginning >of the script and giving the file an executable mode. The "#!" must be >the first two characters of the file. On some platforms, this first >line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") >or Windows ("\r\n") line ending. Note that the hash, or pound, >character, "#", is used to start a comment in Python. > >The script can be given a executable mode, or permission, using the >chmod command: > >$ chmod +x myscript.py > >----------- > >So I created a file named helloworld.py, and put in it: > >#! /usr/bin/env python >print "Hello, world!" > >and then used >$ chmod +x helloworld.py >to set the permissions. Finally, I went to my terminal and typed >$ helloworld.py >but I was given the bash: helloworld.py: command not found error. > >Can someone tell me >(1)Am I right in saying that something is directly executable if I can >enter the filename in the command line and it runs? >(2)Am I setting up the script to be directly executable correctly? >and (3)Am I trying to run the directly executable script correctly? > >Thanks a lot. I hope this post isn't too hard to follow; I know I'm >asking a lot. > >~~Ted Present > [3] cd to the directory that contains helloworld.py, then ./helloworld.py (When you enter helloworld.py as a command, the shell searches the PATH for helloworld.py and if it is not found, it complains. If you tell it that it's in the current directory, it will get it without searching.) From max2 at fisso.casa Thu Sep 1 15:03:27 2005 From: max2 at fisso.casa (max(01)*) Date: Thu, 01 Sep 2005 19:03:27 GMT Subject: named pipe input Message-ID: <3gIRe.6091$O6.328317@news3.tin.it> hi there. i have some problems understanding following behaviour. consider this: ... $ cat file_input_3.pl #!/usr/bin/perl open MIAPIPE, "una_pipe"; while ($riga = ) { print STDOUT ("$riga"); } $ cat file_input_3.py #!/usr/bin/python import sys MIAPIPE = open("una_pipe", "r") for riga in MIAPIPE: print riga, ... where una_pipe is a named pipe (created with mkfifo). when i run this on console #1: ... $ ./file_input_3.pl ... and this un console #2: ... $ cat > una_pipe aaa bbb ccc ... then each line typed in console #2 appears on console #1 as soon as the line is terminated (hit return). BUT if i try to do the same with the python code, something different happens: i have to type ALL the lines on console #2 and complete the cat command (ctrl-d) before seeing the lines echoed on console #1. i tried the -u flag but doesnt seem to work. any help? bye From bokr at oz.net Mon Sep 19 18:58:40 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 19 Sep 2005 22:58:40 GMT Subject: How to program efficient pattern searches in a list of float numbers? References: <1127113354.897477.235360@g44g2000cwa.googlegroups.com> Message-ID: <432f4074.1914477543@news.oz.net> On 19 Sep 2005 00:02:34 -0700, "malv" wrote: >Simple case: >In this list, how to find all occurences of intervals of n adjacent >indexes having at least one list-member with a value between given >limits. >Visualizing the list as a two-dimensional curve, this is like >horizontally dragging a given rectangle over the curve and finding the >x coordinates where the curve passes through the rectangle.(Define such >a x-index coordinate as the left corner of the rectangle.) > >More complicated case: >Given a pair of rectangles spaced relatively to each other in a fixed >manner. Drag this rectangle pair horizontally over the above >two-dimensional curve and list the indexes of the occurences where the >curve passes simultaneously through both rectangles. >(Define such a x-index coordinate as the leftmost corner of the >rectangle pair). > >These problems can be solved by programming a naive search advancing >index by index. It seems obvious that due to the localized properties >searched for, much more efficient searches should be possible. >After having found the occurence-indexes for one particular rectangle >set, how to find the pattern occurences after changing one or more >rectangle parameters? > for the first problem, maybe (untested beyond the below): >>> from itertools import groupby >>> data = [5+i%5 for i in xrange(40)] >>> data [5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] >>> [g.next()[0] for k,g in groupby(enumerate(data), lambda t: 6 <1127116577.368805.305390@g47g2000cwa.googlegroups.com> Message-ID: >>>>> "ed" (E) wrote: > import socket > import threading > import traceback > def scan(ip, thebegin, theend): > global ip > global thebegin > global theend Making parameters global is a bad idea (I think). Moreover, thebegin and theend aren't used in scanThread. And port_counter still isn't passed. Better give all required data as parameters to the scanThread constructor. Something like: class scanThread(threading.Thread): def __init__(self, ip, port): self.ip, self.port = ip, port def run(self): ... use self.ip and self.port instead of ip and port_counter > port_counter = 0 > for port_counter in range(thebegin, theend): > scanThread().start() scanThread(ip, port_number).start() > # end function ------------------- > scan("localhost", 0, 10000) Now you're starting 10000 threads at the same time. Your OS probably won't like that. Use a ThreadPool instead. Or divide the IP range into a number of blocks, start a fixed number of threads, and give each thread a block of IP numbers. The latter approach would be simpler IMO. You may also have to take into account if your OS allows a maximum number of open sockets for a process. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From noreply at gcgroup.net Thu Sep 1 09:33:36 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 01 Sep 2005 13:33:36 GMT Subject: scroll a frame to display several lines of widgets at a time Message-ID: I need to display a couple of labels and a checkbox from each entry in my database. Simple enough, but there are several hundred records, and I only want to display 5 or 10 at a time. Can this be accomplished by putting everything in a Frame(), using width, height, grid_propagate(0) , and a scrollbar? or do I have to grid 5 rows at a time? If the latter, can I just grid over the previous 5 or do they have to be explicitly removed first. Thanks. Bill From simonwittber at gmail.com Mon Sep 5 00:12:24 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 4 Sep 2005 21:12:24 -0700 Subject: Magic Optimisation In-Reply-To: <7xwtlw88ge.fsf@ruckus.brouhaha.com> References: <1125892146.709749.45740@g49g2000cwa.googlegroups.com> <7xwtlw88ge.fsf@ruckus.brouhaha.com> Message-ID: <1125893544.309084.202220@g49g2000cwa.googlegroups.com> Yes. It slows down the loop when there are only a few iterators in the pool, and speeds it up when there are > 2000. My use case involves < 1000 iterators, so psyco is not much help. It doesn't solve the magic creation of locals from instance vars either. Sw. From onurb at xiludom.gro Wed Sep 14 05:03:26 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 14 Sep 2005 11:03:26 +0200 Subject: An interesting python problem In-Reply-To: <1126685773.612907.77270@g14g2000cwa.googlegroups.com> References: <1126685773.612907.77270@g14g2000cwa.googlegroups.com> Message-ID: <4327e760$0$15850$636a15ce@news.free.fr> Johnny Lee wrote: > Hi, > Look at the follow command in python command line, See what's > interesting?:) > > >>>>class A: > > i = 0 > >>>>a = A() >>>>b = A() >>>>a.i = 1 >>>>print a.i, b.i > > 1 0 Quite what I would expect. First you declare i as being a *class* attribute of A, with value 0. Then you create 2 instances a and b of A. Then you add to a an *instance* variable named i (that then shadows the class variable of the same name), with value 1. Then you print a.i, wihci is the instance variable i of a, and b.i, which is the class variable i of A, with value 0. > --------------------------------------- > > >>>>class A: > > arr = [] > >>>>a = A() >>>>b = A() >>>>a > > <__main__.A instance at 0x00C96698> > >>>>b > > <__main__.A instance at 0x00CA0760> > >>>>A > > > >>>>a.arr.append("haha") >>>>print a.arr , b.arr > > ['haha'] ['haha'] Now you create a class A with a *class* variable arr which is an empty list, and 2 instances a and b of A. Then you append to a.arr - which is A.arr, so when you print a.arr and b.arr, you in fact print A.arr >>>>a.arr = ["xixi"] Then you add an instance variable arr to a, shadowing A.arr >>>>print a.arr , b.arr > > ['xixi'] ['haha'] So now you print a.arr and A.arr (accessed thru b) (snip) > >>>>class X: > > def __init__(self): > self.arr = [] > >>>>m = X() >>>>n = X() >>>>m.arr.append("haha") >>>>print m.arr, n.arr > > ['haha'] [] > Here you define a class X with an *instance* variable arr, and two instances m and n of X, then append to m.arr, which of course has no impact on n. I dont see anything interesting nor problematic here. If you understand the difference between class attributes and instance attributes, the difference between mutating an object and rebinding a name, and the attribute lookup rules in Python, you'll find that all this is the normal and expected behavior. Or did I miss something ? -- bruno desthuilliers - is Python much more readable than Perl ??? python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mark.dufour at gmail.com Sat Sep 10 18:36:41 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Sun, 11 Sep 2005 00:36:41 +0200 Subject: First release of Shed Skin, a Python-to-C++ compiler. Message-ID: <8180ef6905091015361d3ffdf7@mail.gmail.com> After nine months of hard work, I am proud to introduce my baby to the world: an experimental Python-to-C++ compiler. It can convert many Python programs into optimized C++ code, without any user intervention such as adding type declarations. It uses rather advanced static type inference techniques to deduce type information by itself. In addition, it determines whether deduced types may be parameterized, and if so, it generates corresponding C++ generics. Based on deduced type information, it also attempts to convert heap allocation into stack and static preallocation (falling back to libgc in case this fails.) The compiler was motivated by the belief that in many cases it should be possible to automatically deduce C++ versions of Python programs, enabling users to enjoy both the productivity of Python and the efficiency of C++. It works best for Python programs written in a relatively static C++-style, in essence enabling users to specify C++ programs at a higher level. At the moment the compiler correctly handles 124 unit tests, six of which are serious programs of between 100 and 200 lines: -an othello player -two satisfiability solvers -a japanese puzzle solver -a sudoku solver -a neural network simulator Unfortunately I am just a single person, and much work remains to be done. At the moment, there are several limitations to the type of Python programs that the compiler accepts. Even so, there is enough of Python left to be able to remain highly productive in many cases. However, for most larger programs, there are probably some minor problems that need to be fixed first, and some external dependencies to be implemented/bridged in C++. With this initial release, I hope to attract other people to help me locate remaining problems, help implement external dependencies, and in the end hopefully even to contribute to the compiler itself. I would be very happy to receive small programs that the compiler does or should be able to handle. If you are a C++ template wizard, and you would be interested in working on the C++ implementation of builtin types, I would also love to get in contact with you. Actually, I'd like to talk to anyone even slightly interested in the compiler, as this would be highly motivating to me. The source code is available at the following site. Please check the README for simple installation/usage instructions. Let me know if you would like to create ebuild/debian packages. Sourceforge site: http://shedskin.sourceforge.net Shed Skin blog: http://shed-skin.blogspot.com Should you reply to this mail, please also reply to me directly. Thanks! Credits Parts of the compiler have been sponsored by Google, via its Summer of Code program. I am very grateful to them for keeping me motivated during a difficult period. I am also grateful to the Python Software Foundation for chosing my project for the Summer of Code. Finally, I would like to thank my university advisor Koen Langendoen for guiding this project. Details The following describes in a bit more detail various aspects of the compiler. Before seriously using the compiler, please make sure to understand especially its limitations. Main Features -very precise, efficient static type inference (iterative object contour splitting, where each iteration performs the cartesian product algorithm) -stack and static pre-allocation (libgc is used as a fall-back) -support for list comprehensions, tuple assignments, anonymous funcs -generation of arbitrarily complex class and function templates (even member templates, or generic, nested list comprehensions) -binary tuples are internally analyzed -some understanding of inheritance (e.g. list(dict/list) becomes list>) -hierarchical project support: generation of corresponding C++ hierarchy, including (nested) Makefiles; C++ namespaces -annotation of source code with deduced types -builtin classes, functions (enumerate, sum, min, max, range, zip..) -polymorphic inline caches or virtual vars/calls (not well tested) -always unbox scalars (compiler bails out with error if scalars are mixed with pointer types) -full source code available under the MIT license Main Limitations/TODO's -Windows support (I don't have Windows, sorry) -reflection (getattr, hasattr), dynamic inheritance, eval, .. -mixing scalars with pointer types (e.g. int and None in a single variable) -mixing unrelated types in single container instance variable other than tuple-2 -holding different types of objects in tuples with length >2; builtin 'zip' can only take 2 arguments. -exceptions, generators, nested functions, operator overloading -recursive types (e.g. a = []; a.append(a)) -expect some problems when mixing floats and ints together -varargs (*x) are not very well supported; keyword args are not supported yet -arbitrary-size arithmetic -possible non-termination ('recursive customization', have not encountered it yet) -profiling will be required for scaling to very large programs -combining binary-type tuples with single-type tuples (e.g. (1,1.0)+(2,)) -unboxing of small tuples (should form a nice speedup) -foreign code has to be modeled and implemented/bridged in C++ -some builtins are not implemented yet, e.g. 'reduce' and 'map' From onurb at xiludom.gro Wed Sep 28 07:30:49 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 28 Sep 2005 13:30:49 +0200 Subject: Module organization In-Reply-To: References: Message-ID: <433a7eea$0$7358$626a14ce@news.free.fr> Lasse V?gs?ther Karlsen wrote: > I am slowly learning Python and I'm already starting to write some minor > modules for myself. Undoubtedly there are better modules available > either built-in or 3rd party that do the same as mine and much more but > I need to learn it one way or another anyway. > > What I'm wondering about is module organization. > > I created my own directory for storing my modules and added the full > path to this to PYTHONPATH (Windows XP platform). > > This means that "import modulename" works for my modules now. > > However, the name of my module is "db" or "database", a module name that > will likely conflict with other modules I might encounter later. > > As such, I was thinking of doing the same that the "distutils" set of > modules have done, by creating a subdirectory and storing them there, so > I created a "lvk" directory in that directory of mine and moved the > module in there, but now "import lvk.modulename" doesn't find the module. What you want is a package: http://www.python.org/doc/current/tut/node8.html#SECTION008400000000000000000 > Is there a trick to this? Do I have to store my own modules beneath > C:\Python24\Lib? or can I use the organization I've tried just with some > minor fixes to make python locate my modules? briefly put, add an (even empty) __init__.py file in your lvk directory, and it should work fine (minus potential import problems in your modules, but that should be easy to fix...) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From linux-sh-admin at m17n.org Wed Sep 28 05:06:22 2005 From: linux-sh-admin at m17n.org (linux-sh-admin at m17n.org) Date: Wed, 28 Sep 2005 18:06:22 +0900 Subject: You python-list@python.org are not member (linux-sh ML) References: <200509280905.j8S94apQ022008@tsukuba.m17n.org> Message-ID: <200509281806.FMLAAB22036.linux-sh@m17n.org> You are not a member of this mailing list . If you know the general guide of this list, please send mail with the mail body guide to the address linux-sh-ctl at m17n.org where guide is equal to GUIDE for case insensitive. From bokr at oz.net Fri Sep 30 18:49:38 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 30 Sep 2005 22:49:38 GMT Subject: PEP 350: Codetags References: <4338bc2f.2535976150@news.oz.net> Message-ID: <433dbe81.2864557025@news.oz.net> On Fri, 30 Sep 2005 13:27:57 -0400, =?iso-8859-1?Q?Fran=E7ois?= Pinard wrote: >[Tom Anderson] > >> ISO 8601 suggests writing date-and-times like 2005-09-26T12:34:56 - >> using a T as the separator between date and time. I don't really like >> the look of it, but it is a standard, so i'd suggest using it. > >ISO 8601 suggests a few alternate writings, and the ``T`` you mention is >for only one of them, meant for those cases where embedded spaces are >not acceptable. Other ISO 8601 writings accept embedded spaces, and >this is how ISO 8601 is generally used by people, so far that I can see. > The most detailed discussion I could find was http://hydracen.com/dx/iso8601.htm (BTW, IMO the practice of charging for standards documents (as the ISO and IEEE etc do) in hard copy form is understandable, but charging for .pdf versions is perversely contrary to the purpose of wide dissemination necessary for wide adoption. IOW, IMO they ought to think of another way to get funded). Anyway, the 'T' looks to me to be optional by mutual agreement between particular information exchangers, but otherwise required? Regards, Bengt Richter From bittervine at gmail.com Sun Sep 4 15:58:12 2005 From: bittervine at gmail.com (cjfrovik@gmail.com) Date: 4 Sep 2005 12:58:12 -0700 Subject: Assigning 'nochage' to a variable. Message-ID: <1125863892.634906.243680@g47g2000cwa.googlegroups.com> Has anyone else felt a desire for a 'nochange' value resembling the 'Z'-state of a electronic tri-state output? var1 = 17 var1 = func1() # func1() returns 'nochange' this time print var1 # prints 17 It would be equivalent to: var1 = 17 var2, bool1 = func1() if bool1: var1 = var2 print var1 # prints 17 BR/ CJF From peter at engcorp.com Fri Sep 9 08:22:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Sep 2005 08:22:47 -0400 Subject: subprocess solved all my problems In-Reply-To: References: Message-ID: Jacek Pop?awski wrote: > In the last week I was working to create script which will read command > from socket, call it, return result, stdout, stderr and kill it after > timeout. > After playing with threads, processes, spawns and popens I found > subprocess module. [snip rest of answer] While in general it's greatly appreciated when people post followups showing the answer to their problems, by not posting this in response to the original thread (and by changing the subject line) you are vastly reducing the value of your post. It's much less likely someone searching the archives will ever discover that you did find a solution than if you were to go back and repost it to the original thread. (If you can't find it in your news server, you could probably use Google Groups. I *think* this was the thread you were referring to, but you should confirm for yourself: http://groups.google.com/group/comp.lang.python/browse_thread/thread/94281f5a797489b1/ebca44930a016f74?lnk=st&q=group:comp.lang.python.*+jacek+popen+thread&rnum=2#ebca44930a016f74 ) -Peter From skorpio11 at gmail.com Sat Sep 3 20:05:47 2005 From: skorpio11 at gmail.com (skorpio11 at gmail.com) Date: 3 Sep 2005 17:05:47 -0700 Subject: plotting with gnuplot.py In-Reply-To: <1125780572.786802.112280@f14g2000cwb.googlegroups.com> References: <1125653745.659417.134620@z14g2000cwz.googlegroups.com> <1125780572.786802.112280@f14g2000cwb.googlegroups.com> Message-ID: <1125792347.652336.263800@g14g2000cwa.googlegroups.com> Still having some issues plotting: In attempting as explained above: import Gnuplot,Numeric filename = ('Default.PL1') data = scipy.io.array_import.read_array(filename) y = data[:,1] x = data[:,0] z = data[:,2] //I think u need to take the transpose of this column before plotting.. x=Numeric.transpose(x) y=Numeric.transpose(y) g=Gnuplot.Gnuplot(debug=1) d=Gnuplot.Data(x,y) g('set logscale xy') g.plot(d) The file executes without generating any plot being displayed however the debug option generates this output: gnuplot> set terminal windows . . gnuplot> plot 'c:\documen~1\leon\loca`l\temp\tmpuskt1' notitle When I open this file in wordpad it contains the contents of the d array. Any ideas why gnuplot is not outputing to the screen?? From tjreedy at udel.edu Mon Sep 5 15:28:35 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 Sep 2005 15:28:35 -0400 Subject: Warning when doubly linked list is defined gloablly References: <1124881914.018491.315800@g14g2000cwa.googlegroups.com> <1125920251.848815.208400@g44g2000cwa.googlegroups.com> Message-ID: "chand" wrote in message news:1125920251.848815.208400 at g44g2000cwa.googlegroups.com... > Please let me know how to > resolve this warning message..!! > SyntaxWarning: name 'g_opt_list' is used prior to global declaration Post the entire error traceback. Post the entire error traceback. Post the entire error traceback ;-). > > > > > [hundreds? more snipped] Don't post hundread of blank lines. It took me at least half a minute to delete them for this reply. Terry J. Reedy From simon.brunning at gmail.com Wed Sep 28 07:05:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 28 Sep 2005 12:05:21 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <311b5ce105092800102da32267@mail.gmail.com> References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: <8c7f10c605092804053a6eadf4@mail.gmail.com> On 9/28/05, could ildg wrote: > Python is wonderful except that it has no real private and protected > properties and methods. > Every py object has dict so that you can easily find what fields and methods > an obj has, > this is very convenient, but because of this, py is very hard to support > real private and > protected? My convention, attributes with names prefixed with a single underscore are private. There's nothing to stop anyone using these, but, well, if you take the back off the radio, the warranty is void. > If private and protected is supported, python will be perfect. If *real* private and protected are *enforced*, Python will be the poorer for it. See . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From dont at spam.me Mon Sep 26 14:20:32 2005 From: dont at spam.me (Bugs) Date: Mon, 26 Sep 2005 11:20:32 -0700 Subject: Getting tired with py2exe In-Reply-To: <64snvjld.fsf@python.net> References: <64snvjld.fsf@python.net> Message-ID: What do you think of the idea of putting both py2exe AND py2app under the same umbrella? I don't know what the status of py2app is or who maintains it but I was thinking that it would be ideal if the 2 utilities could share code, ideas, protocols, etc. Seems like this synergy and consistency would be very beneficial. Perhaps then a Linux version could be developed with an identical inferface. Thomas Heller wrote: > Bugs writes: > > >>Any luck on finding anyone to take over py2exe development Thomas? >>It's a GREAT project and would be a shame to see it fall into >>obsolescence. > > > No, nobody stepped up (yet). > > Thomas From tjreedy at udel.edu Sat Sep 24 16:16:57 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2005 16:16:57 -0400 Subject: Editing The Registery References: <9fad636105092413045915687c@mail.gmail.com> Message-ID: "Eyual Getahun" wrote in message news:9fad636105092413045915687c at mail.gmail.com... >I was wondering how could I edit the registery with python believe you can do that with pythonwin extensions, available at python.org From steve at holdenweb.com Mon Sep 5 12:19:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Sep 2005 12:19:35 -0400 Subject: newbie Q: mouse clicks don't seem to get trapped In-Reply-To: <1125925939.370793.78240@z14g2000cwz.googlegroups.com> References: <1125925939.370793.78240@z14g2000cwz.googlegroups.com> Message-ID: mitsura at skynet.be wrote: > Hi, > > I want to display a window containing an image and when I move the > mouse over the image and click on the left Mb, I want to get the > position of the mouse on the image. > I listed the code to view the image below (so far so good) but for some > reason the EVT_LEFT_DOWN/UP does not work. > > Any idea what might be wrong? > > With kind regards, > > Kris > > > > " > class DisplayPicture(wx.Frame): > cD = 0 > # bmp = stream that contains the picture (not a filename!) > # w,h: widht, height of the picture > def __init__(self, parent, id, title, bmp, w, h): > wxFrame.__init__(self,parent,wxID_ANY, title, size = ( w, h), > style=wxDEFAULT_FRAME_STYLE) > > > self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick) > self.Bind(wx.EVT_LEFT_UP, self.OnLeftClick) > > Panel=wx.Panel(self) > wx.StaticBitmap(Panel, -1, bmp, (5, 5) ) > > self.Show() > > def OnLeftClick(self, event): > print "ok" > " > Without actually running the code (so this may not help), have you considered binding the events to the panel rather than the frame? In other words, change self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick) self.Bind(wx.EVT_LEFT_UP, self.OnLeftClick) Panel=wx.Panel(self) to Panel=wx.Panel(self) Panel.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick) Panel.Bind(wx.EVT_LEFT_UP, self.OnLeftClick) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rkern at ucsd.edu Wed Sep 14 17:58:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 14 Sep 2005 14:58:54 -0700 Subject: round() wrong in Python 2.4? In-Reply-To: <11igdm39kc9n76a@corp.supernews.com> References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> <11igdm39kc9n76a@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-09-14, Robert Kern wrote: > >>Antoon Pardon wrote: > >>>0.0225 isn't representable and it happens that the actual number >>>you get differ. Now which number python should choose when it is >>>fed 0.0225, I don't know. But expressing the different behaviour >>>as a change in round, suggest that the O.P. would be wise to >>>learn about floating point problems >> >>Uhh, Python didn't change anything between 2.3 and 2.4 wrt round(). > > That's what Antoon Pardon just said. The above paragraph says > that round() didn't change, and the fact that the OP thinks it > did indicates that the OP needs to learn more about FP. Antoon: "Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down." -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Fri Sep 30 07:37:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Sep 2005 07:37:47 -0400 Subject: A Moronicity of Guido van Rossum In-Reply-To: References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> <77498FFE-AEC3-4148-A113-E434EE4A4E52@ihug.co.nz> <200509292042.36051.jstroud@mbi.ucla.edu> <43D1E0B3-6A3B-442E-9BDE-6DBC1A2466A7@ihug.co.nz> Message-ID: Gerrit Holl wrote: > True. However, most mail to this mailinglist has less than 0.001 spam > probability. As you can see, this one had 0.048 - a vast score, almost > enough to put it in my unsure box. It seems to be just not hammy enough. > It's interesting to see that no none of the foul language words used by > Xah Lee ever occurs in any spam I receive - spam is not that stupid. "Xah Lee: stupider than spam." (?) -neologism-intentional-ly y'rs, Peter From tjreedy at udel.edu Wed Sep 14 20:13:57 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Sep 2005 20:13:57 -0400 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com><7xwtlkrs4c.fsf@ruckus.brouhaha.com> Message-ID: "Rocco Moretti" wrote in message news:dg9jh7$on1$1 at news.doit.wisc.edu... > The algorithm one uses sometimes depends quite heavily on which mindset > you're using. Some algorithms require much more mental effort to > understand when in their recursive form versus the iterative form, and > vice versa. If you're stuck thinking in only one form, you might miss > the better algorithm because it is not as "simple" in that form. This is why I disagree with the extreme recursionist and iterationist camps that both argue that since both forms cover the same ground, one only needs to learn one. > The ideal case would be a programming language that allows you to write > the algorithm in whatever form is simplest/most comfortable, and then > automagically transforms it to the form that works the fastest under the > hood. I suspect that recursion can be always be sped up by doing it within one frame. Some languages/compilers do this for the particular form of linear recursion called tail recursion. In general, recursion to iteration requires two stacks and two loops nested within a third, but there are several special cases which are simpler in one way or another. I think making the right choice will generally require extra input from the programmer. But with the extra info and some restraint in formatting, I think the rest could be automated. A separate tranformation issue is how to reduce double recursion to single recursion, when possible, and even to no recursion, as one can with the Fibonacci example. For functions which produce a set or sequence of structures, a related sort of transformatiom is from all-at-once production to one-at-a-time generation. Terry J. Reedy From hans.eccentricity at gmail.com Wed Sep 7 10:24:54 2005 From: hans.eccentricity at gmail.com (hans.eccentricity at gmail.com) Date: 7 Sep 2005 07:24:54 -0700 Subject: Ode to python References: <1126062515.460542.95260@f14g2000cwb.googlegroups.com> Message-ID: <1126103094.563161.217820@g14g2000cwa.googlegroups.com> Very good poem. Mind if forward it around?? I'll include ur email ID if u don't mind From vincent at visualtrans.de Wed Sep 21 13:09:22 2005 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 21 Sep 2005 19:09:22 +0200 Subject: I am not able to setup pydb2 ! Any help ! References: <1127321226.420209.253360@g43g2000cwa.googlegroups.com> <1127321993.065940.242530@g49g2000cwa.googlegroups.com> Message-ID: "vj" schrieb im Newsbeitrag news:1127321993.065940.242530 at g49g2000cwa.googlegroups.com... |I am new to Python . Please let me where should I issue the command | "setup.py install". | | I have been using the IDLE to run Python scripts. You need to open the command prompt (e.g. by entering "cmd" in the "Run" input box). Now enter "cd C:\vijay\db2\utils\PyDB2-1.1.0-2.tar\PyDB2-1.1.0" to get into the right directory. Now enter "setup.py install" and you should be all set.. -- Vincent From fredrik at pythonware.com Thu Sep 1 05:35:12 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Sep 2005 11:35:12 +0200 Subject: To the python-list moderator References: <200508311704.14077.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > I got one of these too, recently. Maybe somebody is turning up the > screws to get rid of spam that's been appearing on the list? I've been getting these about once a day lately. at first, I suspected some kind of "you're posting to quickly"-filter with a manual "okay, you're whitelisted for another 24 hours" setup, but it seems to block messages mostly by random. and some messages don't seem to get through at all. slightly annoying. From ndbecker2 at gmail.com Fri Sep 30 07:45:30 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 30 Sep 2005 07:45:30 -0400 Subject: compile fails on x86_64 (more) References: <433CE99B.3000304@ee.byu.edu> Message-ID: In file included from scipy/base/src/multiarraymodule.c:44: scipy/base/src/arrayobject.c:41: error: conflicting types for 'PyArray_PyIntAsIntp' build/src/scipy/base/__multiarray_api.h:147: error: previous declaration of 'PyArray_PyIntAsIntp' was here From deets at nospam.web.de Mon Sep 19 12:03:47 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Sep 2005 18:03:47 +0200 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <3p85r3F91u2eU1@uni-berlin.de> > meanwhile, over in python-dev land: > > "Is anyone truly attached to nested tuple function parameters; 'def > fxn((a,b)): print a,b'? /.../ > > Would anyone really throw a huge fit if they went away? I am willing > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > people are up for it." I am - I think that feature is sort of an orthogonality which should be preserved. No doubt its not one of the most important ones - but if I can write a, (b ,c) = 1, (2,3) I'd like to write def foo(a, (b,c)): ... foo(1, (2,3)) too. Diez From skip at pobox.com Thu Sep 29 13:08:49 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 29 Sep 2005 12:08:49 -0500 Subject: Will python never intend to support private, protected and public? In-Reply-To: <1128012129.483760.5540@f14g2000cwb.googlegroups.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <1128012129.483760.5540@f14g2000cwb.googlegroups.com> Message-ID: <17212.8097.355020.247799@montanaro.dyndns.org> Greg> Does anyone know of academic papers that make the case against Greg> "private" in languages? Nope. I'd be interested in seeing academic papers that make the case (with data to back up the claims) that "private" is beneficial. Skip From steve at holdenweb.com Tue Sep 20 16:11:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 20 Sep 2005 21:11:56 +0100 Subject: are variables local only to try/except blocks? In-Reply-To: References: Message-ID: <43306D0C.5070303@holdenweb.com> I am taking the liberty of copying my response to your off-list reply back to the c.l.py community. (and I don't normally top-post except in politeness to other top-posters :-) Seems to me you could avoid many of your problems by simply re-jigging your template to read doInitialStuff # With presumably no exceptions excp = 0 try: doLotsHere() except aParticularSetOfExceptions: excp = 1 if excp: handleException() doLotsMoreStuff() If you have been experiencing problems with "unbound local variables" this is almost certainly because, as you cast your template, there is the problem that if doLotsHere() raises an exception then the "excp" variable will not be bound. The reason for this is that Python variables (technically names) are only "created" (technically, associated with a value) when they are bound by the execution of an assignment. If the exception is raised before the assignment then the variable still (technically) doesn't exist in the current namespace (which your average Pythonista might describe by saying that the name hasn't been bound). There is *some* static analysis in Python to support name scoping, but names must be bound by assignment in order to be referencable (?) without causing an AttributeError or NameError exception. That's a fundamental part of the way Python works. Hence my suggestion that you assign the zero before you do anything that might raise exceptions. You will also note I suggest you check for specific exceptions (you can check for more that one by using a tuple rather than a single exception), as otherwise you may very well end up treating unanticipated exceptions inappropriately and masking their occurrence. regards Steve Barry Searle wrote: > > Sorry, the quick sample was just to illustrate the problem and solution > template. > The generic template would be: > doInitialStuff() > try: > doLotsHere() > excp = 0 > except: > excp = 1 > #endTry > if (excp): doExceptionHandling() > doLotsMoreStuff() > > The template will be used (is being used) for the automatic generation > of a bunch of Jython code, and I wanted to be sure there were not scope > issues (i.e. that excp was not only defined within the try/except blocks). > > Barry Searle, searle at ca.ibm.com, 905-413-4020 (TL:969-4020) > Barry Searle/Toronto/IBM at IBMCA (D3/639/8200/MKM) > "Architect, WebSphere Tools for WsAdmin Scripting and Automated Build " > > > > *Steve Holden * > > 20/09/2005 11:55 AM > > > To > > cc > Barry Searle/Toronto/IBM at IBMCA > Subject > Re: are variables local only to try/except blocks? > > > > > > > > > BarrySearle wrote: > > # Is this valid (or is excp local to try/except)? > > try: > > try: > > doSomething1 > > excp = 0 > > This block is problematic because excp won;t be set if doSomething1 > raises an exception. > > > except: > > excp = 1 > > #endTry > > if (_excp_): doSomething1 # is excp defined here? > > Presumably you are expecting doSomething1 to fail or succeed in some > non-deterministic way? Otherwise this will just raise the same exception > again! > > > excp = 0 > > except: > > excp = 1 > > #endTry > > if (excp): doSomething2 # is excp defined here? > > > > > > # valid, but more verbose (and maybe redundant?) > > excp = 0 > > try: > > excp = 0 > > try: > > doSomething1 > > excp = 0 # reset incase future inner block > > except: > > excp = 1 > > #endTry > > if (_excp_): doSomething1 > > excp = 0 # reset incase inner block set excp=1 > > except: > > excp = 1 > > #endTry > > if (excp): doSomething2 > > > > I am not so interested in what a particular version of the > > Python/Jython interpreter does, but rather what is "right". > > > > Pls "CC" replies to searle at ca.ibm.com (as well as newsgroup) > > Barry Searle, searle at ca.ibm.com > > > Your approach to exception handling is a little simplistic, resulting on > code that reads about as well as a plate of spaghetti. > > What are you actually trying to *do*? What problem do you need to solve? > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.pycon.org > -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From eddie at holyrood.ed.ac.uk Thu Sep 29 07:27:54 2005 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 29 Sep 2005 11:27:54 +0000 (UTC) Subject: another time challenge References: <1127924738.875240.40870@o13g2000cwo.googlegroups.com> Message-ID: nephish at xit.net writes: >Hey there pythoneers >i have another question about time, specifically, the mxDateTime >module. >i have been able to get a RelativeDateTimeDiff between two times, >it gives me a difference between two DateTimes in the form of +3days >+2hours etc... >so, if i have a date that is 6 days and 6 hours from another day, >it will give me Days+6, hours+5. >what i need is something like 6.4 days or close to it. >is there an easy way to convert this ? >if not i can write up something to do the math. >i guess i am just looking for a cleaner shortcut. You could extract the hours,mins,secs part to a DateTimeDelta which supports float() and just divide that into 86400.0. Eddie From chris.cavalaria at free.fr Thu Sep 22 09:11:09 2005 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 22 Sep 2005 15:11:09 +0200 Subject: C#3.0 and lambdas In-Reply-To: <4_qdnTRN-KgMf6zeRVn-hA@comcast.com> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> <43315dd9$0$3051$626a14ce@news.free.fr> <433175c7$0$24718$626a14ce@news.free.fr> <43318d3c$0$29142$626a14ce@news.free.fr> <4_qdnTRN-KgMf6zeRVn-hA@comcast.com> Message-ID: <4332abd1$0$9437$636a15ce@news.free.fr> Steven Bethard a ?crit : > Steven D'Aprano wrote: > >> I would love to see your test code and profiling results that demonstrate >> that explicit tuple unpacking in the body of a function is faster than >> tuple unpacking (implicit or explicit) in the header of a function. > > > Should be pretty close. I believe the byte-code is nearly identical: You forgot the most important function : f3 >>> def f1((x,y)): ... print x,y ... >>> def f2(x_y): ... x,y = x_y ... print x,y ... >>> def f3(x_y): ... print x_y[0], x_y[1] ... >>> import dis >>> dis.dis(f1) 1 0 LOAD_FAST 0 (.0) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (x) 9 STORE_FAST 2 (y) 2 12 LOAD_FAST 1 (x) 15 PRINT_ITEM 16 LOAD_FAST 2 (y) 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> dis.dis(f2) 2 0 LOAD_FAST 0 (x_y) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 2 (x) 9 STORE_FAST 1 (y) 3 12 LOAD_FAST 2 (x) 15 PRINT_ITEM 16 LOAD_FAST 1 (y) 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> dis.dis(f3) 2 0 LOAD_FAST 0 (x_y) 3 LOAD_CONST 1 (0) 6 BINARY_SUBSCR 7 PRINT_ITEM 8 LOAD_FAST 0 (x_y) 11 LOAD_CONST 2 (1) 14 BINARY_SUBSCR 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_CONST 0 (None) 20 RETURN_VALUE >>> From ccurvey at gmail.com Wed Sep 21 20:40:41 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 21 Sep 2005 17:40:41 -0700 Subject: send mail through webmail In-Reply-To: References: Message-ID: <1127349641.662002.213920@g47g2000cwa.googlegroups.com> If you have to do it thru the web, I would use one of the "browser" packages (mechanize, mechanoid, PAMIE, or IshyBrowser). Then you can scrape the site, fill out the forms, press the buttons, etc. This will be a *lot* more painful than using SMTP.... From steve at holdenweb.com Thu Sep 15 07:39:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Sep 2005 12:39:30 +0100 Subject: Oh Yes, They Are [was: Re: Software bugs aren't inevitable] In-Reply-To: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> Message-ID: <43295D72.3000408@holdenweb.com> Paddy wrote: > A work colleague circulated this interesting article about reducing > software bugs by orders of magnitude: > http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905ext.html > > Some methods they talk about include removing error prone and ambiguous > expressions from their ADA based language Sparc - The example they give > is on why they removed the increment operators x++, x-- . > > A bit of googling shows that they have, in the past mentioned Python in > Job specs, but only as one of many languages. > > I was wondering what Praxis thought of Python, and how good it would be > if a Praxis engineer gave a critique of Python as a part of a flow for > producing low bug-count software. > > In this sidebar to the main article: > > http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905extsb1.html > > It seems that they use one equation from the Z notation model and add > it as a comment to their main programming languages function definition > as a comment, then have a means of automatically testing the comment > against the function body. > > This is rather like how doctest can check the test and expected result > given in a doc-string against the implementation given in the function; > indeed I wrote up such an example at work and circulated it amongst the > resident perl mongers. - Gosh it fealt good :-) > > So, How do I get feedback from Praxis, Do they already read > comp.lang.py? > > Cheers, Paddy. > As far as I can see the advantage of this kind of rigor is best kept for the projects where it really matters (e.g. safety-critical monitoring and control systems). Programming is a growing human activity, and I would suggest that one of Python's designed-in advantages is the ease with which comprehensible implementations of known algorithms can be constructed. Given Guido's expressed interest in "Computer Programming for Everyone" this comes as no surprise to more. Nonetheless we have to remember that the vast majority of Python programmers wouldn't care about differences between implementation techniques, being happy that they've found *any* way to get the computer to do what they want. I'm sure that a Praxis evaluation of Python would make a very good presentation at PyCon, whose Call for Proposals recently came out. Yes folks, next time around it's PyCon TX 2006, see http://www.python.org/pycon/2006/cfp regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From tjreedy at udel.edu Wed Sep 14 14:43:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Sep 2005 14:43:44 -0400 Subject: Find day of week from month and year References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> <1126717725.314658.113770@g49g2000cwa.googlegroups.com> Message-ID: > Laguna wrote: >> I want to find the expiration date of stock options (3rd Friday of the >> month) for an any give month and year. >From year and month (and day=1) get the day of the week (n in [0,6]) of the first of the month using some version of the the standard formula (see below) and look up the third friday date in a precalculated 7-element list, or, with n=0 on Saturday, 3rd Friday is 21-n Here is a translation of the guts of a 30-year-old Basic program: def friday3(m,y): # ints if m <= 2: m += 12 y -= 1 d = 1 n = d + 2*m + int(.6*(m+1)) + y + y//4 - y//100 + y//400 + 2 n = int((n/7.0- n//7)*7.0 + .5) # n=0 is Saturday, making 3rd Friday the 21st. return 21 - n >> Requirements: >> d0 = expiration(9, 2005) # d0 would be 16 >> d1 = expiration(6, 2003) # d1 would be 20 >> d2 = expiration(2, 2006) # d2 would be 17 >>> for m,y in ((9,2005), (6,2003), (2,2006)): print friday3(m,y) ... 16 20 17 Terry J. Reedy From aahz at pythoncraft.com Sat Sep 10 12:39:35 2005 From: aahz at pythoncraft.com (Aahz) Date: 10 Sep 2005 09:39:35 -0700 Subject: Why do Pythoneers reinvent the wheel? References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <1126340055.955682.88870@g49g2000cwa.googlegroups.com> <97mav2-lc3.ln1@eskimo.tundraware.com> Message-ID: In article <97mav2-lc3.ln1 at eskimo.tundraware.com>, Tim Daneliuk wrote: > >IMHO, one of Python's greatest virtues is its ability to shift paradigms >in mid-program so that you can use the model that best fits your problem >space. IOW, Python is an OO language that doesn't jam it down your >throat, you can mix OO with imperative, functional, and list processing >coding models simultaneously. > >In my view, the doctrinaire', indeed religious, adherence to OO purity >has harmed our discipline considerably. Python was a nice breath of >fresh air when I discovered it exactly because it does not have this >slavish committment to an exclusively OO model. +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From Ido.Yehieli at gmail.com Fri Sep 30 10:17:36 2005 From: Ido.Yehieli at gmail.com (Ido.Yehieli at gmail.com) Date: 30 Sep 2005 07:17:36 -0700 Subject: what does 0 mean in MyApp(0) In-Reply-To: <1128089733.684329.101320@o13g2000cwo.googlegroups.com> References: <1128089733.684329.101320@o13g2000cwo.googlegroups.com> Message-ID: <1128089856.946552.113050@o13g2000cwo.googlegroups.com> i see you inherit from wxApp. mybe the constructor of that object takes an int value? From could.net at gmail.com Wed Sep 28 03:10:15 2005 From: could.net at gmail.com (could ildg) Date: Wed, 28 Sep 2005 15:10:15 +0800 Subject: Will python never intend to support private, protected and public? Message-ID: <311b5ce105092800102da32267@mail.gmail.com> Python is wonderful except that it has no real private and protected properties and methods. Every py object has dict so that you can easily find what fields and methods an obj has, this is very convenient, but because of this, py is very hard to support real private and protected? If private and protected is supported, python will be perfect. -------------- next part -------------- An HTML attachment was scrubbed... URL: From claudio.grondi at freenet.de Mon Sep 12 13:17:29 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 12 Sep 2005 17:17:29 -0000 Subject: Is it possible to detect if files on a drive were changed without scanning the drive? Message-ID: <3olkhcF6g6vaU1@individual.net> It is maybe not a pure Python question, but I think it is the right newsgroup to ask for help, anyway. After connecting a drive to the system (via USB or IDE) I would like to be able to see within seconds if there were changes in the file system of that drive since last check (250 GB drive with about four million files on it). How to accomplish this? (best if providing directly a Python receipe for it :-) Do available file systems have something like archive attribute assigned to the root directory of the drive? I suppose not. Am I right? I ask this question having Microsoft Windows 2000 and Windows proprietary NTFS file system in mind, but I am also interested to know it about Linux or Unix file systems. I know, that looking for the archive attribute of the top directories doesn't help when the change happened to files somewhere deeper in the hierarchy of directories. Any hints are welcome. Claudio From epost2 at gmail.com Fri Sep 16 08:39:05 2005 From: epost2 at gmail.com (bruce) Date: 16 Sep 2005 05:39:05 -0700 Subject: How to clear screen in Python interactive shell mode? In-Reply-To: References: <1126844313.379059.207200@z14g2000cwz.googlegroups.com> Message-ID: <1126874345.548970.135560@o13g2000cwo.googlegroups.com> elif os.name in ("nt", "dos", "ce"): # emacs/Windows What`s the right statement here? From pipene-news at pu.kielce.pl Fri Sep 23 15:39:08 2005 From: pipene-news at pu.kielce.pl (Artur M. Piwko) Date: Fri, 23 Sep 2005 19:39:08 +0000 (UTC) Subject: Run VPython on FC3 References: Message-ID: In the darkest hour on Fri, 16 Sep 2005 15:45:33 -0700, York screamed: >>>/usr/local/lib/libgtkgl.so.4.0.0 >>>/usr/local/lib/libgtkgl.so.4 >>> >>>Does anybody know a solution for this problem? >>> >> >> You need libgtk-(open)gl package (i don't know the exact name in FC). >> > Actually the gtkgl was installed, I can find it at /usr/local/lib: > /usr/local/lib/libgtkgl.so.4.0.0 > /usr/local/lib/libgtkgl.so.4 > Check for presence of /usr/local/lib in /etc/ld.so.conf Append it if necessary. Don't forget to run ldconfig afterwards. -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:228B ] [ 21:38:09 user up 10743 days, 9:33, 1 user, load average: 0.06, 0.06, 0.06 ] I considered atheism but there weren't enough holidays. From python.leojay at gmail.com Wed Sep 28 05:52:42 2005 From: python.leojay at gmail.com (Leo Jay) Date: Wed, 28 Sep 2005 17:52:42 +0800 Subject: about install wxPython in Redhat Linux AS 4 In-Reply-To: References: <4e307e0f0509280128503e5e24@mail.gmail.com> Message-ID: <4e307e0f050928025254e0b94a@mail.gmail.com> On 9/28/05, Martin Franklin wrote: > Leo, > > I don't have AS 4 but fedora core 4 has wx in it's YUM repositories I > assume RedHat has too, so perhaps you need to use the officially > sanctioned version. If you want to use the latest and greatest then you > will most likely need to build them from source (which means installing > the -devel packages for python & GTK) > > Martin > Thanks for your reply, AS 4 don't have neither yum nor apt-get. and i tried to build the wxpython from scratch, but, after building wxwindow correctly, i encountered dozens of errors when installing wxpython. i'm just a rookie that i have no idea about how to handle these errors. -- Best Regards, Leo Jay From jjl at pobox.com Sat Sep 24 07:13:52 2005 From: jjl at pobox.com (John J. Lee) Date: 24 Sep 2005 11:13:52 +0000 Subject: Help on regular expression match References: <1127453790.376977.130780@g47g2000cwa.googlegroups.com> <1127459357.717852.245250@o13g2000cwo.googlegroups.com> Message-ID: <878xxmyaz3.fsf@pobox.com> "Johnny Lee" writes: > Fredrik Lundh wrote: [...] > To the HTMLParser, there is another problem (take my code for example): > > import urllib > import formatter > parser = htmllib.HTMLParser(formatter.NullFormatter()) > parser.feed(urllib.urlopen(baseUrl).read()) > parser.close() > for url in parser.anchorlist: > if url[0:7] == "http://": > print url > > when the baseUrl="http://www.nba.com", there will raise an > HTMLParseError because of a line of code " 2001, 2002 !>". I found that this line of code is inside  :    ... ...   ... ... --------------------------- any ideas on making it "see" the button for what it is in amongst the garbage? I think /it's/ getting confused here. From ascensiontech at gmail.com Fri Sep 16 13:42:22 2005 From: ascensiontech at gmail.com (Peter Hartmann) Date: Fri, 16 Sep 2005 13:42:22 -0400 Subject: influence platorm during install -end user question Message-ID: <9bd31756050916104216e32eb9@mail.gmail.com> How do I influence the platform type during install? Could you look at this and tell me what I'm doing wrong? It's still using information from get_platform instead of using my preference. [root at k12linux pyosd-0.2.14]# python setup.py install --install-purelib=lib.linux=i686-2.3 --install-lib=/usr/lib/python2.3/site-packages running install running build running build_py running build_ext running install_lib creating /usr/lib/python2.3/site-packages/pyosd copying build/lib.linux-x86_64-2.3/pyosd/__init__.py -> /usr/lib/python2.3/site-packages/pyosd copying build/lib.linux-x86_64-2.3/pyosd/daemon.py -> /usr/lib/python2.3/site-packages/pyosd byte-compiling /usr/lib/python2.3/site-packages/pyosd/__init__.py to __init__.pyc byte-compiling /usr/lib/python2.3/site-packages/pyosd/daemon.py to daemon.pyc On 9/15/05, Peter Hartmann wrote: > Hello, > I could really use some help. I'm trying to install a python program > on centos4 x86_64. When I run 'python setup.py' it ends up in > /usr/lib64/python2.3/site-packages/ instead of > /usr/lib/python2.3/site-packages. It's a problem because the program > I'm trying to install is a dependency for something that is only > 32bit. How can I specify a 32bit install? What I've tried so far: > When I try 'python setup.py build --build-lib > /usr/lib/python2.3/site-packages' and 'python setup.py install > --install-lib /usr/lib/python2.3/site-packages', it installs the 64bit > version into the 32bit library. Can anyone help me? > > Thanks, > Peter > From james hal-pc.org Mon Sep 19 19:49:12 2005 From: james hal-pc.org (james hal-pc.org) Date: Mon, 19 Sep 2005 18:49:12 -0500 Subject: web scrapping - POST and auto-login Message-ID: <432f4f04$0$10624$a726171b@news.hal-pc.org> please excuse my ignorance of Python. i know enough to be dangerous (was able however to make Freevo support my FM tuner with a little hacking). Ultimate goal: read N bytes from PATTERN on page A into VARIABLE. POST VARIABLE into TABLE on site B. email VARIABLE to myself. what i have to work with: --------------------------- #!/usr/local/bin/python from urllib import urlopen from re import search URL = "http://wifirouter/WL_WPATable.asp" pattern = "wl_key1 value='*([0-9,a-f,]*)" doc = urlopen(URL).read() result = search(pattern, doc) print result.group(1) --------------------------- I'm trying to update the WEP key on a wireless router via script and email the results to myself. this will be run once a week. Site A already generates random keys, so i figure that's a good place to get VARIABLE from. The example above gives me the current key of the router. What i'm having trouble with is the key on site A (one i wrote myself http://www.hal-pc.org/networking/cgi-bin/wepgen.cgi ) provides 128bit keys by default, but i only want to use 64bit (10 characters). so.. rather than make it select 64bit and all i figure it would be easier to use the above example for getting the /current/ key, modified it to read the entire 26 character string from site A, but [1] how do i crop it to 10 characters. [2] how can i then auto-login to site B (the router's web config via pop-up dialog box. *not* a form) and then [3] post VARIABLE and save the changes. I know this sounds like a lot, but if anyone can provide me with any example code i can maybe modify to fit, or point me to some good reference material. all the pages i found on logging into a site involve ssl and cookies, which, in this case at least, isn't involved here. If there is any other info i can provide (ie. sections of relevent HTML) then let me know. any assistance you have to offer is greatly appreciated. -- - - james hal-pc.org - - "Friends don't let friends use Mandrake" - - - - - - - - - - - - - - - From andymac at bullseye.apana.org.au Fri Sep 9 21:23:24 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 10 Sep 2005 12:23:24 +1100 Subject: Using Python with COM to communicate with proprietary Windows software In-Reply-To: <5bMhQyygYQbAxWGqorX8DcbkrRte@4ax.com> References: <5bMhQyygYQbAxWGqorX8DcbkrRte@4ax.com> Message-ID: <4322358C.8030402@bullseye.apana.org.au> On Fri, 09 Sep 2005 08:36:00 +0200, Thomas Heller wrote: {...} >(I have released and announced this 3 weeks ago, but haven't got a >single feedback. So it seems the need to access custom interfaces is >very low.) I have downloaded it and am trying to find the time to play with it (unsuccessfully so far). As someone working with a large, complex, COM library with minimal IDispatch support, I'm really looking forward to this. However, at the moment I'm limited to Python 2.2 and ctypes 0.6.3 (which is allowing me to get the job done!!). Regardless, I thank you for what you have released! Cheers, Andrew. ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From jgrahn-nntq at algonet.se Sat Sep 17 17:37:52 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 17 Sep 2005 21:37:52 GMT Subject: pinging from within python References: Message-ID: On Mon, 12 Sep 2005 01:36:35 +0200, billiejoex wrote: > Impacket module can helps you to construct the ip/icmp packet structure, > then you can send the packet and wait for the ECHOREPLY by using a > RAW_SOCKET. > Here's an example: > http://oss.coresecurity.com/impacket/ping.py Yeah, but is he willing to be root, and ditch Windows, just to be able to ping? Exec()ing the ping utility is often better, but beware -- different pings take different options. [the original poster] >> I need a simple script to run the ping command with some parameters and be >> able to read the return value of the ping function. What is "the return value of the ping function"? You can use the ping utility for many different things, and it reports many different kinds of outcomes. It's not black and white. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From nothingcanfulfill at gmail.com Tue Sep 27 23:02:51 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 27 Sep 2005 20:02:51 -0700 Subject: __call__ in module? In-Reply-To: <7Gk_e.28$PA1.5188@monger.newsread.com> References: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> <7Gk_e.28$PA1.5188@monger.newsread.com> Message-ID: <1127876571.722322.18260@f14g2000cwb.googlegroups.com> Thanks for this information. It'd really be interesting to see how well this works for the code I wish to apply it to. Thanks again and have a GREAT day. -Wes From beliavsky at aol.com Wed Sep 21 07:16:13 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 21 Sep 2005 04:16:13 -0700 Subject: scipy for python 2.4 on windows References: <1127298673.310643.138690@g49g2000cwa.googlegroups.com> Message-ID: <1127301373.418335.129910@f14g2000cwb.googlegroups.com> Z.L. wrote: > I am a newbie to python, and have not so much experiences on package > installation and related issues. I am looking for Scipy binaries for > python 2.4 on windows. Please see the recent thread "use SciPy with Python 2.4.1?" for discussion of this. From abkhd at earth.co.jp Wed Sep 28 15:16:39 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 28 Sep 2005 12:16:39 -0700 Subject: ANN: pyMinGW support for Python 2.4.2 (final) is available Message-ID: <1127934999.819068.173350@g43g2000cwa.googlegroups.com> This is to inform those interested in compiling Python in MinGW that an updated version of pyMinGW is now available. Get it from here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html Regards Khalid From peter at engcorp.com Mon Sep 26 14:21:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Sep 2005 14:21:20 -0400 Subject: The ^ operator In-Reply-To: <1127758172.599605.325390@g14g2000cwa.googlegroups.com> References: <1127758172.599605.325390@g14g2000cwa.googlegroups.com> Message-ID: Tuvas wrote: > What exactly does the ^ operator do? I've seen, for example, that > 3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are > not equal, and if they are equal, outputs 0, or what? Thanks! It performs an "exclusive-OR" (XOR) operation on the binary data corresponding to those values. Where the boolean AND operation returns a 1 where both inputs are 1 and a 0 otherwise, and boolean OR returns a 1 if either input is 1 but 0 otherwise, the XOR operator returns a 1 if the two inputs are different (i.e. one is 0 and the other is 1) but a 0 if they are the same. When done on the binary value, each corresponding bit is compared using the above logic. For example, 3 is 0011 in binary, and 4 is 0100, so: 011 binary for 3 ^ 100 binary for 4 --- = 111 (which is binary for 7). (match up the binary digits vertically, so the first digit in the result comes from the 0 and the 1 above it, in the two input values). -Peter From gherron at islandtraining.com Fri Sep 16 12:43:38 2005 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 16 Sep 2005 09:43:38 -0700 Subject: No newline using printf In-Reply-To: <1126831050.903747.13040@z14g2000cwz.googlegroups.com> References: <1126831050.903747.13040@z14g2000cwz.googlegroups.com> Message-ID: <432AF63A.4080900@islandtraining.com> Samuel wrote: >Hello, > >I have been searching for an answer for almost two hours now and have >not found an answer. I want this code: > >for i in range(3): > print i # or whatever > >To produce this output: >012 > >How can I print a word without appending a newline character? Appending >a "," to the print statement only substitutes the newline for a space, >which is not what I am looking for. > >Any hints? > >Thanks, >-Samuel > > > The solution is to take over full control of the output with sys.stdout.write. Use '%1d' % i to convert your number into a single character string. Use sys.stdout.write to send exactly the characters you want to sys.stdout. Thus: sys.stdout.write('%1d' % i) should do what you want. Dr Gary Herron Digipen Institute of Technology From fredrik at pythonware.com Tue Sep 27 17:28:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Sep 2005 23:28:05 +0200 Subject: __call__ in module? References: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> Message-ID: "ncf" wrote. >I have a feeling that this is highly unlikely, but does anyone in here > know if it's possible to directly call a module no. From deets at nospam.web.de Sun Sep 4 12:53:32 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 04 Sep 2005 18:53:32 +0200 Subject: regular expression unicode character class trouble Message-ID: <3o0n4bF3hmbaU1@uni-berlin.de> Hi, I need in a unicode-environment the character-class set("\w") - set("[0-9]") or aplha w/o num. Any ideas how to create that? And what performance implications do I have to fear? I mean I guess that the characterclasses aren't implementet as sets, but as comparison-function that compares a value with certain well-defined ranges. Regards, Diez From python-url at phaseit.net Mon Sep 19 15:08:06 2005 From: python-url at phaseit.net (Diez B. Roggisch) Date: Mon, 19 Sep 2005 19:08:06 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 19) Message-ID: QOTW: "Python makes data-driven programming easy :-)" -- Kent "Python rewards abstraction." -- Alex Martelli As unicode becomes more and more prevalent, the issue of regular expressions matching unicode character sets occurs more often. A current thread has advice: http://groups.google.com/group/comp.lang.python/msg/a4b7d3e24a514afd Todd Steury learns about large float representations in python - and that applying some algebra sometimes yields better results than the naive approach: http://groups.google.com/group/comp.lang.python/msg/7f5afb4976277ddc pyparsing, the de-facto-standard for parser generation in python, is available at version 1.3.3: http://groups.google.com/group/comp.lang.python.announce/msg/ff39b02ac712ac79 A new PyRex version addressing bugs ships: http://groups.google.com/group/comp.lang.python.announce/msg/b30bd0575b6bd080 Metaclasses are so complicated as to make some of their artifacts appear buggy - but luckily they aren't ... http://groups.google.com/group/comp.lang.python/msg/a1190851125ce7b5 .NET 3.0 features provoke a discussion on python's nested-tuple function arguments: http://groups.google.com/group/comp.lang.python/msg/ee80ba95b76d76b Stackless receives popular publicity for its gaming ability: http://developers.slashdot.org/developers/05/09/17/182207.shtml?tid=156&tid=10 Note how dramatically memory-management perspectives can differ: http://developers.slashdot.org/comments.pl?sid=162565&cid=13587741 Sudoku puzzles are fun to solve -- both "in real", and by writing software solvers. Python-based solvers on different levels of complexity can be seen here: http://groups.google.com/group/comp.lang.python/msg/f7cb534119b877b9 Accessing COM-components from python is usually done with win32com -- but in certain corner cases, comtypes serves you better (or at all): http://groups.google.com/group/comp.lang.python/msg/e4075543c2d30200 Creating histograms is a common problem -- another problem is which one is the preferred way to do so: http://groups.google.com/group/comp.lang.python/browse_frm/thread/60d405c5282ad36a/faa050cc5d76f6f0?q=dictionary&rnum=2#faa050cc5d76f6f0 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From tundra at tundraware.com Sat Sep 10 05:55:42 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 10 Sep 2005 05:55:42 EDT Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <8tdav2-js1.ln1@eskimo.tundraware.com> Message-ID: <98nav2-1n3.ln1@eskimo.tundraware.com> Stefano Masini wrote: > On 10 Sep 2005 03:16:02 EDT, Tim Daneliuk wrote: > >>frameworks are unlikely to serve them well as written. I realize this is >>all at a level of complexity above what you had in mind, but it's easy >>to forget that a significant portion of the world likes/needs/benefits >>from things that are *not* particularly generic. This is thus reflected >>in the software they write. > > > In my opinion this has got more to deal with the open source vs. > proprietary debate, that I wouldn't like to talk about, since it's > somewhat marginal. I think the point I was trying to make was there are times when a generic factoring of reusable code is unimportant since the code is so purpose-built that doing a refactoring makes no sense. > > What I was pointing out is well summarized in the subject: Why do > Pythoneers reinvent the wheel? > Reinventing the wheel (too much) is Bad for both the open source > community and industry. It's bad for development in general. I got the I don't share your conviction on this point. Reinventing the wheel makes the wheel smoother, lighter, stronger, and rounder. Well, it *can* do this. Of far greater import (I think) is whether any particular implementation is fit to run across a breadth of platforms. To me, a signficant benefit of Python is that I am mostly able to program the same way across Unix, Windows, Mac and so on. > If such an aid to _general_ problem solving is indeed missing (I might > be wrong) from the current state of python, I don't really think the > reason is related to industry. I would look for reasons elsewhere, > like it beeing difficult to come out with effective decisional support > in an open source community, or something like this. I can certainly > see the challenge of who and how should decide what goes in the > library, and what not. This is too abstract for me to grasp - but I admit to be old and feeble ;) I think what you see today in the standard library are two core ideas: 1) Modules that are more-or-less pass-through wrappers for the common APIs found in Unix and 2) Modules needed commonly to "do the things that applications do" like manipulate data structures or preserve active objects on backing store. If what you want here is for everyone to agree on a common set of these and stick exclusively to them, I think you will be sorely disappointed. OTOH, if someone has a better/faster/smarter reimplementation of what exists, I think you'd find the community open to embracing incremental improvement. But there is always going to be the case of what happened when I wrote 'tconfpy'. The existing configuration module was nice, but nowhere near the power of what I wanted, so I wrote something that suited me exactly (well ... sort of, 'tconfpy2' is in my head at the moment). If the community embraced it as a core part of their work, I'd be delighted (and surprised), but I don't need for that to happen in order for that module to have value to *me*, even though it does not displace the existing stuff. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From http Tue Sep 6 12:13:01 2005 From: http (Paul Rubin) Date: 06 Sep 2005 09:13:01 -0700 Subject: Job Offer in Paris, France : R&D Engineer (Plone) References: <7xbr37u8ut.fsf@ruckus.brouhaha.com> <7xpsrn3100.fsf@ruckus.brouhaha.com> <7x4q8y35lx.fsf@ruckus.brouhaha.com> Message-ID: <7xvf1ew4xe.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > > Do you even realize you're having this conversation over the Python > > mailing list/newsgroup, rather than by private email? > > Did you consider asking *that* question privately ;-? Hehe, good comeback. Seriously, I figured enough other clpy people might have the same questions I did that I felt correct in using the newsgroup. From theller at python.net Wed Sep 7 12:01:03 2005 From: theller at python.net (Thomas Heller) Date: Wed, 07 Sep 2005 18:01:03 +0200 Subject: py2exe 0.6.1 released References: <1KbTe.51152$F23.643754@twister2.libero.it> Message-ID: "Giovanni Bajo" writes: > Thomas Heller wrote: > >>> I tried it using the wx singlefile example, but unfortunately the >>> resulting executable segfaults at startup (using Python 2.3.3 on >>> Windows 2000, with latest wxWindows). >> >> Yes, I can reproduce that. I'm still using wxPython 2.4.2.4 for >> Python >> 2.3.5, and that combo works. I have done a few tests, and wxPython >> 2.5.1.5 also works, while 2.5.5.1 crashes. > > Ah that's fine, then. I thought it was one of those "only in my computer" kind > of issue :) > >>> How can I debug it? >> >> I'll assume that's a serious question. > > Of course it was, I'm not sure why you should doubt it. I was just trying to > being helpful to you, thinking that it could have been hard to reproduce. > Luckily, you can look into it yourself. I wasn't offended ;-). Debugging the bundled executables is difficult - because the source file debug info is lost (or at least MSVC isn't able to access it). So you end up steppiung through the disassembly. >> I've done all this, and it seems it is crashing when trying to import >> _gdi.pyd. Next would be to debug through _memimported.pyd, but I >> don't have a debug build of wxPython. > > OK. Do you believe that _memimported.pyd can eventually converge to something > stable? Emulating LoadLibrary for all versions of Windows is not an easy task > after all. Wine might provide some insights. Currently there's no platform specific code in this emulation. But I have to admit I don't use win98 any more. I hope that _memimporter.pyd eventually becomes stable, the new 0.6.2 release contains some important fixes. For the original problem: the code to load extensions contained in packages was buggy. With 0.6.2 the wxPython singlefile sample at least works wit wxPython 2.4.2.4 + python 2.3.5, and wxPython 2.6.1.0 + Python 2.4.1. Thomas From pedro.werneck at terra.com.br Sat Sep 17 13:46:55 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sat, 17 Sep 2005 14:46:55 -0300 Subject: Possible bug in "metaclass resolution order" ? In-Reply-To: <1126972310.484861.138970@o13g2000cwo.googlegroups.com> References: <1126972310.484861.138970@o13g2000cwo.googlegroups.com> Message-ID: <20050917144655.2e7ec1b7.pedro.werneck@terra.com.br> On 17 Sep 2005 08:51:50 -0700 "Michele Simionato" wrote: Hi > I think this is more of a documentation issue than of a bug. No... I don't think it's a documentation issue. What's the problem with the documentation in this case ? Trying to use 'type' as a metaclass with a subclass of another class using a custom metaclass is an error and should raise the same exception the metaclass conflict does. In fact, is the same error. > It may seems strange at first, but __metaclass__ and __class__ may be > different. > > For instance, if M is metaclass > > >>> class C(object): pass > > >>> C.__metaclass__ = M > > you get a class with metaclass hook equal to M, but C.__class__ is > still 'type'. But in this case, it's a __metaclass__ attribute defined after class creation, after the call to the metaclass found in object.__class__, not dict["__metaclass__"] which have priority over object.__class__. The interpreter is not aware of this __metaclass__ attribute during class creation, since it's not in the dict passed on the type(name, bases, dict) call. > In you example, setting the __metaclass__ to 'type' does not change > the metaclass of the created class, which is inherited from the base > class. Yes, but, as I said, dict["__metaclass__"] has priority over the base class __class__. If I use a metaclass which is not a subclass of my base classes metaclass I get a TypeError: metaclass conflict exception. If I use 'type' which is also not a subclass of my base classes metaclass, I was supposed to get the same exception, but the interpreter ignores dict["__metaclass__"] and use the metaclass in base class __class__. Seems like the problem is in Objects/typeobject.c, PyType_IsSubtype (814-846) or the for loop in 1604-1621. Seems like PyType_IsSubtype is returning true for a type being a subtype of it's own subtypes and it never reaches the exception and return NULL. The problem seems to be the third if statement and after it, when the winner and metatype are exchanged if different. It's more evident using 'type' because it's the base of all types, but after looking the source code, I tested with this code: Python 2.4.1 (#1, Sep 16 2005, 17:47:47) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. c>>> class M_A(type): pass ... >>> class A: __metaclass__ = M_A ... >>> class M_B(M_A): pass ... >>> class B(A): __metaclass__ = M_B ... >>> class C(B): __metaclass__ = M_A ... >>> C.__class__ >>> C.__metaclass__ >>> Is this supposed to happen ? C's metaclass must be a subclass of M_B. If I try with any other class not related to this hierarchy, I will get a metaclass conflict error. But with M_A, the error is ignored, probably because PyType_IsSubtype is returning 1 for M_A being a subtype of M_B and the winner and metatype are exchanged later, so we end with M_B as C's real type. > I suggest you to file a documentation bug. Unfortunately the basic > documentation about metaclasses is a bit lacking and you have to > discover many things by trial and errors. I still think this is a bug, not a documentation issue. Regards -- Pedro Werneck > > Michele Simionato > > -- > http://mail.python.org/mailman/listinfo/python-list > From theller at python.net Fri Sep 9 11:50:08 2005 From: theller at python.net (Thomas Heller) Date: Fri, 09 Sep 2005 17:50:08 +0200 Subject: [Py2exe-users] py2exe 0.6.2 released In-Reply-To: <6.2.5.2.2.20050907100804.04a1d5e0@blue-cove.com> (Ray Schumacher's message of "Wed, 07 Sep 2005 10:12:33 -0700") References: <6.2.5.2.2.20050907100804.04a1d5e0@blue-cove.com> Message-ID: Ray Schumacher writes: > First, Thanks again for the update. > > At 08:55 AM 9/7/2005, Thomas Heller wrote: > >> This part of the code is distributed under the MPL 1.1, so this >> license is now pulled in by py2exe. > > As I read it, it seems that I need to include an Exibit A > http://www.mozilla.org/MPL/MPL-1.1.html#exhibit-a > filled out so that it includes the py2exe home, as well as Python, probably. > It could be put in the Zip or Rar to be viewed on extraction. > Does this sound correct? Probably. But IANAL. Thomas From rdh at new.rr.com Fri Sep 23 17:30:39 2005 From: rdh at new.rr.com (DataSmash) Date: 23 Sep 2005 14:30:39 -0700 Subject: batch mkdir using a file list In-Reply-To: References: <1127500054.273772.112470@g14g2000cwa.googlegroups.com> <1127501470.425241.212450@g43g2000cwa.googlegroups.com> <1127502885.612276.304560@g47g2000cwa.googlegroups.com> Message-ID: <1127511039.122701.103910@g43g2000cwa.googlegroups.com> Awesome! That worked! Much thanks to Peter and all of you who took the time to answer my question. R.D. From steve at holdenweb.com Sun Sep 4 09:46:26 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 04 Sep 2005 08:46:26 -0500 Subject: os.system(r"ls") prints to screen?? In-Reply-To: <1125832488.379489.147760@g49g2000cwa.googlegroups.com> References: <1125795750.304104.280660@g49g2000cwa.googlegroups.com> <1125832488.379489.147760@g49g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > Steve Holden wrote: > >>This is all pretty basic stuff. Perhaps you should stop your verbal >>assault on the computer science community and start to learn the >>principles of what you are doing. > > > is this a supressed behavior that a human animal can finally > instinctively and justifiably release at another in a group frenzy? > Seems to me that you'd know more about frenzy than me. Having read many of your posts it seems to me that they are deliberately calculated to inflame the reader. To be successfully so critical of others you need to demonstrate superior knowledge and judgment, which your original question revealed to be lacking. To put it another way: "People who live in glass houses shouldn't throw stones". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From larry.bates at websafe.com Tue Sep 13 16:39:31 2005 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Sep 2005 15:39:31 -0500 Subject: Python and SMB, again... In-Reply-To: <1126559171.730797.285040@g43g2000cwa.googlegroups.com> References: <1126559171.730797.285040@g43g2000cwa.googlegroups.com> Message-ID: <43273903.9040405@websafe.com> You might want to take a look at Webdrive (www.webdrive.com). It does what I "think" you are describing for ftp, http, https, and WebDAV. -Larry Bates Atila Olah wrote: > On 1997/06/05 Peter Henning wrote: > >>SMB, ldap, imap4rev1 >> >>Is there an SMB library? I want to be able to access SMB shares > >>from python, or publish shares onto a network neighbourhood from > >>a python server. If anyone has implemented SMB in python, could >>you point me to the code? Otherwise, would like Samba be a good >>starting-point for implementing a python SMB module? > > > I was wondering if there are any news on this topic... Anyway, I have a > project to do, and it is about implementing a SMB server on the client > machine that translates other protocols to SMB (ftp, for example). So, > for example, the site ftp.openbsd.org could be viewed in \\My Network > Places\FTP Networks (or whatever). There are two posible solutions: > > The first is to implement a SMB server on the client machine. Maybe > this one is't the most effective way to do this, but anyway, in this > case I'll need a smb module. If anyone could help me, I'd be glad. If I > can't do this in Python, and there are other programming languages that > support this option, please tell me. > > The second option is to create a virtual drive and map the network > content into it. Even in this case, i can share it only to be visible > in My Network Places, but it isn't the point. To create a virtual > drive, I have to study the partition table of virtual drives, and even > then, I know only one virtual drive module, in C. But I'd be happy if > you coud tell me something useful on this option. > > Anyway, if you know a third option, that is better than these, or if > you think you know, wich one of these is better, just let me know. This > is the harder part of my project and I can't get out of it. It is a > simple cross-platform file sharing protocol for my mature exam work. > The linux-part is done, so all I need is to do the Windows stuff. I'm > new in Windows programming, and I'm helpless, so any ideas are > welcome... > From steve at holdenweb.com Tue Sep 13 07:42:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Sep 2005 12:42:21 +0100 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: <8180ef6905091303211a4856bb@mail.gmail.com> References: <8180ef690509120611513ad8e8@mail.gmail.com> <43259C81.4060603@sweetapp.com> <8180ef69050912100116e5b2fb@mail.gmail.com> <4326A434.9030802@sweetapp.com> <8180ef6905091303211a4856bb@mail.gmail.com> Message-ID: Mark Dufour wrote: >>You forgot to check for an error when: >>o when you wrote f.error [attribute "error" might not exist e.g. f is >> None] >>o you called str(f.error) [might contain unicode characters that can't >> be converted to a string using the default >> encoding] >>o when you used the % operator [format string might be wrong] >>And, of course, pretty much every expression can result in a memory error. > > > I don't mind the program bailing out in such a case and telling me > where it went wrong, so I can fix the problem. I just don't really see > the need for catching exceptions yourself. Especially not in > well-tested code, potentially to be compiled. > > >>Exception handling is a boon because almost EVERY expression that you >>write can result in a error and checking each one is tedious in the >>extreme. So people forget and then their programs exhibit very odd >>behavior that is very difficult to debug. > > > What do you mean odd behaviour? If they don't catch exceptions, the > program will bail out, showing what went wrong, yeah? > > >>If you look at the Python C source, you'll notice that probably 50% of >>the code is devoted to error handling (that was a guess). > > > That's a lot of error handling.. > Mark: You have achieved so much with the first release of Shed Skin that it's strange to see you apparently trying to argue that exceptions aren't necessary when in fact they are such a fundamental part of Python's philosophy. Their real value is in removing the necessity to perform explicit error checking after each operation in a program. For example, when I write try: func1(...) func2(...) except SomeException: handle the exception the authors of func1()) and func2() don't have to worry about explicitly returning control if some condition they can't handle occurs. They just write raise SomeException knowing that this will immediately cause all calling contexts to be unstacked until the context is reached that is prepared to handle the exception. Without such an ability the logic of the functions tends to look something like if (errorCondition1): return SomeErrorFlag1 elif (errorCondition2): return SomeErrorFlag2 else: perform normal computation return Value and the calling code then has to check for the flags before handling the return value. So basically exceptions allow simplification of program structure with more effective and simpler error handling. If you read through (for example) the code you'll find in the standard library and you'll get a better feel for the usefulness of exceptions. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bathing at gmail.com Wed Sep 21 06:31:13 2005 From: bathing at gmail.com (Z.L.) Date: 21 Sep 2005 03:31:13 -0700 Subject: scipy for python 2.4 on windows Message-ID: <1127298673.310643.138690@g49g2000cwa.googlegroups.com> I am a newbie to python, and have not so much experiences on package installation and related issues. I am looking for Scipy binaries for python 2.4 on windows. Could somebody here kindly give some suggestion to this? Thanks in advance. From steve at holdenweb.com Thu Sep 1 21:57:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Sep 2005 20:57:56 -0500 Subject: cgi, reusing html. common problem? In-Reply-To: References: Message-ID: John M. Gabriele wrote: > I'm putting together a small site using Python and cgi. > > (I'm pretty new to this, but I've worked a little with > JSP/servlets/Java before.) > > Almost all pages on the site will share some common (and > static) html, however, they'll also have dynamic aspects. > I'm guessing that the common way to build sites like this > is to have every page (which contains active content) be > generated by a cgi script, but also have some text files > hanging around containing incomplete html fragments which > you read and paste-in as-needed (I'm thinking: > header.html.txt, footer.html.txt, and so on). > > Is that how it's usually done? If not, what *is* the > usual way of handling this? > There are a million ways to solve this particular problem, despite Python's "TSBOAPOOOWTDI" (see "import this") philosophy (because the philosophy is addressing primitive programming rather than application frameworks). You could do something as simple as writing a module "webPage" that defines a function page(path, content) that does something along the lines of: def page(path, content): return """\ If you want titles, add another argument %s """ % content Then in your generation routines you can build up content in the traditional way by generating individual fragments of HTML and appending them to a list. So you start with content = [] then for every fragment you generate you do content.append(fragment) and finally your content is generated with something like content = webPage.page("siteroot/subdir/page1.html", "".join(content)) If you don't care that a page contains a navbar link to itself (a sign of web immaturity, but by no means inexcusable) then you don't even need to pass the page's path into the function. Hope this gives you a few ideas. This problem has been considered by many people, but clearly no outstanding solution has yet been devised, otherwise we'd all be using it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dieter at handshake.de Wed Sep 21 14:39:41 2005 From: dieter at handshake.de (Dieter Maurer) Date: 21 Sep 2005 20:39:41 +0200 Subject: Simpler transition to PEP 3000 "Unicode only strings"? References: Message-ID: "Petr Prikryl" writes on Tue, 20 Sep 2005 11:21:59 +0200: > ... > The idea: > ========= > > What do you think about the following proposal > that goes the half way > > If the Python source file is stored in UTF-8 (or > other recognised Unicode file format), then the > encoding declaration must reflect the format or > can be omitted entirely. In such case, all > simple string literals will be treated as > unicode string literals. > > Would this break any existing code? Yes: modules that construct byte strings (i.e. strings which should *not* be unicode strings). Nevertheless, such a module may be stored in UTF-8. From jbausano at vt.edu Mon Sep 26 21:09:51 2005 From: jbausano at vt.edu (John Bausano) Date: Mon, 26 Sep 2005 21:09:51 -0400 Subject: Dynamic character substitution. Message-ID: Hello all, I've been using Ansys which is a commercial FEA package which can be controlled through its own scripting language they call APDL. Now I'm trying to write some stand alone code in Python to supplement my current efforts. In Ansys I can do something like this. *do,n,1,3 #loop through n *dim,data%n%,1000,2 #creates variables arrays data1(1000,2), data2(1000,2).. *vread,data%n%,filename%n% #fills arrays with data from filename1,. Thanks john From fperez.net at gmail.com Wed Sep 14 15:44:17 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 14 Sep 2005 13:44:17 -0600 Subject: working with VERY large 'float' and 'complex' types References: Message-ID: Todd Steury wrote: > Greetings Python'ers: > > I'm just an amature who occasionally uses Python for complex mathematical > models. The current model I'm working with occasionally generates really > large numbers that are either "float" or "complex" types. These numbers are > so large that I either get an overflow error, or some funky code like #INF > or 1.#INDj. However I really need these numbers to be calculated (although > precision isn't key). Is there a way to get python to increase the size > limit of float and complex numbers? I should mention that I'm using a lot of > pre-made modules and functions like math.exp() and scipy.special.erf() that > don't seem to be able to use available types like "Decimal" or "FixedPoint" > (especially since these don't seem to handle complex numbers). Python floats are C doubles underneath, so you're stuck. You need extended numeric types. Decimal is slow as molasses, and was not designed for mathematical work (rather for finance-type fixed-point work). Use this instead: http://calcrpnpy.sourceforge.net/clnumManual.html Cheers, f From twic at urchin.earth.li Mon Sep 19 12:22:44 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 19 Sep 2005 17:22:44 +0100 Subject: style question: anything wrong with super(type(self), self).f() ? In-Reply-To: <1127145205.959666.10310@o13g2000cwo.googlegroups.com> References: <1127145205.959666.10310@o13g2000cwo.googlegroups.com> Message-ID: On Mon, 19 Sep 2005, Adam Monsen wrote: > Is there anything wrong with using something like super(type(self), > self).f() to avoid having to hardcode a type? What happens when that method gets called by an overriding method in a derived class? > For example: > > class A(object): > def f(self): > print "in A.f()" > > class B(A): > def f(self): > super(type(self), self).f() > > obj = A() > obj.f() # prints "in A.f()" Continuing your example: class C(B): def f(self): super(type(self), self).f() obj = C() obj.f() Think about what's going to happen. Then try it! > By "wrong" I mean, is there any reason why this is just a Bad Idea? That rather depends if the behaviour i demonstrate above is useful to you. :) > Seems helpful to me, if I change the name of the 'B' class, I don't have > to change super() calls as well. It would indeed be very useful. tom -- buy plastic owl From mrjbq7 at gmail.com Thu Sep 1 22:18:02 2005 From: mrjbq7 at gmail.com (MrJbQ7) Date: 1 Sep 2005 19:18:02 -0700 Subject: Proposal: add sys to __builtins__ In-Reply-To: References: Message-ID: <1125627482.106596.283790@g43g2000cwa.googlegroups.com> Steve Holden wrote: > I wonder if it would be worth special-casing the AttributeError [snip] What is it that Tim Peters said? "Special cases aren't special enough..." Besides, a better way is to use your ~/.pythonrc file for customizing according to your needs. A simple: echo "import sys, os" >> ~./pythonrc will do the job. Thanks, John Benediktsson From gsakkis at rutgers.edu Sat Sep 24 21:06:48 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 24 Sep 2005 21:06:48 -0400 Subject: Parsing an HTML a tag References: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> <1qfr7w2rvpxy4.i01rt25iqa2e$.dlg@40tude.net> <1127607406.791752.160460@g43g2000cwa.googlegroups.com> Message-ID: <1127610418.f4524631f00df35ac6324e7689dc00b9@teranews> "George" wrote: > I'm very new to python and I have tried to read the tutorials but I am > unable to understand exactly how I must do this problem. > > Specifically, the showIPnums function takes a URL as input, calls the > read_page(url) function to obtain the entire page for that URL, and > then lists, in sorted order, the IP addresses implied in the " HREF=? ? ?>" tags within that page. > > > """ > Module to print IP addresses of tags in web file containing HTML > > >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/easy.html') > ['0.0.0.0', '128.255.44.134', '128.255.45.54'] > > >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/pytorg.html') > ['0.0.0.0', '128.255.135.49', '128.255.244.57', '128.255.30.11', > '128.255.34.132', '128.255.44.51', '128.255.45.53', > '128.255.45.54', '129.255.241.42', '64.202.167.129'] > > """ > > def read_page(url): > import formatter > import htmllib > import urllib > > htmlp = htmllib.HTMLParser(formatter.NullFormatter()) > htmlp.feed(urllib.urlopen(url).read()) > htmlp.close() > > def showIPnums(URL): > page=read_page(URL) > > if __name__ == '__main__': > import doctest, sys > doctest.testmod(sys.modules[__name__]) You forgot to mention that you don't want duplicates in the result. Here's a function that passes the doctest: from urllib import urlopen from urlparse import urlsplit from socket import gethostbyname from BeautifulSoup import BeautifulSoup def showIPnums(url): """Return the unique IPs found in the anchors of the webpage at the given url. >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/easy.html') ['0.0.0.0', '128.255.44.134', '128.255.45.54'] >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/pytorg.html') ['0.0.0.0', '128.255.135.49', '128.255.244.57', '128.255.30.11', '128.255.34.132', '128.255.44.51', '128.255.45.53', '128.255.45.54', '129.255.241.42', '64.202.167.129'] """ hrefs = set() for link in BeautifulSoup(urlopen(url)).fetch('a'): try: hrefs.add(gethostbyname(urlsplit(link["href"])[1])) except: pass return sorted(hrefs) HTH, George From tjreedy at udel.edu Thu Sep 1 15:05:25 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Sep 2005 15:05:25 -0400 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> Message-ID: "Rocco Moretti" wrote in message news:df73m2$btd$1 at news.doit.wisc.edu... > There is just one giant roadblock to that suggestion - Sourceforge > requires a login to post bugs/patches. After reading this and the rest of your post, and remembering others like it, I decided this maybe is a real point. Remembering that the site invited emailed doc comments, I rechecked the About this Document page referenced at the bottom of each doc page and found the following: "General comments and questions regarding this document should be sent by email to docs at python.org. If you find specific errors in this document, either in the content or the presentation, please report the bug at the Python Bug Tracker at SourceForge." So I emailed a general suggestion (with specific wording ;-) that error reports also be allowed via email -- and quoted your post to explain why. Terry J. Reedy From john at hazen.net Mon Sep 19 20:15:35 2005 From: john at hazen.net (John Hazen) Date: Mon, 19 Sep 2005 17:15:35 -0700 Subject: How am I doing? In-Reply-To: References: <86slw1znup.fsf@bhuda.mired.org> <1127161587.863795.214000@z14g2000cwz.googlegroups.com> Message-ID: <20050920001535.GA21183@gate2.hazen.net> * Jason [2005-09-19 16:28]: > I've restructured my code with the assistance of George and Mike which > is now as follows... > > import random > > class HiScores: > def __init__(self,hiScores): > self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores] With your redefined hiScores, the above is wrong. I think it should just be: self.hiScores=[entry for entry in hiScores] Your original code used the slicing to pull the score and name out of a single string. Since you've split the string into its two parts, you don't need the indexing anymore. > def showScores(self): > for name,score in self.hiScores: > print "%s - %s" % name,score The error you cite below is due to trying to zfill an integer, not a string. I'm not going to modify your code, but I would use integers all over for the scores, and only turn to a string (and do the zfill) when outputting it. def showScores(self): for name,score in self.hiScores: score = str(score).zfill(5) #untested print "%s - %s" % name,score > def main(): > > hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] This looks like an indentation error to me. Is hiScores indented in your version? > a=HiScores(hiScores) > print "Original Scores\n---------------" > a.showScores() > > while 1: > newScore=random.randint(0,10000) As I said, I would use int's throughout, but to use it as-is, change the above line to: newScore=str(random.randint(0,10000)) > if newScore.zfill(5) > a.lastScore(): > print "Congratulations, you scored %d " % newScore > name=raw_input("Please enter your name :") > a.addScore(newScore,name) > a.showScores() > > if __name__=="__main__": > main() > 1) The most important is that when run, the program crashes with > > AttributeError: 'int' object has no attribute 'zfill' > > I've read as many websites as I can about zfill and I can't see why on > earth it's failing. I think I explained this above. You're trying to call a string method on an integer. > > 2) The output of the predefined hiscores is now... > > 10000 - Alpha () > 07500 - Beta () > 05000 - Gamma () > 02500 - Delta () > 00000 - Epsilon () Are you sure it's not: ('10000', 'Alpha') - () etc. ? I think this is a result of your still doing indexing to separate the score and the name, even though you've already separated the name and score into tuples in the predefined list: >>> hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] >>> s=hiScores[0] >>> s ('10000', 'Alpha') >>> s[:5] ('10000', 'Alpha') >>> s[5:] () >>> p = (s[:5],s[5:]) >>> p (('10000', 'Alpha'), ()) >>> print "%s - %s" % p ('10000', 'Alpha') - () >>> > Why are there the pairing parenthesis there? George very kindly showed > me another way which was to have... > > def showScores(self): > for entry in self.hiScores: > print entry[0:5]," - ",entry[5:] > > But using that method output the entire list in it's full format (sorry > if that's not the correct terminology). But give me a small plus mark > for changing code and not simply copying George :) > > 3) The hardest thing to 'understand' is the line... > self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores] This is now slicing into the tuple for each entry, instead of into the string, so your results are unexpected. slicing past the end of a tuple returns the empty tuple (which I think is the '()' you're getting in your output. > TIA HTH- John From tzot at sil-tec.gr Mon Sep 26 12:34:53 2005 From: tzot at sil-tec.gr (Christos Georgiou) Date: Mon, 26 Sep 2005 19:34:53 +0300 Subject: Question about smtplib, and mail servers in general. References: <9_6dnY_ct8a0lK3eRVn-qQ@powergate.ca> Message-ID: On Tue, 20 Sep 2005 16:48:41 +0200, rumours say that Piet van Oostrum might have written: >And most smtp servers that I know also pass mail from any from-address to >any to-address if the IP number of he client machine belongs to a trusted >range (usually the range that belongs to the ISP). So I can send both my >private mail and my work mail from both my home ISP's smtp server and my >work's smtp server (but only if I am at the proper location). You might start having troubles, though, as soon as SPF checks get more widespread. Say your work mail is piet at example.com, and your private mail is piet at yagoohoogle.com; if you send email through your office mail server with the envelope "MAIL FROM: piet at yagoohoogle.com\n", then some (and eventually many) receiving servers shall ask yagoohoogle.com for their SPF record, and since your office mail server won't probably show up as a valid email sender from yagoohoogle.com , your email will get rejected. That's a good thing. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From erniedude at gmail.com Tue Sep 13 13:26:55 2005 From: erniedude at gmail.com (Ernesto) Date: 13 Sep 2005 10:26:55 -0700 Subject: Ctypes Install in Linux In-Reply-To: <1126543849.060173.12170@z14g2000cwz.googlegroups.com> References: <1126541371.379893.295950@g43g2000cwa.googlegroups.com> <1126541837.832917.172740@g14g2000cwa.googlegroups.com> <1126542238.904285.208470@g14g2000cwa.googlegroups.com> <1126543849.060173.12170@z14g2000cwz.googlegroups.com> Message-ID: <1126632415.801086.120200@g14g2000cwa.googlegroups.com> THANKS !!! From percivall at gmail.com Sun Sep 4 10:06:18 2005 From: percivall at gmail.com (Simon Percivall) Date: 4 Sep 2005 07:06:18 -0700 Subject: sizeof(long) from python In-Reply-To: <1125841422.794013.152100@f14g2000cwb.googlegroups.com> References: <1125841422.794013.152100@f14g2000cwb.googlegroups.com> Message-ID: <1125842778.161214.301080@g44g2000cwa.googlegroups.com> Take a look at the struct module (http://docs.python.org/lib/module-struct.html), it does what you want. From knipknap at gmail.com Thu Sep 15 20:37:30 2005 From: knipknap at gmail.com (Samuel) Date: 15 Sep 2005 17:37:30 -0700 Subject: No newline using printf Message-ID: <1126831050.903747.13040@z14g2000cwz.googlegroups.com> Hello, I have been searching for an answer for almost two hours now and have not found an answer. I want this code: for i in range(3): print i # or whatever To produce this output: 012 How can I print a word without appending a newline character? Appending a "," to the print statement only substitutes the newline for a space, which is not what I am looking for. Any hints? Thanks, -Samuel From jzgoda at o2.usun.pl Sun Sep 25 17:27:09 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 25 Sep 2005 23:27:09 +0200 Subject: Best practices for dynamically loading plugins at startup In-Reply-To: References: Message-ID: Christoph Haas napisa?(a): > Since I don't know which plugins have been put into that directory > I cannot just "import Plugin1, Plugin2, Plugin3" in the "__init__.py". > So I need to find out the *.py there and load them during startup. > I could do that with a "walk" over that directory. See entry for __import__ at http://www.python.org/doc/2.3/lib/built-in-funcs.html -- Jarek Zgoda http://jpa.berlios.de/ From joachim at ee.ucla.edu Wed Sep 7 13:56:40 2005 From: joachim at ee.ucla.edu (Joachim Dahl) Date: Wed, 07 Sep 2005 10:56:40 -0700 Subject: distutils question Message-ID: I am trying to make a customized install script for an extension module using the distutils.ccompiler class. I want to embed an existing makefile for the C libraries into the Python setup script, but I am not sure what's the right way to do it... E.g., say I want to compile a project as: gcc -Ddef1 -c foo.c -o foo_def1.o gcc -Ddef2 -c foo.c -o foo_def2.o gcc foo_def1.o foo_def2.o -o myext_module.o How would I do that using distutils? It doesn't seem to be possible with the normal core.setup method, and distutils.ccompiler seems to be the best option, but I couldn't get it working... Hopefully someone the list can enlighten me. Thanks! Joachim From theller at python.net Tue Sep 6 15:46:30 2005 From: theller at python.net (Thomas Heller) Date: Tue, 06 Sep 2005 21:46:30 +0200 Subject: py2exe 0.6.1 released References: <1126021854.581774.261940@g43g2000cwa.googlegroups.com> Message-ID: "cmkl" writes: > Hi, > > I didnt succeed to bundle vpython-3.2.3 with py2exe-0.6.1 - regardless > if its build as single file or not: > > "This application has requested the Runtime to terminate it in an > unusual way" and so on... > > This error message seems not generated by py2exe. At least I could not > find a reference to it in the sources of py2exe. Often this is caused by py2exe not including some needed pyds, together with 'sloppy' programming in the extensions themselves. Let me explain: Sometimes, extensions depend on other extensions. Since they cannot directly import functions from each other, Python has an API for that: PyCObject_Import(module_name, cobject_name). This returns an opaque pointer, which often points to a table of functions. Or NULL, in case there's an error. Normally, this import will never fail (because all the extensions are available), so often the return value is *not* checked. Calling one of these functions when the import has failed will then crash the application. In other cases the extension programmers see no other way to report the error except calling PyFatal_Error() when the import failed, which would then give what you see. For py2exe, it may help to use include more modules or the whole package in question and try to build again. Of course, it can also be that py2exe 0.6 has a bug that 0.5.4 did not have, can you try that version? Thomas From fredrik at pythonware.com Thu Sep 15 04:45:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Sep 2005 10:45:36 +0200 Subject: urllib.open problem References: <4328B019.2010104@al.com.au> Message-ID: Astan Chee wrote: > I have a python script which runs perfectly on my machine. > However a machine that I tested it on gives the following error > message: > > Traceback (most recent call last): > File "whip.py", line 616, in OnRebootRunning > File "whip.py", line 626, in RebootCustom > File "urllib.pyc", line 77, in urlopen > File "urllib.pyc", line 170, in open > TypeError: cannot concatenate 'str' and 'NoneType' objects > > The code snipplet where this error > happens is > f = urllib.urlopen("http://www.hotmail.com/) > notes= f.readlines() > > Does anyone know what causes this error? Im perplexed because it works > on some machines and it doesnt work on other computers although they all > have the same spec. assuming you're using Python 2.4, the relevant portion of urllib.py looks like this: urltype, url = splittype(fullurl) if not urltype: urltype = 'file' if urltype in self.proxies: proxy = self.proxies[urltype] urltype, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + urltype # <-- this is line 170 the error message indicates that urltype is None when you get to line 170, and the only way it can get set to None is a bogus proxy setting (causing splittype to fail). checking the environment for things that end with "_proxy" should help. From midday.hu at gmail.com Fri Sep 30 07:48:54 2005 From: midday.hu at gmail.com (midday.hu at gmail.com) Date: 30 Sep 2005 04:48:54 -0700 Subject: how to stop info output on screen Message-ID: <1128080934.730144.217060@f14g2000cwb.googlegroups.com> Hi, Does someone know how to stop "the information output on screen"? Now when I run my code, it outputs a lot of message when calling other libraries, together with the info with the print command I used. How can I mask these info on screen when calling other libraries and how I can mask the info output produced by the print command? Is there a way to mask them separately. Thanks a lot if anyone knows it. Kind regards of your help Midday From eurleif at ecritters.biz Fri Sep 23 13:35:35 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 23 Sep 2005 17:35:35 GMT Subject: replacments for stdio? In-Reply-To: <1127477278.036977.189230@g44g2000cwa.googlegroups.com> References: <1127477278.036977.189230@g44g2000cwa.googlegroups.com> Message-ID: Ido.Yehieli at gmail.com wrote: > i was wondering if anyone have written a GUI module that can > function as a replacment for stdin/stdout? ie. has a file like > interface, by which one could just assaign it to sys.stdout or > sys.stdin and have all your prints and raw_inputs and other such things > shown in a GUI window? Xterm? From no.spam.for.me. at thanks.com Mon Sep 5 02:55:15 2005 From: no.spam.for.me. at thanks.com (Mike P.) Date: Mon, 05 Sep 2005 06:55:15 GMT Subject: XML Pickle with PyGraphLib - Problems Message-ID: <431bebd1$1@news.unimelb.edu.au> Hi all, I'm working on a simulation (can be considered a game) in Python where I want to be able to dump the simulation state to a file and be able to load it up later. I have used the standard Python pickle module and it works fine pickling/unpickling from files. However, I want to be able to use a third party tool like an XML editor (or other custom tool) to setup the initial state of the simulation, so I have been playing around with the gnosis set of tools written by David Mertz. In particular I have been using the gnosis.xml.pickle module. Anyway, this seems to work fine for most data structures, however I have problems getting it to work with pygraphlib version 0.6.0.1 (from sourceforge). My simulation needs to store data in a set of graphs, and pygraphlib seems like a nice simple python graph library, that I found easy to use. Anyway, the problem is that I can successfully pickle to XML a data structure containing a pygraphlib graph, but I have trouble reloading/unpickling the very same data structure that was produced by the XML pickle module. I get an XMLUnpicklingError. Anyone have any ideas? Here's some output from the interactive prompt of a small example which demonstrates the error: ========================================================================== C:\home\src>python ActivePython 2.4 Build 244 (ActiveState Corp.) based on Python 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pygraphlib import pygraph >>> graph = pygraph.DGraph() >>> graph.add_edge('Melbourne', 'Sydney') >>> graph.add_edge('Melbourne', 'Brisbane') >>> graph.add_edge('Melbourne', 'Adelaide') >>> graph.add_edge('Adelaide', 'Perth') >>> print graph DGraph: 5 nodes, 4 edges >>> graph DGraph: 5 nodes, 4 edges Melbourne -> ['Sydney', 'Brisbane', 'Adelaide'] Brisbane -> [] Perth -> [] Sydney -> [] Adelaide -> ['Perth'] >>> import gnosis.xml.pickle >>> file = open('graph.xml', 'w') >>> gnosis.xml.pickle.dump(graph, file) >>> file.close() >>> f2 = open('graph.xml', 'r') >>> g2 = gnosis.xml.pickle.load(f2) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\gnosis\xml\pickle\_pickle.py", line 152, in load return parser(fh, paranoia=paranoia) File "C:\Python24\lib\site-packages\gnosis\xml\pickle\parsers\_dom.py", line 42, in thing_from_dom return _thing_from_dom(minidom.parse(fh),None,paranoia) File "C:\Python24\lib\site-packages\gnosis\xml\pickle\parsers\_dom.py", line 175, in _thing_from_dom container = unpickle_instance(node, paranoia) File "C:\Python24\lib\site-packages\gnosis\xml\pickle\parsers\_dom.py", line 59, in unpickle_instance raw = _thing_from_dom(node, _EmptyClass(), paranoia) File "C:\Python24\lib\site-packages\gnosis\xml\pickle\parsers\_dom.py", line 234, in _thing_from_dom node_val = unpickle_instance(node, paranoia) File "C:\Python24\lib\site-packages\gnosis\xml\pickle\parsers\_dom.py", line 95, in unpickle_instance raise XMLUnpicklingError, \ gnosis.xml.pickle.XMLUnpicklingError: Non-DictType without setstate violates pickle protocol.(PARANOIA setting may be too high) >>> =========================================================================== I find it strange that: a) the standard pickle/unpickle works b) the xml pickle dumps the file but the xml unpickle can't load it. I'm guessing the problem lies somewhere with implementing __setstate__ and __getstate__ for pygraphlib (I don't know much about this - haven't used them before). However, I am a bit reluctant to go in and start playing around with the internals pygraphlib, as I was hoping to just use it, and ignore the internal implementation (as you would with any library). Funny how the standard pickle module doesn't need to do this. Another thing I tried was the generic xml marshaller (xml.marshal.generic) that comes with PyXML 0.8.4 (for Python 2.4 on windows). This also fails but for different reasons. The marshaller doesn't support the boolean and set types which are part of Python 2.4 and are used in pygraphlib. I get errors of the form: AttributeError: Marshaller instance has no attribute 'tag_bool' AttributeError: Marshaller instance has no attribute 'm_Set' Again strange given that bool and sets should be supported in Python 2.4. Anyway, back to my question - does anyone have any suggestions as to where I could proceed next? I was hoping to be able to XML Pickle/Unpickle Python data structures containing graphs from pygraphlib fairly easily without having to stuff around in the internals of third party libraries. It would be nice if I could just concentrate on my application logic :-) Any ideas? Cheers. Mike P. From steve.horsley at gmail.com Tue Sep 6 14:06:15 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Tue, 06 Sep 2005 19:06:15 +0100 Subject: killing thread after timeout In-Reply-To: References: Message-ID: Jacek Pop?awski wrote: > Hello. > > I am going to write python script which will read python command from > socket, run it and return some values back to socket. > > My problem is, that I need some timeout. I need to say for example: > > os.system("someapplication.exe") > > and kill it, if it waits longer than let's say 100 seconds > > I want to call command on separate thread, then after given timeout - > kill thread, but I realized (after reading Usenet archive) that there is > no way to kill a thread in Python. > > How can I implement my script then? > > PS. it should be portable - Linux, Windows, QNX, etc Probably the easiest way is to use select with a timeout (see the docs for library module select). eg. a, b c = select.select([mySocket], [], [], timeout) if len(a) == 0: print 'We timed out' else: print 'the socket has something for us' Steve From nick at craig-wood.com Fri Sep 23 07:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 23 Sep 2005 11:30:02 GMT Subject: How to use a timer in Python? References: Message-ID: Nico Grubert wrote: > There is no cronjob anymore now. I just need to check if there is a lock > file. How would you modify my short program to avoid the situation "Ie > someone can get in there after you read the directory but before > you create the file."? You can't do it with files. You can do it with directories though... Both processes need to be using the same lock, so something like this (all untested ;-) import os import time WINDOWS_SHARE = 'C:\\Temp' lock_file = os.path.join(WINDOWS_SHARE, "transfer.lock") gained_lock = False while not gained_lock: try: os.mkdir(lock_file) gained_lock = True except OSError: print "Busy, please wait..." time.sleep(10) f = open(WINDOWS_SHARE + '/myfile', 'w') f.write("test 123") f.close() os.rmdir(lock_file) print "Done!" You need to do the same thing to the program which currently creates transfer.lock - so it waits if the transfer.lock is in existence too. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From alessandro.bottoni at infinito.it Mon Sep 12 15:22:30 2005 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Mon, 12 Sep 2005 19:22:30 GMT Subject: Unfortunate newbie questions! References: Message-ID: > - What book or doc would you recommend for a thorough > thrashing of object oriented programming (from a Python > perspective) for someone who is weak in OO? In other > words, how can someone learn to think in an OO sense, > rather than the old linear code sense? Hopefully, heavy > on problems and solutions! If OOP is the problem, you could try this: Object Oriented Analysys Peter Coad, Edward Yourdon Prentice Hall Old by quite informative As an alternative, have a look at the following ones. Thinking in Python: http://www.mindview.net/Books/TIPython Dive into Python: http://diveintopython.org/ How to Think Like a Computer Scientist: http://www.ibiblio.org/obp/thinkCSpy/ > - In college, I came to admire the Schaum's Outline book > approach--again heavy on problems and solutions! What's > the closest Python equivalent? Maybe this: Python Cookbook Alex Martelli, David Ascher O'Reilly HTH ----------------------------------- Alessandro Bottoni From lechequier at gmail.com Fri Sep 9 14:41:29 2005 From: lechequier at gmail.com (lechequier at gmail.com) Date: 9 Sep 2005 11:41:29 -0700 Subject: Python Design Principles In-Reply-To: References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> Message-ID: <1126291289.420473.262990@g49g2000cwa.googlegroups.com> In a previous post, I asked about the inconsistency in usage patterns in operating on mutable and immutable types. Thanks Dave and everyone else for answering my question so thoughtfully and helping me to understand the reasoning about why the different usage patterns are not deemed to be inconsistent. But I am still puzzled by the argument that has been given for why methods that operate on mutable types should return None, namely, that the designers of python didn't want the users to shoot themselves in the foot by thinking a method simply returned a result and left the data structure unchanged. In the context of fundamental design principles, if you asked a random sample of Python gurus what is more Pythonesque: preventing users from shooting themselves in the foot or making things easier to accomplish, my impression is that people would overwhelmingly choose the latter. After all, the fact that Python is not strongly typed and is interpreted rather than compiled gives plenty of ways for people to shoot themselves in the foot but what is gained is the abilitity to do more with less code. But in this instance, by not allowing operations on mutable types to return the mutated objects, it seems that the other side is being taken, sacrificing programmer producitivity for concerns about producing possible side effects. It is somewhat ironic, I think, that Java, a language whose design principles clearly side on preventing users from shooting themselves in the foot, much more so thatn Python, generally allows you to get back the mutated object. I'm not trying to change minds here but just to understand better how this particular design decision fits into Python's overall design principles. thanks, Scott Dave Benjamin wrote: > lechequier at gmail.com wrote: > > Let's say I define a list of pairs as follows: > > > >>>l = [('d', 3), ('a', 2), ('b', 1)] > > > > > > Can anyone explain why this does not work? > > > >>>h = {}.update(l) > > > > > > and instead I have to go: > > > >>>h = {} > >>>h.update(l) > > > > to initialize a dictionary with the given list of pairs? > > > > when an analagous operation on strings works fine: > > > >>>s = "".join(["d","o","g"]) > > > > > > Seems inconsistent. > > Python is actually quite consistent in this regard: methods that modify > an object in-place return None; methods that do not modify an object > in-place return a new object instead. Since strings are immutable, they > cannot be modified in-place, so it makes sense for the "join" method to > return a new string. On the other hand, Python's dictionaries are > imperative-style and so most operations on a dictionary modify an > existing dictionary. > > I was initially bothered by the phenomenon of so many methods returning > None because they could not be chained. But I have come to deeply > appreciate this style for a couple of reasons. First, it makes it clear > which methods are side-effecting (like "update") and which are not (like > "sort"). > > Second, it is not always clear what a good return value is for a > mutator. Perhaps {}.update() should return the dictionary, making > chaining convenient. Perhaps it should return the total number of items > after updating. Or maybe it should return the number of new keys that > were added, or a list of those keys. All of these are plausible > behaviors; the problem is that "update" is not a function. Its job is to > change something, not return something. Any possible return value would > be a convenience for certain tasks and useless for other tasks. > > It's also hard to remember, in my opinion. For example, JavaScript has a > "push" method on the Array object which behaves like Python's "append" > method on lists: > > js> var a = []; > js> a.push(5); > 1 > js> a.push(6); > 2 > > I bet you that almost nobody knows that "push" returns the new length of > the Array. It could just as easily have returned "a" here. I could > always write "a.length", if I really needed to know the new length. This > sort of thing becomes language trivia, and when I write in JavaScript I > always ignore the result of "push" because, even if *I* know what it > returns, chances are that my readers don't. > > Another reason that Python adopts the convention of returning None for > mutators is that it discourages the use of side-effecting code in > expressions. Mixing side-effects with expressions can lead to code that > is hard to read and understand. This is often debated by those who know > better and wish to write things like "h.update(a).update(b)" (method > chaining) or "while (line = file.readline()): ...". Python's decision is > pretty clear, and it's also evident in the division between statements > and expressions. > > Regardless of whether you like Python's style decision or not, if you > dig deeper I think you will find that it is pretty consistent, and that > there are useful benefits to Python's way of handling side effects. > > Dave > > PS. If mutators had to return a value, I'd have them return "self", > probably 95% of the time. But then, it wouldn't be Python anymore. It'd > be Ruby, maybe. From pkilambi at gmail.com Thu Sep 29 13:01:40 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 29 Sep 2005 10:01:40 -0700 Subject: grouping array Message-ID: <1128013300.041801.248180@g14g2000cwa.googlegroups.com> hi if I have an array say x = [[2,2,0,0,1,1], [1,1,0,0,1,1], [1,1,0,0,1,1]] I basically want to group regions that are non zero like I want to get the coordinates of non zero regions..as (x1,y1,x2,y2) [(0,0,2,1),(0,4,2,5)] which show the top left(x1,y1) and bottom right(x2,y2) corners of each group.hope i am clear. Thanks From wolfgang.keller.nospam at gmx.de Tue Sep 13 05:45:16 2005 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Tue, 13 Sep 2005 11:45:16 +0200 Subject: PyGTK or wXPython? References: <%BvVe.998$m56.33493@twister1.libero.it> Message-ID: > (I do not use/program/own any McOS system, so I cannot > tell you anything about the Apple Platform). WxPython _can_ give you a native Mac "look and feel", if you are willing to take into account certain issues (such as e.g. menu bars not tied to windows, no MDI, no multi-pane etc.). It is afaik _not_ automatic. PyGTK uses X. There are window managers available which try to emulate an Aqua "look", but there's afaik no way to detach the menu bar from the window etc... If you are willing to GPL your own applications, PyQt is another option. Sincerely, Wolfgang Keller From http Mon Sep 19 17:25:14 2005 From: http (Paul Rubin) Date: 19 Sep 2005 14:25:14 -0700 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <7xll1swy11.fsf@ruckus.brouhaha.com> Michael Ekstrand writes: > > def drawline((x1, y1), (x2, y2)): > > # draw a line from x1, y1 to x2, y2 > > foo(x1, y1) > > bar(x2, y2) > > Yow! I did not know you could even do this. > > My vote would be +1 for keeping them in the language... they look far > too useful to deprecate/remove... I'm +1 for keeping them in the language and +1000 on keeping them in Python 2.5. Removing them would break existing code and therefore should not be done until Python 3.0 if at all. From NutJob at gmx.net Thu Sep 1 04:37:45 2005 From: NutJob at gmx.net (NutJob at gmx.net) Date: 1 Sep 2005 01:37:45 -0700 Subject: Is my thread safe from premature garbage collection? Message-ID: <1125563865.759423.197960@o13g2000cwo.googlegroups.com> Hello all, I'm aware that in Python an object is cleared for garbage collection as soon as the last reference to it disappears. Normally this is fine. However, in my current project I'm creating a bunch of threads which are supposed to run until they've completed their run() method, and I'm worried that if I do not keep references to these thread objects around, the GC might happily delete them (and thereby kill my thread routines maybe?) while they're not done yet. Is this fear justified? Or is the Python GC smart enough to leave thread objects alone until their run() methods have finished? If not, I do have a workaround, but it is a bit clumsy IMO. Basically I would just keep a list into which each thread object enters a reference to itself on creation. This way I'd ensure that I have a reference to the thread to prevent the GC from killing it. Then, when a thread is about to finish its run() method, the thread finds and removes that reference to itself from my list of thread references. Anyway, if anyone could make a definite statement on whether threads are safe from unwanted garbage collection, that'd be really great. Thanks in advance for any helpful replies! Cheers, antred From tjreedy at udel.edu Mon Sep 19 19:26:18 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Sep 2005 19:26:18 -0400 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <7xll1swy11.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xll1swy11.fsf at ruckus.brouhaha.com... > I'm +1 for keeping them in the language and +1000 on keeping them > in Python 2.5. Removing them would break existing code and therefore > should not be done until Python 3.0 if at all. I believe the idea of removing nested tuple parameters before 3.0 has been withdrawn. Guido is mildly considering the possibility for 3.0. Terry J. Reedy From bokr at oz.net Tue Sep 27 03:45:07 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 27 Sep 2005 07:45:07 GMT Subject: PEP 350: Codetags References: Message-ID: <4338bc2f.2535976150@news.oz.net> On Mon, 26 Sep 2005 15:35:21 -0700, Micah Elliott wrote: >Please read/comment/vote. This circulated as a pre-PEP proposal >submitted to c.l.py on August 10, but has changed quite a bit since >then. I'm reposting this since it is now "Open (under consideration)" >at . > >Thanks! Generally, I like this (I've even rambled on the subject myself before ;-) But I don't think DONE is a "synonym" for "TBD" or "FIXME" etc. Some quick reactions: (in case I don't get to detailed comments ;-) 1) IMO DONE (or a well-chosen alternative) should be reserved as a tag that you insert *after* a TODO-type code tag, and should NOT replace the TODO. Cleaning TODO/DONE pairs out of a source is a good job for a tool, which can be given an optional name for a project log file or DONE file etc. or take it from an environment variable or other config mechanism. This could run as a cron job, to clean and log, and notify etc. IOW, no error-prone manual DONE file stuff. 2) In general, I think it might be good to meet Paul Rubin half way re convention vs syntax, but I don't think code tagging should be part of the language syntax per se. (-*- cookies -*- really are defacto source syntax that snuck in by disguise IMO) So perhaps a python command line option could invoke an "official" tool, with some more options passed to it to do various checking or extracting etc. 3) Since a source containing code tags is usually the source for a module, a python expression with implicit scope of this module is a precise way of referring to some elements, e.g., # TODO: clean up uses of magic $MyClass.MAGIC tool can know MyClass.MAGIC is valid expr or ? 4) Why can't a codetag be on the same line as code? What's wrong with assert something, message # ???: Really always so? <> Is it just to make tag lines python parser independent easily? To be purist, you still have to deal with s = """ # FIXME: I'm embedded in a string that needs the python parser to exclude <> """ or make conventional rule against it. 5) Sometimes time of day can be handy, so maybe <2005-09-26 12:34:56> could be recognized? 6) Maybe some way of bracketing a section of code explicitly, e.g., # FIXME: rework everything in this section def foo(): pass class Bar: """and so forth""" # ...: 7) A way of appending an incremental progress line to an existing code tag line, e.g., # FIXME: This will take a while: rework foo and bar # ...: test_foo for new foo works! # ...: vacation Later a tool can strip this out to the devlog.txt or DONE file, when the tool sees an added progress line like # ---: woohoo, completed ;-) My preliminary .02USD for now ;-) Regards, Bengt Richter From mwm at mired.org Fri Sep 23 01:01:38 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 23 Sep 2005 01:01:38 -0400 Subject: Sniffing Text Files References: Message-ID: <86oe6kgyx9.fsf@bhuda.mired.org> David Pratt writes: > Hi. I have files that I will be importing in at least four different > plain text formats, one of them being tab delimited format, a couple > being token based uses pipes (but not delimited with pipes), another > being xml. There will likely be others as well but the data needs to > be extracted and rewritten to a single format. The files can be fairly > large (several MB) so I do not want to read the whole file into > memory. What approach would be recommended for sniffing the files for > the different text formats. I realize CSV module has a sniffer but it > is something that is limited more or less to delimited files. I have > a couple of ideas on what I could do but I am interested in hearing > from others on how they might handle something like this so I can > determine the best approach to take. Many thanks. With GB memory machines being common, I wouldn't think twice about slurping a couple of meg into RAM to examine. But if that's to much, how about simply reading in the first bytes, and checking that for the characters you want? should be large enough to reveal what you need, but small enogh that your'e comfortable reading it in. I'm not sure that there aren't funny interactions between read and readline, so do be careful with that. Another approach to consider is libmagic. Google turns up a number of links to Python wrappers for it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mark.dufour at gmail.com Sat Sep 24 08:23:06 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Sat, 24 Sep 2005 14:23:06 +0200 Subject: Shed Skin Python-to-C++ Compiler 0.0.3 Release: some fixes, 3 MB Windows package Message-ID: <8180ef69050924052337832a69@mail.gmail.com> Hi all, Thanks to the people trying out Shed Skin 0.0.2 and letting me know about several problems they encountered. I have released an updated version, 0.0.3. It contains some fixes, adds support for several builtin functions (sorted, xrange..) and the Windows version is now a mere 3 MB, instead of 20 :-) Shed Skin's main purpose is to optimize algorithmic-like Python code, by applying advanced global type inference techniques. It does not support e.g. exceptions (yet), and there are currently some other limitations. Importing modules requires some extra work on the part of the user (see the README for details,) although some imports are currently supported (some math, random functions and sys.argv.) What you gain by using Shed Skin is highly optimized code (industrial C++ compiler), independent of any virtual machine. It is also possible to create highly optimized extension modules this way. I invite anyone to try not too large algorithmic-like programs (e.g. AI stuff) with Shed Skin and to let me know if there are any problems. Even though 129 test programs already work well (6 of which are larger than 100 lines), there are still many unimplemented minor features that I can easily fix, provided someone shows me a nice use case. Thanks to the people that have sent me failing code snippets before! http://shedskin.sourceforge.net http://shed-skin.blogspot.com Thanks! Mark Dufour. From frodo at fortress.site Fri Sep 9 17:38:21 2005 From: frodo at fortress.site (Unknown) Date: Fri, 09 Sep 2005 21:38:21 GMT Subject: error processing variables Message-ID: PROBLEM: for some reason, the variables won't work outside the function. I tried fix it by converting the variables to str and unicode and still no joy. The only way it works is by typing each source and destination file by hand on the shutil.copy2() method. Or by specifying the functions *inside* the function itself. Any ideas? ERROR: Traceback (most recent call last): File "data/scripts/wifi.py", line 76, in main toHPU() File "data/scripts/wifi.py", line 32, in toHPU s.copy2(toHPU,wlan) File "/usr/lib/python2.4/shutil.py", line 92, in copy2 copyfile(src, dst) File "/usr/lib/python2.4/shutil.py", line 41, in copyfile if _samefile(src, dst): File "/usr/lib/python2.4/shutil.py", line 31, in _samefile return os.path.samefile(src, dst) File "/usr/lib/python2.4/posixpath.py", line 218, in samefile s1 = os.stat(f1) TypeError: coercing to Unicode: need string or buffer, function found CODE: import shutil #variables s = shutil toHPU = "/etc/sysconfig/network/toHPU.wifi" wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d" toAnyWifi = "/etc/sysconfig/network/toAny.wifi" wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88" def toHPU(): s.copy2(toHPU,wlan) s.copy2(toAnyWifi,wired) #end #execute function toHPU() --------------- From hugh.macdonald at gmail.com Wed Sep 7 04:52:43 2005 From: hugh.macdonald at gmail.com (Hugh Macdonald) Date: 7 Sep 2005 01:52:43 -0700 Subject: Reading in external file - error checking and line numbers... Message-ID: <1126083162.994845.20850@z14g2000cwz.googlegroups.com> I'm writing a tool at the moment that reads in an external file (which can use any Python syntax) At the moment, I'm reading the file in using: scriptLines = open(baseRippleScript).read() exec scriptLines However, if I raise an exception in my main code, in a function that is called from the external script, the stack trace just has: File "", line 8, in ? Ideally, I'd want to be able to avoid throwing exceptions and would like to, from my main code, print out an error that included the script name (easily accessible) and the line number (less easily accessible). Is there a better way of executing an external script that would let me access at any time the line number from the external script that is being executed. More specifically, if a function is called from an external script with an invalid parameter type, I want to be able to flag it accurately to the user.... Hope this made sense - let me know if I've confused you at all..... -- Hugh Macdonald From twic at urchin.earth.li Sun Sep 25 17:03:24 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 25 Sep 2005 22:03:24 +0100 Subject: [RFC] Parametric Polymorphism In-Reply-To: References: Message-ID: On Sun, 25 Sep 2005, Catalin Marinas wrote: > Sorry if this was previously discussed but it's something I miss in > Python. I get around this using isinstance() but it would be cleaner to > have separate functions with the same name but different argument types. > I think the idea gets quite close to the Lisp/CLOS implementation of > methods. > > Below is just simple implementation example (and class functions are > not supported) but it can be further extended/optimised/modified for > better type detection like issubclass() etc. The idea is similar to > the @accepts decorator: > > methods = dict() > > def method(*types): > def build_method(f): > assert len(types) == f.func_code.co_argcount > > if not f.func_name in methods: > methods[f.func_name] = dict() > methods[f.func_name][str(types)] = f > > def new_f(*args, **kwds): > type_str = str(tuple([type(arg) for arg in args])) > assert type_str in methods[f.func_name] > return methods[f.func_name][type_str](*args, **kwds) > new_f.func_name = f.func_name > > return new_f > > return build_method Neat. I'd come up with the same general idea myself, but since i am a worthless slob, i never actually implemented it. Is there any reason you have to stringify the type signature? Types are hashable, so a tuple of types is hashable, so you can just use that as a key. Replace "methods[f.func_name][str(types)] = f" with "methods[f.func_name][types] = f" and "type_str = str(tuple([type(arg) for arg in args]))" with "type_str = tuple(type(arg) for arg in args)". And then rename type_str to types thoughout. Also, we can exploit the closureness of new_f to avoid a dict lookup: f_implementations = methods[f.func_name] def new_f(*args, **kwds): types = tuple(type(arg) for arg in args) return f_implementations[types](*args, **kwds) tom -- double mashed, future mashed, millennium mashed; man it was mashed From agostino.russo at gmail.com Tue Sep 20 17:27:03 2005 From: agostino.russo at gmail.com (ago) Date: 20 Sep 2005 14:27:03 -0700 Subject: Object default value In-Reply-To: <1127250684.979408.137790@o13g2000cwo.googlegroups.com> References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> <5r_Xe.25006$S26.11723@tornado.texas.rr.com> <1127250684.979408.137790@o13g2000cwo.googlegroups.com> Message-ID: <1127251623.723308.225370@f14g2000cwb.googlegroups.com> In fact even IF I could get a default value to work as mentioned, then I would be creating potential name conflicts between the DataAttribute.DefaultValue and the other metadata. I.e. when calling obj.attr.x I could refer to DataAttribute.x or DataAttribute.value.x. It's a no go. From luismgz at gmail.com Sun Sep 25 21:09:41 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 25 Sep 2005 18:09:41 -0700 Subject: Django Vs Rails References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <3o54knF46solU1@uni-berlin.de> <1126171655.554721.304130@g43g2000cwa.googlegroups.com> <1126802157.139711.226740@f14g2000cwb.googlegroups.com> <871x3q19m9.fsf@ieee.org> <1127627320.065510.238990@g47g2000cwa.googlegroups.com> Message-ID: <1127696981.003425.258600@g43g2000cwa.googlegroups.com> If you are looking for something pythonic, full featured and very easy to use, you should check this out: http://karrigell.sourceforge.net Give it a try and let me know how it goes... Cheers, Luis From nils.grimsmo at gmail.com Wed Sep 14 05:04:14 2005 From: nils.grimsmo at gmail.com (Nils Grimsmo) Date: 14 Sep 2005 02:04:14 -0700 Subject: round() wrong in Python 2.4? In-Reply-To: References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Message-ID: <1126682094.781278.106730@o13g2000cwo.googlegroups.com> I am running Debian unstable for 386. Python 2.4 is from the official package archive, and seems to be compiled with GCC 4.0.2. $ dpkg -l python2.4 ii python2.4 2.4.1-4 ... $ python2.4 Python 2.4.1+ (#2, Sep 4 2005, 21:58:51) [GCC 4.0.2 20050821 (prerelease) (Debian 4.0.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> $ gcc-4.0 --version gcc-4.0 (GCC) 4.0.2 20050725 (prerelease) (Debian 4.0.1-3) Klem fra Nils From bearophileHUGS at lycos.com Tue Sep 6 09:01:40 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Sep 2005 06:01:40 -0700 Subject: Command config, quitting, binary, Timer References: <1125798251.839994.121350@g14g2000cwa.googlegroups.com> <3o02fqF3h5igU1@uni-berlin.de> <1125848913.564915.186120@g44g2000cwa.googlegroups.com> <7almh1h9a1k887gqlq06c0tkfuaa0bkc1m@4ax.com> Message-ID: <1126011700.513890.185140@z14g2000cwz.googlegroups.com> Dennis Lee Bieber: >Yes, but only when ref-counts go to 0... it may be that this tight loop never allowed stuff to go to 0 ref-counts. It definitely never returned control, so besides eating memory that way, any events for the GUI framework were also not being handled and had to be queued.< This memory allocation problem is present even without the loop. In this other example if you keep cliking on the Go button, the memory used keep growing: from Tkinter import * def dogo(): b.config(command=dogo) root = Tk() b = Button(root, text="Go", command=dogo) b.pack() root.mainloop() >with leading 0s, that int() call is probably interpreting the string as OCTAL, rather than DECIMAL.< This can be fixed with a different dictionary that doesn't contain the leading 0s, to be used just for the first (not the "-") nibble. >What is the real use case for this conversion?< You are right, I'll remove the int conversion. Thank you, a bear hug, Bearophile From auditor400 at gmail.com Tue Sep 13 16:15:51 2005 From: auditor400 at gmail.com (felipevaldez) Date: 13 Sep 2005 13:15:51 -0700 Subject: high performance hyperlink extraction In-Reply-To: <1126635070.605561.208790@g44g2000cwa.googlegroups.com> References: <1126635070.605561.208790@g44g2000cwa.googlegroups.com> Message-ID: <1126642551.601348.215960@f14g2000cwb.googlegroups.com> pretty nice, however, u wont capture the more and more common javascripted redirections, like click me nor
nor
. im guessing it also wont handle correctly thing like:
click but you probably already knew all this stuff, didnt you? well, anyway, my 2 cents are, that instead of parsing the html looking for urls, like http://XXXX.XXXXXX.XXX/XXX?xXXx=xXx#x or something like that. //f3l From kent37 at tds.net Sat Sep 10 22:10:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Sep 2005 22:10:32 -0400 Subject: Escaping certain characters In-Reply-To: <42ed452f$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> <42ed452f$1@griseus.its.uu.se> Message-ID: <432390e2$1_1@newspeer2.tds.net> Jan Danielsson wrote: > Robert Kern wrote: > [---] > >>>Hmm... On second thought, I need to escape more characters. >>> >>>Is there no other way to escape characters in strings? >> >>Which characters? > > > I need to escape '\n', '"', '[' and ']'. I finally went with a few of > these: > string.replace('\n', '\\n') > string.replace('"', '\\"') You might like this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Kent From ggg at zzz.it Sun Sep 4 05:10:07 2005 From: ggg at zzz.it (Giuseppe di Sabato (aka deelan)) Date: Sun, 04 Sep 2005 11:10:07 +0200 Subject: Code for generating validation codes (in images) In-Reply-To: <1125824039.381538.309520@g43g2000cwa.googlegroups.com> References: <1125824039.381538.309520@g43g2000cwa.googlegroups.com> Message-ID: <4OySe.35732$TR5.18501@news.edisontel.com> morphex wrote: > Hi, > > does anyone of you know of some code I can use to generate validation > code images? > > Those images you can see on various login forms used to prevent bots > for performing a brute-force attack.. take a look at the "pycaptcha" package: later, deelan. -- deelan, #1 fan of adriana lima! From prinster at mail.com Sat Sep 24 14:12:45 2005 From: prinster at mail.com (Stephen Prinster) Date: Sat, 24 Sep 2005 18:12:45 GMT Subject: Parsing an HTML a tag In-Reply-To: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> References: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> Message-ID: George wrote: > How can I parse an HTML file and collect only that the A tags. I have a > start for the code but an unable to figure out how to finish the code. > HTML_parse gets the data from the URL document. Thanks for the help Have you tried using Beautiful Soup? http://www.crummy.com/software/BeautifulSoup/ From fredrik at pythonware.com Tue Sep 6 17:57:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 6 Sep 2005 23:57:07 +0200 Subject: __dict__ of object, Was: Regular Expression IGNORECASE differentfor findall and split? References: Message-ID: Chris wrote: > but more of a basic question following, I was doing the following before: > > method = 'split' # came from somewhere else of course > result = re.__dict__[method].(REGEX, TXT) > > precompiling the regex > > r = compile(REGEX) > > does give an regex object which has the needed methods > > print dir(r) > ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', > 'search', 'split', 'sub', 'subn'] > > but how do I evaluate them without explicitly calling them? > > result = r.__???MAGIC???__[method](TXT) > > obviously I am not a Python pro ;) I really don't understand why you think you have to write your RE code that way, but the mechanism you're looking for is getattr: result = getattr(r, method)(TXT) From ms at cerenity.org Sun Sep 11 13:31:23 2005 From: ms at cerenity.org (Michael Sparks) Date: Sun, 11 Sep 2005 18:31:23 +0100 Subject: First release of Shed Skin, a Python-to-C++ compiler. References: Message-ID: <432469eb$0$1294$ed2619ec@ptn-nntp-reader02.plus.net> Mark Dufour wrote: > With this initial release, I hope to attract other people to help me > locate remaining problems, Well, you did say you want help with locating problems. One problem with this is it doesn't build... If I try and build (following your instructions), I get presented with a whole slew of build errors - knock on errors from the first few: In file included from builtin_.cpp:1: builtin_.hpp:4:29: gc/gc_allocator.h: No such file or directory builtin_.hpp:5:23: gc/gc_cpp.h: No such file or directory In file included from builtin_.cpp:1: builtin_.hpp:89: error: syntax error before `{' token builtin_.hpp:93: error: virtual outside class declaration Which C++ libraries are you dependent on? (Stating this would be really useful, along with specific versions and if possible where you got them :) For reference, I'm building this on SuSE 9.3, under which I also have boehm-gc-3.3.5-5 installed. I suspect you're using the same gc library (having downloaded libgc from sourceforge and finding the includes don't match the above include names) but a different version. For reference this version/distribution of boehm-gc has the following file structure: /usr/include/gc.h /usr/include/gc_backptr.h /usr/include/gc_config_macros.h /usr/include/gc_cpp.h /usr/include/gc_local_alloc.h /usr/include/gc_pthread_redirects.h /usr/lib/libgc.a /usr/lib/libgc.la /usr/lib/libgc.so /usr/lib/libgc.so.1 /usr/lib/libgc.so.1.0.1 It's specifically the gc_cpp.h file that makes me suspect it's the same gc. Regards, Michael. From agostino.russo at gmail.com Tue Sep 20 17:01:23 2005 From: agostino.russo at gmail.com (ago) Date: 20 Sep 2005 14:01:23 -0700 Subject: Object default value In-Reply-To: <5r_Xe.25006$S26.11723@tornado.texas.rr.com> References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> <5r_Xe.25006$S26.11723@tornado.texas.rr.com> Message-ID: <1127250083.301445.81810@g49g2000cwa.googlegroups.com> I am trying to write a generic DataAttribute class in order to simplify access to object attributes and attached attribute-metadata for end users with little programming experience. Requirement 1: accessing the "default" value should be easy (using assignment operator, via descriptors like __get__ and __set__). Requirement 2: access to the attribute-metadata should also be as intuitive as possible. Requirement 3: possibly the DataAttribute should also be callable, to return for instance, an history of its values. class DataAttribute(object): value=1 #default old=2 .... class Obj(object): attr=DataAttribute() #From end user prospective, ideally: obj=Obj() x = obj.attr #x=1 xold = obj.attr.old #xold=2 obj.attr = 3 #obj.attr.value=3 xold = obj.attr.old #xold=1 xhistory = obj.attr(startdate, enddate) #xhistory = [[date1, 4],[date2,5],[date3,6]] xtimestmap = x.attr.timestamp print obj.attr == obj.attr.value #True If I use __get__ then I cannot access the metadata. I could create a separate Obj attribute for each metadata item, but then I would litter the Obj namespace (typical object will have several attributes each with lots of metadata) and potentially create name conflicts. Not to mention that DataAttributes should be attached/deleted on the fly and if each attribute becames a set of attributes this operation is complex (metclasses?). If I use __call__ + __set__ but then I am introducing an asymmetry: x = obj.attr() obj.attr = 2 I could use getters and setters but that is not really convenient nor intuitive From phil at riverbankcomputing.co.uk Sun Sep 4 09:42:42 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 4 Sep 2005 14:42:42 +0100 Subject: ANN: SIP v4.3 Released Message-ID: <200509041442.42147.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of SIP v4.3 available from http://www.riverbankcomputing.co.uk/sip/. SIP is a tool for generating Python modules that wrap C or C++ libraries. It is similar to SWIG. It is used to generate PyQt and PyKDE. Full documentation is available at http://www.river-bank.demon.co.uk/docs/sip/sipref.html. SIP is licensed under the Python License and runs on Windows, UNIX, Linux and MacOS/X. SIP requires Python v2.3 or later (SIP v3.x is available to support earlier versions of Python). This release includes the following changes: - Python's cyclic garbage collector is fully supported - support for mapping between Python and C++ exceptions - support for __pos__ and __abs__ - the support for accessing C structure members has been greatly improved - C structures can have constructors and destructors defined so that they can be made to behave more Pythonically. Other features of SIP include: - support for Python new-style classes - generated modules are quick to import, even for large libraries - support for Qt's signal/slot mechanism - thread support - the ability to re-implement C++ abstract and virtual methods in Python - the ability to define Python classes that derive from abstract C++ classes - the ability to spread a class hierarchy across multiple Python modules - support for C++ namespaces - support for C++ exceptions - support for C++ operators - an extensible build system written in Python that supports over 50 platform/compiler combinations. From steve at REMOVETHIScyber.com.au Thu Sep 29 11:04:27 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 30 Sep 2005 01:04:27 +1000 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 28 Sep 2005 16:36:03 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> No, but that is precisely why Python's semi-private variables are >> usually better. Names like _X and class.__X are warnings to the developer >> "use these at your own risk", without preventing developers who need them >> from using them. You have most of the benefits of private variables with >> none of the disadvantages. > > I'm sorry but I thought the idea was to actually reduce the risk of > bugs, not merely attach the risk to the right person. If changing the > way a class uses its own private variables breaks an application > because another class was using the private variable unexpectedly, > then that's bad, regardless of whether the other class's author was > notified or not. It's better to let the compiler automatically flag > these things, than to depend on conventions. Better for who? The idiot who doesn't take even a modicum of attention to the class creator who warns "Use these variables with care because they are subject to change without notice"? Or better for the developers who were prevented from making careful, intelligent use of the variables because of an misguided attempt to protect them from changes to the code that may or may not ever take place? You count the risk of bugs from semi-private variables, but you don't count the cost of lost opportunities caused by preventing access to those variables. Nor do you count the cost of "copy and paste" coding, both in extra development time and extra maintenance. Of course if you ignore the costs and lost opportunities of locked-down private variables they will be "better". -- Steven. From mwm at mired.org Tue Sep 6 22:07:59 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 06 Sep 2005 22:07:59 -0400 Subject: Optional algol syntax style References: <1125960497.067473.326830@g14g2000cwa.googlegroups.com> Message-ID: <868xy9ocjk.fsf@bhuda.mired.org> "Christoph Rackwitz" writes: > You didn't quite get the OP's intention, I guess. > > The OP wanted Python to be a bit more freeform by adding "end" tags. > That might be an improvement for web scripting, but I haven't seen the > solutions of the existing frameworks and won't dare to compare. Existing frameworks (the one's I've looked at anyway) tend to replace indents with end tags of some kind. Doing anything else tends to get ugly unless the language you are templating for treats whitespace the same way Python does. I'd argue that you're better off using a real templating system than trying to mangle Python into becoming a more acceptable templating system. For templates, you tend to want to access multiple different names spaces that are only vaguelly related to the Python contextual name spaces. For example, you may want CGI (or whatever variables) available directly in the template, rather than as CGI["foobar"].value. However, you don't want them showing up in front of your templat variables; you want to be able to say "add CGI variables foo, bar and foobar to the current name space" in a short manner. Templating systems (well, the better ones, anyway) let you manipulate those name spaces in ways you can't do in python. Cheeta and ClearSilver come to mind as systems that will let you do this. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Fri Sep 9 22:07:48 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 10 Sep 2005 02:07:48 GMT Subject: Python linear algebra module -- requesting comments on interface References: Message-ID: <43223b17.1061197000@news.oz.net> On Fri, 9 Sep 2005 04:58:43 -0700 (PDT), "C. Barnes" wrote: > >Hi, I'm in the process of writing a Python linear >algebra module. > >The current targeted interface is: > > http://oregonstate.edu/~barnesc/temp/linalg/ > >The interface was originally based on Raymond >Hettinger's >Matfunc [1]. However, it has evolved so that now it >is >nearly identical to JAMA [2], the Java matrix library. > >I am soliticing comments on this interface. > >Please post up any criticism that you have. Even >small >things -- if something isn't right, it's better to fix >it now than later. > Wondering whether you will be supporting OpenGL-style matrices and operations for graphics. UIAM they permit optimizations in both storage and operations due to the known zero and one element values that would appear in full matrix representations of the same. http://www.rush3d.com/reference/opengl-redbook-1.1/appendixg.html Also wondering about some helper function to measure sensitivity of .solve results when getting near-singular, but maybe that's an out-side-of-the package job. >From a quick look, it looks quite nice ;-) Regards, Bengt Richter From cfbolz at googlemail.com Thu Sep 15 07:46:54 2005 From: cfbolz at googlemail.com (Carl Friedrich Bolz) Date: Thu, 15 Sep 2005 13:46:54 +0200 Subject: Software bugs aren't inevitable In-Reply-To: References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <7xwtlkrs4c.fsf@ruckus.brouhaha.com> Message-ID: <3488990505091504467e784f65@mail.gmail.com> Hi! 2005/9/15, Jerzy Karczmarczuk : [snip] > But, I have used myself the cascading version. It was done on purpose, in > order to get to the following solution. > [[I preferred to use a global dict, but other ways of doing it are also > possible]]. > > fibdic={0:0,1:1} > def fibd(n): > if not fibdic.has_key(n): > r=fibd(n-1)+fibd(n-2) > fibdic[n]=r > return fibdic[n] > > And here the recursion limit won't get you!! > But the memoization techniques are rarely taught nowadays... > > ===== > > And the story doesn't end here. There are backtracking solutions, which > in functional (lazy) languages can be emulated through co-recursion, and > in Python by the use of generators. > > Jerzy Karczmarczuk > -- > http://mail.python.org/mailman/listinfo/python-list > It is also possible to do a version that scales logarithmically with n. It relies on the observation that calculation of the fibonacci series can be done by taking the upper left entry of the following matrix exponentiation: n /1 1\ \1 0/ Since exponentiation can be done logarithmically this can be used to calculate fibonacci series faster (at least for big values of n): def mul(m1, m2): ((a, b), (c, d)) = m1 ((e, f), (g, h)) = m2 return [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]] def expo(m, n): if n == 0: return [[1, 0], [0, 1]] if n % 2 == 0: r = expo(m, n//2) return mul(r, r) else: return mul(m, expo(m, n - 1)) def fib(n): return expo([[1, 1], [1, 0]], n)[0][0] With this you can calculate really big fibonacci numbers without increasing the recursion depth, even though the expo function is recursively written. Cheers, Carl Friedrich Bolz From steve at holdenweb.com Wed Sep 28 06:32:26 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Sep 2005 11:32:26 +0100 Subject: PEP 350: Codetags In-Reply-To: <200509270209.06500.hancock@anansispaceworks.com> References: <20050926223521.GE10940@kitchen.client.attbi.com> <200509270209.06500.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > On Monday 26 September 2005 05:35 pm, Micah Elliott wrote: > >>Please read/comment/vote. This circulated as a pre-PEP proposal >>submitted to c.l.py on August 10, but has changed quite a bit since >>then. I'm reposting this since it is now "Open (under consideration)" >>at . > > > Overall, it looks good, but my objection would be: > > >>:Objection: I aesthetically dislike for the comment to be terminated >> with <> in the empty field case. >> >>:Defense: It is necessary to have a terminator since codetags may be >> followed by non-codetag comments. Or codetags could be limited to >> a single line, but that's prohibitive. I can't think of any >> single-character terminator that is appropriate and significantly >> better than <>. Maybe ``@`` could be a terminator, but then most >> codetags will have an unnecessary @. > > > The <> terminator is evil. People will hate that. If there are no fields, > you should just be able to leave it off. This will have an additional > advantage in that many will already have compliant codetags if you leave > off this requirement. > > You worry over the need to detect the end of the block, but wouldn't '\n\n' > be a much more natural delimiter? I.e.: > > # TODO: This is a multi-line todo tag. > # You see how I've gone to the next line. > > # This, on the other hand is an unrelated comment. You can tell it's not > # related, because there is an intervening blank line. I think people > # do this naturally when writing comments (I know I do -- I'm fairly > # certain I've seen other people do it). > # > # Whereas, as you can see, a mere paragraph break can be represented by > # a blank comment line. > # > # Whitespace formatting, after all, is VERY PYTHONIC. ;-) > # Delimiters on the other hand -- well, we prefer not to mention > # the sort of languages that use those, right? ;-) > +1 > Another possibility is to recognize lines like: > > #--------------------------------------- > #*************************************** > #======================================= > > I.e. a comment mark followed by a line composed of repeating characters > as an alternative separator. These are also pretty in pretty common > use. > -0 regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From jepler at unpythonic.net Tue Sep 27 14:26:17 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 27 Sep 2005 13:26:17 -0500 Subject: Getting a number out of a string In-Reply-To: <1127844971.471405.172860@g47g2000cwa.googlegroups.com> References: <1127844971.471405.172860@g47g2000cwa.googlegroups.com> Message-ID: <20050927182617.GA31612@unpythonic.net> You can index into a string: >>> s = '06897' >>> s[2] '8' You can also turn each character into an integer, in various ways: >>> [int(c) for c in s] [0, 6, 8, 9, 7] >>> map(int, s) [0, 6, 8, 9, 7] Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From noway at sorry.com Sat Sep 3 18:13:43 2005 From: noway at sorry.com (Giovanni Bajo) Date: Sat, 03 Sep 2005 22:13:43 GMT Subject: ANN: PyInstaller 1.0 in the works: package your Python app into a single-file executable Message-ID: Hello, http://pyinstaller.hpcf.upr.edu/ PyInstaller is a program that packages Python programs into stand-alone executables, under both Windows and Linux. This is similar to the famous py2exe, but PyInstaller is also able to build fully-contained (single file) executables, while py2exe can only build directories containing an executable with multiple dynamic libraries. PyInstaller is an effort to rescue, maintain and further develop Gordon McMillan's Python Installer (now PyInstaller). Their official website is not longer available and the original package is not longer maintained. Believing that it is still far superior to py2exe we have setup this page to continue its further development. We have just begun development on PyInstaller. Feel free to join us in the effort! Please consult our Roadmap (http://pyinstaller.hpcf.upr.edu/pyinstaller/roadmap) to check our plans. -- Giovanni Bajo From hyakugei at gmail.com Thu Sep 29 15:19:03 2005 From: hyakugei at gmail.com (Jos) Date: 29 Sep 2005 12:19:03 -0700 Subject: Using Asyncore/chat for game server question. Message-ID: <1128021543.080543.29570@g49g2000cwa.googlegroups.com> Hello all. I have a working server, using the asyncore/chat module, which enables logging in, rooms and private messaging. I've used this framework to make some simple games that only required message broadcasting via the server. I'd now like to move the game logic into the server. My recent reading includes the article "Multithreaded Game Scripting with Stackless Python" http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/ I'm not so interested in moving to Stackless, although i've also been looking at Nanothreads offered in the "Lightweight Game Toolkit" as a way to implement the above ideas in plain python. http://lgt.berlios.de/#nanothreads However, that's a bit off from my Question. So here is is: How do i enable the/a game object, running on the server, to send messages "on its own". I understand that the asyncore module is based on the "Reactor" design, which is, duh, reactive rather then active... So how do i make my server "active" ;). A simple example would be a server based on asyncore, with multiple connections, which broadcasts a "pulse" to the connected clients every second. Thanks for any help, pointers, words of advice, etc etc! Jos From tste3576 at bellsouth.net Fri Sep 9 14:19:40 2005 From: tste3576 at bellsouth.net (fchef) Date: 9 Sep 2005 11:19:40 -0700 Subject: working with multiple frame instances Message-ID: <1126289980.428233.201980@o13g2000cwo.googlegroups.com> I am looking for some advice on working with Multiple frame instances. Essentially I need to be able to refer to specific control values in a frame and be able to hide/show a specific frame. In VB you can reference a particular frame with something like Controls.Form("My form").DoSomething. Is there something analogous to this in Python? Or is there a better approach all together? From hancock at anansispaceworks.com Fri Sep 23 12:20:31 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 23 Sep 2005 11:20:31 -0500 Subject: What is "self"? In-Reply-To: <4334224E.8050800@commonlawgov.org> References: <43335c5f$1_4@alt.athenanews.com> <200509230948.19033.hancock@anansispaceworks.com> <4334224E.8050800@commonlawgov.org> Message-ID: <200509231120.31411.hancock@anansispaceworks.com> On Friday 23 September 2005 10:42 am, Peter wrote: > Terry Hancock wrote: > >How exactly is that? Anybody who uses "i" as a variable name for > >anything other than an innermost loop index is a sick and twisted > >code sadist. > > > Agreed, though to say "code sadist" is a little hard don't ya think? ;) I don't know, I thought it quite poetic. ;-) > >You'd prefer what? "count" or "kount" or "i_am_an_innermost_loop_index_counter". > >I mean "explicit is better than implicit", right? > > > >Maybe Fortran warped my brain, but I just don't see the benefit here. > > > Me ither. > > I am no english professor, but isn't the word "i" usualy pointed at > something you will, have, can, or can't do in english? > "me" or "self" or "this" or "my" or "cls" or "inst" are refering to just > the object, nothing more, nothing less (except for "my" which is like > referring to "something i own") and are much more human-comprehendable. > IMHO. Whoa, you totally lost me there, dude. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From johnnyandfiona at hotmail.com Fri Sep 30 04:08:52 2005 From: johnnyandfiona at hotmail.com (Johnny Lee) Date: 30 Sep 2005 01:08:52 -0700 Subject: A problem while using anygui Message-ID: <1128067732.572142.251830@z14g2000cwz.googlegroups.com> Hi, I've met a problem while using anygui to create a GUI. Here is a brief example from Dave: ### def guidialog(): def ok(**kw): win.destroy() app.remove(win) # anygui.link(btn_ok, ok) # app.run() return n #qtgui will NEVER get here ### As you can see, the program will never get the sentence "return n". I googled for the problem but didn't find much help. So any one here could give me a hand? thanks regards, Johnny From elke.hohls at delair.de Fri Sep 30 06:57:10 2005 From: elke.hohls at delair.de (Elke Hohls) Date: Fri, 30 Sep 2005 12:57:10 +0200 Subject: Python-list Digest, Vol 24, Issue 451 In-Reply-To: References: Message-ID: <433D1A06.1050005@delair.de> Sorry, the last line is wrong: PySDLXMLNodeType = PyMyType ..above the correction // == PyMyExtention.c ================================================= . : typedef struct { PyObject_HEAD long lAttribute; } PyMyObject; static PyObject* PyMyObject_NewC (long lAttribute) { PyMyObject *self; PyMyObject *type; self = new PyMyObject self->lAttribute = lAttribute; return (PyObject*)self; } static PyMethodDef PyMyObject_methods[] = { {"PyMyObject_NewC", (PyCFunction)PyMyObject_NewC, METH_NOARGS, "Create PyMyObject_NewC from C-Code"}, {NULL} /* Sentinel */ }; : static PyTypeObject PyMyType = { PyObject_HEAD_INIT(NULL) : }; //===================================================================/ python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > > ------------------------------------------------------------------------ > > Today's Topics: > > 1. Re: Soap Question (WSDL) (Adriaan Renting) > 2. Re: Will python never intend to support private, protected > and public? (Gregor Horvath) > 3. return (PyObject*)myPyType; ...segmentation fault! (elho) > 4. Re: Self reordering list in Python (zooko) > > > ------------------------------------------------------------------------ > > Subject: > Re: Soap Question (WSDL) > From: > "Adriaan Renting" > Date: > Fri, 30 Sep 2005 11:22:36 +0200 > To: > > > To: > > > > You need the WSDL file if you want external probrams to be able to discover what WebService you are running, so it depends on your need if you need to use one. You can perfectly run a SOAP service without a WSDL file, using SOAPpy, only then external programs do not have a way to find out how to talk to you. > A WSDL file just defines what messages, operations, urls etc. you accept/send/offer. > If your external applications know how to talk to you, you can do without a WSDL file. > > It contains stuff like: > > > > ... > > > > > > > > > > > > > > >>>>"Armin" 09/30/05 12:56 am >>> > > Hey everyone, > > I am trying to write a web app. that connects to flickr using SOAP. The > book 'Dive into python' says I need to have a WSDL file to connect, > while the only useful soap related url flickr api > (flickr.com/services/api) provides is the following: > > The SOAP Server Endpoint URL is http://www.flickr.com/services/soap/ > > What am I supposed to do here? Help is very much appreciated at this > point. > > Thanks, > Armin > > > > ------------------------------------------------------------------------ > > Subject: > Re: Will python never intend to support private, protected and public? > From: > Gregor Horvath > Date: > Fri, 30 Sep 2005 11:31:59 +0200 > To: > python-list at python.org > > To: > python-list at python.org > > > Paul Rubin wrote: > >> Gregor Horvath writes: > > >>> Someone has a problem and tweaks a private variable as a workaround. >> >> >> They should have patched the source instead. >> > > I think they are going to do that. In the meantime our friend has a > working solution otherwise he would have nothing but broken code today. > >> >> Believe it or not, not all development environments are that >> disorganized. > > > Martians? > Examples? > > This has nothing to do with organisation but a lot with natural > influances and constraints of software development (except really simple > programs) > > -- > Greg > > > ------------------------------------------------------------------------ > > Subject: > return (PyObject*)myPyType; ...segmentation fault! > From: > elho > Date: > Fri, 30 Sep 2005 11:50:42 +0200 > To: > python-list at python.org > > To: > python-list at python.org > > > I called a own python type 'PyType' with a c function and returned it > into my python programm - there it fault. > It is said that the object has a NULL-Pointer when I try to debug it? > > Here are the importent snips from my code: > > > // == test.py ========================================================= > . > : > myNewPyType = PyMyExtention.GetValue ("xxx") > # printings for testing > print "...back to python... test.py" > print "pp\t ...PyMyType.PyMyObject:", type(tySdlXml) > //===================================================================/ > > > // == PyMyExtention.c ================================================= > . > : > static PyObject* wrap_GetValue (PyObject* self, PyObject* args) > { > char* pchXXX; > if (!PyArg_ParseTuple(args, "s", &pchXXX)) > { > return 0; > } > > long llong = CFunktion::CallMe(pchXXX); > > // returning Python-Objekt > PyObject *pyType = PyMyObject_NewC (llong); > cout << "cc ..." << ((PyMyType*)pyType)->lAttribute << endl; > cout << "\t ...proof object-valid pointer?" << (void*)pyType << endl; > return (PyObject*)pyType; > } > . > : > //===================================================================/ > > > // == PyMyExtention.c ================================================= > . > : > typedef struct { > PyObject_HEAD > long lAttribute; > } PyMyObject; > > static PyObject* PyMyObject_NewC (long lAttribute) > { > PySDLXMLNode *self; > PySDLXMLNode *type; > > self = new PySDLXMLNode; > self->lAttribute = lAttribute; > > return (PyObject*)self; > } > > static PyMethodDef PyMyObject_methods[] = { > {"PyMyObject_NewC", (PyCFunction)PyMyObject_NewC, METH_NOARGS, > "Create PyMyObject_NewC from C-Code"}, > {NULL} /* Sentinel */ > }; > > : > > static PyTypeObject PySDLXMLNodeType = { > PyObject_HEAD_INIT(NULL) > : > }; > //===================================================================/ > > > // ::: output :::::::::::::::::::::::::::::::::::::::::::::::::::: > > cc ...135603272 > t ...proof object-valid pointer?: 0x8165940 > ...back to python... test.py > Segmentation fault > > //===================================================================/ > > > ...you see: It returns to python but over there the object is something > bad. So what is wrong? > > > ------------------------------------------------------------------------ > > Subject: > Re: Self reordering list in Python > From: > "zooko" > Date: > 30 Sep 2005 02:54:08 -0700 > To: > python-list at python.org > > To: > python-list at python.org > > > I've implemented such an LRU Cache in Python. My technique was to > weave a doubly-linked list into the dict, so that it is O(dict) for all > LRU operations. I benchmarked it against someone's Python-list-based > implementation from the ActiveState cookbook and noted that on my > machine the better constant factors of the Python list win out when the > list is cache contains fewer than about 16000 elements. Of course, > once you exceed that cross-over point, the asymptotically worse > behavior of the list-based implementation becomes a big factor. If you > have more than 16000 or so elements then you really oughtn't use a > list-based LRU cache. > > http://zooko.com/repos/pyutil/pyutil/pyutil/cache.py > > I haven't benchmarked it against Evan Podromou's heap implementation > yet, but obviously inserting and removing things from a heapq heap is > O(N). > > You can find unit tests and benchmarking tools in the pyutil/test > directory. > > Regards, > > Zooko > > P.S. I read this list sporadically, so if you want me to read your > response, please Cc: zooko at zooko.com. Thanks. > > > -- Kind regards / Mit freundlichen Gr??en Elke Hohls -------------------------------------------------------------------------- Elke Hohls delair Air Traffic Systems GmbH Lilienthalplatz 3 38108 Braunschweig Germany Tel: +49 (0)531 215 36-210 Fax: +49 (0)531 215 36-19 E-mail: elke.hohls at delair.de http://www.delair.de From lycka at carmen.se Tue Sep 27 13:39:30 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 27 Sep 2005 19:39:30 +0200 Subject: Carrying variables over from function to function In-Reply-To: References: Message-ID: Ivan Shevanski wrote: > Thanks for your quick responce Roy, thats exactly what I needed. =) No, it isn't! ;) It might seem like a good idea right now, but it's not a good choice in the long run. It's like peeing in bed: Initially it's both a relief and you get warm and cosy, but you'll end upp with a mess that you (or someone else) will need to clean up later. Sure, it's unproblematic in this tiny example, but it's a bad habit to rely on global variables in cases that are easily solved without them. The obvious solution in your case is to just pass on the variable you need. There are several problems with globals that will become appearent as your code grows bigger, and you can't see all details in the program in the same instant. Your global namespace will get cluttered by a lot of names that are used far away in the code, the code in your functions will become difficult to understand, and it will be more difficult to see how the functions interact to each other. Your programs will also be brittle, since a change in one place is more likely to break some other code in another place in your program. Besides, if your code relies on changing global variables, your functions get very restricted: You can't have two or more sets of data being modified by these functions at the same time. It's pretty common in Python, that people use global variables for objects that are really constants (although Python won't enforce that) and it's common that these varaible names are written with CAPS. There are also cases where we want to keep some kind of module global state, and globals can be used for that, but it should be used only when needed. I just scanned through 55 000 lines of Python code in 276 files here at work, and found about a dozen occurences of the global keyword. In other words, it's very uncommon here that we use global variables that aren't just constants. The normal way to share data between functions is to pass data in as arguments, and out as return values. If you want objects to keep state between function calls without passing them around, consider using object-oriented code, but lets wait a bit with that. Anyway, here are two examples of a small program using globals or passing parameters. # Global version def getYear(): global year year = None while year is None: try: year = int(raw_input(prompt)) except ValueError: pass def calcAge(): global age age = current_year - birth_year def printAge(): print "*"*age print "You are", age, "years." def main(): global prompt prompt = 'What year were you born? ' getYear() global birth_year birth_year = year prompt = 'What year is it now? ' getYear() global current_year current_year = year calcAge() printAge() main() # Parameter passing version def getYear(prompt): year = None while year is None: try: year = int(raw_input(prompt)) except ValueError: pass return year def calcAge(start, end): return end - start def printAge(age): print "*"*age print "You are", age, "years." def main(): birth_year = getYear('What year were you born? ') current_year = getYear('What year is it now? ') age = calcAge(birth_year, current_year) printAge(age) main() In this case, the fact that getYear() in the global version assigns to the global "year" when you need to work with two different year is an inconvenience. If you imagine that you'd do something like "when was X born, when was Y born, when was Z born, then Y is oldest", you'll see that it's really stupid to have your functions write to globals instead of returning values directly to the caller of the function. From ccurvey at gmail.com Thu Sep 15 11:04:15 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 15 Sep 2005 08:04:15 -0700 Subject: brain cramp: emulating cgi.FieldStorage In-Reply-To: <1126793506.904795.222000@g49g2000cwa.googlegroups.com> References: <1126793506.904795.222000@g49g2000cwa.googlegroups.com> Message-ID: <1126796655.880567.318670@g44g2000cwa.googlegroups.com> figured it out... os.environ["QUERY_STRING"] = "foo=bar" fs = cgi.FieldStorage() functionToBeTested(fs) From fuzzyman at gmail.com Sun Sep 11 15:32:36 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Sep 2005 12:32:36 -0700 Subject: CGIHTTPServer, popen3, and windoze Message-ID: <1126467156.398627.275750@f14g2000cwb.googlegroups.com> Hello all, I may well post this a a bug on Monday (after testing with Python 2.3) - but I thought I'd post here to see if anyone has any ideas. The basic problem is that under Python 2.4 (and windoze XP SP2) CGIHTTPServer isn't passing the CGI environment variables to scripts it runs. I've checked that the environment variables all exist in os.environ before the subprocess is launched using popen3. I've *also* checked that when I launch a test subprocess using popen3 myself, environment variables *are* passed on - so I'm a bit confused... I wonder if anyone can shed any light on this behavior ? All the best, Fuzzyman http://www.voidspace.org.uk/python P.S. I've also patched CGIHTTPServer so that it can handle paths wih spaces and CGIs in subdirectories of the 'cgi-bin' folder. I'll *suggest* these changes to the maintainers - but my tests were on the original version. From jgrahn-nntq at algonet.se Sat Sep 3 12:15:25 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 3 Sep 2005 16:15:25 GMT Subject: How to identify which interface a broadcast packet comes in on? References: Message-ID: On Sat, 03 Sep 2005 18:46:05 +0800, Lincoln Yeoh wrote: > Hi, > > If I have a program listening on 0.0.0.0:(someport) on all interfaces, > how do I know which network interface a broadcast packet is coming in > on - assuming Linux and _many_ interfaces. And how do I set which > interface a frame will leave on, assuming I'm sending a raw frame (no > IP address, just the ethernet address). > > If I use C, it seems I'm to use the IP_PKTINFO socket options, > send/recv the ancillary messages and set/check the ipi_ifindex value. ... > How would I achieve the same thing in Python? Someone may want to correct me, but from what I can see, the socket module is almost a 1:1 mapping between the socket support your C lib has, and Python. Plus some compatibility code for Windows. You should be able to do everything you can do in C. Your code may become Linux-specific if you're not careful, though. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From correia_jREMOVECAPS at hotmail.com Tue Sep 27 21:01:25 2005 From: correia_jREMOVECAPS at hotmail.com (J Correia) Date: Wed, 28 Sep 2005 01:01:25 GMT Subject: Human readable number formatting References: <1127862406.11827.2.camel@localhost.localdomain> Message-ID: "Alex Willmer" wrote in message news:1127862406.11827.2.camel at localhost.localdomain... > When reporting file sizes to the user, it's nice to print '16.1 MB', > rather than '16123270 B'. This is the behaviour the command 'df -h' > implements. There's no python function that I could find to perform this > formatting , so I've taken a stab at it: > > import math > def human_readable(n, suffix='B', places=2): > '''Return a human friendly approximation of n, using SI prefixes''' > prefixes = ['','k','M','G','T'] > base, step, limit = 10, 3, 100 > > if n == 0: > magnitude = 0 #cannot take log(0) > else: > magnitude = math.log(n, base) > > order = int(round(magnitude)) // step > return '%.1f %s%s' % (float(n)/base**(order*step), \ > prefixes[order], suffix) > > Example usage > >>> print [human_readable(x) for x in [0, 1, 23.5, 100, 1000/3, 500, > 1000000, 12.345e9]] > ['0.0 B', '1.0 B', '23.5 B', '100.0 B', '0.3 kB', '0.5 kB', '1.0 MB', > '12.3 GB'] > > I'd hoped to generalise this to base 2 (eg human_readable(1024, base=2) > == '1 KiB' and enforcing of 3 digits at most (ie human_readable(100) == > '0.1 KB' instead of '100 B). However I can't get the right results > adapting the above code. > > Here's where I'd like to ask for your help. > Am I chasing the right target, in basing my function on log()? > Does this function already exist in some python module? > Any hints, or would anyone care to finish it off/enhance it? > > With thanks > > Alex > > This'll probably do what you want with some minor modifications. def fmt3(num): for x in ['','Kb','Mb','Gb','Tb']: if num<1024: return "%3.1f%s" % (num, x) num /=1024 >>> print [fmt3(x) for x in [0, 1, 23.5, 100, 1000/3, 500, 1000000, 12.345e9]] ['0.0', '1.0', '23.5', '100.0', '333.0', '500.0', '976.6Kb', '11.5Gb'] HTH. From lycka at carmen.se Tue Sep 13 12:34:09 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 13 Sep 2005 18:34:09 +0200 Subject: Launching Python programs from Linux shell script In-Reply-To: <1126533765.007072.257980@g43g2000cwa.googlegroups.com> References: <1126279887.147197.170670@g43g2000cwa.googlegroups.com> <1126533765.007072.257980@g43g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > Thanks! How do you add Python in Linux to the path? This works out of the box in most modern Linux distributions. If you're open to suggestions, I'd suggest that you have a look at Ubuntu. It's a user friendly Linux distribution with rather close ties to the Python community. Anyway, if Python is installed in a non-standard location on your machine, you might need to set up two things: PATH to the directory containing the python binary. PYTHONPATH to the directories containing Python modules and packages. How to do this has nothing to do with Python, it just depends on what shell(s) you use in Linux, and this is frankly not the forum for that. See e.g. http://docs.python.org/tut/node4.html and http://www.python.org/doc/tut/node8.html for more about PATH and PYTHONPATH--actually, it might be a good idea to read the whole tutorial if you're a beginner. From russandheather at gmail.com Tue Sep 27 18:11:57 2005 From: russandheather at gmail.com (Qopit) Date: 27 Sep 2005 15:11:57 -0700 Subject: Overhead of individual python apps Message-ID: <1127859117.870343.96740@g44g2000cwa.googlegroups.com> I'm setting up a system that consists of several small python applications that all communicate amongst each other on the same pc. When running in Windows, launching each application generates a process, and each of those processes ends up taking up > 4MB of system memory. This memory usage is as reported by the Windows Task manager for the python.exe image name. My Question: Is there any way to reduce this per-process overhead? eg: can you set it somehow so that one python.exe instance handles multiple processes? One possibility considered is to run them as threads of a single process rather than multiple processes, but this has other drawbacks for my application and I'd rather not, Another possibility I considered is to strip out all but the most essential imports in each app, but I tested this out and it has marginal benefits. I demonstrated to myself that a simple one liner app consisting of 'x = raw_input()' still eats up > 2.7MB . I also tried -O but it, not surprisingly, did nothing for the one-liner. I'm simply running the .py files and I am still on v2.3 All help appreciated! Thanks, Russ From steve at holdenweb.com Mon Sep 26 14:32:25 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 26 Sep 2005 19:32:25 +0100 Subject: The ^ operator In-Reply-To: <1127758172.599605.325390@g14g2000cwa.googlegroups.com> References: <1127758172.599605.325390@g14g2000cwa.googlegroups.com> Message-ID: Tuvas wrote: > What exactly does the ^ operator do? I've seen, for example, that > 3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are > not equal, and if they are equal, outputs 0, or what? Thanks! > ^ is the "bit XOR" operation. It treats its left and right operands as binary numbers: the result has a one-bit in those bit positions where one operand has a zero and the other has a one. A B | A XOR B ----+-------- 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 0 If you want exponentiation, try **. >>> 3**4 81 >>> 3**5 243 >>> 3**6 729 >>> 3**7 2187 >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From eargon at gmail.com Sun Sep 25 18:50:07 2005 From: eargon at gmail.com (Eyual Getahun) Date: Sun, 25 Sep 2005 15:50:07 -0700 Subject: Find out if host is alive Message-ID: <9fad6361050925155037c91b11@mail.gmail.com> What is the fastest way to find out a host is alive should i make a sys call and ping or is thier an easier way -------------- next part -------------- An HTML attachment was scrubbed... URL: From michaels at rd.bbc.co.uk Wed Sep 21 07:58:32 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Wed, 21 Sep 2005 12:58:32 +0100 Subject: Crypto.Cipher.ARC4, bust or me doing something wrong? References: <7x8xxqdbpk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Michael Sparks writes: >> I'm looking at using this library and to familiarise myself writing >> small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 >> I've found that I can't get it to decode what it encodes. This might >> be a case of PEBKAC, but I'm trying the following: > > You have to reinitialize the cipher state for decryption, as someone > else explained. You also have to make sure that keys are unique and > independent for separate messages. Hmm... Thanks for this. > For most applications you probably > want to think about adding authentication. Indeed - though I'm working bottom up. How a key gets transfered from a to b safely will be another step. Another one will be how to trust that exchange, for how long, and how much, etc. I'm well aware that this is a well trod area though, hence why I'm working bottom up. > In general you shouldn't > use arc4 unless you know what you're doing. Having looked at how it works from a user perspective, it's fairly inappropriate anyway, due to wanting to work over unreliable channels anyway. > What's the application? Components for secure communications and identity confirmation. Use cases: * Signing content multicast by the BBC to indicate that it came from the BBC. (ohh, so many issues :-) * Signing content captured on a mobile device such that we know that it came from that mobile. Specific high level use case of that is to be able to accept contributions from people from arbitrary devices and know who they came from. Perhaps embedded in the essence. * Related to that would be the ability to tag content with rights [1] information, and to know it's not been tampered with. [1] eg Who created it. When? Has it been published/broadcast or not? When? Have additional rights over and above fair use/dealing been granted (eg creative commons attribution license). * Similarly people want the ability to protect data in transit between trusted end points. Some people using the system would probably be looking to build restrictions management as well, but that's largely beyond the scope of our system. Indeed restrictions management would require breaking our system. For these use cases to work, encryption & digest tools are clearly an option, and hence having components that support encryption and digest are (to say the least) useful. They're obviously not the only techniques though. Rather than re-inventing wheels I thought I'd pick a library sit down and see how pycrypt's meant to be used before actually going anyway. (Amongst other reasons, this is why I suspected me, rather than the library :-) Given the pycrypt library docs page starts off with: "This documentation assumes you have some basic knowledge about the Python language, but not necessarily about cryptography." I do for example know enough about cryptography to know that me devising my own approach is foolhardy. Thus the statement above appealed :) As a result I decided to sit down and learn how to use this to form some basic components for encryption/decryption. Given another part early in the docs was """A central goal of the author's has been to provide a simple, consistent interface for similar classes of algorithms.""" I decided to start off with "sketches" implementing minimal examples for each digest and cipher. I'm now working through the Public Key examples. FWIW, I'm well aware how easy it is to get cipher/digest/etc based security/id systems wrong. I'm really starting with pycrypt because it looked simple enough, low level enough and self contained enough to act as a base for working with existing more complex systems. I supsect we'll end up looking at or wrapping some other library instead/as well, but it struck me as a nice starting point. Anyway, once I've gone through all of the existing digests/ciphers/PK ciphers, I'll post the snippets up on our site as raw examples for pycrypto, which will hopefully be a) correct usage b) be useful to others. Thanks for the comments, Michael. -- Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From duncan.booth at invalid.invalid Thu Sep 8 04:10:15 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Sep 2005 08:10:15 GMT Subject: generator object, next method References: <1126164425.475226.143510@g14g2000cwa.googlegroups.com> Message-ID: simonwittber at gmail.com wrote: > >>>> gen = iterator() >>>> gen.next > >>>> gen.next > >>>> gen.next > >>>> gen.next > >>>> gen.next is gen.next > False > > > What is behind this apparently strange behaviour? (The .next method > seems to alternately bind to two different objects) It is a combination of factors. 1) Every time you access gen.next you create a new method-wrapper object. 2) Typing an expression at the interactive prompt implicitly assigns the result of the expression to the variable '_' 3) When the method-wrapper is destroyed the memory becomes available to be reused the next time a method-wrapper (or other object of similar size) is created. So in fact you have 6 different objects produced by your 6 accesses to gen.next although (since you never have more than 3 of them in existence at a time) there are probably only 3 different memory locations involved. From siona at chiark.greenend.org.uk Tue Sep 13 11:36:51 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Sep 2005 16:36:51 +0100 (BST) Subject: round() wrong in Python 2.4? References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Message-ID: Nils Grimsmo wrote: >Why did round() change in Python 2.4? > >$ python2.3 >Python 2.3.5 (#2, Jun 19 2005, 13:28:00) >[GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2 >>>> round(0.0225, 3) >0.023 >>>> "%.3f" % round(0.0225, 3) >'0.023' >>>> >$ python2.4 >Python 2.4.1 (#2, Jul 12 2005, 09:22:25) >[GCC 4.0.1 (Debian 4.0.1-1)] on linux2 >>>> round(0.0225, 3) >0.021999999999999999 >>>> "%.3f" % round(0.0225, 3) >'0.022' >>>> > >(Is this due to the different GCC used?) That would look like a good guess to me: $ python Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> round(0.0225, 3) 0.023 >>> "%.3f" % round(0.0225, 3) '0.023' >>> Is that python2.4 of yours from the python2.4 package or one you compiled up yourself? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From theller at python.net Tue Sep 13 04:15:18 2005 From: theller at python.net (Thomas Heller) Date: Tue, 13 Sep 2005 10:15:18 +0200 Subject: Using Python with COM to communicate with proprietary Windows software References: Message-ID: <8xy18ju1.fsf@python.net> Joakim Persson writes: > On Fri, 09 Sep 2005 08:36:00 +0200, Thomas Heller > wrote: > >>Sounds like a perfect job for comtypes, which is a COM library >>implemented in pure Python, based on ctypes. comtypes should make it >>easy to access custom (non-dispatch derived) com interfaces, or the >>vtable based part of dual interfaces - it would be good however, if you >>have a type library for the interfaces. >> >>http://sourceforge.net/projects/comtypes/ >> >>No docs yet, but there are tests included which should get you started. >> >>(I have released and announced this 3 weeks ago, but haven't got a >>single feedback. So it seems the need to access custom interfaces is >>very low.) >> >>Thommas > > After some testing today, it does seem to do exactly what I wanted -- > I can now access the "custom" but IDispatch-like COM interface that I > couldn't access with win32com (or with Java + jawin). It might be > possible in other ways, but using comtypes was definitely the most > painfree way (everything, including the return values from the > methods, worked as expected). Thank you very much. > > Of course, this does not complete my task -- although I can now use my > interface to send messages and commands to the big log tool, I still > need to implement a COM server and pass a pointer to its interface > through one of the messages to the com server to be able to receive > data: > > BridgeInterface.StartLogging(filename) <--- works fine, didn't work > before > BridgeInterface.Advise(ptr) <--- Now, I need to create a new > interface for receiving the data sent from the log application, so > that I can (at first) print it > > This _shouldn't_ be too difficult -- I know which methods must be > implemented (basically just some kind of event handling to deal with > randomly arriving log points, should be implemented as "onMsg()" on my > COM server side, and some other similar methods), but I don't really > know how. I have tried doing simple COM servers using win32com, but is > it equally possible to implement such a simple thing in comtypes? I > didn't find any server side examples in comtypes, but perhaps there is > a way? There is not yet any server support in comtypes, but it will be added. In the meantime you could use the ctypes.com package that is included in ctypes itself, there are even samples. Thomas From peter at engcorp.com Thu Sep 8 20:39:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Sep 2005 20:39:17 -0400 Subject: Video display, frame rate 640x480 @ 30fps achievable? In-Reply-To: <1126220191.485416.32770@f14g2000cwb.googlegroups.com> References: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> <1126220191.485416.32770@f14g2000cwb.googlegroups.com> Message-ID: Guenter wrote: > I would be interested in how many frames this reaches on my computer. > Did you create like two arbitrary images under PLI and then display > them one after another? Then stop the time and count how many times you > were able to switch between the two? > > One feature I need to figure out when using PLI is that I need to move > a cursor over the image, controlled by a joystick. But I could add that > with the drawing feature when creating the image. Maybe it would be a good idea to tell us something about the nature of the image you'll be displaying (though the fact that it needs a cross-hair or something is useful information, for a start). For example, is it a photographic image? A map? A drawing? Is it generated dynamically, or is it static? Do you pan over it, or zoom it, or what? -Peter From steve at REMOVETHIScyber.com.au Fri Sep 30 06:50:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 30 Sep 2005 20:50:10 +1000 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xzmpwuxd0.fsf@ruckus.brouhaha.com> <20050930075313.67b9b676.jk@ospaz.ru> Message-ID: On Fri, 30 Sep 2005 06:31:44 +0200, Fredrik Lundh wrote: > en.karpachov at ospaz.ru wrote: > >> Looks like you must know every one of the base classes of the NotSoSecret, >> whether there is some base class named Secret? And, if so, you must also >> know these classes _implementation_ > > that information isn't hidden, so there's nothing "you must know". finding out > is a matter of writing a very small program, or tinkering at the interactive prompt > for a couple of seconds. Which of course is only possible because Python does not hide information, it uses semi-private attributes rather than secret private ones, and allows close to full introspection. Still, en.karpachov at ospaz.ru's point that you must know the base classes is correct. It is *easy* to find them out (NotSoSecret.__bases__ should do it), but if you don't you are taking a chance that your class name doesn't clash with one of the bases. In other words, this is a Gotcha, not a world-shattering disaster. -- Steven. From free.condiments at gmail.com Fri Sep 9 22:09:35 2005 From: free.condiments at gmail.com (Sam Pointon) Date: 9 Sep 2005 19:09:35 -0700 Subject: Redundant code in multiple methods In-Reply-To: <1126292646.472895.259480@g44g2000cwa.googlegroups.com> References: <1126292646.472895.259480@g44g2000cwa.googlegroups.com> Message-ID: <1126318175.710895.292550@z14g2000cwz.googlegroups.com> How about using a class, with __call__, as a wrapper instead of the function itself? class FunctionWrapper(object): def __init__(self, cls, function): self._function = function self._cls = cls def __call__(self, *args, **kwargs): REQUEST = self.REQUEST SESSION = REQUEST.SESSION dbConnection = self._cls.getDBConnection() logger = self._cls.getLogger() trackStatsHere() # set up some local variables here # change some global variables here try: return self._function(self._cls, *args, **kwargs) except: raise "handle the error here" finally: dbConnection.close() class User(object): def __init__(self): def View(cls, self, localvariables): #Needs the cls argument before self to take the FunctionWrapper first argument myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc self.View = FunctionWrapper(self, View) def Edit(cls, self): #Ditto myHtmlDoc = """make the htmldocument here using all of the previous variables""" # play with data here return myHtmlDoc self.Edit = FunctionWrapper(self, Edit) #the rest of the class From steve at holdenweb.com Mon Sep 5 17:10:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Sep 2005 17:10:05 -0400 Subject: Possible improvement to slice opperations. In-Reply-To: <7xfysjb83b.fsf@ruckus.brouhaha.com> References: <0BZSe.13427$xl6.12703@tornado.tampabay.rr.com> <7xfysjb83b.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > >>Given that Python has a 1's-complement operator already I don;t see >>why you can't just leave Python alone and use it, > > > What's the meaning of the 1's complement operator (for example, what > is ~1), when ints and longs are the same? Python 2.2.1 (#1, Aug 25 2004, 16:56:05) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ~1L -2L >>> ~1 -2 >>> import sys >>> sys.maxint*4 8589934588L >>> ~(sys.maxint*4) -8589934589L >>> $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> ~1L -2L >>> ~1 -2 >>> sys.maxint*4 8589934588L >>> ~(sys.maxint*4) -8589934589L >>> What's going to change when ints and longs are finally integrated? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mrosenstihl at t-online.de Wed Sep 21 06:53:31 2005 From: mrosenstihl at t-online.de (Markus Rosenstihl) Date: Wed, 21 Sep 2005 12:53:31 +0200 Subject: How to copy a file from one machine to another machine References: Message-ID: Hi I think scp is also a solution. I am sure there exist free sshserveres for windows. THat would make the stuff a bit more secure, and the login can be automated via public-key. Regards Markus From grblanco at gmail.com Fri Sep 16 15:31:46 2005 From: grblanco at gmail.com (JerryB) Date: 16 Sep 2005 12:31:46 -0700 Subject: Dictionary sorting problem Message-ID: <1126899106.189220.209940@o13g2000cwo.googlegroups.com> Hi, I have a dictionary for counting ocurrences of strings in a document. The dictionary looks like this: 'hello':135 'goodbye':30 'lucy':4 'sky':55 'diamonds':239843 'yesterday':4 I want to print the dictionary so I see most common words first: 'diamonds':239843 'hello':135 'sky':55 'goodbye':30 'lucy':4 'yesterday':4 How do I do this? Notice I can't 'swap' the dictionary (making keys values and values keys) and sort because I have values like lucy & yesterday which have the same number of occurrences. Thanks. From giles_brown at hotmail.com Mon Sep 26 04:23:17 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 26 Sep 2005 01:23:17 -0700 Subject: Would this be Guido's pen? References: Message-ID: <1127722997.338478.307440@f14g2000cwb.googlegroups.com> Yeah and of course http://www.masterlock.com/promos/python/8413python_lock.shtml is Guido's security cable too. Giles From apocode at gmail.com Fri Sep 30 10:39:05 2005 From: apocode at gmail.com (Abdullah Yoldas) Date: Fri, 30 Sep 2005 16:39:05 +0200 Subject: How to learn DNS Server's IP address Message-ID: <72bbd9be0509300739w33d45fbdk448d15c11959eba9@mail.gmail.com> How can I learn the DNS Server's IP address for my network, programmatically? The idea is to learn DNS Server IP and initialize medusa.resolveraccordingly. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lamthierry at gmail.com Wed Sep 14 10:13:50 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 14 Sep 2005 07:13:50 -0700 Subject: Writing at the beginning of a file Message-ID: <1126707230.693569.187200@g49g2000cwa.googlegroups.com> Let's say I already wrote a file and have the following: testing testing testing testing testing testing Is there an easy way to write something of variable length at the top of the file? For example, 6 testing written testing testing testing testing testing testing I tried to write some garbage on top right after opening the file and then use seek to overwrite the garbage, but since the string to be written can be of variable length, I'm not sure how much garbage I have to write initially. The other way to do what I want is to write the whole thing to a new file, but I want to skip that method if there's an alternative way. Another way of doing it is to buffer the whole file writing into some variable, but that means I have to change 2000+ lines of codes and change fp.write() to something else. Any suggestions please? Thanks Thierry From paolo_veronelli at tiscali.it Fri Sep 23 06:06:17 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Fri, 23 Sep 2005 12:06:17 +0200 Subject: Wrapping classes In-Reply-To: References: Message-ID: <4333D399.30505@tiscali.it> Paolino wrote: > class NotInitializedObjects(type): > def __init__(cls,*_): > realInit=cls.__init__ > def __newInit__(self,*pos,**key): > def _init(): > realInit(self,*pos,**key) > self._init=_init > cls.__init__=__newInit__ > def __getattribute__(self,attr): > def getter(attr): > return object.__getattribute__(self,attr) > if '_init' in getter('__dict__'): > getter('_init')() > del self._init > return getter(attr) > cls.__getattribute__=__getattribute__ > A lighter solution can be overriding __getattr__. This will produce more object-like behaving instances even when not initialized, aka you can call methods and access class attributes without triggering the init (not very useful) class NotInitializedObjects(type): def __init__(cls,*_): realInit=cls.__init__ def __newInit__(self,*pos,**key): def _init(): realInit(self,*pos,**key) self._init=_init cls.__init__=__newInit__ def __getattr__(self,attr): if hasattr(self,'_init'): self._init() del self._init if hasattr(self,attr): return getattr(self,attr) raise AttributeError cls.__getattr__=__getattr__ ### Test with previous testing code A cleaner solution is decoupling the intensive calculation attributes from __init__ and use descriptors for them.But this is impossible if /the/ instance value is the intensive one to be calculated. Ciao Paolino ___________________________________ Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! http://it.toolbar.yahoo.com From zanesdad at bellsouth.net Sun Sep 4 16:43:20 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Sun, 04 Sep 2005 16:43:20 -0400 Subject: dual processor In-Reply-To: <7xd5nolhn7.fsf@ruckus.brouhaha.com> References: <0NGSe.4128$3R1.94@fe06.lga> <7xd5nolhn7.fsf@ruckus.brouhaha.com> Message-ID: <431B5C68.4080009@bellsouth.net> Paul Rubin wrote: >Jeremy Jones writes: > > >>to pass data around between processes. Or an idea I've been tinkering >>with lately is to use a BSD DB between processes as a queue just like >>Queue.Queue in the standard library does between threads. Or you >>could use Pyro between processes. Or CORBA. >> >> > >I think that doesn't count as using a the multiple processors; it's >just multiple programs that could be on separate boxes. >Multiprocessing means shared memory. > > I disagree. My (very general) recommendation implies multiple processes, very likely multiple instances (on the consumer side) of the same "program". The OP wanted to know how to get Python to "take advantage of the dual processors." My recommendation does that. Not in the sense of a single process fully exercising multiple CPUs, but it's an option, nonetheless. So, in that respect, your initial "no" was correct. But, >This module might be of interest: http://poshmodule.sf.net > > > Yeah - that came to mind. Never used it. I need to take a peek at that. This module keeps popping up in discussions like this one. JMJ From steve at REMOVETHIScyber.com.au Mon Sep 12 09:40:16 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 12 Sep 2005 23:40:16 +1000 Subject: encryption with python References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <1126128663.573686.148670@g44g2000cwa.googlegroups.com> <87wtlohh1b.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: Thank you to Mike Meyer, Kirk Sluder, and anyone who made constructive comments and/or corrections to my earlier post about generating student IDs as random numbers. Especially thanks to Marc Rintsch who corrected a stupid coding mistake I made. Serves me right for not testing the code. Kirk pointed out that there is a good usage case for using a one-way encryption function to encrypt a Social Security Number to the student ID: > you are prepared to deal with the inevetable, "I lost my > password/student ID, can you still look up my records?" Whether the usefulness of that use outweighs the risks is not something we can decide, but I hope the original poster is considering these issues and not just blindly going for the technical solution. For example, this is one possible way of dealing with students who have lost their student ID: - ask student for their name, d.o.b. and SSN; - search the database for students whose name, d.o.b. and SSN match; - if you have more than one match, there is a serious problem; - otherwise you may consider that the student has proven their own identity to you sufficiently, so you can safely tell them the student ID. No need for a function that calculates the ID from the SSN, with the associated risk that Black Hats will break the algorithm and use the student ID to steal students' SSNs. In effect, this scheme uses the algorithm "look it up in a secure database" as the one-way function. It is guaranteed to be mathematically secure, although it is vulnerable to bad guys cracking into the database. Thanks also to James Stroud for his amusing extension to the one-time pad algorithm. If you have a need to be able to reconstruct the data, then of course you need some sort of cryptographic function that can encrypt the data and decrypt it. But that begs the question of whether or not you actually do need to be able to reconstruct the data. The point of my post was that you may not need to, in which case a random number is as good as any other ID. James also protested that passwords are "security through obscurity", since "All they have to do is to get that secret key and all those records are easily readable." Of course this is technically correct, but that's not what security through obscurity means to folks in the security business. The difference between security through obscurity and security through a secret key is profound: if I reverse-engineer your secret algorithm, I can read every record you have. But if I discover the secret key belonging to one person, I can only read that person's messages, not anyone else's. As James says, "The point is that *something has to be kept secret* for encryption security to work." Absolutely correct. But now think of the difference between having keys to your door locks, compared to merely keeping the principle of the door handle secret. -- Steven. From mark.dufour at gmail.com Tue Sep 13 04:51:35 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 13 Sep 2005 10:51:35 +0200 Subject: Using Shed Skin under Windows or OSX Message-ID: <8180ef69050913015153f75f44@mail.gmail.com> Hello all, My apologies to everyone who has tried Shed Skin under Windows or OSX, and could not get it to run. I have to stress that it really is experimental software, and certainly not ready for production use at this point. However, that is not an excuse for a vague and/or too difficult installation prodedure. I hope to find and spend some time behind Windows and OSX boxes this week, to fix any problems and hopefully make it easy to install the compiler on them. For now, two very helpful persons have posted instructions on how to get Shed Skin sort of working under either operating system (there are still some problems with the unit tests..) http://mail.python.org/pipermail/python-list/2005-September/298697.html http://www.blogger.com/comment.g?blogID=14063458&postID=112636132130703717 thanks! mark. Mark. From haircut at gmail.com Fri Sep 9 14:07:07 2005 From: haircut at gmail.com (Adam Monsen) Date: 9 Sep 2005 11:07:07 -0700 Subject: disabling TCP connections, just for one script In-Reply-To: <3odvrbF5igmgU1@uni-berlin.de> References: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> <3odvrbF5igmgU1@uni-berlin.de> Message-ID: <1126289227.812917.84210@g14g2000cwa.googlegroups.com> I know very little about socket programming and even less about sockey.py... any idea what behavior would have to be modified? Further complicating matters (for me), it appears some of the socket programming code is in C, and my C skills are lacking. -- Adam Monsen http://adammonsen.com/ From Scott.Daniels at Acm.Org Mon Sep 5 09:26:57 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 05 Sep 2005 06:26:57 -0700 Subject: Possible improvement to slice opperations. In-Reply-To: References: Message-ID: <431c3b4f$1@nntp0.pdx.net> Magnus Lycka wrote: > Ron Adam wrote: >> ONES BASED NEGATIVE INDEXING I think Ron's idea is taking off from my observation that if one's complement, rather than negation, was used to specify measure-from- right, we would have a simple consistent system (although I also observed it is far too late to do that to Python now). Using such a system should not define things as below: >> | a | b | c | >> +---+---+---+ >> -4 -3 -2 -1 but rather use a form like: >> | a | b | c | >> +---+---+---+ >> ~3 ~2 ~1 ~0 >> The '~' is the binary not symbol which when used >> with integers returns the two's compliment. Actually, the ~ operator is the one's complement operator. > For calculated values on the slice borders, you still > have -1 as end value. But if you are defining the from-right as ones complement, you use one's complement on the calculated values and all proceeds happily. Since this could happen in Python, perhaps we should call it Pytho?. >> a[1:~1] -> center, one position from both ends. > > This is just a convoluted way of writing a[1:-2], which > is exactly the same as you would write today. Actually, a[1 : -1] is how you get to drop the first and last characters today. I suspect you knew this and were just a bit in a hurry criticizing a lame-brained scheme. -Scott David Daniels Scott.Daniels at Acm.Org From http Fri Sep 16 17:27:39 2005 From: http (Paul Rubin) Date: 16 Sep 2005 14:27:39 -0700 Subject: encryption with python? References: <432A4DE0.9070803@ucsd.edu> <432A52C0.10201@ucsd.edu> Message-ID: <7xirx0ln3o.fsf@ruckus.brouhaha.com> Robert Kern writes: > > http://www.nightsong.com/phr/crypto/p3.py > > [Ed Hotchkiss wrote:] > > Awesome. I just started Python today so I'd have no idea ... how good is > > this encryption compared to PGP? p3.py's functionality is nothing like PGP: it just encrypts character strings with a secret key. It has no public key encryption, no key management, etc. Also, its algorithm is nonstandard since it's designed for fast encryption speed using only the Python standard library, since some applications run in environments where they don't have enough control to use C extensions, yet they still have reasons to want to encrypt stuff. If you're doing a high security application, you need control over your computing environment (enough to be able to run C extensions, etc.) and not just your algorithms, and so you should use a C extensions that follows a standard like AES. You also reduce your legal liability exposure by following standards. Imagine you choose some algorithm and it gets broken and you have to explain to a jury why your software lost megabucks of your clients' money, or whatever. If you chose 3DES or AES, you can say you followed the best advice of both the federal government and the banking industry. If you chose anything else, you're in deep mazola. So even if you somehow calculate that p3.py has .002% chance of getting broken and AES-EAX has .003% chance, the "objectively" worse choice of AES is still preferable in that kind of application since you could still get unlucky either way. That said, the algorithm in p3.py should be reasonably sound for most typical purposes. Also, its API is extremely simple. It's harder to mess up with it than with a typical crypto library that gives you lower level building blocks. The main cost of that ease of use is that the ciphertext is several dozen bytes longer than the plaintext. > That said, it's Paul's own algorithm, so it hasn't been tested and > attacked as thoroughly as PGP's algorithms. It relies on the security of > the underlying hash. Unfortunately, that hash has been broken recently, > although I'm not sure if that break actually affects the security of how > it's used in this algorithm. Paul could tell you more. I think that attack (an O(2**63) method for finding free collisions in SHA1) doesn't apply here, since the attacker doesn't have control over the input to the hash function. From roccomoretti at hotpop.com Thu Sep 1 10:43:37 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 01 Sep 2005 09:43:37 -0500 Subject: Well, Python is hard to learn... In-Reply-To: References: Message-ID: wen wrote: > due to the work reason, i have to learn python since last month. i have > spent 1 week on learning python tutorial and felt good. but i still don't > understand most part of sourcecode of PYMOL(http://pymol.sourceforge.net/) > as before. Well, last time I checked, a good chunk of PyMol was written in C. Knowing Python may help you to learn C, but I doubt that one week is going to be sufficient. But I agree that Python is deceptive. It's so easy to learn and use, you can easily convince yourself you're a better programmer than you actually are. From xah at xahlee.org Wed Sep 7 05:58:35 2005 From: xah at xahlee.org (Xah Lee) Date: 7 Sep 2005 02:58:35 -0700 Subject: determine if os.system() is done Message-ID: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> suppose i'm calling two system processes, one to unzip, and one to ?tail? to get the last line. How can i determine when the first process is done? Example: subprocess.Popen([r"/sw/bin/gzip","-d","access_log.4.gz"]); last_line=subprocess.Popen([r"/usr/bin/tail","-n 1","access_log.4"], stdout=subprocess.PIPE).communicate()[0] of course, i can try workarounds something like os.system("gzip -d thiss.gz && tail thiss"), but i wish to know if there's non-hack way to determine when a system process is done. Xah xah at xahlee.org ? http://xahlee.org/ From fredrik at pythonware.com Fri Sep 16 07:59:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Sep 2005 13:59:35 +0200 Subject: multiple replaces References: <1126868971.917556.214610@g44g2000cwa.googlegroups.com> Message-ID: Harald Armin Massa wrote: > sth. like > rpdict={"":"%(tree)s","":"%(house)s","%","%%"} > > for key, value in rpdict.iteritems(): > h1=h1.replace(key, value) > > but ... without the garbage, in one command. > > I guess there are very, very, very wise solution for this problem, but > I do not know of them. http://effbot.org/zone/python-replace.htm From lists at nabble.com Fri Sep 9 18:23:11 2005 From: lists at nabble.com (kooto (sent by Nabble.com)) Date: Fri, 9 Sep 2005 15:23:11 -0700 (PDT) Subject: py2app and Bittornado In-Reply-To: <1125445446.261711.248200@g49g2000cwa.googlegroups.com> References: <1125442841.042912.197950@g14g2000cwa.googlegroups.com> <1125445446.261711.248200@g49g2000cwa.googlegroups.com> Message-ID: <826877.post@talk.nabble.com> bsharitt wrote: > > You wouldn't happen to know a nice way to interact with the > PythonMac-SIG group without subscribing and subjecting my inbox to rape > by a bunch of useless messages would you? > Check out Nabble - for python-list at python.org - there is a searchable bi-directional archive/forum http://www.nabble.com/Python---python-list-f2962.html there is also a forum/archive where you can cross browse and search all Python lists - http://www.nabble.com/Python-f2926.html for PythonMac-SIG - it's http://www.nabble.com/Python---pythonmac-sig-f2970.html Note all posting are bidirectional, that means the mirror on Nabble will be in synch with Python lists. People who prefer a web forum view can browse and post through the web and discuss things with the list users seamlessly. hope this helps. -- Sent from the Python - python-list forum at Nabble.com: http://www.nabble.com/py2app-and-Bittornado-t266210.html#a826877 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve.horsley at gmail.com Thu Sep 22 17:37:12 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Thu, 22 Sep 2005 22:37:12 +0100 Subject: win32 service and time.sleep() In-Reply-To: References: Message-ID: Oracle wrote: > On Tue, 20 Sep 2005 10:49:13 -0400, rbt wrote: > >> I have a win32 service written in Python. It works well. It sends a >> report of the status of the machine via email periodically. The one >> problem I have is this... while trying to send an email, the script >> loops until a send happens and then it breaks. Should it be unable to >> send, it sleeps for 10 minutes with time.sleep(600) and then wakes and >> tries again. This is when the problem occurs. I can't stop the service >> while the program is sleeping. When I try, it just hangs until a reboot. >> Can some suggest how to fix this? >> > > You could try doing it the hard way. In a loop, sleep for 1-5 seconds at > a time. Everytime you complete a sleep, check the elapsed time. If the > elapsed time is >= the total sleep duration, fall out of the sleep loop > and try your email again. This should allow your service to stop within > 1-5 seconds of your request while imposing little to no load on the system. I adopted that solution just last week. When you wake (every few seconds), you check for a stop flag (and exit if needed of course) before checking if its time to do work-work. Works a treat. Another option is to use a threading.Condition, and have the service thread wait(600). The thread that calls to stop the service can set the stop flag and then notify() the Condition. Steve From sjmaster at gmail.com Tue Sep 20 14:43:17 2005 From: sjmaster at gmail.com (Steve M) Date: 20 Sep 2005 11:43:17 -0700 Subject: Getting tired with py2exe In-Reply-To: References: Message-ID: <1127241797.610338.201800@z14g2000cwz.googlegroups.com> What about PyInstaller that was announced the other day? The feature list looks great, and it appears the developers intend to maintain and enhance the program indefinitely. http://groups.google.com/group/comp.lang.python/browse_thread/thread/b487056b7b1f99bc/583da383c1749d9f?q=ANN&rnum=1&hl=en#583da383c1749d9f http://pyinstaller.hpcf.upr.edu/pyinstaller Feature highlights: * Packaging of Python programs into standard executables, that work on computers without Python installed. * Multiplatform: works under Windows, Linux and Irix. * Multiversion: works under any version of Python since 1.5. * Dual packaging mode: * Single directory: build a directory containing an executable plus all the external binary modules (.dll, .pyd, .so) used by the program. * Single file: build a single executable file, totally self-contained, which runs without any external dependency. * Support for automatic binary packing through the well-known UPX compressor. * Optional console mode (see standard output and standard error at runtime). * Selectable executable icon (Windows only). * Fully configurable version resource section in executable (Windows only). * Support for building COM servers (Windows only). From webmaster at fidelitylodge.com Tue Sep 6 20:24:06 2005 From: webmaster at fidelitylodge.com (Webmaster - Fidelity Lodge #113) Date: Tue, 06 Sep 2005 20:24:06 -0400 Subject: Last mod date Message-ID: <431E3326.3030607@fidelitylodge.com> This is my first post--I'm a Java developer trying to expand my horizons. I'm trying to figure out how to find out the last modification date/time for a file. I've found a reference to *PyOS_GetLastModificationTime *as an Operating System Utility, but I can't figure out which module I need to import to access it. I'm using Python version 2.4.1 on a box running Windows (it works, and nobody else in the house wants to use it). Thanks in advance, Mike From jgrahn-nntq at algonet.se Sat Sep 17 17:30:04 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 17 Sep 2005 21:30:04 GMT Subject: pcapy listen on multiple devices References: Message-ID: On Mon, 12 Sep 2005 17:02:31 +0200, billiejoex wrote: > Hi all. I noticed that with the original pcap sniffing library it is > possible to listen on multiple devices by using "select()" or "poll()" > function. Yes; you can ask pcap for the file descriptor which corresponds to your sniffed device. That works at least on Unixes. (There is also the 'any' pseudo-interface, if you are on Linux (and other Unixes?). You get to listen /everywhere/ in one session.) > These function aren't present in pcapy module. Do you got any suggestion to > avoid this problem? Modify pcapy so you can get the file descriptor from it. Pcapy is great, but it doesn't expose libpcap literally. Maybe the original authors had no use for getfd(). I've been meaning to write The Pcap Bindings To End All Pcap Bindings for almost a year now, but I never seem to get around to it ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From dale at riverhall.nospam.co.uk Mon Sep 19 12:27:48 2005 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Mon, 19 Sep 2005 17:27:48 +0100 Subject: Validating XML parsers Message-ID: <0GBXe.2$l56.1@fe14.usenetserver.com> A few days ago there was a discussion about which XML parser to use with Python. However, the discussion didn't cover validating parsers, at least, not w3.org XML Schemas. I looked into all the parsers that came up in the discussion but found no mention of w3.org schemas. It seems there are a few DTD validating parsers but that's all. I'm not concerned about speed so much as a reasonably sound implementation. What's out there? Have I missed something? Thanks. -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From simon.brunning at gmail.com Wed Sep 28 10:06:06 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 28 Sep 2005 15:06:06 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <00C39639-DDD6-41A7-BEA9-F78EFA3288A5@ihug.co.nz> References: <311b5ce105092800102da32267@mail.gmail.com> <8c7f10c605092804053a6eadf4@mail.gmail.com> <813D949A-554B-4801-BE07-13F652A218AD@ihug.co.nz> <8c7f10c605092804552f1dac9@mail.gmail.com> <00C39639-DDD6-41A7-BEA9-F78EFA3288A5@ihug.co.nz> Message-ID: <8c7f10c6050928070667059254@mail.gmail.com> On 9/28/05, Tony Meyer wrote: > That's not what the documentation says: So, either the docs are wrong, or I am. You be the judge. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From notrealaddress at all.com Tue Sep 20 07:03:53 2005 From: notrealaddress at all.com (Chris Dewin) Date: Tue, 20 Sep 2005 20:03:53 +0900 Subject: Question about smtplib, and mail servers in general. Message-ID: Hi. I've been thinking about using smtplib to run a mailing list from my website. s = smtplib.SMTP("server") s.sendmail(fromaddress, toaddresess, msg) I know that in this instance, the toaddresses variable can be a variable of type list. Suppose the list contains well over 100 emails. Would that create some sort of drain on the mail server? Would I be better off doing it in some other way? -- www.wintergreen.in From sakcee at gmail.com Thu Sep 15 02:21:31 2005 From: sakcee at gmail.com (Sakcee) Date: 14 Sep 2005 23:21:31 -0700 Subject: ddd or eclipse with mod_python Message-ID: <1126765291.108775.324560@g43g2000cwa.googlegroups.com> Hi I am using mod_python for web development, I am in need of some ide , can i use ddd or eclipse with pydev with mod_python. can these ide's handle requests from mod_python and run server side scripts any help or pointers are greatly appreciated thanks clive From onurb at xiludom.gro Mon Sep 12 12:40:15 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 12 Sep 2005 18:40:15 +0200 Subject: How to protect Python source from modification In-Reply-To: <1126542417.580959.66680@g47g2000cwa.googlegroups.com> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> <1126542417.580959.66680@g47g2000cwa.googlegroups.com> Message-ID: <4325af70$0$14835$626a54ce@news.free.fr> Frank Millman wrote: > Peter Hansen wrote: > >>Frank Millman wrote: >> (snip) >>>The only truly secure solution I can think of would involve a radical >>>reorganisation of my program >> >>Please define what "truly secure" means to you. >> > > > Fair question. I am not expecting 'truly' to mean 100% - I know that is > impossible. I will try to explain. > > Here are some assumptions - > 1. A system adminstrator is responsible for the system. > 2. There is a single userid and password for connecting to the > database. This must be stored somewhere so that the client program can > read it to generate the appropriate connection string. The users do not > need to know this userid and password. > 3. Each user has their own userid and password, > which is stored in the > database in a 'users' table. I use this in my program for > authentication when a user tries to connect. Why not simply using the security system of your RDBMS ? If you set up appropriate privileges in the RDBMS, you won't have to store any userid/password in the program, and no user will be able to bypass anything, even if connecting directly (like with a CLI DB client) to the RDBMS. > [snip] > > (snip more) > > I am not concerned about anyone reading my code - in fact I am looking > forward to releasing the source and getting some feedback. > > My concern is this. I have all this fancy authentication and business > logic in my program. If someone wants to bypass this and get direct > access to the database, it seems trivially easy. All they have to do is > read my source, find out where I get the connection string from, write > their own program to make a connection to the database, and execute any > SQL command they want. That's why RDBMS have an authentication and security system. This doesn't means your program doesn't have or cannot add it's own security management, but it should be based on the RDBMS one. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From david.murmann at rwth-aachen.de Fri Sep 30 13:06:40 2005 From: david.murmann at rwth-aachen.de (David Murmann) Date: Fri, 30 Sep 2005 19:06:40 +0200 Subject: Feature Proposal: Sequence .join method In-Reply-To: References: <3q3logFcrs5qU1@news.dfncis.de><3q3p80Fd1cbmU1@news.dfncis.de> <3q3pt9Fd7pklU1@news.dfncis.de> Message-ID: <3q59hrFda7g6U1@news.dfncis.de> Michael Spencer wrote: > Terry Reedy wrote: >> "David Murmann" wrote in message >> news:3q3pt9Fd7pklU1 at news.dfncis.de... >> >>>> def join(sep, seq): >>>> return reduce(lambda x, y: x + sep + y, seq, type(sep)()) >>> >>> damn, i wanted too much. Proper implementation: >>> >>> def join(sep, seq): >>> if len(seq): >>> return reduce(lambda x, y: x + sep + y, seq) >>> return type(sep)() >>> >>> but still short enough >> >> >> For general use, this is both too general and not general enough. >> >> If len(seq) exists then seq is probably reiterable, in which case it >> may be possible to determine the output length and preallocate to make >> the process O(n) instead of O(n**2). I believe str.join does this. A >> user written join for lists could also. A tuple function could make a >> list first and then tuple(it) at the end. >> >> If seq is a general (non-empty) iterable, len(seq) may raise an >> exception even though the reduce would work fine. >> >> Terry J. Reedy >> >> >> > For the general iterable case, you could have something like this: > > >>> def interleave(sep, iterable): > ... it = iter(iterable) > ... next = it.next() > ... try: > ... while 1: > ... item = next > ... next = it.next() > ... yield item > ... yield sep > ... except StopIteration: > ... yield item > ... > >>> list(interleave(100,range(10))) > [0, 100, 1, 100, 2, 100, 3, 100, 4, 100, 5, 100, 6, 100, 7, 100, 8, > 100, 9] Well, as en.karpachov at ospaz.ru pointed out, there is already itertools.chain which almost does this. In my opinion it could be useful to add an optional keyword argument to it (like "connector" or "link"), which is iterated between the other arguments. > but I can't think of a use for it ;-) Of course, i have a use case, but i don't know whether this is useful enough to be added to the standard library. (Yet this would be a much smaller change than changing all sequences ;) thanks for all replies, David. From stanc at al.com.au Wed Sep 14 19:19:53 2005 From: stanc at al.com.au (Astan Chee) Date: Thu, 15 Sep 2005 09:19:53 +1000 Subject: urllib.open problem Message-ID: <4328B019.2010104@al.com.au> Hi Guys, I have a python script which runs perfectly on my machine. However a machine that I tested it on gives the following error message: Traceback (most recent call last): File "whip.py", line 616, in OnRebootRunning File "whip.py", line 626, in RebootCustom File "urllib.pyc", line 77, in urlopen File "urllib.pyc", line 170, in open TypeError: cannot concatenate 'str' and 'NoneType' objects The code snipplet where this error happens is f = urllib.urlopen("http://www.hotmail.com/) notes= f.readlines() Does anyone know what causes this error? Im perplexed because it works on some machines and it doesnt work on other computers although they all have the same spec. Thanks for the help Cheers Stan From peter at engcorp.com Thu Sep 29 22:06:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Sep 2005 22:06:05 -0400 Subject: Where to find python c-sources In-Reply-To: <0LZ_e.19644$Ix4.10480@okepread03> References: <0LZ_e.19644$Ix4.10480@okepread03> Message-ID: <5N-dnZny3YyaA6HenZ2dnUVZ_tKdnZ2d@powergate.ca> Dave Benjamin wrote: > Tor Erik S?nvisen wrote: >> I need to browse the socket-module source-code. I believe it's >> contained in the file socketmodule.c, but I can't locate this file... >> Where should I look? > > You can browse the Python CVS tree here: > http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/ > > For example, the file you asked for is viewable here: > http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/socketmodule.c?rev=1.314&view=auto And only three hits down in this Google search: http://www.google.com/search?q=python+socketmodule.c plus one additional click on "view" once you're there... -Peter From brp13 at yahoo.com Wed Sep 21 14:58:52 2005 From: brp13 at yahoo.com (Tuvas) Date: 21 Sep 2005 11:58:52 -0700 Subject: Python GUIs In-Reply-To: <1127327542.145980.261460@o13g2000cwo.googlegroups.com> References: <1127327542.145980.261460@o13g2000cwo.googlegroups.com> Message-ID: <1127329132.872036.307010@g47g2000cwa.googlegroups.com> As a bit more of an update, I have decided to create a list of strings, but am having a problem. To illistrate this in a simple manner. B='\x12','\x32' B[0]='\x12' I cannot get this to work, and I need to get it to work somehow. How can I make it happen? Is there a function that I should use, a special trick, etc? Or is there just no way to make it work? Thanks! From konrad.hinsen at laposte.net Wed Sep 14 10:03:28 2005 From: konrad.hinsen at laposte.net (konrad.hinsen at laposte.net) Date: 14 Sep 2005 07:03:28 -0700 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: <1126706608.019913.234580@g47g2000cwa.googlegroups.com> Stefano Masini wrote: > There are a few ares where everybody seems to be implementing their > own stuff over and over: logging, file handling, ordered dictionaries, > data serialization, and maybe a few more. > I don't know what's the ultimate problem, but I think there are 3 main reasons: > 1) poor communication inside the community (mhm... arguable) > 2) lack of a rich standard library (I heard this more than once) > 3) python is such an easy language that the "I'll do it myself" evil > side lying hidden inside each one of us comes up a little too often, > and prevents from spending more time on research of what's available. I'd like to add one more that I haven't seen mentioned yet: ease of maintenance and distribution. Whenever I decide to use someone else's package for an important project, I need to make sure it is either maintained or looks clean enough that I can maintain it myself. For small packages, that alone is often more effort than writing my own. If I plan to distribute my code to the outside world, I also want to minimize the number of dependencies to make installation simple enough. This would only stop being a concern if a truly automatic package installation system for Python existed for all common platforms - I think we aren't there yet, in spite of many good ideas. And even then, the maintenance issue would be even more critical with code distributed to the outside world. None of these issues is specific to Python, but with Python making new developments that much simpler, they gain in weight relative to the effort of development. > It seems to me that this tendency is hurting python, and I wonder if > there is something that could be done about it. I once followed a I don't think it hurts Python. However, it is far from an ideal situation, so thinking about alternatives makes sense. I think the best solution would be self-regulation by the community. Whenever someone discovers three date-format modules on the market, he/she could contact the authors and suggest that they sit together and develop a common version that satisfies everyone's needs, perhaps with adaptor code to make the unified module compatible with everyone's individual modules. Konrad. From twic at urchin.earth.li Thu Sep 15 08:39:29 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 15 Sep 2005 13:39:29 +0100 Subject: Sorting Unix mailboxes In-Reply-To: <1126628615.046122.325960@g43g2000cwa.googlegroups.com> References: <1126628615.046122.325960@g43g2000cwa.googlegroups.com> Message-ID: [posted and mailed, in case the OP has given up on reading the group!] On Tue, 13 Sep 2005, sfeil at io.com wrote: > I'm writing a program in python to sort the mail in standard Unix > email boxes. In my "prof of concept" example I am coping a letter to a > second mailbox if the letter was send from a particular email > address. When I read the destination mailbox with cat, I can see that > something is getting copied to it, but the mail program does not > recognize any new letters in the destination mailbox. It would seam > that the "OutFile.write(Message.get_unixfrom())" line is > essential. Absolutely! The From line is the key element in mailbox structure. > However if I run with this line uncommented then I get an the following > error. "TypeError: argument 1 must be string or read-only character > buffer, not None". This is happening because Message.get_unixfrom is returning None, rather than a proper From line. According to its documentation, thus method "defaults to None if the envelope header was never set". Since you've never set the envelope header, this behaviour is therefore not surprising. But didn't the envelope header get set when you created the message? Actually, no - you created it with "email.message_from_file(Envelope.fp)", which reads the contents of the email from the file Envelope.fp. Envelope.fp, however, isn't the complete text of the mailbox entry, it's just (AFAICT) the payload of the message. Therefore, the message you create has no headers or envelope, just the body. > I created this program by following an example posted somewhere on the > Internet, that I can't seam to find anymore. At one time I was able to > get Python to put new letters in a mailbox. > > Also, I was wondering is there were a way to use Python to delete items > from a mailbox. Not really. This is a universal problem which affects all programs, regardless of language, with work with file formats consisting of variable-sized records - there's no wasy way to delete them. > I could create I temp box of non-deleted then copy to the source box, > but that seams messy. A cleaner way would be to copy the non-deleted messages to a new file, then to throw away the old file and rename the new one to replace it. This would avoid the second copy. Alternatively, you could read and write simultaneously with one file, then truncate at the end; this takes a bit more care, though. > Here is my example program.. Right. Some of this makes sense to me, but there's quite a lot here that i don't get. Perhaps some of this is a result of the code being excised from its natural context, though. > def CopyToBox(Source,Address,Destination): > AddressRE=re.compile( > "([a-zA-Z0-9._-]+)@([a-zA-Z0-9._-]+)\.([a-zA-Z0-9]+)") Why did you write the regexp to capture the address as three groups? It seems like the only thing you ever do with the groups is put them back together again! Also, it's better to define the regexp once, at global scope, to avoid having to compile it every time the function runs. > InFile = open("/home/stevef/mail/%s" % Source) > OutFile = open("/home/stevef/mail/%s" % Destination,"a") > Box = mailbox.PortableUnixMailbox(InFile) > Envelope=Box.next() Why 'Envelope'? That object is a Message, not an Envelope! And did you really mean to throw away the first message in the box like this? > while 1: > Envelope=Box.next() > if Envelope == None: > break Why an infinite loop with a break and an explicit next call? Why not a for loop over the mailbox? > print Envelope.getallmatchingheaders("from")[0] > Match=AddressRE.search( > Envelope.getallmatchingheaders("from")[0]) Why getallmatchingheaders("from")[0] rather than getfirstmatchingheader["from"]? > if Match: > Set=Match.groups() > if "%s@%s.%s" % Set == Address: > print "Copy letter from %s@%s.%s" % Set > Message = email.message_from_file(Envelope.fp) Message now contains the email's payload, but not its headers or envelope details, so ... > #OutFile.write(Message.get_unixfrom()) ##error That doesn't work. > OutFile.write("\n") > OutFile.write(Message.as_string()) > InFile.close() > OutFile.close() > return There's no need for an explicit return here. I have to sympathise with you over python's mail-handling libraries, though; having both the rfc822 and email modules around at the same time is quite a headache. Luckily, there's a way to make things simpler and much easier to work with, using a trick described in the docs for the mailbox module: rather than letting the mailbox module make the message objects (using the rfc822 module to do it), we can supply our own message factory function, with which we can create email-module messages right from the start. You need a function like this: def msgfactory(f): while True: try: return email.message_from_file(f) except: pass Then you can make a mailbox like this: mbox = mailbox.PortableUnixMailbox(f, msgfactory) The messages in it will then be email.Message instances. I'd then write the main function like this (you'll need to import os.path): MBOX_DIR = "/home/stevef/mail" def CopyToBox(src, addr, dst): in_ = file(os.path.join(MBOX_DIR, src)) out = file(os.path.join(MBOX_DIR, dst), "a") for mail in mailbox.PortableUnixMailbox(in_, msgfactory): if (addr in mail["from"]): out.write(mail.as_string(True)) in_.close() out.close() Simple, eh? tom -- Also, a 'dark future where there is only war!' ... have you seen the news lately? -- applez From NutJob at gmx.net Thu Sep 1 05:31:49 2005 From: NutJob at gmx.net (NutJob at gmx.net) Date: 1 Sep 2005 02:31:49 -0700 Subject: Is my thread safe from premature garbage collection? In-Reply-To: References: <1125563865.759423.197960@o13g2000cwo.googlegroups.com> Message-ID: <1125567109.267704.199020@o13g2000cwo.googlegroups.com> Splendid! =) Thanks guys! From billiejoex at fastwebnet.it Mon Sep 5 16:41:13 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Mon, 5 Sep 2005 22:41:13 +0200 Subject: Python compiled? References: Message-ID: I'm sorry. Maybe you misunderstanded. I know the great advanteges deriving by using interpretation too, I appreciate it very much (I'm newbie in Python and the interpeter really helps me out in many situations), but a 'pure' interpretated language needs obligatorily an interpreter and (sorry for repeating) this could be a problem for distribution (imho). Py2exe is surely a good compromise but it is not comparable to an executable file compiled, for example, in C for obvious sizing reasons (I never used PyInstaller. I surely try it out as soon as possible, but I didn't think that the output package size is too much different than py2exe one). For these reasons I think that an hibrid language that permits interpretation and compilation at the same time, should be a great advantage. best regards From striker at trip.net Fri Sep 9 10:36:34 2005 From: striker at trip.net (stri ker) Date: Fri, 9 Sep 2005 09:36:34 -0500 Subject: How to upgrade to 2.4.1 on Mac OS X tiger In-Reply-To: <1126275430.044429.72830@g49g2000cwa.googlegroups.com> References: <1126102477.882046.95490@z14g2000cwz.googlegroups.com> <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> <1126196055.843689.208130@g43g2000cwa.googlegroups.com> <1126275430.044429.72830@g49g2000cwa.googlegroups.com> Message-ID: <240A8896-CC28-41A8-A5BA-FAC609344C56@trip.net> Has anyone here upgraded from 2.3 to 2.4 on Tiger? If so how'd ya do it? TIA, Kevin From steve at holdenweb.com Fri Sep 2 13:19:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Sep 2005 12:19:41 -0500 Subject: pain In-Reply-To: <9rqdnQ4tBPYC8IXeRVn-hg@powergate.ca> References: <42f1f51b$0$11068$e4fe514c@news.xs4all.nl> <1123166972.948428.219140@g47g2000cwa.googlegroups.com> <200509011902.44745.jstroud@mbi.ucla.edu> <9rqdnQ4tBPYC8IXeRVn-hg@powergate.ca> Message-ID: Peter Hansen wrote: > Steve Holden wrote: > >>and the day managers stop being ignorant we'll all be able to fly around >>on pigs. Not wishing to offend the pigs, of course. >> >>still-working-for-myself-ly y'rs - steve > > > What Steve means here, of course, is that he is his own manager. > > ;-) > Right. This means I get to make fun of my own pointy hair. at-least-as-long-as-i-still-have-hair-ly y'rs -steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From deets at nospam.web.de Sun Sep 18 05:52:35 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Sep 2005 11:52:35 +0200 Subject: Python game coding In-Reply-To: <3p4revF8h5onU2@uni-berlin.de> References: <8f6Xe.14083$FW1.371@newsread3.news.atl.earthlink.net> <3p4revF8h5onU2@uni-berlin.de> Message-ID: <3p4rn0F8h5onU3@uni-berlin.de> Diez B. Roggisch wrote: > >> Very interesting! >> BTW: I wonder if and when someone will use stackless python or pygame >> as a >> basis for developing a _visual_ development environment for 2D >> games/multimedia like Macromedia Director. It would be a killer app. > > > Blender. It currently doesn't use stacklass AFAIK, but that shouldn't be > too hard to fix. Oop - I read 3d instead of 2d.. Hm, 3d _can_ do 2d, so just don't allow your cameras do fancy stuff like rotating :) Diez From daniel.dittmar at sap.corp Fri Sep 9 12:31:12 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 09 Sep 2005 18:31:12 +0200 Subject: re module help In-Reply-To: <1126277869.480420.3740@g47g2000cwa.googlegroups.com> References: <1126277869.480420.3740@g47g2000cwa.googlegroups.com> Message-ID: rattan at cps.cmich.edu wrote: > if I start replacing regex by re I get stuck at replacement of > regex.symcomp() and regex.pattern() Groups identified by names are part of the standard regular expression syntax: regex.symcomp ('\([a-z][a-z0-9]*\)') becomes re.compile ('(?Pid[a-z][a-z0-9]*)') I get AttributeError for both regex.pattern and regex.compile ('abc').pattern. re compiled regular expression have a pattern attribute, this was named givenpat and realpat in the regex module. Daniel From mikael at isy.liu.se Thu Sep 15 12:11:18 2005 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 15 Sep 2005 18:11:18 +0200 Subject: Tkinter add_cascade option_add In-Reply-To: References: <8sCdnf5Vq94_1bXenZ2dnUVZ_sudnZ2d@nmt.edu> Message-ID: Eric Brunel wrote in reply to Bob Greschke: > I'm still not sure what your exact requirements are. Do you want to have > a different font for the menu bar labels and the menu items and to set > them via an option_add? If it is what you want, I don't think you can do > it: the menus in the menu bar are just ordinary items for tk, and you > can't control separately the different kind of menu items. I guess he has the same problem as I have. See sample code: from Tkinter import * class App(Tk): def __init__(self): Tk.__init__(self) self.option_add('*Menu.font', 'helvetica 24 bold') self.menuBar=Menu(self) self.fileMenu=Menu(self.menuBar,tearoff=0) self.subMenu=Menu(self.fileMenu) self.fileMenu.add_cascade(label='foo', menu=self.subMenu) self.subMenu.add_command(label='bar',command=self.foo) self.subMenu.add_command(label='baz',command=self.foo) self.fileMenu.add_command(label='Quit',command=self.quit) self.menuBar.add_cascade(label='File',menu=self.fileMenu) self.config(menu=self.menuBar) def foo(self): pass app=App() app.mainloop() What happens on my WinXP-box when I run this code is that the menu bar still is displayed in the standard font, which seems to be Helvetica 8. I.e. The text 'File' is still small, while everything else in the menus is displayed in Helvetica 24 bold. Adding font=... to any of the commands above does not change the appearance of 'File'. I have no problems changing the appearance of any individual text in the menu except for the mentioned 'File'. I can change the appearance of 'foo' in the self.fileMenu.add_cascade row, but nothing happens to 'File' if I try to specify a font in the self.menuBar.add_cascade row. Doesn't that seem a bit peculiar? But... The example you gave does not change the appearance of the menus at all on my machine. I guess it was supposed to? Is this simply a Windows-issue that cannot easily be solved? Or is it possibly so that this just happens to be a problem on a few ill-configured computers? Or am I possibly blind? /MiO From zanesdad at bellsouth.net Fri Sep 23 08:16:51 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 23 Sep 2005 08:16:51 -0400 Subject: File processing In-Reply-To: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> References: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> Message-ID: <4333F233.1020605@bellsouth.net> Gopal wrote: >Hello, > >I'm Gopal. I'm looking for a solution to the following problem: > >I need to create a text file config.txt having some parameters. I'm >thinking of going with this format by having "Param Name - value". Note >that the value is a string/number; something like this: > >PROJECT_ID = "E4208506" >SW_VERSION = "18d" >HW_VERSION = "2" > >In my script, I need to parse this config file and extract the Values >of the parameters. > >I'm very new to python as you can understand from the problem. However, >I've some project dealines. So I need your help in arriving at a simple >and ready-made solution. > >Regards, >Gopal. > > > Would this (http://www.python.org/doc/current/lib/module-ConfigParser.html) do what you need? It's part of the standard library. - JMJ From brobigi at yahoo.com Mon Sep 5 10:36:18 2005 From: brobigi at yahoo.com (Pandiani) Date: 5 Sep 2005 07:36:18 -0700 Subject: DrPython debugger In-Reply-To: References: <1125847774.714715.55590@f14g2000cwb.googlegroups.com> Message-ID: <1125930978.388735.299410@o13g2000cwo.googlegroups.com> Thanks for repy. However, I found SimpleDebugger 0.5 from sourceforge.net as plugin for drPython but I'm getting error message because DrPython cannot load module drPythonChooser and it seems that the module is removed from latest version of drPython. Or maybe I wasn't able to figure out how to install it...:) From invalidemail at aerojockey.com Fri Sep 30 18:23:12 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 30 Sep 2005 15:23:12 -0700 Subject: PEP 308 accepted - new conditional expressions In-Reply-To: <3q4ro9Fd770nU3@individual.net> References: <3q4ro9Fd770nU3@individual.net> Message-ID: <1128118992.630064.275680@z14g2000cwz.googlegroups.com> Reinhold Birkenfeld wrote: > X if C else Y Oh well. Just about any conditional is better than no conditional. Carl Banks From fredrik at pythonware.com Sat Sep 3 10:39:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 3 Sep 2005 16:39:59 +0200 Subject: python logo References: <1125730325.391485.7690@z14g2000cwz.googlegroups.com> <43195F1E.6050608@optushome.com.au> Message-ID: Tim Churches wrote: > PPS Emerson's assertion might well apply not just to Python logos, but > also, ahem, to certain aspects of the Python standard library. you've read the python style guide, I presume? http://www.python.org/peps/pep-0008.html From python-novice at gmx.de Thu Sep 22 12:34:05 2005 From: python-novice at gmx.de (python-novice at gmx.de) Date: Thu, 22 Sep 2005 18:34:05 +0200 (MEST) Subject: Indexed variables Message-ID: <19551.1127406845@www41.gmx.net> Hello, being an almost complete Python AND programming neophyte I would like to ask the following - very elementary, as I might suspect - question: How do I do the following flawed things right: a1=a2=0 def f(x): if x == a1: a1 = a1 + 1 elif x == a2: a2 = a2 + 1 Now if I call f with f(a2) only a1, of course, is incremented because the if-clause does only check for the value of the input and the values of a1 and a2 are identical. So how do I define the function such as to discrimate wheter I call it by f(a1) or f(a2) ? Thank you very much, Peter -- Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen f?r GMX Partner: http://www.gmx.net/de/go/partner From edvard+news at majakari.net Wed Sep 14 06:26:42 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 14 Sep 2005 13:26:42 +0300 Subject: What XML lib to use? References: <0001HW.BF4CD7C600321189F0407550@news.individual.de> Message-ID: <878xy06j31.fsf@titan.staselog.com> Kalle Anke writes: > I'm confused, I want to read/write XML files but I don't really understand > what library to use. > > I've used DOM-based libraries in other languages, is PyXML the library to > use? It depends. Like there's no best car - "best" is very dependant on use of the vehicle concerned in addition to personal preferences - there's no best XML module either. Some seem very well in many respects, though :) I recommend using EffBot's ElementTree. It's very simple to use (you get to do stuff without thinking delicacies of parsing/generating), and it is _fast_. Now let me repeat the last part - normally speed is of no concern with the computers we have nowadays, but using eg. xml.minidom to process files of size > 10 MB, your system might get very sluggish unless you are quite careful in traversing the parse tree (and maybe even then). Using a SAX / full-compliant DOM parser could be good for learning things, though. As I said, depends a lot. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From pierre.barbier at cirad.fr Sat Sep 17 09:29:18 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sat, 17 Sep 2005 15:29:18 +0200 Subject: Brute force sudoku cracker In-Reply-To: References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> Message-ID: <432c1983$0$7931$626a14ce@news.free.fr> Tom Anderson a ?crit : > On Fri, 16 Sep 2005, Bas wrote: > >> -any ideas how to easily incorporate advanced solving strategies? >> solve(problem1) and solve(problem2) give solutions, but >> solve(problem3) gets stuck... > > > the only way to solve arbitrary sudoku problems is to guess. Well, that's true, but most of the sudoku puzzles can be solved in linear time ! And also having a linear time solving algorithm allows you to really reduce the time used when you need backtracking. BTW, the three given examples can be solved without backtracking. I made one very recently (mmhh ... first complete version made yesterday, still need a little bit of debug on the backtracking part), and it's pretty quick (made in Ruby but well, I suppose timing are similar), it never get stuck for long even if it fails, it fails quickly ... Pierre From steve at REMOVETHIScyber.com.au Fri Sep 30 07:12:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 30 Sep 2005 21:12:32 +1000 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7x64sjvvfq.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 30 Sep 2005 00:58:17 -0700, Paul Rubin wrote: > Steve Holden writes: >> Good grief, the ultimate choice is to use Python because you like it, >> or not to use it because you don't. Enough with the picking every >> available nit, please. Consent or stop complaining :-) > > Riiight. "If she was walking in that neighborhood she must have > wanted it". Nobody is forcing you to use Python. If you don't like it, feel free to use Java or C++ or Ada or whatever language you prefer. Sheesh, I know people get really worked up over language philosophies, but comparing lack of "real" private variables to rape is going overboard. -- Steven. From en.karpachov at ospaz.ru Fri Sep 30 01:03:01 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Fri, 30 Sep 2005 09:03:01 +0400 Subject: Feature Proposal: Sequence .join method In-Reply-To: References: <3q3logFcrs5qU1@news.dfncis.de> Message-ID: <20050930090301.0f55db49.jk@ospaz.ru> On Thu, 29 Sep 2005 20:37:31 -0600 Steven Bethard wrote: > I don't like the idea of having to put this on all sequences. If you > want this, I'd instead propose it as a function (perhaps builtin, > perhaps in some other module). itertools module seems the right place for it. itertools.chain(*a) is the same as the proposed [].join(a) -- jk From http Sun Sep 4 04:24:17 2005 From: http (Paul Rubin) Date: 04 Sep 2005 01:24:17 -0700 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <7x7je1tl9w.fsf@ruckus.brouhaha.com> Message-ID: <7x8xyd5jgu.fsf@ruckus.brouhaha.com> Steve Holden writes: > > legitimate. Python's core developers are in a leadership position for > > Python whether they like it or not; and users and volunteers absorb > > the attitudes of the leaders. > > So, what you are saying is because the developers (I explain in > another post on this thread that I'm not a developer, but I *am* a > director for the PSF), having taken the time and trouble to produce > something that you (for want of a better example) find incredibly > useful, are now beholden to improve it still further and make it still > more useful, because otherwise nobody else will feel it necessary to > create and maintain documentation of high quality? The developers are not beholden to anyone for anything, but if they also act as Python advocates and claiming that Python is good or well-documented software, they're the ones responsible for backing up the claims. If they want to say that it's experimental/unreliable or poorly documented, their responsibility is much lower. But they promote it as being suitable for critical applications. > Bear in mind that the PSF made its very first grants last year. OK, I thought it had been doing stuff like that for longer. My error. > The reason none of those grants was awarded to a documentation > project was that the (volunteer) Grants Committee and helpers didn't > see any documentation projects worthy of support. It looks to me like the approach of calling for random proposals doesn't get the right kind of proposals. The PSF should instead make its own list of stuff it wants done, and call for people to step forward to do those things. Or if there's enough funds, it should hire some full time people and assign tasks to them. > What Python really needs is for Python enthusiasts to understand that > the future of the language is largely in their hands. It's easy to say > "but I can't do this" or "I can't do that". Forget such > negativity. Find something you *can* do to improve Python - document a > module, chair a conference, or (as *you* already do) contribute your > knowledge and experience to c.l.py to improve the level of Python > awareness. No, that's completely wrong; most of the suggestions I've made to improve Python cannot be made by "outsiders". I can't add modules to the stdlib that I think belong there. Only the core developers can do that. I can't add conditional expressions to the language to stop clpy newbies from asking for them practically every other week. Only the BDFL can do that. I can't phone up John Shipman and ask him on behalf of the PSF if he'll re-license his tkinter manual so Python can include it, because only the PSF can do that. You get the idea. Anyway, I don't want to be a Python developer or Python volunteer. I'm just a user. I do volunteer work on other projects that don't happen to be Python. If I had more time or energy available to do more volunteer work, I'd still put it in those other projects and not in Python. Python for me is a tool, like a hammer. If the hammers I use keep breaking or hitting the nails the wrong way, I might contact the manufacturer and urge various improvements, but I'm not interested in their suggestions that I come work on improving the hammers myself. I want to build houses, not make hammers. I'm not bashing Python and I'm happy to be a user, but my volunteering priorities are elsewhere. > I have done all of these things, and I firmly believe that each could > have been done better. Unfortunately those with superior skills chose > not to engage the Python community. Which left it stuck with me. Poor > Python. I don't know that my skills are so superior, but I believe I'm engaging the Python community. > Most of all, realise that there is no "us" and "them". *We* are > "them", and it's up to *us* to accept that and try to improve things. "We" (i.e. "you") is not "me" except on an incidental basis. See above. > Please understand that I don't mean to belittle anyone who has made > any kind of contribution to Python (even Xah Lee has his place, though > I tremble to think so). I just want more Python users to understand > that there are many contributions they could make that are well within > their capabilities, and to get off their butts and start doing > something! Thanks for the pep talk but you're not telling me anything I don't already know. Really, I like your posts and appreciate the work you've done, but that particular line of advice comes across as patronizing. I know what projects I want to allocate my volunteer development time to and Python isn't one of them. From luismgz at gmail.com Sat Sep 17 10:51:11 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 17 Sep 2005 07:51:11 -0700 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: References: Message-ID: <1126968671.658845.6820@g49g2000cwa.googlegroups.com> This is great news. Congratulations! By the way, I read in your blog that you would be releasing a windows intaller soon. Have you, or anyone else, managed to do it? Cheers, Luis From Uri.Nix at gmail.com Mon Sep 26 02:16:14 2005 From: Uri.Nix at gmail.com (Uri Nix) Date: 25 Sep 2005 23:16:14 -0700 Subject: subprocess considered harmfull? In-Reply-To: <1127695474_23907@spool6-east.superfeed.net> References: <1127655407.113698.205440@z14g2000cwz.googlegroups.com> <1127695474_23907@spool6-east.superfeed.net> Message-ID: <1127715374.336617.87770@g49g2000cwa.googlegroups.com> Roger Upole wrote: > "Fredrik Lundh" wrote in message news:mailman.928.1127678532.509.python-list at python.org... > > Steven Bethard wrote: > > > >> > Using the following snippet: > >> > p = > >> > subprocess.Popen(nmake,stderr=subprocess.PIPE,stdout=subprocess.PIPE, \ > >> > universal_newlines=True, bufsize=1) > >> > os.sys.stdout.writelines(p.stdout) > >> > os.sys.stdout.writelines(p.stderr) > >> > Works fine on the command line, but fails when called from within > >> > Visual Studio, with the following error: > >> > File "C:\Python24\lib\subprocess.py", line 549, in __init__ > >> > (p2cread, p2cwrite, > >> > File "C:\Python24\lib\subprocess.py", line 609, in _get_handles > >> > p2cread = self._make_inheritable(p2cread) > >> > File "C:\Python24\lib\subprocess.py", line 650, in _make_inheritable > >> > DUPLICATE_SAME_ACCESS) > >> > TypeError: an integer is required > >> > >> This looks like these known bugs: > >> http://python.org/sf/1124861 > >> http://python.org/sf/1126208 > >> > >> Try setting stderr to subprocess.PIPE. I think that was what worked for > >> me. (You might also try setting shell=True. That's what I currently > >> have in my code that didn't work before.) > > > > if someone wants to investigate, is seeing this problem, and have the win32 > > extensions on their machine, try changing this line in subprocess.py: > > > > if 0: # <-- change this to use pywin32 instead of the _subprocess driver > > > > to: > > > > if 1: # <-- change this to use _subprocess instead of the pywin32 driver > > > > and see if it either fixes the problem (not very likely) or gives you a better > > error message (very likely). > > > > > > > > The error msg is only slightly better: > > error: (6, 'DuplicateHandle', 'The handle is invalid.') > > Basically, gui apps like VS don't have a console, so > GetStdHandle returns 0. _subprocess.GetStdHandle > returns None if the handle is 0, which gives the original > error. Pywin32 just returns the 0, so the process gets > one step further but still hits the above error. > > Subprocess.py should probably check the > result of GetStdHandle for None (or 0) > and throw a readable error that says something like > "No standard handle available, you must specify one" > > Roger > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups > ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- I gathered as much about why this happens in VS. A further question is why does n't os.popen fall in the same trap? Cheers, Uri From steve at REMOVETHIScyber.com.au Sun Sep 18 08:45:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 18 Sep 2005 22:45:32 +1000 Subject: Putting a lock on file. References: <1127026738.905504.214360@g43g2000cwa.googlegroups.com> Message-ID: On Sat, 17 Sep 2005 23:58:58 -0700, Harlin Seritt wrote: > I have a file that a few different running scripts will need to access. > Most likely this won't be a problem but if it is, what do I need to do > to make sure scripts don't crash because the input file is in use? > Would it be best to run a loop like the following: > > flag = 0 > while not flag: > try: > open(file, 'r').read() > flag = 1 > except: > pass > > This may seem nice on paper but I hate to run a while for an > indeterminate amount of time. Is there anything else that can be done > that would be better? Instead of while flag, use a for loop. That way, when you have tried unsuccessfully some known number of times, you can report back to the user that you have tried and failed. Also, in any serious program you should give better error reporting than the above, especially for file-related errors. A bare "except:" that catches all errors is generally bad practice. Eg, suppose you meant to write "open(filename, 'r').read()" but accidentally mistyped ".raed()" instead. Your except clause would catch the error, and you would spend hours trying to work out why your file can't be opened. Try something like this: import errno def get_file(fname, max_tries=10): """Returns the contents of fname, or None if there is an error.""" for i in range(max_tries): try: fp = open(fname, 'r') text = fp.read() fp.close() # don't wait for Python to close it for you return text except IOError, (error, message): if error == errno.ENOENT: print "No such file. Did you look behind the couch?" break elif error == errno.EIO: print "I/O error -- bad media, no biscuit!" break elif error in (errno.EPERM, errno.EACCES): print "Permission denied. Go to your room!" break elif error == errno.EINTR: print "Interupted call... trying again." continue elif error in (errno.EWOULDBLOCK, errno.EAGAIN): print "Temporary error..." \ " please wait a few seconds and try again." continue else: # Some other error, just print Python's message. print message else: # only called if you don't break print "Sorry, the file is in use. Please try again later." return None You should look at the module errno, together with the function os.strerror(), for more details. Of course, many people don't worry about giving their own explanations for IOErrors, and simply return the same error that Python does. These two pages might be useful too: http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html http://www.gnu.org/software/libc/manual/html_node/File-Locks.html -- Steven. From desparn at wtf.com Mon Sep 5 10:56:48 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Mon, 05 Sep 2005 10:56:48 -0400 Subject: Proposal: add sys to __builtins__ References: Message-ID: "Michael J. Fromberger" wrote in news:Michael.J.Fromberger-3F0330.09342305092005 at localhost: > In article , > Rick Wotnaz wrote: > >> Michael Hoffman wrote in >> news:df7jlu$1te$1 at gemini.csx.cam.ac.uk: >> >> > What would people think about adding sys to __builtins__ so >> > that "import sys" is no longer necessary? This is something I >> > must add to every script I write that's not a one-liner since >> > they have this idiom at the bottom: >> > >> > if __name__ == "__main__": >> > sys.exit(main(sys.argv[1:])) >> > >> > [...] >> > >> > In short, given the wide use of sys, its unambiguous nature, >> > and the fact that it really is built-in already, although not >> > exposed as such, I think we would be better off if sys were >> > always allowed even without an import statement. >> >> +1 here. As far as I'm concerned, both os and sys could be >> special- cased that way. That said, I would guess the >> likelihood of that happening is 0. > > While I'm mildly uncomfortable with the precedent that would be > set by including the contents of "sys" as built-ins, I must > confess my objections are primarily aesthetic: I don't want to > see the built-in namespace any more cluttered than is necessary > -- or at least, any more than it already is. > > But "os" is another matter -- the "os" module contains things > which might well not be present in an embedded Python > environment (e.g., file and directory structure navigation, > stat). Do you really want to force everyone to deal with that? > Is it so much more work to add "import os" to those Python > programs that require it? > > Of course, you might counter "why should we force everybody else > to type `import os' just in case somebody wants to imbed > Python?" But then, why don't we just include the whole standard > library in __builtins__? Or, since that would be too much, > maybe we survey the user community and include the top fifteen > most included modules! Where do you draw the line? Do you > really want to hard-code user opinions into the language? > > Right now, we have a nice, simple yet effective mechanism for > controlling the contents of our namespaces. I don't think this > would be a worthwhile change. -1. > You're right that there is no necessity for such a change. I was not actually talking about importing *any* module in every case, but rather about importing, say, 'sys' when, for example, sys.argv appeared in the code and no import had been specified. In another post I go into a little more detail about what I meant, but in any case I did not and do not think it's necessary. I have no problem keying in the import statement and the current system works fine. It could be argued that it would be convenient in the case of quick utility code not to have to import well-known modules explicitly, and it could be argued that 'sys' in particular contains much that is so seemingly fundamental that it could be built in. I'd not argue that it should be split out if it were already built in; it seems to be borderline standard as it is. I suppose it's a C mindset talking, there. When I'm cobbling together a Q&D script, my routine often involves running it once and then going back in and inserting the single import line that I forgot. It's a minor annoyance, because it seems clear to me that the needed information is actually available to Python when it kicks out its NameError. But it *is* minor, and I am not seriously proposing a change to Python in this regard. -- rzed From xah at xahlee.org Thu Sep 8 17:54:20 2005 From: xah at xahlee.org (Xah Lee) Date: 8 Sep 2005 14:54:20 -0700 Subject: reading the last line of a file In-Reply-To: References: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> <1126168591.395956.118840@z14g2000cwz.googlegroups.com> Message-ID: <1126216460.523018.71840@g44g2000cwa.googlegroups.com> isn't there a way to implement tail in python with the same class of performance? how's tail implemented? Xah xah at xahlee.org ? http://xahlee.org/ Fredrik Lundh wrote: > Fredrik Lundh wrote: > > > zcat|tail is a LOT faster. > > and here's the "right way" to use that: > > from subprocess import Popen, PIPE > p1 = Popen(["zcat", filename], stdout=PIPE) > p2 = Popen(["tail", "-1"], stdin=p1.stdout, stdout=PIPE) > last_line = p2.communicate()[0] > > (on my small sample, this is roughly 15 times faster than the empty for loop) > > From gmane-esc at mmf.at Mon Sep 12 07:39:35 2005 From: gmane-esc at mmf.at (Erich Schreiber) Date: Mon, 12 Sep 2005 13:39:35 +0200 Subject: Premature wakeup of time.sleep() Message-ID: In the Python Library Reference the explanation of the time.sleep() function reads amongst others: > The actual suspension time may be less than that requested because > any caught signal will terminate the sleep() following execution > of that signal's catching routine. Also, the suspension time may > be longer than requested by an arbitrary amount because of the > scheduling of other activity in the system. I don't understand the first part of this passage with the premature wakeup. What signals would that be? I've written a script that tries to bench the responsiveness of a virtual Linux server. My script sleeps for a random time and on waking up calculates the difference of the proposed and actual wakeup time. The essential code fragment is while True: ts = tDelay() t1 = time.time() time.sleep(ts) t2 = time.time() twu = str(datetime.datetime.utcfromtimestamp(t1 + ts)) logResults(LOGFILE, twu, ts, int((t2-t1-ts)*1000)) Whereas tDelay() returns a (logarithmically) randomly distributed real number in the range [0.01, 1200] which causes the process to sleep from 10 ms to 20 minutes. In the logs I see a about 1% of the wake-up delays beeing negative from -1ms to about -20ms somewhat correlated with the duration of the sleep. 20 minute sleeps tend to wake-up earlier then sub-second sleeps. Can somebody explain this to me? Regards, Erich Schreiber From onurb at xiludom.gro Tue Sep 6 13:31:06 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 06 Sep 2005 19:31:06 +0200 Subject: Django Vs Rails In-Reply-To: References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <1125975775.892662.231980@f14g2000cwb.googlegroups.com> <431dca31$0$29335$636a15ce@news.free.fr> Message-ID: <431dd25c$0$2327$626a14ce@news.free.fr> D H wrote: > bruno modulix wrote: > >> D H wrote: >> >> (snip) >> >>> Go with Rails. Django is only like a month old. >> >> >> Please take time to read the project's page. Django has in fact three >> years of existence and is already used on production websites, so it's >> far from pre-alpha/planning stage. >> > > Don't make any assumptions about what I have and haven't read. Don't make the assumption that the advice to read the project's page was directed to you only !-) > Django > was only publicly released in mid-July. Less than two months ago. > I never implied it was "pre-alpha" or in a "planning" stage. That what I understood from your post, and I guess most readers would understand it that way. Now the fact that Django, while being young as a publicly realeased project, has in fact 3 years of existence *on production websites* is IMHO worth mentioning, so peoples who haven't read the project's page yet don't make the assumption that it must be too young to be usable in production. The "take time to read..." advice was directed to these people as well !-) Regards -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" From rrr at ronadam.com Mon Sep 19 23:03:15 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 20 Sep 2005 03:03:15 GMT Subject: Question About Logic In Python In-Reply-To: References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Mon, 19 Sep 2005 12:16:15 +0200, sven wrote: > > >>to make sure that an operation yields a boolean value wrap a bool() >>around an expression. >>None, 0 and objects which's len is 0 yield False. >>so you can also do stuff like that: > > > Are there actually any usage cases for *needing* a Boolean value? Any > object can be used for truth testing, eg: > > if the_str > > is to be preferred over: > > if bool(the_str) > > or even worse: > > if bool(the_str != "") > > Or wait, I have thought of one usage case: if you are returning a value > that you know will be used only as a flag, you should convert it into a > bool. Are there any other uses for bool()? Of course if any of the default False or True conditions are inconsistent with the logic you use, you need to do explicit truth testing. if val > -1: Where 0 would be True condition. if arg != None: Where '' could be a True condition. Also... you need to be careful what order you do your comparisons in as.. (1 and 2) != (2 and 1) # they are both True, but not equal. bool(1 and 2) == bool(2 and 1) (1 and 2) * value != (2 and 1) * value # except if value is False. bool(1 and 2) * value == bool(2 and 1) * value So.. bool(a and b) * value Would return value or zero, which is usually what I want when I do this type of expression. Cheers, Ron From jstroud at mbi.ucla.edu Sat Sep 10 18:04:24 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 10 Sep 2005 15:04:24 -0700 Subject: encryption with python In-Reply-To: <87k6hok51e.fsf@debian.kirkjobsluder.is-a-geek.net> References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <7x8xy4enhg.fsf@ruckus.brouhaha.com> <87k6hok51e.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <200509101504.24141.jstroud@mbi.ucla.edu> On Saturday 10 September 2005 14:01, Kirk Job Sluder wrote: > Providing any kind of access to data involves creating a security hole. > This is the biggest flaw in most discussions of computer security. On 9/9/05 Steven D'Aprano wrote: > There are "one-way" encryption functions where the result can't easily be > traced back to the input, but why do you need the input anyway? Here is my > quick-and-dirty student ID algorithm: I have invented the perfect security protocol that solves a major problem with the one-time-pad. The problem with most one-time-pad protocols is that you still need to have the pad around, creating a major security hole. I have solved that problem here. It has all of the steps of the usual one-time-pad plus an extra step. 1. Generate a random number the size of your data. 2. XOR your data with it. 3. Destroy the original data. Here is the additional step: 4. Destroy the random number. You can see now that no adversary can resonably reconstruct the plain text. This protocol might be terribly inconvenient, though, because it makes the origina data unaccessible. Oh well, just a necessary byproduct of theoritcally perfect security. I hereby place this algorithm in the public domain. Use it freely. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From reinhold-birkenfeld-nospam at wolke7.net Wed Sep 14 16:42:31 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 14 Sep 2005 22:42:31 +0200 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: <1126719171.467217.149220@g14g2000cwa.googlegroups.com> References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> <1126715343.490964.5640@f14g2000cwb.googlegroups.com> <3or48lF7480dU1@individual.net> <1126719171.467217.149220@g14g2000cwa.googlegroups.com> Message-ID: <3org9nF7c96uU1@individual.net> n00m wrote: > Got it! He is a kind of pythonic monsters. > > Btw, why it's impossible to reply to old threads? > Namely, there're no more "Reply" link in them. > Only "Reply to author" etc. Perhaps because you are not using a real Usenet client? Reinhold From hancock at anansispaceworks.com Wed Sep 28 11:26:28 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 28 Sep 2005 10:26:28 -0500 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xbr2dxqqq.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> Message-ID: <200509281026.28820.hancock@anansispaceworks.com> On Wednesday 28 September 2005 08:32 am, Paul Rubin wrote: > Unless you can show that all Python code is bug-free, you've got to > consider that there might be something to this private and protected > stuff. Of course, "unless you can show that all Java code is bug-free, you've got to consider that this private and protected stuff might be bunk", too. ;-) "never", "always", "-free" are very dangerous concepts. :-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From billiejoex at fastwebnet.it Mon Sep 5 14:36:59 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Mon, 5 Sep 2005 20:36:59 +0200 Subject: Python compiled? Message-ID: Hi all. I'm sorry for a noob question like this but I'll try to ask it anyway. One of the greatest problem that may discourage a new user to choose Python language is it's interpreted nature. Another important problem is that no interpreter is installed on Windows machine by default and this makes harder to distribute the software. Does it is planned that, in a far future, Python will implement a form of compilation? This would be awesome. From nephish at xit.net Thu Sep 29 09:07:48 2005 From: nephish at xit.net (nephish at xit.net) Date: 29 Sep 2005 06:07:48 -0700 Subject: another time challenge In-Reply-To: References: <1127924738.875240.40870@o13g2000cwo.googlegroups.com> Message-ID: <1127999268.817393.4500@g47g2000cwa.googlegroups.com> cool, thanks -shawn From michaelschneider at fuse.net Thu Sep 29 10:08:28 2005 From: michaelschneider at fuse.net (Michael Schneider) Date: Thu, 29 Sep 2005 10:08:28 -0400 Subject: What python idioms for private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> Message-ID: <3f11a$433bf55e$d8c4f6e6$10834@FUSE.NET> I have been following this thread with great interest. I have been coding in C++ since the late 80's and Java since the late 90's. I do use private in these languages, with accessors to get at internal data. This has become an ingrained idiom for me. When I create a python object, it is natural for me to want to use familiar idioms. Hare are the places where private is useful to me: Design Intent: 1) mark an object as dirty in a setter (anytime the object is changed, the dirty flag is set without requiring a user to set the dirty flag 2) enforce value constraints (even if just during debugging) 3) lazy init, don't bring the data in until needed 4) adding debug info 5) .... more here???? I do write code that violates private - memory ptr access in C++ - reflection in java - aspects in java I usually violate private when adding an aspect to a class, and I don't want this code in every class. Example, persistence. I really like the C# properties, you can access data with a data accessor, but add functionality is triggered when accessing the data. I like the data access syntax, better then the set/get functions. I need the functionality to achieve the design goals above, so i use function, but the are ugly, especially in math code. It would be easy for me to say "Add public and private to python so I can code the way that I am used to". What are some python alternatives to achieve the design intents specified above above? Thanks Mike From oliver.eichler at dspsolutions.de Mon Sep 12 05:59:08 2005 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Mon, 12 Sep 2005 11:59:08 +0200 Subject: exceptions from logging on Windows Message-ID: Hi, I experience several exceptions from python's logging system when using the rollover feature on Windows. Traceback (most recent call last): File "c:\Python24\lib\logging\handlers.py", line 62, in emit if self.shouldRollover(record): File "c:\Python24\lib\logging\handlers.py", line 132, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file Googeling revealed that this has been experienced by others, too, however no workaround or solution has been provided. Is this the latest status on this topic? Do I miss something? Thanks for help, Oliver From alengarbage at yahoo.com Mon Sep 12 11:29:52 2005 From: alengarbage at yahoo.com (Lenny G.) Date: 12 Sep 2005 08:29:52 -0700 Subject: fully-qualified namespaces? Message-ID: <1126538992.707768.225820@z14g2000cwz.googlegroups.com> Suppose I have a python module named Hippo. In the Hippo module is a class named Crypto. The Crypto class wants to 'from Crypto.Hash import SHA' which refers to the module/classes in python-crypto. Other classes in the Hippo module want to 'import Crypto' referring to Hippo.Crypto. How do I do this? For now, I just renamed my Hippo.Crypto to Hippo.HippoCrypto and everything is okay as long as I use 'HippoCrypto' to refer to that class. But, this is of course redundant. What I really want to do is use 'import Crypto' # to refer to python-crypto 'import Hippo.Crypto' # to refer to Hippo.Crypto but the 2nd item doesn't seem to work from within the Hippo module. What am I missing? Thanks, Lenny G. From steve at holdenweb.com Thu Sep 29 07:33:24 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Sep 2005 12:33:24 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7x4q84s13w.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xfyroe5vh.fsf@ruckus.brouhaha.com> <7x4q84s13w.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Gregor Horvath writes: > >>>If you don't want the compiler to make sure your private instance >>>variables stay private, then don't declare them that way. You're the >>>one asking for less flexibility. >> >>I want to declare them as private, but want to give the flexibilty to >>access them at the users own risk. > > > What else do you want to let users do at their own risk? Treat > integers as pointers, like in C? Both are violations of type safety. > > >>Declaring everything as public is nonsene, because there should be a >>garanteed stable interface. > > > You could have a "friend" declaration like in C++, if you want to let > some class see the private instance variables of another class. > > I can't think of a single time that I've ever seen a legitimate use of > name mangling to reach from one class into another in a Python > application (I don't count something like a debugger). If you're got > some concrete examples I wouldn't mind looking. [psst ... do you think they've stopped now?] -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From rixil at hotmail.com Sun Sep 18 00:22:37 2005 From: rixil at hotmail.com (rixil at hotmail.com) Date: 17 Sep 2005 21:22:37 -0700 Subject: complex data types? References: Message-ID: <1127017357.053187.45370@g43g2000cwa.googlegroups.com> richard wrote: > I'd like to have an array in which the elements are various data types. > How do I do this in Python? > > For example: > > array[0].artist = 'genesis' > array[0].album = 'foxtrot' > array[0].songs = ['watcher', 'time table', 'friday'] > array[1].artist = 'beatles' > array[1].album = 'abbey road' > array[1].songs = ['come', 'something', 'maxwell'] > > Everything I try generates errors or results in array[0].songs equaling > array[1].songs. I feel I'm missing something obvious. If you show us where array[0] and array[1] are being initialized, it would be easier to diagnose the problem. At the same time, if array[0].songs equals array[1] songs, you are probably initializing both array[0] and array[1] with the same object. Since array[0] and array[1] both refer to the same object, a change to one will be reflected in the other. I hope this is what you're looking for. Michael Loritsch From peter at engcorp.com Wed Sep 28 14:28:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Sep 2005 14:28:14 -0400 Subject: import problems in packages In-Reply-To: References: Message-ID: St?phane Ninin wrote: > Traceback (most recent call last): > File "main.py", line 8, in ? > main() > File "main.py", line 5, in main > handler = HandlerFactory().makeHandler(command) > File "c:\ROOT\Handlers\HandlerFactory.py", line 6, in HandlerFactory > import Handlers.Default.HandlerFactory > ImportError: No module named Default.HandlerFactory Are you sure that's right? You asked it to import Handlers.Default.HandlerFactory but it is apparently importing just Default.HandlerFactory instead? This seems unexpected to me, though perhaps it can happen in certain situations. It's a hint, anyway. Are the earlier four lines which you did show us relevant? (i.e. if that's line six, what was on lines one, two, three, and four?) -Peter From steve at REMOVETHIScyber.com.au Wed Sep 28 08:30:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 28 Sep 2005 22:30:23 +1000 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: For some reason, the original post never made it to my newsreader, so apologies for breaking threading by replying to a reply when I mean to answer the original post. On Wed, 28 Sep 2005 12:05:21 +0100, Simon Brunning wrote: > On 9/28/05, could ildg wrote: >> Python is wonderful except that it has no real private and protected >> properties and methods. Do you know any language that has real private and protected attributes? There may be some. I don't know. But anyone who says "C++" is fooling themselves: #define private public And your "real private and protected" objects are no longer private or protected. Simon wrote: > If *real* private and protected are *enforced*, Python will be the > poorer for it. See > . That's a wonderful, if long, essay. I don't think the author is wrong, but I think his choice of terminology does Python a disservice (it is hard to argue in favour of anarchy and chaos even to enlightened sensible managers, let alone old dinosaurs and control-freaks). It is too easy to mistakenly read that essay as saying that Python finds a middle ground between two binary opposites of control and chaos. That's not the case: chaos is a privative, not an actual thing. Chaos is what you have when you have zero control. The question should be, how much control a language needs: control is a continuous variable, not a binary on/off state. Less control gives more flexibility. More control reduces opportunities. That's a minor quibble really, the essay is grand and should be read by all developers. -- Steven. From Nainto at gmail.com Sat Sep 17 15:43:40 2005 From: Nainto at gmail.com (Nainto) Date: 17 Sep 2005 12:43:40 -0700 Subject: FTP status problems. (Again) In-Reply-To: References: <1126924074.901404.214550@g49g2000cwa.googlegroups.com> <1126932146.25366.3.camel@blackwidow> <1126933138.25366.7.camel@blackwidow> <1126959503.745828.124600@g47g2000cwa.googlegroups.com> <1126962482.066731.61010@g47g2000cwa.googlegroups.com> Message-ID: <1126986220.091358.212100@g44g2000cwa.googlegroups.com> I'm really sorry that I keep having problems with this. :-( Now I get: TypeError: Error when calling the metaclass bases[] str() takes at most 1 arguement (3 given) and the Traceback is: file "formattedthing", line 2, in '?' classProgressFile(file) With the following code: import ftplib class ProgressFile(file): def read(self, size = None): from sys import stdout if size is not None: buff = file.read(self, size) if buff: stdout.write('.') else: stdout.write('\n') return buff else: buff = '' while True: new_str = file.read(self, 1024) stdout.write('.') if new_str: buff = buff + new_str else: stdout.write('\n') break return buff if __name__ == '__main__': ftp = ftplib.FTP("ftp.sadpanda.cjb.cc") ftp.login("sadpanda","PASSWORDEDITEDOUT") file = "/FrenchBrochure.pages.zip" ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024) ftp.quit() Thanks so muchy for help guys. :-) From jeffrey.schwab at rcn.com Fri Sep 23 08:25:59 2005 From: jeffrey.schwab at rcn.com (Jeff Schwab) Date: Fri, 23 Sep 2005 08:25:59 -0400 Subject: What is "self"? In-Reply-To: References: <43335c5f$1_4@alt.athenanews.com> Message-ID: <5o2dnXRuCuTEaa7enZ2dnUVZ_tCdnZ2d@rcn.net> Rick Wotnaz wrote: > Roy Smith wrote in > news:roy-DE5389.07461923092005 at reader1.panix.com: > > >>Ron Adam wrote: >> >>>You can actually call it anything you want but "self" is sort >>>of a tradition. >> >>That's true, but I think needs to be said a bit more >>emphatically. There's no reason to call it anything other than >>"self" and a newcomer to the language would be well advised to >>not try and be creative here. Using "self" is virtually >>universal, and calling it anything else will just lead to >>confusion by other people who have to read your code. > > > I've long thought that Guido missed an opportunity by not choosing > to use 'i' as the instance identifier, and making it a reserved > word. For one thing, it would resonate with the personal pronoun > 'I', and so carry essentially the same meaning as 'self'. It could > also be understood as an initialism for 'instance'. And, because it > is shorter, the number of objections to its existence *might* have > been smaller than seems to be the case with 'self' as the > convention. > > And as a side benefit, it would make it impossible to use as a loop > index a language feature that would be a huge selling point among a > lot of experienced programmers. And an annoyance to others. From fredrik at pythonware.com Mon Sep 26 10:21:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Sep 2005 16:21:03 +0200 Subject: number of python users References: Message-ID: Bryan wrote: > is there a rough estimate somewhere that shows currently how many python 1.5 vs > 2.2 vs 2.3 vs 2.4 users there are? have a majority moved to 2.4? or are they > still using 2.3? etc... Here are current PIL download statistics (last 10 days): 75.6% /downloads/PIL-1.1.5.win32-py2.4.exe 18.0% /downloads/PIL-1.1.5.win32-py2.3.exe 2.2% /downloads/PIL-1.1.5.win32-py2.2.exe 4.2% /downloads/PIL-1.1.5.win32-py2.1.exe Note that these are fresh downloads for Windows, not users. People who run other systems, or are happy with their existing installation, isn't included (so older versions are probably more common than they appear). (fwiw, I still have users on 1.5.2 for most of my libraries. usually huge Unix systems that nobody wants to break just because they can...) From grante at visi.com Wed Sep 7 14:15:16 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 07 Sep 2005 18:15:16 -0000 Subject: Sniffer with RAW SOCKETS References: Message-ID: <11hubhkral16b2a@corp.supernews.com> On 2005-09-07, billiejoex wrote: > Hi all. I'm trying to make a simple icmp sniffer by using > SOCK_RAW. Just a suggestion: you'd probably be better off using the PCAP library. > The code below works but ONLY if I first use the sendto() > function. Does anybody knows why? 'Fraid not. -- Grant Edwards grante Yow! I just bought at FLATBUSH from MICKEY visi.com MANTLE! From fredrik at pythonware.com Thu Sep 29 15:05:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 21:05:28 +0200 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com><7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com><20050929182936.50b6ec54.jk@ospaz.ru> <20050929225610.504bd9d5.jk@ospaz.ru> Message-ID: en.karpachov at ospaz.ru wrote: > Do you ever heard of that funny things named "an interface" and "an > implementation"? the "shared DLL:s ought to work" school of thought, you mean? From drochom at googlemail.com Thu Sep 15 10:18:55 2005 From: drochom at googlemail.com (drochom) Date: 15 Sep 2005 07:18:55 -0700 Subject: Removing duplicates from a list In-Reply-To: <1126793332.635421.18630@g44g2000cwa.googlegroups.com> References: <1126697915.879705.300450@g44g2000cwa.googlegroups.com> <1126706415.609072.92570@o13g2000cwo.googlegroups.com> <1126793332.635421.18630@g44g2000cwa.googlegroups.com> Message-ID: <1126793935.694622.142330@o13g2000cwo.googlegroups.com> there wasn't any information about ordering... maybe i'll find something better which don't destroy original ordering regards przemek From simon.brunning at gmail.com Wed Sep 28 08:17:25 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 28 Sep 2005 13:17:25 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7x3bnppfad.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7x3bnppfad.fsf@ruckus.brouhaha.com> Message-ID: <8c7f10c605092805174676e078@mail.gmail.com> On 28 Sep 2005 05:06:50 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Steven D'Aprano writes: > > Do you know any language that has real private and protected attributes? > > Java? Oh, there are ways around private and protected, even in Java. CGLIB spings to mind. But you'd be wise to follow the rules, especially if you work in a team. When writing Java, I write Java. When writing Python, I write Python. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Thu Sep 29 07:30:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Sep 2005 12:30:11 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <20050929140748.486867ca.jk@ospaz.ru> References: <311b5ce105092800102da32267@mail.gmail.com> <433A974A.2070006@newcenturycomputers.net> <20050929140748.486867ca.jk@ospaz.ru> Message-ID: en.karpachov at ospaz.ru wrote: > On Wed, 28 Sep 2005 08:14:50 -0500 > Chris Gonnerman wrote: > > >>There are two philosophies about programming: >> >>-- Make it hard to do wrong. >> >>-- Make it easy to do right. >> >>What you are promoting is the first philosophy: Tie the programmer's >>hands so he can't do wrong. Python for the most part follows the >>second philosophy, > > > So it is for the very this reason there is no assignment operator in the > Python? > If you are really asking whether assignment was deliberately designed as a statement rather than an operator, the answer is "yes". http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression Note also that the Python alternative is now rather out of date: rather than writing while True: line = f.readline() if not line: break ...do something with line... We would nowadays write for line in f: ...do something with line... which seems to feel quite natural to most Python programmers. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From steve at holdenweb.com Fri Sep 2 13:22:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Sep 2005 12:22:16 -0500 Subject: Bug in string.find In-Reply-To: References: <7xy86k3r7n.fsf@ruckus.brouhaha.com><4314b190.174021119@news.oz.net> Message-ID: Dennis Lee Bieber wrote: > On Fri, 02 Sep 2005 00:23:14 GMT, Ron Adam declaimed > the following in comp.lang.python: > > >>So how do I express a -0? Which should point to the gap after the last >>item. >> > > Step one: Obtain a processor that uses ones-complement arithmetic. > Ah, the good old Univac 418 ... [drools into beard and mumbles] > Step two: Port Python to said processor... > Unfortunately the 418 would probably come in at about a micro-pystone, so perhaps we should emulate it on something more modern? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From barnesc at engr.orst.edu Wed Sep 14 03:48:52 2005 From: barnesc at engr.orst.edu (barnesc at engr.orst.edu) Date: Wed, 14 Sep 2005 00:48:52 -0700 Subject: Builtin classes list, set, dict reimplemented via B-trees Message-ID: <1126684132.4327d5e4335b6@webmail.oregonstate.edu> Hi again, Since my linear algebra library appears not to serve any practical need (I found cgkit, and that works better for me), I've gotten bored and went back to one of my other projects: reimplementing the Python builtin classes list(), set(), dict(), and frozenset() with balanced trees (specifically, counted B-trees stored in memory). In short, this allows list lookup, insertion, deletion in O(log(N)) time. It allows the set and dictionary types to be maintained in order, and insert/lookup/remove operations here take O(log(N)) time as well. Getting the k least or k greatest elements takes O(log(N)+k) time. I'm about 50% done with the implementation of this module. I thought I'd use this for Dijkstra's algorithm and some schedulers, but then I noticed that a binary heap can be retrofitted to have the DECREASE-KEY operation (see e.g. David Eppstein's priorityQueue). Thus my B-tree based classes aren't really necessary, since there are simpler heap implementations that do the same thing. So my question is: are there any other *practical* applications of a B-tree based list/set/dict ? In other words, is this module totally worth coding, or is it just academic wankery and theoretical flim flam ? :) Thanks for your comments/opinions/etc... - Connelly Barnes 'Y29ubmVsbHliYXJuZXNAeWFob28uY29t'.decode('base64') --------------------------------------------------------------------- Detailed overview of the bcollections module (from the docstring) --------------------------------------------------------------------- """ ... The bset() and bdict() classes improve upon the builtin set and dictionary types by maintaining the elements in sorted order. Generally, the b* classes are a factor of O(log(N)) slower[2] than the corresponding builtin classes, except for certain operations: - For a bset(), it takes O(log(N)) time to get the minimum, maximum, or ith element. Also, it takes O(log(N)+k) time to get the k first, k last, or any slice of k elements from the sorted set. - For a bdict(), dictionary keys can be retrieved in sorted order with the above time bounds. - For a blist(), items can be inserted and removed in O(log(N)) time. It takes O(log(N)+k) time to get, set, or delete a slice of k elements. ... blist - List implemented via B-tree. bset - Set implemented via B-tree. Additional methods: - s.min() - Minimum element - s.max() - Maximum element - s.index(x) - Index of x in sorted list of elements. - s.next(x) - Least element which is > x (x need not be in the set). - s.previous(x) - Greatest element which is < x (x need not be in the set). - s[i] - Get element i from sorted list. - s[i:j] - Get slice from sorted list. bfrozenset - Immutable set implemented via B-tree. bdict - Dict implemented via B-tree. Additional methods: - a.min() - Minimum key - a.max() - Maximum key - a.index(k) - Index of k in sorted list of keys. - s.next(x) - Least key which is > x (x need not be an existing key). - s.previous(x) - Greatest key which is < x (x need not be an existing key). - a.get_key_at(i) - Get key at index i from sorted list of keys. - a.get_key_at(i, j) - Get slice from sorted key list. """ From juho.schultz at helsinki.fi Tue Sep 27 05:01:57 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Tue, 27 Sep 2005 12:01:57 +0300 Subject: Changing the module not taking effect in calling module In-Reply-To: <1127810252.595755.54540@g14g2000cwa.googlegroups.com> References: <1127810252.595755.54540@g14g2000cwa.googlegroups.com> Message-ID: Gopal wrote: > Hi, > > I've a module report.py having a set of funtions to open/close/write > data to a log file. I invoke these functions from another module > script.py. > > Whenever I'm changing something in report.py, I'm running the file > (however, it has not effect). After that I'm running script.py again. > However, the output is not taking effect. > > If I shut the IDLE interpreter and all the other files and then reopen > again; and then run script.py, the output is taking effect. > > Is there any way to improve it? I'm new to Python. > > -Gopal. > you could try "reload(module)" instead of "import module" or running the file. From benji at benjiyork.com Sun Sep 4 23:45:04 2005 From: benji at benjiyork.com (Benji York) Date: Sun, 04 Sep 2005 23:45:04 -0400 Subject: learning python In-Reply-To: <1125889638.110220.172010@z14g2000cwz.googlegroups.com> References: <1125886211.816019.201070@z14g2000cwz.googlegroups.com> <1125887831.3fb3e29f106c8f78f93b86aa1197a085@teranews> <1125889638.110220.172010@z14g2000cwz.googlegroups.com> Message-ID: <431BBF40.7020709@benjiyork.com> placid wrote: > Christopher Culver wrote: >>"placid" writes: >>>I was just wondering about good books that teach python (either with >>>programming or no programming experience at all) ? Or some online >>>tutorial? >> >>Did you even bother doing a web search? "Learn Python" or "Python >>tutorial" would be enough. > > > yeah, see i didnt even think of that. > > thanks man That was either a very gracious way to take a public correction, or an expertly executed bit of sarcasm, either way, placid, I applaud you. -- Benji York From andreas.zwinkau at googlemail.com Tue Sep 20 02:27:42 2005 From: andreas.zwinkau at googlemail.com (beza1e1) Date: 19 Sep 2005 23:27:42 -0700 Subject: functional or object-oriented? In-Reply-To: References: <1127149721.962815.46690@g43g2000cwa.googlegroups.com> Message-ID: <1127197662.611619.232010@g49g2000cwa.googlegroups.com> This nails it down, yes. :) I probably was too deep into OOP thinking-mode to work pythonic. So i am now rediscovering the python way. Have you read Paul Grahams On Lisp (or was it one of his essays)? He is strongly in favor of functional programming. Mainly because Lisp favors it. He does say though, simulations and CAD programs are inherently OO. But now i am writing a game modelling engine, i find objects are not the best way anytime in these fields either. From cmkleffner at gmx.de Mon Sep 26 12:55:27 2005 From: cmkleffner at gmx.de (cmkl) Date: 26 Sep 2005 09:55:27 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.3 Release: some fixes, 3 MB Windows package References: Message-ID: <1127753727.337510.246040@g49g2000cwa.googlegroups.com> I'va got a trojan message by my virus scanner trying to download the 0.03 exe-file. Something to worry about? Carl Mark Dufour schrieb: > Hi all, > > Thanks to the people trying out Shed Skin 0.0.2 and letting me know > about several problems they encountered. I have released an updated > version, 0.0.3. It contains some fixes, adds support for several > builtin functions (sorted, xrange..) and the Windows version is now a > mere 3 MB, instead of 20 :-) > > Shed Skin's main purpose is to optimize algorithmic-like Python code, > by applying advanced global type inference techniques. It does not > support e.g. exceptions (yet), and there are currently some other > limitations. Importing modules requires some extra work on the part of > the user (see the README for details,) although some imports are > currently supported (some math, random functions and sys.argv.) What > you gain by using Shed Skin is highly optimized code (industrial C++ > compiler), independent of any virtual machine. It is also possible to > create highly optimized extension modules this way. > > I invite anyone to try not too large algorithmic-like programs (e.g. > AI stuff) with Shed Skin and to let me know if there are any problems. > Even though 129 test programs already work well (6 of which are larger > than 100 lines), there are still many unimplemented minor features > that I can easily fix, provided someone shows me a nice use case. > Thanks to the people that have sent me failing code snippets before! > > http://shedskin.sourceforge.net > http://shed-skin.blogspot.com > > > Thanks! > Mark Dufour. From zanesdad at bellsouth.net Thu Sep 8 07:29:35 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 08 Sep 2005 07:29:35 -0400 Subject: Manging multiple Python installation In-Reply-To: References: Message-ID: <4320209F.9070901@bellsouth.net> Roel Schroeven wrote: >Jeremy Jones wrote: > > > >>Andy Leszczynski wrote: >> >> >>>Is there any way to pass the prefix to the "make install"? Why "make" >>>depends on that? >>> >>>A. >>> >>> >>> >>What does it matter? If you *could* pass it to make, what does that buy >>you? I'm not a make guru, but I'm not sure you can do this. Someone >>else better versed in make will certainly chime in if I'm wrong. But I >>think make just looks at the Makefile and does what it's going to do. >>If you want different behavior, you edit the Makefile or you get the >>Makefile created differently with configure. >> >> > >That way you could install to a different directory without having to >rebuild the whole thing. I don't think that uses case happens very >often, but I've certainly encountered it (not in relation to Python though). > > > I guess I'm still having a hard time understanding "what does it matter?". Even if he reconfigures, he's not going to rebuild the whole thing unless he does a make clean. For example, I just built Python twice, once with a prefix of /usr/local/apps/pytest1 and then with a prefix of /usr/local/apps/pytest2 and timed the compile: BUILD 1: jmjones at qiwi 7:16AM Python-2.4.1 % cat compile_it.sh ./configure --prefix=/usr/local/apps/pytest1 make make install ./compile_it.sh 107.50s user 9.00s system 78% cpu 2:28.53 total BUILD 2: jmjones at qiwi 7:18AM Python-2.4.1 % cat compile_it.sh ./configure --prefix=/usr/local/apps/pytest2 make make install ./compile_it.sh 21.17s user 6.21s system 56% cpu 48.323 total I *know* a significant portion of the time of BUILD 2 was spent in configure. So if he's really eager to save a few CPU seconds, he can edit the Makefile manually and change the prefix section. Maybe I'm just a slow file editor, but I would do configure again just because it'd probably be faster for me. Not to mention potentially less error prone. But he's going to have to build something again. Or not. He *should* be able to just tar up the whole directory and it should "just work". I moved /usr/local/apps/pytest1 to /usr/local/apps/pyfoo and imported xml.dom.minidom and it worked. I'm guessing the python binary searches relative to itself first (??). But if I move the python binary to a new location, it doesn't find xml.dom.minidom. JMJ From pmaupin at gmail.com Sun Sep 4 23:54:52 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 4 Sep 2005 20:54:52 -0700 Subject: Possible improvement to slice opperations. References: Message-ID: <1125892492.759723.146480@g47g2000cwa.googlegroups.com> > After considering several alternatives and trying out a few ideas with a > modified list object Bengt Richter posted, (Thank You), I think I've > found a way to make slice operation (especially far end indexing) > symmetrical and more consistent. I don't know that it makes it more consistent. I could be persuaded, but it would have to be by real-life examples with calculated slice indices and stride. I do this thing all the time, and find the current rules simple and very consistent. Occasionally, I might wish that things were a little different, but there is always a workaround. I would have to see some real code examples, of sufficient scope to see that there are fewer workarounds with this proposal than with the current implementation. FWIW, there is a reasonable workaround for the case where the indices might be negative and you would like zero or greater to mean 'end of list'. If "x" is the index variable, you can use the expression (x<0 and x or None) for the index value in the slice. If you find yourself doing this often, you can write a little function for it -- def EndIndex(x): return x<0 and x or None. But in real code, I fear you might need a similar helper function for similar issues with your change. I just don't know what those are without more thought. Regards, Pat From pcorbett at chiark.greenend.org.uk Thu Sep 29 10:19:11 2005 From: pcorbett at chiark.greenend.org.uk (Peter Corbett) Date: 29 Sep 2005 15:19:11 +0100 Subject: A rather unpythonic way of doing things References: <37ll1gci8v.fsf@chiark.greenend.org.uk> Message-ID: <37irwkc5y8.fsf@chiark.greenend.org.uk> Richie Hindle writes: > > [Peter] > > http://www.pick.ucam.org/~ptc24/yvfc.html > > [Jeff] > > Yuma Valley Agricultural Center? > > Yaak Valley Forest Council? > > I went through the same process. My guess is "Yes, Very F'ing Clever." > Peter? You're all thinking about it the wrong way (he says, being cryptic). Peter -- A frightful hobgoblin is stalking throughout Europe. - The Communist Manifesto, 1st English Edition From max at alcyone.com Fri Sep 2 19:11:48 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 02 Sep 2005 16:11:48 -0700 Subject: unicode and os.system In-Reply-To: References: Message-ID: Dumbkiwi wrote: > Can anyone help me to work through this issue? I'm a bit lost as to where > to start. If you want to convert it to UTF-8, then do so with u.decode('utf-8') -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Liberty is the right to do whatever the law permits. -- Charles Louis Montesquieu From mwm at mired.org Mon Sep 19 22:48:52 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 19 Sep 2005 22:48:52 -0400 Subject: How am I doing? References: <86slw1znup.fsf@bhuda.mired.org> <1127161587.863795.214000@z14g2000cwz.googlegroups.com> Message-ID: <8664swjvxn.fsf@bhuda.mired.org> "Brett Hoerner" writes: > Wouldn't the standard idiom be to actually put the code under the > if-name, and not make a whole new main() function? Depends on how big the main() function is. By making it a function, you make it possible for other modules to run it directly. In particular, if foo.py goes into the python library, then "foo" can be: #!/usr/bin/env python from foo import main main() which means your main gets the (rather trivial) benefit of being precompiled. > I'm not sure I see the reason behind main(), couldn't that also > interfere with other modules since main() seems like it might be > common, not sure how it would work as I'm pretty new to Python myself. > from script import * ... what happens when you have two main()s? You can't have two main()s. You can *define* two main()s, but only one of them can be bound to that name. So yes, if you do "from foo import *", then you can lose the binding to one of the mains. But if your code isn't in a routine, you can't get to it by name anyway. In any case, "from foo import *" is frowned upon - it makes it hard to figure out where the variables in the namespace you do that in came from. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ramirez08063 at itc.nl Thu Sep 22 09:44:28 2005 From: ramirez08063 at itc.nl (Jorge Ramirez) Date: Thu, 22 Sep 2005 15:44:28 +0200 Subject: Open PDF Message-ID: <36141C39871E4D4DAE92F79D1838543601B176C8@itcnt14.itc.nl> Hello, I would like to know how to open a PDF document from a python script, any suggestions are appreciated. Thanks, JR -------------- next part -------------- An HTML attachment was scrubbed... URL: From jforcier at strozllc.com Mon Sep 19 12:06:15 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: 19 Sep 2005 09:06:15 -0700 Subject: Python in XCode - autoindent? Message-ID: <1127145975.020990.9150@g47g2000cwa.googlegroups.com> Hoping at least some of you use XCode... In futzing with PyObjC and Cocoa programming on my Mac, I've come to know XCode a little better, and am considering switching to it from my existing editor (TextMate). However, it appears to lack your typical auto-indenting that I'm sure most of you also find indispensable, e.g. hitting Return after a 'def', 'class', 'if' etc results in an automatic indentation. Has anyone found a way to get this working? Google's not helping, and while XCode does have intendation preferences, they either don't work for Python syntax (even though the CodeSense, highlighting and so forth work fine with the language) or I've still got something set wrong. Thanks, Jeff From david.murmann at rwth-aachen.de Thu Sep 29 22:22:45 2005 From: david.murmann at rwth-aachen.de (David Murmann) Date: Fri, 30 Sep 2005 04:22:45 +0200 Subject: Feature Proposal: Sequence .join method Message-ID: <3q3logFcrs5qU1@news.dfncis.de> Hi all! I could not find out whether this has been proposed before (there are too many discussion on join as a sequence method with different semantics). So, i propose a generalized .join method on all sequences with these semantics: def join(self, seq): T = type(self) result = T() if len(seq): result = T(seq[0]) for item in seq[1:]: result = result + self + T(item) return result This would allow code like the following: [0].join([[5], [42, 5], [1, 2, 3], [23]]) resulting in: [5, 0, 42, 5, 0, 1, 2, 3, 0, 23] You might have noticed that this contains actually two propsals, so if you don't like str.join applying str() on each item in the sequence replace the line result = result + self + T(item) with result = result + self + item My version has been turned down in the past as far as i read, yet, i find the first version more useful in the new context... you can pass a sequence of lists or tuples or really any sequence to the method and it does what you think (at least what i think :). Any comments welcome, David. From michele.simionato at gmail.com Sat Sep 17 11:51:50 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Sep 2005 08:51:50 -0700 Subject: Possible bug in "metaclass resolution order" ? In-Reply-To: References: Message-ID: <1126972310.484861.138970@o13g2000cwo.googlegroups.com> I think this is more of a documentation issue than of a bug. It may seems strange at first, but __metaclass__ and __class__ may be different. For instance, if M is metaclass >>> class C(object): pass >>> C.__metaclass__ = M you get a class with metaclass hook equal to M, but C.__class__ is still 'type'. In you example, setting the __metaclass__ to 'type' does not change the metaclass of the created class, which is inherited from the base class. I suggest you to file a documentation bug. Unfortunately the basic documentation about metaclasses is a bit lacking and you have to discover many things by trial and errors. Michele Simionato From g.horvath at gmx.at Wed Sep 28 11:31:18 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Wed, 28 Sep 2005 17:31:18 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xbr2dxqqq.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > > Name mangling is a poor substitute for private variables. If you want > to be able to share private variables with other classes under certain > circumstances, it's better to use something like C++'s "friend" > declaration, where you can export the variables to a specific other class. That assumes that you always know for sure that the given variable will always be used as a private/friend variable in the lifecycle of the software. Software is too complictated to know everything in advance. "Software lives" and totalitarian laws destroy easy living. -- Greg From python.leojay at gmail.com Sat Sep 24 15:53:49 2005 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 25 Sep 2005 03:53:49 +0800 Subject: Parsing an HTML a tag In-Reply-To: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> References: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> Message-ID: <4e307e0f05092412537fc041b9@mail.gmail.com> you may define a start_a in MyHTMLParser. e.g. import htmllib import formatter class HTML_Parser(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.AbstractFormatter(formatter.NullWriter())) def start_a(self, args): for key, value in args: if key.lower() == 'href': print value html = HTML_Parser() html.feed(open(r'a.htm','r').read()) html.close() On 24 Sep 2005 10:13:30 -0700, George wrote: > How can I parse an HTML file and collect only that the A tags. I have a > start for the code but an unable to figure out how to finish the code. > HTML_parse gets the data from the URL document. Thanks for the help > > def HTML_parse(data): > from HTMLParser import HTMLParser > parser = MyHTMLParser() > > parser.feed(data) > > class MyHTMLParser(HTMLParser): > > def handle_starttag(self, tag, attrs): > > def handle_endtag(self, tag): > > def read_page(URL): > "this function returns the entire content of the specified URL > document" > import urllib > connect = urllib.urlopen(url) > data = connect.read() > connect.close() > return data > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Best Regards, Leo Jay From jstroud at mbi.ucla.edu Wed Sep 7 18:35:07 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 7 Sep 2005 15:35:07 -0700 Subject: encryption with python In-Reply-To: <1126128663.573686.148670@g44g2000cwa.googlegroups.com> References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <1126128663.573686.148670@g44g2000cwa.googlegroups.com> Message-ID: <200509071535.07674.jstroud@mbi.ucla.edu> On Wednesday 07 September 2005 14:31, jlocc at fau.edu wrote: > Basically I will like to combine a social security number (9 digits) > and a birth date (8 digits, could be padded to be 9) and obtain a new > 'student number'. It would be better if the original numbers can't be > traced back, they will be kept in a database anyways. Hope this is a > bit more specific, thanks!!! Then your best bet is to take a reasonable number of bits from an sha hash. But you do not need pycrypto for this. The previous answer by "ncf" is good, but use the standard library and take 9 digits to lessen probability for clashes import sha def encrypt(x,y): def _dosha(v): return sha.new(str(v)).hexdigest() return int(_dosha(_dosha(x)+_dosha(y))[5:13],16) Example: py> encrypt(843921299,20050906) 522277004 Each student ID should be unique until you get a really big class. If your class might grow to several million, consider taking more bits of the hash. Also, as long as you remember the function, you can get back the student ID from the birthday and SS, in case they drop out and re-enroll next year. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tdwdotnet at gmail.com Tue Sep 20 08:29:22 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 20 Sep 2005 13:29:22 +0100 Subject: Question about smtplib, and mail servers in general. In-Reply-To: References: Message-ID: <9afea2ac05092005293fb9de99@mail.gmail.com> On 20/09/05, Daniel Dittmar wrote: > Chris Dewin wrote: > > Hi. I've been thinking about using smtplib to run a mailing list from my website. > > > > s = smtplib.SMTP("server") > > s.sendmail(fromaddress, toaddresess, msg) > > > > Not really an answer to your question, but it's probably considered bad > style to publish the email addresses of the recipients via the address > list. Use a neutral To-address (best: the mailing list address) and add > the recipients via bcc: headers. > For clarity The toaddreses don't show in the email, they are the envelope TO: addreses. The addresses in the email's TO: Headers are shown to the recipient and these are the ones that should be "disguised" as best practice for mailing lists. The email module's replace_header('to', 'new-text) will do the job for you. From jstroud at mbi.ucla.edu Thu Sep 29 18:04:44 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 29 Sep 2005 15:04:44 -0700 Subject: Moronicity Xha Lee, Jargonizer In-Reply-To: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> Message-ID: <200509291504.44274.jstroud@mbi.ucla.edu> Note: I hereby proclaim Xha Lee with a new title: "Moronocity Xha Lee, Jargonizer ('fuck')". There needs to be an email filter that, when a thread is begun by a specific user (Moronicity Xha Lee, Jargonizer ('fuck'), for example), it cans every message in that thread. Any suggestions on how to do this in python? James On Thursday 29 September 2005 14:50, Delaney, Timothy (Tim) wrote: > Sherm Pendley wrote: > > "Matt" writes: > >> OK... your post seems to indicate a belief that everyone else is > >> somehow incompetent. > > > > Xah's just a troll - best to just ignore him. He posts these diatribes > > to multiple groups hoping to start a fight. > > You have to admit though, he's remarkably good at getting past > Spambayes. Despite classifying *every* Xah Lee post as spam, he still > manages to get most of his posts classified as 0% or 1% spam. > > It's very annoying - I've maxxed out the rules I can use in Outlook (my > work account) so I can't afford to add a specific one to trash his > emails... > > Tim Delaney -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From oshecho at gmail.com Mon Sep 12 16:56:34 2005 From: oshecho at gmail.com (Echo) Date: Mon, 12 Sep 2005 16:56:34 -0400 Subject: Detailed traceback Message-ID: <910885da05091213561bc2d645@mail.gmail.com> I have been working on handling unhanded exceptions and making a detailed print out of the traceback after the exception. I found that traceback.extract_tb worked nice and was quite simple. During my searching around I found out that it might be possible to get the variables and their respective values for each frame. I found this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 to be extremely helpful. My only problem with that is that there appears to be no way to get the line of code for a frame. So I was wondering if it was possible to get the line of code for a frame. -- -Echo From sybrenUSE at YOURthirdtower.com.imagination Fri Sep 16 11:24:31 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 16 Sep 2005 17:24:31 +0200 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> Message-ID: Terry Hancock enlightened us with: > This is ludicrous sophistry. The technical reason for having ANY high > level languages is "psychological". Computers are happier with binary > code, over ANY language that must be interpreted. Computers aren't happy. They couldn't care less about the programming language. > Programming languages are an interface to Human minds, so the > argument that one system of representation is easier to understand > is an argument that that system is *better* in that it is a better > interface. Well said! I'm going to remember that one :) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From superprad at gmail.com Mon Sep 12 11:23:37 2005 From: superprad at gmail.com (PyPK) Date: 12 Sep 2005 08:23:37 -0700 Subject: Grouping lists In-Reply-To: <1126287022.125226.39620@f14g2000cwb.googlegroups.com> References: <1126285304.909396.229440@g49g2000cwa.googlegroups.com> <1126287022.125226.39620@f14g2000cwb.googlegroups.com> Message-ID: <1126538617.525515.192830@z14g2000cwz.googlegroups.com> hmm thanks for that..but kind of not sure how this groupby works.. also if I want to group elements with one value apart how would this change.Should this change in groupby part or in the loop? something like... lst = [1,1,2,1,3,5,1,1,1,1,2,7,7] returns (0,3),4,5,(6,10),(11,12) so its something like if there is 1,1,2 then the grouping is done.. I am asking this as I could not quit follow what exactly groupby does.. Also if someone could explain me what exactly this groupby is doing that would be helpful. Thanks again. From michele.petrazzo at TOGLIunipex.it Thu Sep 22 05:49:21 2005 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 22 Sep 2005 11:49:21 +0200 Subject: python image library TIFF In-Reply-To: References: Message-ID: <43327e21$0$8493$5fc30a8@news.tiscali.it> bryan rasmussen wrote: > Hi > does anyone have any experience using the Python Image library to > determine if a Tiff is in the G4 or G3 codec? PIL don't support G3/G4 encoding. You can use freeimagepy that is another python graphic package. Michele (freeimagepy developer :) ) From Bulkan at gmail.com Sun Sep 4 22:10:11 2005 From: Bulkan at gmail.com (placid) Date: 4 Sep 2005 19:10:11 -0700 Subject: learning python Message-ID: <1125886211.816019.201070@z14g2000cwz.googlegroups.com> Hi all, I was just wondering about good books that teach python (either with programming or no programming experience at all) ? Or some online tutorial? Thanks From lycka at carmen.se Tue Sep 13 12:19:54 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 13 Sep 2005 18:19:54 +0200 Subject: How to protect Python source from modification In-Reply-To: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Message-ID: Frank Millman wrote: > Hi all > > I am writing a multi-user accounting/business system. Good! > The client program contains all the authentication and business logic. Not good. You lose...if it's *only* in the client. Of course, there is no such thing as a safe system, and you need a pragmatic approach to deciding a level of security. For a system like this, I'd certainly prefer to design the system so that it's immune to modifications in any software running on a machine that isn't "safe", such as a typical end user PC. IOW, no direct DB access allowed (at least not with anything but select permissions) and all authentication and security related verifications etc in a server process which isn't available to ordinary users. However, such schemes aren't immune to flaws. First of all, there might be mistakes in the implementations (how ever cleverly they are made) and there are always people who have access to servers and databases. You need audits and checks on various levels to handle such things. You can probably get transaction logs for the database system to be stored on some other server, which might make it more difficult for someone who manipulates the system to hide their tracks. All external transactions (especially payments from the system) need to be audited and scanned for irregularities. Can all payments be traced back to valid business transactions? Are there patterns in payments that stick out, such as many small transactions to the same receiver? Security checks like these should probably be made completely outside your accounting/business software, and by people who have nothing to do with your main system. Regardless of your intentions, there is no way you can stop people from hurting themselves. The customer of the system will basically set a ceiling for the security of the system, depending on how ambitious they are, and what kind of infrastructure they can provide etc. Small customers might well demand perfect security, but they probably don't want to pay for it. > It has dawned on me that anyone can bypass this by modifying the > program. As it is written in Python, with source available, this would > be quite easy. My target market extends well up into the mid-range, but > I do not think that any CFO would contemplate using a program that is > so open to manipulation. Just distribute zipped library instead of .py files, and you've raised the bar to the same level as if you've written it in Java. I.e. it's as if you send your mail in envelopes (just not glued together) instead of in postcards. No one will accidentally see the source code, but the persistent user can. > There is the question of where state should be maintained. If on the > server, I would have to keep all the client/server connections open, > and maintain the state of all the sessions, which would put quite a > load on the server. Really? How many users do you imagine? How would you plan to organize your servers? One process per connection, one thread per connection or asynchronous processing in one thread as in Twisted or asyncore? Perhaps you should have a look at Twisted ot asyncore? > This raises the question of whether I should even bother with a gui > client, or bite the bullet and only have a browser based front end. > Judging from recent comments about new technologies such as Ajax, a lot > of the disadvantages have been overcome, so maybe this is the way to > go. It's still a big difference, isn't it? Have you seen a web based accounting system that you thought was good enough? > It would be a shame to scrap all the effort I have put into my > wxPython-based front end. On the other hand, it would be pointless to > continue with an approach that is never going to give me what I want. > Any advice which helps to clarify my thinking will be much appreciated. A wxPython client and a Twisted server might well be a useful combo. If you have well written Python modules for validating data etc, you might just run them in both client and server to achieve instant feedback on the client without lowering the security bar. A budget solution if you want to keep a simple fat client / thin server solution is to run the clients on a box that the end users can't manipulate. Just let them access that box via VNC and only run this client program there. It's not completely trivial to set up such a safe environment though, but it basically gives you an application server and very thin clients that still give you the same rich UI as wxPython on their desktops. They'll have to get used to a non-Windows GUI though, unless you choose to run Citrix instead of VNC (or use one application server per user :). From lamthierry at gmail.com Fri Sep 16 10:30:02 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 16 Sep 2005 07:30:02 -0700 Subject: Walking through directories and files Message-ID: <1126881002.020507.311720@g44g2000cwa.googlegroups.com> I'm trying to use the os.walk() method to search all the directory from a root directory and display their contents. For example, I want my output to be like the following: directoryA stuffs.c stuffs2.cpp directoryB asd.c asdf.cpp Any ideas how to do it? Currently, I can only print all the filenames first and then the directory names. Thanks Thierry From ndbecker2 at gmail.com Tue Sep 27 07:20:44 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 27 Sep 2005 07:20:44 -0400 Subject: @staticmethod, backward compatibility? Message-ID: How can I write code to take advantage of new decorator syntax, while allowing backward compatibility? I almost want a preprocessor. #if PYTHON_VERSION >= 2.4 @staticmethod ... Since python < 2.4 will just choke on @staticmethod, how can I do this? From vel.accel at gmail.com Tue Sep 20 16:53:10 2005 From: vel.accel at gmail.com (D.Hering) Date: 20 Sep 2005 13:53:10 -0700 Subject: Line Scan and Removal In-Reply-To: References: <1127245425.284114.206620@z14g2000cwz.googlegroups.com> Message-ID: <1127249590.743507.260530@z14g2000cwz.googlegroups.com> Take a look at ADaM (& ESML for unifying format) and see if some of their image processing tools can help you. http://datamining.itsc.uah.edu/adam/documentation.html Dieter From rkern at ucsd.edu Tue Sep 27 20:22:11 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 27 Sep 2005 17:22:11 -0700 Subject: What tools are used to write and generate Python Library documentation. In-Reply-To: <200509270217.00676.hancock@anansispaceworks.com> References: <200509270217.00676.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > On Monday 26 September 2005 10:24 pm, Kenneth McDonald wrote: > >>I have a module I'd like to document using the same style... > > Google for "epydoc", "pydoc", and "happydoc". > > You've already received a comment about markup standards, > although you will find more information at the web pages > for the above tools. I'm pretty sure that none of them create documents in the style of the standard library's documentation (the only interpretation I can attach to "using the same style"). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pruebauno at latinmail.com Fri Sep 2 09:53:36 2005 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 2 Sep 2005 06:53:36 -0700 Subject: anaconda.real in RH7.1 References: Message-ID: <1125669216.690734.265910@g14g2000cwa.googlegroups.com> Allan Adler wrote: > I'm using the book, "Programming Python", by Mark Lutz, as a reference. No offence to Mark Lutz or O'Reilly but I consider "Programming Python" one of the worst books I have read (in my case an old first edition). It overwhelms the beginning programmer ("Learning Python" is probably better for that), it bores the experienced programmer to death with introductory details and does not work as a reference book. It is a nice survey of application areas for python, but the book lacks a clear goal, purpose and a problem it tries to address. It needs more focus. It needs to be marketed correctly also. I believe too many people new to python buy that book and get discouraged about Python, O'Reilly and programming when they should buy something else instead. That said what you probably want is "Python in a Nutshell" by O'Reilly which is a good reference book it has a concise introduction of Python in the beginning and after that, documentation for the most usefull libraries out there. Personally I use the online documentation a lot: If I know the the name of the module (for example it starts with sys.zz) I use: http://www.python.org/doc/2.4.1/modindex.html If I know what I want but not the name I use: http://www.python.org/doc/2.4.1/lib/lib.html From nav+posts at bandersnatch.org Tue Sep 20 09:36:43 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 20 Sep 2005 09:36:43 -0400 Subject: Replacing an XML element? Message-ID: <87wtlbdfo4.fsf@localhost.localdomain> I've been trying to figure out how to do something that seems relatively simple, but it's just not coming together for me. I'm hoping someone will deign to give me a little insight here. The problem: We have XML documents that use a custom table format that was designed primarily for typesetting documents. It's a column-first oriented scheme, and now we need a way to convert these table elements to HTML style row-first tables. I would like to be able to do something like this: doc = xml.dom.minidom.parse(input) for table in doc.getElementsByTagName('COLTABLE'): newtable = coltable_to_rowtable(table) ## this is what I can't figure out doc.replace(table, newtable) output.write(doc.toxml('utf-8')) I'm pretty sure I'm missing something obvious, but haven't been able to find any examples. Someone please whack me with a cluestick, Nick -- #include /* sigmask (sig.c) 20041028 PUBLIC DOMAIN */ int main(c,v)char *v;{return !c?putchar(* /* cc -o sig sig.c */ v-1)&&main(0,v+1):main(0,"Ojdl!Wbshjti!=ojdlAwbshjti/psh?\v\1");} From dieter.vanderelst at ugent.be Tue Sep 6 13:03:36 2005 From: dieter.vanderelst at ugent.be (Dieter Vanderelst) Date: Tue, 06 Sep 2005 19:03:36 +0200 Subject: Python versus Perl Message-ID: <431DCBE8.7090606@ugent.be> Dear all, I'm currently comparing Python versus Perl to use in a project that involved a lot of text processing. I'm trying to determine what the most efficient language would be for our purposes. I have to admit that, although I'm very familiar with Python, I'm complete Perl noob (and I hope to stay one) which is reflected in my questions. I know that the web offers a lot of resources on Python/Perl differences. But I couldn't find a satisfying answer to my questions: 1 - How does the speed of execution of Perl compares to that of Python? 2 - Regular Expressions are a valuable tool in text processing. I have noticed that Regular Expressions are executed very fast in Python. Does anybody know whether Python executes RE faster than Perl does? 3 - In my opinion Python is very well suited for text processing. Does Perl have any advantages over Python in the field of textprocessing (like a larger standard library maybe). I hope somebody can answer my questions. Of course, every remark and tip on Python/Perl in texprocessing is most welcome. With kind regards, Dieter From klaus.roedel at vipco.de Tue Sep 20 03:32:15 2005 From: klaus.roedel at vipco.de (klaus.roedel at vipco.de) Date: 20 Sep 2005 00:32:15 -0700 Subject: py2exe 0.6.2 version resources Message-ID: <1127201535.064565.91670@g14g2000cwa.googlegroups.com> Hi @all, I've implementet a simple setup script for my application with py2exe. The setup.py works fine, but now I want to add version resources to my *.exe-file. But how can I do it? I've tested it with the setup.cfg, but that doesn't work. I alwayse became the errormessage: error: error in setup.cfg: command 'py2exe' has no such option 'version_legalcopyright' until I've deleted all options. I'm using python 2.4.1 and py2exe 0.6.2 on Windows XP SP2. Thanks for any help. Greets, Klaus PS: Here my example setup.py: from distutils.core import setup import glob import py2exe install = dict(script="startApp.py", dest_base="My Application", icon_resources=[(1, "img\\icon.ico")]) opts = dict(py2exe= dict(dist_dir="Application")) setup(name = 'My Application', author="Klaus R?del", data_files=[("img", glob.glob("img\\*.png")), ("img", glob.glob("img\\*.ico")), ("", ["my_dll.dll"])], options = opts, windows=[install]) And here my example setup.cfg: [py2exe] version-companyname=which ever version-filedescription=the little application name version-fileversion=0.1.0 version-legalcopyright=Hmm... version-legaltrademarks=blah blah version-productname=the little applications product name version-productversion=0.1.0 From joseph.steffl at medtronic.com Wed Sep 14 13:08:45 2005 From: joseph.steffl at medtronic.com (tryit) Date: 14 Sep 2005 10:08:45 -0700 Subject: Find day of week from month and year In-Reply-To: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> Message-ID: <1126717725.314658.113770@g49g2000cwa.googlegroups.com> Laguna wrote: > Hi Gurus, > > I want to find the expiration date of stock options (3rd Friday of the > month) for an any give month and year. I have tried a few tricks with > the functions provided by the built-in module time, but the problem was > that the 9 element tuple need to be populated correctly. Can anyone > help me out on this one? > > Thanks a bunch, > Laguna > > Requirements: > > d0 = expiration(9, 2005) # d0 would be 16 > d1 = expiration(6, 2003) # d1 would be 20 > d2 = expiration(2, 2006) # d2 would be 17 From mauriceling at acm.org Sun Sep 18 00:15:00 2005 From: mauriceling at acm.org (Maurice Ling) Date: Sun, 18 Sep 2005 14:15:00 +1000 Subject: reading files with error In-Reply-To: <20050918015812.GA10421@unpythonic.net> References: <20050918015812.GA10421@unpythonic.net> Message-ID: <432CE9C4.70100@acm.org> jepler at unpythonic.net wrote: >I have written a program to do something similar. My strategy is: > * use os.read() to read 512 bytes at a time > * when os.read fails, seek to the next multiple of 512 bytes > and write '\0' * 512 to the output >I notice this code doesn't deal properly with short reads, but in my experience >they never happen (because the disk error makes an entire block unreadable, and >a block is never less than 512 bytes) > >I use this code on a unix-style system. > >def dd(src, target, bs=512): > src = os.open(src, os.O_RDONLY) > if os.path.exists(target): > target = os.open(target, os.O_WRONLY | os.O_APPEND, 0600) > existing = os.lseek(target, 0, SEEK_END) > else: > existing = 0 > target = os.open(target, os.O_WRONLY | os.O_CREAT, 0600) > > total = os.lseek(src, 0, SEEK_END) / bs > os.lseek(src, existing, SEEK_SET) > os.lseek(target, existing, SEEK_SET) > > if existing: print "starting at", existing > i = existing / bs > f = 0 > lastrem = -1 > > last = start = time.time() > while 1: > try: > block = os.read(src, bs) > except os.error, detail: > if detail.errno == errno.EIO: > block = "\0" * bs > os.lseek(src, (i+1) * bs, SEEK_SET) > f = f + 1 > else: > raise > if block == "": break > > i = i + 1 > os.write(target, block) > > now = time.time() > if i % 1000 or now - last < 1: continue > last = now > > frac = i * 1. / total > rem = int((now-start) * (1-frac) / frac) > if rem < 60 or abs(rem - lastrem) > .5: > rm, rs = divmod(rem, 60) > lastrem = rem > spd = i * 512. / (now - start) / 1024 / 1024 > sys.stderr.write("%8d %8d %8d %3.1f%% %6d:%02d %6.1fMB/s\r" > % (i, f, i-f, i * 100. / total, rm, rs, spd)) > sys.stderr.write("\n") > > Sorry but what are SEEK_END and SEEK_SET? Maurice -- Maurice Han Tong LING, BSc(Hons)(Biochem), AdvDipComp, CPT, SSN, FIFA, MASBMB, MAMBIS, MACM Doctor of Philosophy (Science) Candidate, The University of Melbourne mobile: +61 4 22781753, +65 96669233 mailing address: Department of Zoology, The University of Melbourne Royal Parade, Parkville, Victoria 3010, Australia residence: 9/41 Dover Street, Flemington, Victoria 3031, Australia resume: http://maurice.vodien.com/maurice_resume.pdf www: http://www.geocities.com/beldin79/ -------------- next part -------------- A non-text attachment was scrubbed... Name: mauriceling.vcf Type: text/x-vcard Size: 337 bytes Desc: not available URL: From http Tue Sep 20 17:23:10 2005 From: http (Paul Rubin) Date: 20 Sep 2005 14:23:10 -0700 Subject: Best Encryption for Python Client/Server References: <200509191446.15240.jstroud@mbi.ucla.edu> Message-ID: <7x1x3j77sx.fsf@ruckus.brouhaha.com> Steve Holden writes: > > Here's my mission: simple P2P class with encryption of whatever type > > of file is being sent, and authentication via encrypted user > > name/password. So any type of file or login being sent over the net, > > any communication between the scripts should be encrypted, > > regardless of whether it is client/server communication, or file > > transfer. > Robert's suggestion was a good one, as ssh (rather than SSH) is very > good at building encrypted tunnels between arbitrary processes. If you want to use SSL in a similar fashion, try stunnel (http://www.stunnel.org). Frankly I've never understood why ssh even exists, but it's very widespread by now, and works pretty well within its limitations. From cdkrug at worldnet.att.net Mon Sep 19 09:00:18 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Mon, 19 Sep 2005 13:00:18 GMT Subject: Creating a list of Mondays for a year References: Message-ID: On Mon, 19 Sep 2005 12:10:04 GMT, Chris wrote: > Thanks to everyone for your help! > > That fit the need perfectly. > > In article , > secun at yahoo.com says... >> Is there a way to make python create a list of Mondays for a given year? >> >> For example, >> >> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005', >> '1/31/2005','2/7/2005', ... ] >> You can also calculate it using the Julian Day Number. Google on astronomical calculations, or read the introduction to one of the Numerical Recipies. . . books for a discussion and algorithm. From Scott.Daniels at Acm.Org Tue Sep 6 18:53:44 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 06 Sep 2005 15:53:44 -0700 Subject: infinite loop In-Reply-To: References: Message-ID: <431e119b$1@nntp0.pdx.net> LOPEZ GARCIA DE LOMANA, ADRIAN wrote: > Hi all, > > I have a question with some code I'm writting: > > > def main(): > if option == 1: > function_a() > elif option == 2: > function_b() > else: > raise 'option has to be either 1 or 2' > if iteration == True: > main() > ... I want an infinite loop, but after some iterations (996) it breaks: > ... RuntimeError: maximum recursion depth exceeded > > > I don't understand it. Why am I not allowed to iterate infinitely? > Something about the functions? What should I do for having an infinite loop? You are asking in your code for infinite recursive regress. Eventually the stack overflows. An infinite loop would look like: def main(): if option == 1: function_a() elif option == 2: function_b() else: raise 'option has to be either 1 or 2' while iteration: if option == 1: function_a() elif option == 2: function_b() else: raise 'option has to be either 1 or 2' Which you might want to rewrite as: def main(): choices = {1: function_a, 2:function_b} choices[option]() while iteration: choices[option]() --Scott David Daniels Scott.Daniels at Acm.Org From nephish at xit.net Wed Sep 7 16:10:12 2005 From: nephish at xit.net (nephish at xit.net) Date: 7 Sep 2005 13:10:12 -0700 Subject: can i move attribute values from one class to another? In-Reply-To: <1126122451.859806.242600@g44g2000cwa.googlegroups.com> References: <1126122451.859806.242600@g44g2000cwa.googlegroups.com> Message-ID: <1126123812.043472.115490@g49g2000cwa.googlegroups.com> oh wait. never mind , i figgured it out! thanks anyway From trentm at ActiveState.com Wed Sep 7 23:51:45 2005 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 7 Sep 2005 20:51:45 -0700 Subject: improvements for the logging package In-Reply-To: <17183.45260.647117.513372@montanaro.dyndns.org> References: <1125935246.425351.260880@z14g2000cwz.googlegroups.com> <20050906172418.GL4377@ActiveState.com> <17182.22978.718108.100126@montanaro.dyndns.org> <20050907171420.GB31649@ActiveState.com> <17183.45260.647117.513372@montanaro.dyndns.org> Message-ID: <20050908035145.GA4861@ActiveState.com> [skip at pobox.com wrote] > > >> - It's a package, but contrary to any other package I've ever seen, > >> most of its functionality is implemented in __init__.py. > > Trent> I'm not defending the implementation, but does this cause any > Trent> particular problems? > > No, it just seems symptomatic of some potential organizational problems. Fair enough. I'm all for having consistent and well structure code in the stdlib. > >> import logging > >> logging.info('hello world') > >> > >> ought to just work (implicitly add a stream handler connected to > >> stderr to the root logger). > > Trent> Maybe. Unless that causes troubles for real use. > > Maybe there's a bug then (or maybe the docs still need work). When I > executed (all of these examples were typed at an interactive prompt): > > import logging > logging.info('hello world') > > I get no output. Looking at the doc for the basicConfig() function, I see: > > The functions debug(), info(), warning(), error() and critical() will > call basicConfig() automatically if no handlers are defined for the root > logger. > Unfortunately your getting caught by the default logging level being WARN, so that any log level below that is tossed. import logging logging.basicConfig() logging.error("help!") logging.warn("stay away from the river") logging.info("nice sunset, eh?") Running that generates: ERROR:root:help! WARNING:root:stay away from the river > Trent> Having lazy configuration like this means that it can be a subtle > Trent> thing for top-level application code to setup the proper logging > Trent> configuration. > > Again, based on my reading of the basicConfig doc, it seems like the logging > package is supposed to already do that. Sort of. I guess all it implies is that if application code wants to do special log handler setup then it needs to make sure to work in the case of basicConfig() having been called and not. The configuration stuff is quite subtle. The docs need to give good best practices for a could coverage of reasonable use cases. Nothing catastrophic will happen with a weird logging configuration -- probably just more log messages that you'd want. > It was probably the log4j roots that provided the non-PEP 8 naming. Definitely. > I suspect the naming could be improved while providing backward > compatibility aliases and deprecating those names. Do you mean naming like "makeLogRecord" etc? I thought PEP 8 said camelCase (or whatever it is called) was okay? Trent -- Trent Mick TrentM at ActiveState.com From rrr at ronadam.com Thu Sep 29 15:02:29 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 29 Sep 2005 19:02:29 GMT Subject: Dynamically adding and removing methods In-Reply-To: References: Message-ID: <9TW_e.116607$xl6.4642@tornado.tampabay.rr.com> Terry Reedy wrote: > "Ron Adam" wrote in message > news:sXA_e.112986$xl6.67455 at tornado.tampabay.rr.com... > >>Actually I think I'm getting more confused. At some point the function >>is wrapped. Is it when it's assigned, referenced, or called? > > > When it is referenced via the class. Ok, that's what I suspected. Thanks for clarifying this. > If you lookup in class.__dict__, the function is still a function. Now why did I not think of doing that? :-) >>>>class C(object): > > ... def meth(self): pass > ... > >>>>C.__dict__['meth'] > > > >>>>C.meth > > > >>>>C().meth > > > Ok, I got it now. Given class 'C' below, i.m(1) does.... >>> class C(object): ... def m(self, x): ... return repr(x) ... >>> i = C() >>> boundmeth = i.__getattribute__('m') >>> boundmeth > >>> boundmeth(1) '1' >>> import dis >>> dis.dis(boundmeth) 3 0 LOAD_GLOBAL 0 (repr) 3 LOAD_FAST 1 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE >>> dis.dis(C.m) 3 0 LOAD_GLOBAL 0 (repr) 3 LOAD_FAST 1 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE >>> dis.dis(C.__dict__['m']) 3 0 LOAD_GLOBAL 0 (repr) 3 LOAD_FAST 1 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE Hmm... that didn't tell me anything. (?) >>> boundmeth > >>> C.m >>> C.__dict__['m'] Time to start digging around in the source code I guess. ;-) > I am not sure, without looking, how much of this is language definition and > how much CPython implementation, but I think mostly the latter, as long as > the inheritance tree lookup behavior is as specified. > > Terry J. Reedy Yes, it hard to tell sometimes where CPython ends and Python begins. Cheers, Ron From steve at REMOVETHIScyber.com.au Tue Sep 20 18:56:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 21 Sep 2005 08:56:11 +1000 Subject: Question About Logic In Python References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> <432f3b24.1913117797@news.oz.net> Message-ID: On Mon, 19 Sep 2005 22:31:05 +0000, Bengt Richter wrote: > On Mon, 19 Sep 2005 23:46:05 +1000, Steven D'Aprano wrote: >>Are there actually any usage cases for *needing* a Boolean value? Any >>object can be used for truth testing, eg: [snip] > making an index (it's an int subclass), as in > > >>> things = None, 0, 1, 0.0, 5.0, '', 'a', [], [1], {}, {1:2} > >>> for thing in things: > ... print 'if %-6r would act like if %s' % (thing, ('False','True')[bool(thing)]) > ... That's a pretty artificial example though. Your general index ranges from 0 to n inclusive, where n is unlikely to be 1. That limits the usefulness of the idiom sequence_or_mapping[bool(thing)] to a tiny set of cases. As near as I can tell, explicitly converting objects to booleans is mostly useful for demonstrating that booleans aren't needed for truth testing. -- Steven. From martin at v.loewis.de Mon Sep 26 18:02:11 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 Sep 2005 00:02:11 +0200 Subject: Memory stats In-Reply-To: References: Message-ID: <43386FE3.7060606@v.loewis.de> Tarek Ziad? wrote: > I am trying to find a general memory profiler that can measure the > memory usage in Python program > and gather some stats about object usages, and things like that. As Diez says, use gc: gc.getobjects() gives you all container objects. If you want a list of all objects (container or not), you have to compile a debug build of Python. Regards, Martin From jason at jasonmhirst.co.uk Sat Sep 17 21:55:47 2005 From: jason at jasonmhirst.co.uk (Jason) Date: Sun, 18 Sep 2005 02:55:47 +0100 Subject: Can someone explain what I've done wrong... In-Reply-To: <20050918014916.3914.922618735.divmod.quotient.18204@ohm> References: <20050918014916.3914.922618735.divmod.quotient.18204@ohm> Message-ID: Thanks for the explanation JP Calderone. Have to say, I was confused with the post (I received via email, can't see it on the newsgroup yet) from Astan Chee saying he couldn't understand how the Person class was destroyed. I'm still new(ish) with Python but I was lead to believe the __del__ call was pretty reliable. Thanks for the heads up on that. Thanks again. From stijndesaeger at gmail.com Fri Sep 30 01:17:50 2005 From: stijndesaeger at gmail.com (vdrab) Date: 29 Sep 2005 22:17:50 -0700 Subject: pywordnet install problems Message-ID: <1128057470.285356.211160@g49g2000cwa.googlegroups.com> hello pythoneers, I recently tried to install wordnet 2.0 and pywordnet on both an ubuntu linux running python 2.4 and a winXP running activePython 2.4.1, and I get the exact same error on both when I try to "from wordnet import *" : running install error: invalid Python installation: unable to open /usr/lib/python2.4/config/Makefile (No such file or directory) Adding the directories and files in question (touch Makefile) makes the install go through but (obviously) breaks the import of wordnet.py: >>> import wordnet Traceback (most recent call last): File "", line 1, in ? File "wordnet.py", line 1348, in ? N = Dictionary(NOUN, 'noun') File "wordnet.py", line 799, in __init__ self.indexFile = _IndexFile(pos, filenameroot) File "wordnet.py", line 945, in __init__ self.rewind() File "wordnet.py", line 958, in rewind if (line[0] != ' '): IndexError: string index out of range Is this pywordnet package abandoned, are there weird versioning issues, or am I just extremely unlucky for the install to fail on two machines? any help greatly appreciated, vdrab. From benji at benjiyork.com Thu Sep 22 14:01:13 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 22 Sep 2005 14:01:13 -0400 Subject: Linux/Python -> SQL*Server Connexion chain In-Reply-To: <4332eb77$0$20867$626a14ce@news.free.fr> References: <4332eb77$0$20867$626a14ce@news.free.fr> Message-ID: <4332F169.201@benjiyork.com> Gilles Lenfant wrote: > Have you guys any good experience on connecting a Python (Zope) app > running on Linux to a Windoze SQL*Server ? Yep. I wrote bindings to ODBTP (http://odbtp.sourceforge.net/) using ctypes. It worked really well, good performance and quite reliable. You can see an alpha version at http://benjiyork.com/software.html. I'm not using it any more, but have a more recent version that I really should package up. -- Benji York From es_uomikim at ALA_MA_KOTAop.pl Mon Sep 5 07:48:47 2005 From: es_uomikim at ALA_MA_KOTAop.pl (es_uomikim) Date: Mon, 05 Sep 2005 13:48:47 +0200 Subject: simple question: $1, $2 in py ? In-Reply-To: <3o2mfcF3t26kU1@uni-berlin.de> References: <3o2mfcF3t26kU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> >> As far as I understand there's no $1, $2... etc stuff right ? > > > Yes - but there is sys.argv > Oh, yes. Right : ) It feels that I miss-looked it. thank You very much for an advice : ) greetz, T -- "Przyjacielu, lepiej nas dobrze wypieprz zamiast prawi? nam kazania. Nawr?ci? nas nie zdo?asz..." Marquis Donatien Alphonse Fran?ois de Sade From mark.dufour at gmail.com Tue Sep 13 06:21:02 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 13 Sep 2005 12:21:02 +0200 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: <4326A434.9030802@sweetapp.com> References: <8180ef690509120611513ad8e8@mail.gmail.com> <43259C81.4060603@sweetapp.com> <8180ef69050912100116e5b2fb@mail.gmail.com> <4326A434.9030802@sweetapp.com> Message-ID: <8180ef6905091303211a4856bb@mail.gmail.com> > You forgot to check for an error when: > o when you wrote f.error [attribute "error" might not exist e.g. f is > None] > o you called str(f.error) [might contain unicode characters that can't > be converted to a string using the default > encoding] > o when you used the % operator [format string might be wrong] > And, of course, pretty much every expression can result in a memory error. I don't mind the program bailing out in such a case and telling me where it went wrong, so I can fix the problem. I just don't really see the need for catching exceptions yourself. Especially not in well-tested code, potentially to be compiled. > Exception handling is a boon because almost EVERY expression that you > write can result in a error and checking each one is tedious in the > extreme. So people forget and then their programs exhibit very odd > behavior that is very difficult to debug. What do you mean odd behaviour? If they don't catch exceptions, the program will bail out, showing what went wrong, yeah? > If you look at the Python C source, you'll notice that probably 50% of > the code is devoted to error handling (that was a guess). That's a lot of error handling.. thanks! mark. From zaladin at home.se Fri Sep 9 12:15:44 2005 From: zaladin at home.se (Joakim Persson) Date: Fri, 09 Sep 2005 18:15:44 +0200 Subject: Using Python with COM to communicate with proprietary Windows software References: Message-ID: <5bMhQyygYQbAxWGqorX8DcbkrRte@4ax.com> On Fri, 09 Sep 2005 08:36:00 +0200, Thomas Heller wrote: >Joakim Persson writes: > >> I have a rather bloated C++ client prototype which "works", so I >> should have all the code needed to invoke the interface, but this >> client is of course rather bloated in itself and not suitable for my >> experimental programming approach. Am I right in believing that the >> COM interface I am trying to use is of what is called a "custom" type, >> that I cannot access using Python + win32com? > >Sounds like a perfect job for comtypes, which is a COM library >implemented in pure Python, based on ctypes. comtypes should make it >easy to access custom (non-dispatch derived) com interfaces, or the >vtable based part of dual interfaces - it would be good however, if you >have a type library for the interfaces. > >http://sourceforge.net/projects/comtypes/ > >No docs yet, but there are tests included which should get you started. > >(I have released and announced this 3 weeks ago, but haven't got a >single feedback. So it seems the need to access custom interfaces is >very low.) > >Thommas Looks good, I think I downloaded ctypes but didn't put in the effort to wrap the custom COM interface. I have the type library and full documentation of the interface, so IMO it _should_ be possible to make a 100% Python application for testing this particular interface, which would definitely speed up prototyping, which is the entire goal of my work. I will give it a spin tomorrow, and I'll get back on the NG once I have tested it. Many thanks! It seems most Python uses for COM rely on "simple" automation of COM interfaces of the IDispatch type, but I need something more (full client<->server communication and threading, for instance). Hopefully your module will at least let me get one step further... My remaining two options, seeing as I would really like to at least put the data processing and presentation part in Python, are linking Python with C++ for the COM part and building (Data + Presentation) in Python, or making a complete standalone C++ part for the COM part and then _another_ client<->server solution using e.g. named pipes/sockets. -- Joakim Persson M.Sc student, CS/E @ LTH From steve at REMOVETHIScyber.com.au Fri Sep 23 07:50:56 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 23 Sep 2005 21:50:56 +1000 Subject: Finding where to store application data portably References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: On Thu, 22 Sep 2005 19:09:28 +0400, en.karpachov wrote: > There is an other way around: look at your home dir as if it is your > "settings" dir and don't clutter it with files other than application > config dot-files. Just make ~/files/, ~/bin/ ~/lib/ etc. for it. Do you put everything into /etc (/etc/bin, /etc/var, /etc/usr, /etc/mnt, and so forth)? If your home directory is for settings, why would you store files and binaries inside your settings directory? I understand the historical reasons for why ~/ is treated as a structureless grab-bag of everything and anything. That made sense back in the distant past when users used dumb terminals and they had perhaps half a dozen dot files. But at the point your home directory has three times as many dot files as regular files, the time has come to stop doing things just because that's the way they have always been done. -- Steven. From jepler at unpythonic.net Fri Sep 2 23:10:18 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Fri, 2 Sep 2005 22:10:18 -0500 Subject: Record separator for readlines() In-Reply-To: References: Message-ID: <20050903031015.GB26572@unpythonic.net> I think you still have to roll your own. Here's a start: def ireadlines(f, s='\n', bs=4096): if not s: raise ValueError, "separator must not be empty" r = [] while 1: b = f.read(bs) if not b: break ofs = 0 while 1: next = b.find(s, ofs) if next == -1: break next += len(s) yield ''.join(r) + b[ofs:next] del r[:] ofs = next r.append(b[ofs:]) yield ''.join(r) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From skromta at gmail.com Fri Sep 23 15:37:42 2005 From: skromta at gmail.com (Kalle Anke) Date: Fri, 23 Sep 2005 21:37:42 +0200 Subject: parsing a date Message-ID: <0001HW.BF5A26260018E425F0284550@news.individual.de> I want to parse a date string, for example '2005-09-23', and since I haven't done this before I would like to ask what is the best way to do it. I've looked around and the dateutil seems to be what most people use, but unfortunately I only get an empty file when I try to download it. I also tried the standard modules and ended up with this import datetime from time import strptime d = '2005-09-23' w = strptime(d,'%Y-%m-%d') print datetime.date( w[0], w[1], w[2] ) But I suspect there is a better way to do it?? From http Tue Sep 27 20:50:18 2005 From: http (Paul Rubin) Date: 27 Sep 2005 17:50:18 -0700 Subject: PEP 350: Codetags References: <4338bc2f.2535976150@news.oz.net> <7xll1j53xs.fsf@ruckus.brouhaha.com> Message-ID: <7xy85iow1h.fsf@ruckus.brouhaha.com> Terry Hancock writes: > But that's precisely why it would be valuable to have a PEP -- a > central catalog of such conventions makes it possible for checking > software to be consistent. If PyChecker were going to check for such > things, it would do so only because a standard convention had been > established. I'm saying such a PEP should not be approved unless there's already an implementation (e.g. PyChecker patch). If the PEP is then approved, the patch should be merged into the official PyChecker source. From amk at amk.ca Sat Sep 10 07:27:41 2005 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 10 Sep 2005 06:27:41 -0500 Subject: Why do Pythoneers reinvent the wheel? References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 10 Sep 2005 08:53:24 +0200, Stefano Masini wrote: > Well, so we might as well learn a little more and rewrite os.path, the > time module and pickle. Right? :) And in fact people have done all of these: os.path: path.py (http://www.jorendorff.com/articles/python/path/) time: mxDateTime, the stdlib's datetime. pickle: XML serialization, YAML. > So, let's talk about a way to more effectively present available > solutions to our good programmers! :) PEP 206 (http://www.python.org/peps/pep-0206.html) suggests assembling an advanced library for particular problem domains (e.g. web programming, scientific programming), and then providing a script that pulls the relevant packages off PyPI. I'd like to hear suggestions of application domains and of the packages that should be included. --amk From roccomoretti at hotpop.com Thu Sep 1 10:36:50 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 01 Sep 2005 09:36:50 -0500 Subject: OpenSource documentation problems In-Reply-To: References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> Message-ID: Steve Holden wrote: > Every page of the docs links to "About this document", which contains > the following: """If you are able to provide suggested text, either to > replace existing incorrect or unclear material, or additional text to > supplement what's already available, we'd appreciate the contribution. > There's no need to worry about text markup; our documentation team will > gladly take care of that.""" There is just one giant roadblock to that suggestion - Sourceforge requires a login to post bugs/patches. It doesn't seem like much, but as Paul Rubin mentioned, most people who find bugs/unclear passages in the docs aren't scanning the docs explicitly to edit them - they've uncovered the bug after working on some other project, and likely only after banging their head against the wall a few times trying to get it to work. If they have to go through the song and dance of signing up for another website to report the problem, they might just say "forget it." Sure, it's not hard to sign up for Sourceforge, but even a little barrier can stop you from contributing if you're not enthusiastic about it in the first place. Something a simple as allowing doc bugs to be submitted from a webform w/o login would reduce the barrier to contribute. - Increasing the size of the "About" text wouldn't hurt either. (To be honest, I've never noticed that text before, and it never occurred to me look at the "About" page for information on error reports.) That said, I think the Python manuals are great. But saying that they are perfect, or that the editing process couldn't be improved is just deluding yourself. From reinhold-birkenfeld-nospam at wolke7.net Sun Sep 25 16:27:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 25 Sep 2005 22:27:48 +0200 Subject: cElementTree clear semantics In-Reply-To: <1127679685.586120.312690@g47g2000cwa.googlegroups.com> References: <3po78hFbdl84U1@individual.net> <3po7i3Fbdl84U2@individual.net> <1127679685.586120.312690@g47g2000cwa.googlegroups.com> Message-ID: <3pofi4Fas5ndU1@individual.net> Paul Boddie wrote: > Reinhold Birkenfeld wrote: >> D H wrote: >> > I would recommend emailing the author of a library when you have a >> > question about that library. You should know that yourself as well. >> >> Well, if I had e.g. a question about Boo, I would of course first ask >> here because I know the expert writes here. > > Regardless of anyone's alleged connection with Boo or newsgroup > participation level Which was sort of an ironic from my side. I did not expect "D H" to go overboard on this. > the advice to contact the package author/maintainer is sound. Correct. But if the post is already in the newsgroup and the author is known to write there extensively, it sounds ridiculous to say "contact the author". > It happens every now and again that people > post questions to comp.lang.python about fairly specific issues or > packages that would be best sent to mailing lists or other resources > devoted to such topics. It's far better to get a high quality opinion > from a small group of people than a lower quality opinion from a larger > group or a delayed response from the maintainer because he/she doesn't > happen to be spending time sifting through flame wars amidst large > volumes of relatively uninteresting/irrelevant messages. Hey, the flame war stopped before it got interesting ;) Reinhold From tjreedy at udel.edu Wed Sep 7 17:48:26 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 7 Sep 2005 17:48:26 -0400 Subject: bug in numarray? References: <000901c5b3f2$b2b6d030$5c0a030a@PANDA> Message-ID: "Xiangyi" wrote in message news:000901c5b3f2$b2b6d030$5c0a030a at PANDA... > I got the following segmentation fault. >> from numarray import * >> a = zeros((5,100), Float64) >> b = kroneckerproduct(a, identity(12)) >> segmentation fault > > If I use a = zeros((5,100)), everything is fine. Kind of weird! > Can someone help me figure it out? BTW, the python version is 2.4.1 and > > numarray 1.3.2 Bugs or buggy looking behavior in 3rd party add-ons are usually best reported on the mailing list for the package. You may or may not get an answer here. From frank at chagford.com Wed Sep 28 01:12:06 2005 From: frank at chagford.com (Frank Millman) Date: 27 Sep 2005 22:12:06 -0700 Subject: Python in The Economist Message-ID: <1127884326.840476.181880@o13g2000cwo.googlegroups.com> FYI http://www.economist.com/science/displayStory.cfm?Story_id=4368122&CFID=65783500&CFTOKEN=ed98f5-9eb5adc6-80da-4e08-a843-746292fe83b8 Frank Millman From svbrk at start.no Tue Sep 6 07:11:33 2005 From: svbrk at start.no (svbrk at start.no) Date: 6 Sep 2005 04:11:33 -0700 Subject: py2exe 0.6.1 released References: <1KbTe.51152$F23.643754@twister2.libero.it> Message-ID: <1126005093.200664.64140@g47g2000cwa.googlegroups.com> First: Thank you Thomas for the good work with py2exe. The single-file option is something I have been waiting for :-) Will it also be possible to build independent files (such as my_app_data.zip) into the executable? > > I tried it using the wx singlefile example, but unfortunately the resulting > > executable segfaults at startup (using Python 2.3.3 on Windows 2000, with > > latest wxWindows). > > Yes, I can reproduce that. I'm still using wxPython 2.4.2.4 for Python > 2.3.5, and that combo works. I have done a few tests, and wxPython > 2.5.1.5 also works, while 2.5.5.1 crashes. > I have tried two more combinations for this example (samples/singlefile/gui/test_wx.py), both giving segfault on WindowsXP / SP2: 1. Python 2.3.3 with wxPython 2.6.1.0 unicode 2. Python 2.4.1 with wxPython 2.6.1.0 unicode However, the combinations Python 2.4.1 with wxPython 2.4.5.1 ansi Python 2.4.1 with wxPython 2.6.1.0 ansi do not cause segfault, but shows a dialog box pointing to a log file, the contents of which is: Traceback (most recent call last): File "test_wx.py", line 1, in ? File "zipextimporter.pyo", line 78, in load_module File "wxPython\__init__.pyo", line 10, in ? File "zipextimporter.pyo", line 78, in load_module File "wxPython\_wx.pyo", line 3, in ? File "zipextimporter.pyo", line 78, in load_module File "wxPython\_core.pyo", line 15, in ? File "zipextimporter.pyo", line 78, in load_module File "wx\__init__.pyo", line 42, in ? File "zipextimporter.pyo", line 78, in load_module File "wx\_core.pyo", line 4, in ? File "zipextimporter.pyo", line 89, in load_module ImportError: MemoryLoadLibrary failed loading _core_.pyd Maybe this could help localizing the problem? Svein Brekke From theller at python.net Wed Sep 14 02:43:24 2005 From: theller at python.net (Thomas Heller) Date: Wed, 14 Sep 2005 08:43:24 +0200 Subject: p2exe using wine/cxoffice References: Message-ID: James Stroud writes: > Hello, > > My department has switched from vmware to wine/cxoffice. I have been > playing with this all morning, and I've gotten this far. If someone > has done this, could you point me in the right direction > > > euler 65% winpy > Enthought Edition build 1057 > Python 2.3.3 (#51, Feb 16 2004, 04:07:52) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > py> from distutils.core import setup > py> import py2exe > py> import sys > py> sys.argv.append('py2exe') > py> setup(console=["erase.py"]) > running py2exe > *** searching for required modules *** > *** parsing results *** > creating python loader for extension '_sre' > *** finding dlls needed *** > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\distutils\core.py", line 149, in setup > dist.run_commands() > File "C:\Python23\lib\distutils\dist.py", line 907, in run_commands > self.run_command(cmd) > File "C:\Python23\lib\distutils\dist.py", line 927, in run_command > cmd_obj.run() > File "C:\Python23\lib\site-packages\py2exe\build_exe.py", line 183, in run > self._run() > File "C:\Python23\lib\site-packages\py2exe\build_exe.py", line 230, in _run > dlls = self.find_dlls(extensions) > File "C:\Python23\lib\site-packages\py2exe\build_exe.py", line 300, in find_dlls > self.dll_excludes) > File "C:\Python23\lib\site-packages\py2exe\build_exe.py", line 768, in find_dependend_dlls > alldlls, warnings = bin_depends(loadpath, images, dll_excludes) > File "C:\Python23\lib\site-packages\py2exe\build_exe.py", line 1086, in bin_depends > for result in py2exe_util.depends(image, loadpath).items(): > py2exe_util.bind_error: (120, 'Call not implemented', 'C:\\Python23\\DLLs\\_sre.pyd') > I guess this means that wine does not implement some function in imagehlp.dll (which py2exe_util uses). It *may* be possible to write a pure Python version of the binary dependency analysis (afaik, McMillan installer has such code) - but since I don't run py2exe on linux I won't do it myself. Even better would be to fix wine ;-), if my guess is correct. Thomas From piet at cs.uu.nl Fri Sep 2 07:10:03 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 02 Sep 2005 13:10:03 +0200 Subject: Decrypting GPG/PGP email messages References: Message-ID: >>>>> Alessandro Bottoni (AB) wrote: >AB> Of course, I want to be sure that only the allowed people is able to send >AB> such dangerous messages to my server so I will ask my users to encrypt and >AB> digitally sign their messages using Thunderbird, Enigmail and GPG ... What benefit is there in encrypting the messages? It would only prevent people intercepting the message from seeing what's inside, but it won't give you any additional protection on the server. And if somebody can intercept the messages there is a much bigger danger: They could save the message and replay it later. You can't protect against this with encryption (well, with encryption they won't know what they are doing). Neither with a digital signature. Only checking timestamps, keeping track of the messages received and/or a challenge/response system will help in this case. >AB> 1) What would you use to decrypt the messages? The GPG module created by >AB> Andrew Kuchling is declared "incomplete" and "no more maintained" on his >AB> web pages (http://www.amk.ca/python/code/gpg) so I think it is out of the >AB> game. Would you use OpenPGP (http://www.aonalu.net/openpgp/python)? Any >AB> other module? If you only sign, it will be sufficient, but there is a more complete one (including decryption) in http://trac.t7a.org/isconf/file/trunk/lib/python/isconf/GPG.py -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ndbecker2 at gmail.com Fri Sep 30 07:44:14 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 30 Sep 2005 07:44:14 -0400 Subject: Compile fails on x86_64 References: <433CE99B.3000304@ee.byu.edu> Message-ID: In file included from scipy/base/src/multiarraymodule.c:44: scipy/base/src/arrayobject.c: In function 'array_frominterface': scipy/base/src/arrayobject.c:5151: warning: passing argument 3 of 'PyArray_New' from incompatible pointer type error: Command "gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -m64 -mtune=nocona -D_GNU_SOURCE -fPIC -O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -m64 -mtune=nocona -fPIC -Ibuild/src/scipy/base/src -Iscipy/base/include -Ibuild/src/scipy/base -Iscipy/base/src -I/usr/include/python2.4 -c scipy/base/src/multiarraymodule.c -o build/temp.linux-x86_64-2.4/scipy/base/src/multiarraymodule.o" failed with exit status 1 error: Bad exit status from /var/tmp/rpm/rpm-tmp.96024 (%build) From hancock at anansispaceworks.com Wed Sep 14 19:05:18 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 14 Sep 2005 18:05:18 -0500 Subject: working with VERY large 'float' and 'complex' types In-Reply-To: <7xll1z78gi.fsf@ruckus.brouhaha.com> References: <7xll1z78gi.fsf@ruckus.brouhaha.com> Message-ID: <200509141805.18996.hancock@anansispaceworks.com> > "Todd Steury" writes: > > or 1.#INDj. However I really need these numbers to be calculated (although > > precision isn't key). Is there a way to get python to increase the size > > limit of float and complex numbers? This is really a natural problem with such calculations. On Wednesday 14 September 2005 02:30 pm, Paul Rubin wrote: > You could rearrange your formulas to not need such big numbers: > > x = 1000. > log10_z = x / math.log(10) > c,m = divmod(log10_z, 1.) > print 'z = %.5fE%d' % (10.**c, m) I highly recommend you use this kind of solution. Solve the problem with algebra, not with a new library. Most of the time, large numbers can be avoided (particularly if you are not overly concerned with precision), simply by dividing out large constant factors and the like. Logs work better for this problem, as Paul points out. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From mark.dufour at gmail.com Mon Sep 12 09:23:48 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Mon, 12 Sep 2005 15:23:48 +0200 Subject: First release of Shed Skin, a Python-to-C++ compiler. Message-ID: <8180ef69050912062368bced0b@mail.gmail.com> >First the good news: ShedSkin (SS) more or less works on Windows. After >patching gc6.5 for MinGW, building it, and testing it on WinXP with >some succuess, and after patching my local copy of SS, I can get the >test.py to compile from Python to C++, and it seems that I can get >almost all the unit tests in unit.py to pass. Thank you so much for your efforts! I will try to download your patches this afternoon on a roommate's Windows computer, and try to see if I can fix the remaining tests. >Moreover, and since the GC system you used only works in "recent >versions of Windows", it follows that this solution will not work in >all versions. I tested it on Win98 and both GC tests and SS's unit.py >tests crash; although SS can still seem to compile the tests to C++. Thanks!! Since adding GC support took about 10 lines of C++ code, I guess it won't be hard to switch to a different system.. I'll try and see if I can add support for a version that works with Win98.. BTW if anyone is interested in running Shed Skin under OSX.. I got this comment on my blog (http://shed-skin.blogspot.com) (why doesn't everybody just run Gentoo? :P) >Wow, very cool. Congratulations! > >Here's what I had to do to get it working on the Mac (OS X 10.4): > >1. Install the garbage collector from >http://www.hpl.hp.com/personal/Hans_Boehm/gc/ > >2. Add #include above #include in builtin_.hpp > >3. Change makelib to: g++ -dynamiclib -o libss.dylib builtin_.cpp sets_.cpp >random_.cpp math_.cpp copy_.cpp -lgc -lm > >4. Edit ss to use the appropriate path > >5. Use python 2.4 instead of the version 2.2 or 2.3 that comes with OS X (in my >case, I just had to put /usr/local at the start of my path) > >6. Run ./ss test.py > >7. Compile the resulting cpp file with: g++ -L. test.cpp -lss -lgc > >8. Run ./a.out and watch in awe. thanks! mark. From karczma at info.unicaen.fr Fri Sep 9 05:47:41 2005 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Fri, 09 Sep 2005 11:47:41 +0200 Subject: Inconsistent reaction to extend Message-ID: Gurus, before I am tempted to signal this as a bug, perhaps you might convince me that it should be so. If I type l=range(4) l.extend([1,2]) l gives [0,1,2,3,1,2], what else... On the other hand, try p=range(4).extend([1,2]) Then, p HAS NO VALUE (NoneType). With append the behaviour is similar. I didn't try other methods, but I suspect that it won't improve. WHY? It seems that there was already some discussion about consistency and somebody produced the example: h = {}.update(l) which didn't work, but I wasn't subscribed to this nsgr, I couldn't follow this affair. Jerzy Karczmarczuk From Ido.Yehieli at gmail.com Fri Sep 30 08:04:19 2005 From: Ido.Yehieli at gmail.com (Ido.Yehieli at gmail.com) Date: 30 Sep 2005 05:04:19 -0700 Subject: how to stop info output on screen In-Reply-To: <1128080934.730144.217060@f14g2000cwb.googlegroups.com> References: <1128080934.730144.217060@f14g2000cwb.googlegroups.com> Message-ID: <1128081859.390926.8390@o13g2000cwo.googlegroups.com> more on the subject: your "print" statments will also be written to that file that sys.stdout directs to, so maybe that wasn't exactly the solution you wanted to hear. ok, not the nicest solution but maybe it will help you anyway: bind sys.stdout at the begining of the program to a file (don't forget to save it first! let's say stdout = sys.stdout; sys.stdout=file('myLogFile.dat','w') ), and write your own print funktion that goes something like that: def printToConsole(stringToPrint,oldStdOut): ____sys.stdout=oldStdOut ____print stringToPrint ____sys.stdout=file('myLogFile.dat','w') then when you want to print to the console, use this function instead of the print statment. all the rest will go to 'myLogFile.dat' Cheers, Ido. From malvert at telenet.be Tue Sep 6 04:19:03 2005 From: malvert at telenet.be (malv) Date: 6 Sep 2005 01:19:03 -0700 Subject: Online Modification of Python Code In-Reply-To: <431d05a9.719838332@news.oz.net> References: <1125904440.679016.137720@g44g2000cwa.googlegroups.com> <1125911568.690663.152850@o13g2000cwo.googlegroups.com> <3o2is6F3ub9sU1@uni-berlin.de> <431d05a9.719838332@news.oz.net> Message-ID: <1125994743.482944.327170@o13g2000cwo.googlegroups.com> Your algoreload() is of the hand of a master. I'll give it a try. Thank you Bengt! From qhfgva at gmail.com Thu Sep 22 17:06:13 2005 From: qhfgva at gmail.com (qhfgva at gmail.com) Date: 22 Sep 2005 14:06:13 -0700 Subject: authentication for xmlrpc via cgi Message-ID: <1127423173.400444.235620@z14g2000cwz.googlegroups.com> I'm using python 2.2 (hopefully we'll be upgrading our system to 2.3 soon) and I'm trying to prototype some xml-rpc via cgi functionality. If I override the Transport class on the xmlrpclib client and add some random header like "Junk", then when I have my xmlrpc server log it's environment when running, I see the HTTP_JUNK header. If I do this with AUTHORIZATION, the header is not found. Does this ring a bell for anyone? Am I misunderstanding how to use this header? I'm guessing that Apache might be eating this header, but I don't know why. thanks, dustin From paschott at no.yahoo.spamm.com Tue Sep 13 13:03:00 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Tue, 13 Sep 2005 17:03:00 GMT Subject: FTP Error: Windows AS/400 References: <1126627431.665577.103390@o13g2000cwo.googlegroups.com> Message-ID: <4d1ei1hf5a6egh98ucsbii64hgnju1vhbi@4ax.com> I've used DOS FTP to hit AS/400 systems before and usually have to completely qualify the file name or ensure that I'm in the correct directory. When you use command-line FTP to get the file, do these commands mimic your commands? What version of python are you using? If you issue PWD on the FTP site, what is returned when you're in the correct folder? Can you use the sendcmd() function to mimic the functionality of cwd() for this purpose? I don't have easy access to an AS/400 with which to test, but maybe there's an idea or two here that's worth trying. -Pete "Tim G." wrote: > I am trying to use Win Python to ftp files from an AS/400 IFS directory > down to my Windows machine. > > I seem to get stuck when I am trying to send a command to the AS/400 to > switch file systems from native to IFS and then to issue a cd to my > folder. I get the error below. > > If anyone has had experience trying to ftp from a 400, I would greatly > appreciate any info on the topic. > > > Code: > > import ftplib, os > > filename='' > path = "jde7333" > os.chdir('c:\\ftp_jde400') > > ftp = ftplib.FTP('test400') > ftp.login('oneworld', 'onew0r1d') > #ftp.sendcmd('quote site namefmt 1') > ftp.sendcmd('site namefmt 1') > ftp.cwd(path) > #remotefiles = ftp.nlst() > #ftp.retrlines('LIST') > #for filename in remotefiles: > # file = open(filename, 'wb') > # ftp.retrbinary('RETR ' + filename, file.write, 1024) > # file.close() > > ftp.quit() > > > Error: > > Traceback (most recent call last): > File "C:\Python24\Tools\scripts\ftp400.py", line 10, in ? > ftp.cwd(path) > File "C:\Python24\lib\ftplib.py", line 494, in cwd > return self.voidcmd(cmd) > File "C:\Python24\lib\ftplib.py", line 246, in voidcmd > return self.voidresp() > File "C:\Python24\lib\ftplib.py", line 221, in voidresp > resp = self.getresp() > File "C:\Python24\lib\ftplib.py", line 214, in getresp > raise error_perm, resp > ftplib.error_perm: 501 Unknown extension in database file name. From gregpinero at gmail.com Mon Sep 12 23:52:33 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Mon, 12 Sep 2005 23:52:33 -0400 Subject: py2app without a mac? Message-ID: <312cfe2b05091220524ac2db5b@mail.gmail.com> Hey guys, I want to make my python program be installable on a mac, however I have no access to a mac myself. Is there any way I can still use py2app to create the app? Otherwise what other options do I have? (google turned up nothing for me) I don't want to require the users to have python installed so I don't think distutils would work here. Here is a link to my source code if you want to get REALLY involved in answering this question: http://www.blendedtechnologies.com/wp-content/Fast_Job_Applier.zip Much appreciated, -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Wed Sep 7 08:06:22 2005 From: robin at reportlab.com (Robin Becker) Date: Wed, 07 Sep 2005 13:06:22 +0100 Subject: dual processor In-Reply-To: <7xd5nolhn7.fsf@ruckus.brouhaha.com> References: <0NGSe.4128$3R1.94@fe06.lga> <7xd5nolhn7.fsf@ruckus.brouhaha.com> Message-ID: <431ED7BE.2000004@chamonix.reportlab.co.uk> Paul Rubin wrote: > Jeremy Jones writes: > >>to pass data around between processes. Or an idea I've been tinkering >>with lately is to use a BSD DB between processes as a queue just like >>Queue.Queue in the standard library does between threads. Or you >>could use Pyro between processes. Or CORBA. > > > I think that doesn't count as using a the multiple processors; it's > just multiple programs that could be on separate boxes. > Multiprocessing means shared memory. > > This module might be of interest: http://poshmodule.sf.net > It seems it might be a bit out of date. I've emailed the author via sf, but no reply. Does anyone know if poshmodule works with latest stuff? -- Robin Becker From steve at holdenweb.com Wed Sep 28 06:45:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Sep 2005 11:45:08 +0100 Subject: Overhead of individual python apps In-Reply-To: <7xmzlxbnzc.fsf@ruckus.brouhaha.com> References: <1127859117.870343.96740@g44g2000cwa.googlegroups.com> <4339DF2F.6010701@websafe.com> <7xu0g6ovs6.fsf@ruckus.brouhaha.com> <7xmzlxbnzc.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Fredrik Lundh" writes: > >>>That is bogus reasoning. >> >>not if you're a professional software developer and someone's paying you >>to develop an application that is to be run on a platform that they control. > > > An awful lot of Python targeted users are not in that situation, so if > Python's usability suffers for them when it doesn't have to, then > something is wrong with Python. If a useful subset of Python can be crammed into a Nokia cell phone then I really don't think there's much to complain about (except that "it hasn't been done for *my* machine"). Even embedded systems are much larger now than the minicomputers of yesteryear. Everything's relative. Just wait three years! i-remember-when-we-'ad-ter-code-seven-kilobytes-of-assembly-language-wi'-nowt-bu'-a-teletype-ter-edit-t'-paper-tape-wi'-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From EP at zomething.com Fri Sep 9 03:57:58 2005 From: EP at zomething.com (EP) Date: Thu, 8 Sep 2005 23:57:58 -0800 Subject: What's the difference between VAR and _VAR_? In-Reply-To: <1126244885.487859.21660@z14g2000cwz.googlegroups.com> References: <1126239543.098530.98570@f14g2000cwb.googlegroups.com> <1126240211.306844.157130@f14g2000cwb.googlegroups.com> <1126241274.488280.122210@g49g2000cwa.googlegroups.com> <85KdneRT4a5AhLzeRVn-qg@speakeasy.net> <1126244885.487859.21660@z14g2000cwz.googlegroups.com> Message-ID: <20050908235758.1353438522.EP@zomething.com> > I thought there must be something special when you named a VAR with '_' > the first character. Maybe it's just a programming style and I had > thought too much... Perhaps you are thinking of the use of double leading underscore names within class declarations or system defined names with underscores? e.g. __somePrivateVar e.g. __init__ """ 9.6 Private Variables There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes. Truncation may occur when the mangled name would be longer than 255 characters. Outside classes, or when the class name consists of only underscores, no mangling occurs. Name mangling is intended to give classes an easy way to define ``private'' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.) Notice that code passed to exec, eval() or evalfile() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly. """ """ 2.3.2 Reserved classes of identifiers Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: _* Not imported by "from module import *". The special identifier "_" is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, "_" has no special meaning and is not defined. See section 6.12, ``The import statement.'' Note: The name "_" is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention. __*__ System-defined names. These names are defined by the interpreter and it's implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section 3.3, ``Special method names.'' __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ``private'' attributes of base and derived classes. See section 5.2.1, ``Identifiers (Names).'' -------------------------------------------------------------------------------- """ From n00m at narod.ru Thu Sep 8 05:58:36 2005 From: n00m at narod.ru (n00m) Date: 8 Sep 2005 02:58:36 -0700 Subject: Sockets: code works locally but fails over LAN In-Reply-To: References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> <1125681663.710557.320340@f14g2000cwb.googlegroups.com> <3m6ih1taaeo7kndnbuvfl5geed053ivunl@4ax.com> <1125774529.074965.269720@g44g2000cwa.googlegroups.com> <1126112861.235714.278260@g47g2000cwa.googlegroups.com> Message-ID: <1126173516.885501.163220@g44g2000cwa.googlegroups.com> Thanks, Bryan, for the details! Btw, the newest oops in the topic's subject is: the code does not work in the case of: sqls_host, sqls_port = '192.168.0.8', 1433 proxy_host, proxy_port = '192.168.0.3', 1434 ## proxy_host, proxy_port = '127.0.0.1', 1434 ## proxy_host, proxy_port = '', 1434 I.e. when both Python and vbs script run on one machine (with ip = 192.168.0.3) and SQL Server runs on another (with ip = 192.168.0.8) How namely it does not work: in the idle window only one line is printed: VB_SCRIPT:......... that's all. No errors from Python. After timeout expires I get an error message from VBS (smth like preHandShake() failed; I've never seen it before). I just wonder MUST (or not) it work at all (IN THEORY)? PS: again, without Python vbs and sql server contact with each other PERFECTLY. From ivoras at __yahoo.org__ Sat Sep 24 07:05:20 2005 From: ivoras at __yahoo.org__ (Ivan Voras) Date: Sat, 24 Sep 2005 13:05:20 +0200 Subject: How to decompile an exe file compiled by py2exe? In-Reply-To: References: Message-ID: Thomas Jollans wrote: > interpreter. This is based on the assumption that py2exe really > generates a pure exe and not an exe that interprets bytecode python. > be that the case, it may yield decent results, but ugly nontheless. It is - py2exe embeds python bytecodes. It seems it does it in the "library.zip" file (if I'm reading http://starship.python.net/crew/theller/moin.cgi/Py2Exe correctly). Bytecode files extracted should be decompilable to something resembling original python code by a python decompiler (quick Googling finds "decompyle": http://www.crazy-compilers.com/). From fredrik at pythonware.com Wed Sep 21 03:09:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Sep 2005 09:09:31 +0200 Subject: Free seminar on domain-specific modeling References: <7c6fcb4c414d8c78ca098e94860@news.kolumbus.fi> Message-ID: Martijn Iseger wrote: > >> Domain-specific modeling makes software development 5-10 times faster > >> than approaches based on UML or MDA. It accelerates development and > >> reduces complexity by automatically generating full code from > >> higher-abstraction design models. > >> > > Wow, look everyone! A silver bullet! > > > Before slashing down in ignorance - educate yourself on www.dsmforum.org. > After that: feel free to comment. I will make you look a lot more intelligent > Peter Hansen. if you don't understand the "silver bullet" reference, you're not qualified to use phrases like "makes software development 5-10 times faster". From perl at my-header.org Sun Sep 18 11:44:20 2005 From: perl at my-header.org (Matija Papec) Date: Sun, 18 Sep 2005 17:44:20 +0200 Subject: Python Doc Problem Example: os.path.split References: <1127040363.949490.248560@z14g2000cwz.googlegroups.com> Message-ID: X-Ftn-To: Xah Lee "Xah Lee" wrote: >Python Doc Problem Example what makes you sure that this problem would be interesting for groups beside c.l.python? are you begging to be converted to a true religion? :-) -- Matija From tjreedy at udel.edu Wed Sep 14 20:33:14 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Sep 2005 20:33:14 -0400 Subject: Writing at the beginning of a file References: <1126707230.693569.187200@g49g2000cwa.googlegroups.com> Message-ID: "Thierry Lam" wrote in message news:1126707230.693569.187200 at g49g2000cwa.googlegroups.com... > Is there an easy way to write something of variable length at the top > of the file? ... > The other way to do what I want is to write the whole thing to a new > file, but I want to skip that method if there's an alternative way. Grant has already given you the two no's to the questions you asked. > Any suggestions please? A slightly different question "How do I write a variable length file summary after writing the data so that the summary is easy to read without reading the entire file, and so I can add data later?" has a yes answer: 1. reserve a fixed amount of space at the top for a 'pointer' to the summary. 2. write the data 3. write the summary 4. rewind (seek to beginning) and write the 'pointer'. The pointer can be either the offset from the beginning or the offset from the end (= length of summary) in either binary or text format. To read, read the pointer, seek to appropriate place, and read summary. To add data: 1. read the summary 2. write more data, starting where the old summary started 3. write revised summary and pointer. Terry J. Reedy From coollakshman at gmail.com Thu Sep 15 21:03:39 2005 From: coollakshman at gmail.com (laksh) Date: 15 Sep 2005 18:03:39 -0700 Subject: Program crafting IP packets using Scapy Message-ID: <1126832619.590437.154420@g49g2000cwa.googlegroups.com> hi there i just used scapy and this http://packetstorm.linuxsecurity.com/papers/general/blackmagic.txt tutorial to write a program which can send DNS requets in an IP and get the response all this is done in PYTHON ANY ONE if can do the same :-)) im ready to pay them if they can give a better interface to that(python script) along with screen shots .......... YOU WILL BE PAID FOR YOUR JOB (SERIOUS) please reply or give your number to discuss this please do reply faster as i am running out of time Regards and dnt take it as a prank; please act faster and this is nt spam also THANX---------->>>>>>>>> Laksh From stefan.behnel-n05pAM at web.de Sun Sep 25 12:52:25 2005 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 25 Sep 2005 18:52:25 +0200 Subject: Content MathML implementation? Message-ID: Hi! I was looking for an implementation of a parser/model/serializer for Content MathML in Python. Does anyone know about something useful? I need to work with math expressions (arithmetic/bool), especially converting them between different representations (Python, SQL), determining dependencies on variables etc. And since my output format is Content MathML anyway, I wanted to ask if someone has implemented this before I start doing so. To make it clear: Presentation MathML does not help as it has a completely different model that is not usable for my purpose. Thanks for any hints, Stefan From jgrahn-nntq at algonet.se Tue Sep 6 13:22:19 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 6 Sep 2005 17:22:19 GMT Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga> <431cadd6$0$97134$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: On Mon, 05 Sep 2005 21:43:07 +0100, Michael Sparks wrote: > Steve Jorgensen wrote: ... >> I don't get that. Python was never designed to be a high performance >> language, so why add complexity to its implementation by giving it >> high-performance capabilities like SMP? > > It depends on personal perspective. If in a few years time we all have > machines with multiple cores (eg the CELL with effective 9 CPUs on a chip, > albeit 8 more specialised ones), would you prefer that your code *could* > utilise your hardware sensibly rather than not. > > Or put another way - would you prefer to write your code mainly in a > language like python, or mainly in a language like C or Java? If python, > it's worth worrying about! Mainly in Python, of course. But it still feels like a pretty perverted idea to fill a SMP system with something as inefficient as interpreting Python code! (By the way, I don't understand why a computer should run one program at a time all the time. Take a time-sharing system where lots of people are logged in and do their work. Add a CPU there and you'll have an immediate performance gain, even if noone is running programs that are optimized for it!) I feel the recent SMP hype (in general, and in Python) is a red herring. Why do I need that extra performance? What application would use it? Am I prepared to pay the price (in bugs, lack of features, money, etc) for someone to implement this? There's already a lot of performance lost in bloatware people use everyday; why are we not paying the much lower price for having that fixed with traditional code optimization? I am sure some applications that ordinary people use could benefit from SMP (like image processing). But most tasks don't, and most of those that do can be handled on the process level. For example, if I'm compiling a big C project, I can say 'make -j3' and get three concurrent compilations. The Unix shell pipeline is another example. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Wed Sep 28 07:54:23 2005 From: http (Paul Rubin) Date: 28 Sep 2005 04:54:23 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <8c7f10c605092804053a6eadf4@mail.gmail.com> Message-ID: <7xk6h1pfv4.fsf@ruckus.brouhaha.com> Tony Meyer writes: > I'm not sure why I haven't seen this mentioned yet, but a leading > double-underscore does really make a member private:... > As you see, it's there in the dict, but it's obfuscated - but that's > all that other languages do anyway. No, that's false: in languages like Java, private variables are actually private, and if functions in other classes can get to them, it's an error in the Java implementation. The security of things like browser sandboxes depends on the privacy being enforced. Python used to have something called Bastion which was intended to do the same thing, but it didn't work and was removed. From hancock at anansispaceworks.com Wed Sep 7 10:37:41 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 7 Sep 2005 09:37:41 -0500 Subject: Python versus Perl In-Reply-To: References: Message-ID: <200509070937.41888.hancock@anansispaceworks.com> On Wednesday 07 September 2005 04:47 am, Michael Sparks wrote: > Dieter Vanderelst wrote: > > I'm currently comparing Python versus Perl to use in a project that > > involved a lot of text processing. I'm trying to determine what the > > most efficient language would be for our purposes. I have to admit > > that, although I'm very familiar with Python, I'm complete Perl noob > > (and I hope to stay one) which is reflected in my questions. > Your comment """I'm complete Perl noob (and I hope to stay one) """ > would suggest to me that if you really feel that way, stay that way :-) I missed that on the first reading. IMHO, people love perl *really* because it was the first language of its type. However, we learned a lot from that experience, and have since made better languages in the same general category. The best of these of course, is Python. ;-) I felt that way about C, and occasionally Fortran. But I've gotten over it. ;-) I took Perl classes after I learned Python, and I haven't found anything Perl is enough better suited to do that it is worth the trouble of messing with it. Yes, the one and two liner programs are nice, but now that six months have passed and I can no longer remember Perl syntax, it's a lot easier to do it in Python, even if I do wind up using, say, 4 lines of code. The biggest distinction I got from looking at Perl from the perspective of Python is that: 1) Perl makes regular expressions first-class objects, which makes them really easy to use, and a "beginner" subject in a Perl class. 2) Python makes objects and classes really easy to use, so they are a "beginner" subject. However, each can do the other when pressed. So which would you rather have be easy? Regular expression program makes huge incomprehensible piles of gobblygook which you forget 10 seconds after you wrote it, while objects and classes make it easy to understand the structure of your program. Even regular expressions are clearer in Python (IMHO) because of the ability to apply string operations on them. Furthermore, the ready availability of more direct methods of string manipulation encourages more optimized and clearer design decisions (in Python if you just want to find a word, you can just say so, instead of "crafting a routine regular expression"). Performance is a complete non-issue. Both languages are reasonably fast, and neither has a clear advantage on real world projects. Python and Perl are "rivals" precisely because they are very similar in what they can do. So I'd second the suggestion to eschew the Perl if you can at all get away with it. If you're already sold on Python, there's no reason to question your judgement. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From billiejoex at fastwebnet.it Fri Sep 9 11:17:28 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Fri, 9 Sep 2005 17:17:28 +0200 Subject: icmp sniffer with pcapy module Message-ID: <3HhUe.18428$nT3.4640@tornado.fastwebnet.it> Hi all. The source below is a simple icmp sniffer made with pcapy. To decode packets I'm using the EthDecoder() function that returns a rapresentation of the packet including ICMP type, ICMP code, IP source and IP destination. All I need, now, is to get the ip src and ip dst only but I don't know how to do it. I tried to use the IPDecoder instead of EthDecoder to decode packets but misteriously it doesn't works. Does anybody have a good idea about how to get this values only? Best regards #!/usr/bin/python ### sniffer import pcapy from impacket.ImpactDecoder import * def recv_pkts(hdr, data): x = EthDecoder().decode(data) print x def get_int(): devs = pcapy.findalldevs() i=0 for eth in devs: print " %d - %s" %(i,devs[i]) i+=1 sel=input(" Select interface: ") dev=devs[sel] return dev dev = get_int() p = pcapy.open_live(dev, 1500, 0, 100) p.setfilter('icmp') print "Listening on eth: net=%s, mask=%s\n" % (p.getnet(), p.getmask()) p.loop(-1, recv_pkts) From tjreedy at udel.edu Thu Sep 1 15:27:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Sep 2005 15:27:44 -0400 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <7x7je1tl9w.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x7je1tl9w.fsf at ruckus.brouhaha.com... > I think there is an attitude problem in the central Python development > community, which is to expect external volunteers to do stuff with no > cajoling and no guidance. You are correct. No one has volunteered to be a volunteer volunteer coordinator. > That just doesn't work very well. Improvements are possible, certainly. > I was > the first FSF staff programmer on the GNU project and we spent a LOT > of our time coordinating volunteers and maintaining lists of tasks to > recruit people to do, and generally trying to make stuff happen > according to what we saw as the project's priorities, as opposed to > simply passively waiting for code and doc contributions to come to us > fully done. We also saw doing gap-filling and grunt-work that didn't > excite volunteers to be an important part of our purpose as paid > staff: if somebody had to do it and no one volunteered, then the > somebody was us. As far as I know, there currently is no paid staff for Python. Everything is either volunteer or employer-donated time. You could suggest that someone be paid for a few hours a week of volunteer coordination and explain what such work would, concretely, consist of. >The PSF and the FSF both sometimes fund > people to do coding projects. Why does the PSF (apparently) not fund > anyone to do doc projects, like the FSF does? Last fall, PSF funded two projects out of many submissions. Were any doc projects submitted. Perhaps next round, one of us will. One could also send an uninvited proposal. This summer, Google funded about 18 Python-related Summer of Code student projects. Hmm. The title does suggest code, not docs. Terry J. Reedy From jfdoyon at methane.ca Sun Sep 4 14:08:59 2005 From: jfdoyon at methane.ca (=?ISO-8859-1?Q?Jean-Fran=E7ois_Doyon?=) Date: Sun, 04 Sep 2005 14:08:59 -0400 Subject: String from File -> List without parsing In-Reply-To: References: Message-ID: <_KGSe.564$I02.57037@news20.bellglobal.com> Gregor, You want to use eval(): Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> eval('[3,54,5]') [3, 54, 5] >>> Cheers, J.F. Gregor Horvath wrote: > Hi, > > given the dynamic nature of python I assume that there is an elegant > solution for my problem, but I did not manage to find it. > > I have a file that contains for example on line: > > ['147', '148', '146'] > > when I read the file > > f = file("I050901.ids").readlines() > > I have a string > > f[0] == "['147', '148', '146']" > > How can I turn this string into a list > > li == ['147', '148', '146'] > > without parsing? > > -- > Greg From enleverlesO.OmcO at OmclaveauO.com Sun Sep 11 02:35:52 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Sun, 11 Sep 2005 08:35:52 +0200 Subject: getting words from readline References: Message-ID: <4323d270$0$3540$636a15ce@news.free.fr> Hi ! Look : .split() @-salutations Michel Claveau From theller at python.net Tue Sep 20 12:36:56 2005 From: theller at python.net (Thomas Heller) Date: Tue, 20 Sep 2005 18:36:56 +0200 Subject: Getting tired with py2exe Message-ID: I'm slowly getting tired maintaining py2exe. It is far from perfect, although it has interesting features (I would say). The problem, apart from the work, is that it is good enough for me - I can do everything that I need with it. But I assume I use far less libaries than other Python programmers, so a lot of bugs will never bite me. It is also interesting that the recently introduced bundle-files option, which allows to build single-file exes has gained a lot of interest - although the ONLY use case (so far) I have myself for it is to implement inproc COM servers which will compatible with Python clients (and other Python inproc COM servers) because of the total isolation of the Python VMs. Is anyone interested in taking over the maintainance, documentation, and further development? Should py2exe be integrated into another, larger, package? Pywin32 comes to mind, but also Philip Eby's setuptools (that's why I post to distutils-sig as well)... Thomas From max at alcyone.com Fri Sep 9 00:33:49 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 08 Sep 2005 21:33:49 -0700 Subject: What's the difference between VAR and _VAR_? In-Reply-To: <1126240211.306844.157130@f14g2000cwb.googlegroups.com> References: <1126239543.098530.98570@f14g2000cwb.googlegroups.com> <1126240211.306844.157130@f14g2000cwb.googlegroups.com> Message-ID: Johnny Lee wrote: > As what you said, the following two code section is totally the same? > > (I) > class TestResult: > _passxxx_ = "pass" > > (II) > class TestResult: > passxxx = "pass" No, of course not. One defines a class varaible named `_passxxx_', the other defines one named `passsxxx'. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Experience is the name everyone gives to their mistakes. -- Oscar Wilde From superprad at gmail.com Wed Sep 28 16:33:25 2005 From: superprad at gmail.com (PyPK) Date: 28 Sep 2005 13:33:25 -0700 Subject: Pixel Manipulations Message-ID: <1127939605.328848.171860@o13g2000cwo.googlegroups.com> Does anyone know of a simple implementation for detecting straight line .So something like if we have a 2D arary of pixel elements representing a particular Image. How can we identify lines in this Image. for example: ary = [[1,1,1,1,1], [1,1,0,0,0], [1,0,1,0,0], [1,0,0,1,0], [1,0,0,0,1]] So if 'ary' represents pxl of an image which has a horizontal line(row 0),a vertical line(col 0) and a diagonal line(diagonal of ary). then basically I want identify any horizontal or vertical or diagonal line anywhere in the pxl array and return true if its composed of only lines else false... Thanks. From jpopl at interia.pl Tue Sep 13 03:25:17 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Tue, 13 Sep 2005 09:25:17 +0200 Subject: read stdout/stderr without blocking In-Reply-To: References: Message-ID: Only solution which works for now is to redirect stderr to stdout, and read stdout on thread. Code without thread or with read() or read(n) (when n>1) can block. Code with select() and read(1) works, but it is very slow. From http Mon Sep 19 06:54:57 2005 From: http (Paul Rubin) Date: 19 Sep 2005 03:54:57 -0700 Subject: How to write this iterator? References: Message-ID: <7xoe6pjpj2.fsf@ruckus.brouhaha.com> Hmm, here's an approach using the .throw() operation from PEP 342. It's obviously untested, since that feature is not currently part of Python, probably incorrect, and maybe just insane. I renamed "append" to "insert_iterator" since "append" usually means put something at the end, not in the middle. from itertools import cycle class InsertIterator(Exception): pass def itergen(self, *iters): while iters: try: for i,it in (enumerate(it) for it in cycle(iters)): yield it.next() except StopIteration: del iters[i] except InsertIterator, new_iterator: # maybe the i here should be i+1? iters = [new_iterator] + iters[i:] + iters[:i] Now you can say ig = itergen(it1,it2,...) for x in ig: .... and if you want to insert a new iterator, just say ig.throw(InsertIterator, new_iterator) From reinhold-birkenfeld-nospam at wolke7.net Fri Sep 30 14:25:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 30 Sep 2005 20:25:35 +0200 Subject: [Info] PEP 308 accepted - new conditional expressions In-Reply-To: References: <3q4ro9Fd770nU3@individual.net> Message-ID: <3q5e8vFd75o0U1@individual.net> Fredrik Lundh wrote: > Reinhold Birkenfeld wrote: > >> after Guido's pronouncement yesterday, in one of the next versions of Python >> there will be a conditional expression with the following syntax: >> >> X if C else Y >> >> which is the same as today's >> >> (Y, X)[bool(C)] > > hopefully, only one of Y or X is actually evaluated ? (cough) Yes, sorry, it's not the same. The same would be (C and lambda:X or lambda:Y)() if I'm not much mistaken. >> C and X or Y (only if X is True) > > hopefully, "only if X is True" isn't in fact a limitation of "X if C else Y" ? > > /... snip comment that the natural order is C, X, Y and that programmers that > care about readable code will probably want to be extremely careful with this > new feature .../ Yes, that was my comment too, but I'll not demonize it before I have used it. Reinhold From g.horvath at gmx.at Thu Sep 29 04:47:07 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 29 Sep 2005 10:47:07 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xfyroe5vh.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xfyroe5vh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > > If you don't want the compiler to make sure your private instance > variables stay private, then don't declare them that way. You're the > one asking for less flexibility. I want to declare them as privat, but want to give the flexibilty to access them at the users own risk. Declaring everything as public is nonsene, because there should be a garanteed stable interface. -- Greg From peter at engcorp.com Fri Sep 2 11:29:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Sep 2005 11:29:31 -0400 Subject: .pth files question In-Reply-To: <5vr7c735zg.fsf@akron.bmi.ohio-state.edu> References: <5vr7c735zg.fsf@akron.bmi.ohio-state.edu> Message-ID: Benjamin Rutt wrote: > Am I correct in understanding that: > > 1) foo.pth will be used if it is in the directory > /usr/lib/python-2.4/site-packages > > 2) foo.pth will not be read from if it is only placed somewhere in the > PYTHONPATH environment, such as foo.pth exists as the file > /tmp/bar/foo.pth, where PYTHONPATH contains "/tmp/bar"? Both by inspection of the source and by experimentation, it appears you are correct. As the docs say, only the "site-specific paths" (i.e. sys.prefix and sys.exec_prefix, and lib/python/site-packages and lib/site-python) are actually scanned for .pth files, plus any paths added as a result of parsing .pth files that are found. If you want to modify or extend this behaviour, you should take advantage of sitecustomize.py by adding your own behaviour, perhaps scanning os.environ['PYTHONPATH'] to look for .pth files. -Peter From vimakefile at yahoo.com Fri Sep 9 20:12:17 2005 From: vimakefile at yahoo.com (Mike) Date: Fri, 9 Sep 2005 17:12:17 -0700 Subject: python object model diagram References: <1126310041.310250.95120@o13g2000cwo.googlegroups.com> Message-ID: I think he's looking for diagrams of the batteries-included modules and classes. My guess is that he thinks there's a set of "framework" classes that is a lot deeper and class-ier than it is, similar to what you'd find in C++, C#, Java, etc. So, OP - who won the guessing game :) m "gene tani" wrote in message news:1126310041.310250.95120 at o13g2000cwo.googlegroups.com... >I think he's looking for tidy pictures of how metaclasses and > descriptors interact with your classes and instances at compile- & > runtime, something like that (which I haven't seen) > > There's pictures of the class hierarchy for C and j-python: > > http://www.brpreiss.com/books/opus7/html/page114.html > http://www.jython.org/docs/javadoc/overview-tree.html > > , there's pictures of method resolution order in Python Nutshell, (but > I don't think that's what he's looking for.) > > Ara.T.Howard wrote: >> anyone out there know where i might find a python object model diagram? >> > From opstad at batnet.com Fri Sep 2 10:41:34 2005 From: opstad at batnet.com (Dave Opstad) Date: Fri, 02 Sep 2005 07:41:34 -0700 Subject: __setslice__ and classes derived from list Message-ID: According to the documentation the __setslice__ method has been deprecated since Python 2.0. However, if I'm deriving classes from the builtin list class, I've discovered I can't really ignore __setslice__. Have a look at this snippet: ---------------------------------------------------- >>> class V(list): ... def __setitem__(self, key, value): ... if isinstance(key, slice): ... print "Slice:", key.start, key.stop, key.step ... else: ... print "Regular:", key ... super(V, self).__setitem__(key, value) ... def __setslice__(self, i, j, value): ... print "Old method:", i, j ... super(V, self).__setslice__(i, j, value) ... >>> v = V([1,2,4,8]) >>> v [1, 2, 4, 8] >>> v[0] = 100 Regular: 0 >>> v [100, 2, 4, 8] >>> v[1:3] = [99, 99] Old method: 1 3 >>> v [100, 99, 99, 8] >>> v[1:3:1] = [88, 88] Slice: 1 3 1 >>> v [100, 88, 88, 8] >>> v[-1] = 12 Regular: -1 >>> v [100, 88, 88, 12] >>> v[-3:-1] = [77, 66] Old method: 1 3 >>> v [100, 77, 66, 12] ---------------------------------------------------- If I assign to v[1:3] it dispatches via __setslice__, but if I assign to v[1:3:1] it dispatches via __setitem__. The documentation states that if a __setslice__ method is present it will be used, but if one isn't present then a slice will be synthesized and __setitem__ will be used exclusively. Since the builtin list class provides a __setslice__ method, what this means is that any class derived from list still has to make provisions for this ostensibly deprecated method. There's a workaround for this, namely to include this method: def __setslice__(self, i, j, seq): self.__setitem__(slice(i, j), seq) That way any custom code I need to include in __setitem__ doesn't have to be duplicated in __setslice__. But just out of curiosity I thought I'd ask the folks here if there's any other way of doing this? Maybe something like a "noslicelist" class which doesn't have __setslice__, where the standard list class would then be a subclass of noslicelist with the __setslice__ method present for compatibility. That way I could subclass noslicelist myself, and not have to worry about it. Dave From axel at white-eagle.invalid.uk Fri Sep 30 13:55:29 2005 From: axel at white-eagle.invalid.uk (axel at white-eagle.invalid.uk) Date: Fri, 30 Sep 2005 17:55:29 GMT Subject: A Moronicity of Guido van Rossum References: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> <1128013745.763757.144280@g44g2000cwa.googlegroups.com> <1128015868.201617.153240@g14g2000cwa.googlegroups.com> <0001HW.BF63479501083049F0407550@news.individual.de> Message-ID: In comp.lang.perl.misc Kalle Anke wrote: > On Thu, 29 Sep 2005 19:44:28 +0200, Matt wrote > (in article <1128015868.201617.153240 at g14g2000cwa.googlegroups.com>): >> OK... your post seems to indicate a belief that everyone else is >> somehow incompetent. Sounds a bit like the "I am sane, it is everyone >> else who is crazy" concept. Can you suggest a technology or >> technologist who, in your expert opinion, has gotten it right? > He has posted similar posts about other things to at least one other mailing > list, the tone and arguments of these post were exactly the same. I wonder if his postings are related to the phases of the moon? It might explain a lot. Axel From vincent at visualtrans.de Wed Sep 21 12:50:11 2005 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 21 Sep 2005 18:50:11 +0200 Subject: I am not able to setup pydb2 ! Any help ! References: <1127321226.420209.253360@g43g2000cwa.googlegroups.com> Message-ID: "vj" schrieb im Newsbeitrag news:1127321226.420209.253360 at g43g2000cwa.googlegroups.com... | When I run the setup.py script , it throws an error | | Traceback (most recent call last): | File "C:\vijay\db2\utils\PyDB2-1.1.0-2.tar\PyDB2-1.1.0\setup.py", | line 57, in -toplevel- | libraries=[ db2lib ], | File "C:\Python24\lib\distutils\core.py", line 137, in setup | raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg | SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 | [cmd2_opts] ...] | or: setup.py --help [cmd1 cmd2 ...] | or: setup.py --help-commands | or: setup.py cmd --help | | error: no commands supplied | >>> | | Please let me know , what should have been the issue. You need to say "setup.py install" instead of just setup.py HTH, -- Vincent Wehren | | Thanks in advance. | | Vj | From anthony at python.org Thu Sep 22 03:42:10 2005 From: anthony at python.org (Anthony Baxter) Date: Thu, 22 Sep 2005 17:42:10 +1000 Subject: RELEASED Python 2.4.2, release candidate 1 Message-ID: <200509221742.12706.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.2 (release candidate 1). Python 2.4.2 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 more than 60 bugs squished in this release. Assuming no major problems crop up, a final release of Python 2.4.2 will follow in about a week's time. For more information on Python 2.4.2, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.2 Highlights of this new release include: - Bug fixes. According to the release notes, more than 60 have been fixed, including bugs that prevented Python from working properly on 64 bit HP/UX and AIX systems. Highlights of the previous major Python release (2.4) are available from the Python 2.4 page, at http://www.python.org/2.4/highlights.html Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) From sybrenUSE at YOURthirdtower.com.imagination Wed Sep 14 12:33:49 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 14 Sep 2005 18:33:49 +0200 Subject: Python for ARM7? References: Message-ID: Ken Seehart enlightened us with: > I could try to unpack them on another (non-ARM7) linux box and then > move the files over to the ARM7 device. Yep, that should work. > Better yet, can I unpack them on windows XP somehow? Don't know. > If for some reason that is not possible, i suppose my next step is > to find a compatible ARM7 linux installation to unpack on another > machine to steal files from. Why? You can extract the files just fine on any ARM machine. It's the code in the binaries that you can't execute on anything but ARM. Just extracting some files can be done on any system. > It there an easy to obtain the files I need without attempting to > reintall linux? Sure, just use a live CD. > (any other commands that ipkg runs) As I said: you can extract the files even without ipkg. Just untar them and take a good look at the contents. You'll figure it out. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From miki.tebeka at zoran.com Thu Sep 1 04:33:19 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 1 Sep 2005 11:33:19 +0300 Subject: Improving my text processing script In-Reply-To: <1125500982.664278.83810@g47g2000cwa.googlegroups.com> References: <1125500982.664278.83810@g47g2000cwa.googlegroups.com> Message-ID: <20050901083318.GL2656@zoran.com> Hello pruebauno, > import re > f=file('tlst') > tlst=f.read().split('\n') > f.close() tlst = open("tlst").readlines() > f=file('plst') > sep=re.compile('Identifier "(.*?)"') > plst=[] > for elem in f.read().split('Identifier'): > content='Identifier'+elem > match=sep.search(content) > if match: > plst.append((match.group(1),content)) > f.close() Look at re.findall, I think it'll be easier. > flst=[] > for table in tlst: > for prog,content in plst: > if content.find(table)>0: if table in content: > flst.append('"%s","%s"'%(prog,table)) > flst.sort() > for elem in flst: > print elem print "\n".join(sorted(flst)) HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From mwm at mired.org Fri Sep 9 16:49:01 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 09 Sep 2005 16:49:01 -0400 Subject: How to upgrade to 2.4.1 on Mac OS X tiger References: <1126102477.882046.95490@z14g2000cwz.googlegroups.com> <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> <1126196055.843689.208130@g43g2000cwa.googlegroups.com> <1126275430.044429.72830@g49g2000cwa.googlegroups.com> Message-ID: <86hdcu2chu.fsf@bhuda.mired.org> stri ker writes: > Has anyone here upgraded from 2.3 to 2.4 on Tiger? > If so how'd ya do it? You don't. You install 2.4 in parallel with 2.3. You can do pretty much whatever you want with /usr/bin/python, /usr/local/bin/python, etc. - Tiger doesn't seem to use those. I don't remember if I replaced one or not, but don't touch anything else about the 2.3 installtion. I installed the darwinports version of 2.4, and have been using it ever since for all my stuff. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Wed Sep 28 04:24:51 2005 From: http (Paul Rubin) Date: 28 Sep 2005 01:24:51 -0700 Subject: Human readable number formatting References: <1127862406.11827.2.camel@localhost.localdomain> <1127895464.345142.171030@g43g2000cwa.googlegroups.com> Message-ID: <7xirwlbnvw.fsf@ruckus.brouhaha.com> "MrJean1" writes: > Ocha O + 54 - o otro > Nena N + 57 - nk nekto > MInga MI + 60 - mk mikto > Luma L + 63 - l lunto Please tell me you're making this up. From rrr at ronadam.com Mon Sep 5 01:05:20 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 05 Sep 2005 05:05:20 GMT Subject: Possible improvement to slice opperations. In-Reply-To: <1125892492.759723.146480@g47g2000cwa.googlegroups.com> References: <1125892492.759723.146480@g47g2000cwa.googlegroups.com> Message-ID: Patrick Maupin wrote: >>After considering several alternatives and trying out a few ideas with a >> modified list object Bengt Richter posted, (Thank You), I think I've >>found a way to make slice operation (especially far end indexing) >>symmetrical and more consistent. > > > I don't know that it makes it more consistent. I could be persuaded, > but it would have to be by real-life examples with calculated slice > indices and stride. I do this thing all the time, and find the current > rules simple and very consistent. Occasionally, I might wish that > things were a little different, but there is always a workaround. I > would have to see some real code examples, of sufficient scope to see > that there are fewer workarounds with this proposal than with the > current implementation. I'll post a few examples once I'm sure the list object works correctly and then you can play around with it and try it out as well. > FWIW, there is a reasonable workaround for the case where the indices > might be negative and you would like zero or greater to mean 'end of > list'. If "x" is the index variable, you can use the expression (x<0 > and x or None) for the index value in the slice. If you find yourself > doing this often, you can write a little function for it -- def > EndIndex(x): return x<0 and x or None. Thanks, this is a good example. Yes it does remove the need for a work around in those cases. You still need to check for cases where you may cross the -1,0 boundary while incrementing or decrementing an index. But that is an expected condition and easily handled with an 'if' or 'for' loop. > But in real code, I fear you might need a similar helper function for > similar issues with your change. I just don't know what those are > without more thought. > > Regards, > Pat Thanks for the feedback, it was helpful. Cheers, Ron From grante at visi.com Mon Sep 26 14:57:50 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 26 Sep 2005 18:57:50 -0000 Subject: ncurses programming References: <1127754862.781184.224480@z14g2000cwz.googlegroups.com> <874q87pw5f.fsf@wilson.rwth-aachen.de> <86wtl3wu5a.fsf@bhuda.mired.org> Message-ID: <11jgh5eq2a9pb10@corp.supernews.com> On 2005-09-26, Mike Meyer wrote: [...] >>> Py Docs: http://docs.python.org/lib/module-curses.html >> >> This document suggests that Python+ncurses won't work on windows. >> What's the reason for this? > > Could it be that ncurses doesn't work on Windows? At least, it > didn't last time I looked. There was a curses library for > Windows, but you'll have to google for it. I think there used to be something called pdcurses that supposedly worked under windows. That was quite a while ago, I never tried it, and I may be misremembering the name. I've no idea if there was a pdcurses module for python. -- Grant Edwards grante Yow! I will SHAVE and at buy JELL-O and bring my visi.com MARRIAGE MANUAL!! From jeremy+python at jeremysanders.net Tue Sep 20 16:40:22 2005 From: jeremy+python at jeremysanders.net (Jeremy Sanders) Date: Tue, 20 Sep 2005 21:40:22 +0100 Subject: Classes derived from dict and eval Message-ID: Hi - I'm trying to subclass a dict which is used as the globals environment of an eval expression. For instance: class Foo(dict): def __init__(self): self.update(globals()) self['val'] = 42 def __getitem__(self, item): # this doesn't get called from the eval statement print "*", item return dict.__getitem__(self, item) a = Foo() print a['val'] print eval('val*2+6', a) The first print statements also prints "* val", but __getitem__ is never called by the evaluation in the eval statement. Is this a bug? Does anyone have an idea for a workaround? I'm using Python 2.3.3. Thanks Jeremy From rkern at ucsd.edu Tue Sep 6 16:51:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 06 Sep 2005 13:51:23 -0700 Subject: Replacement for lambda - 'def' as an expression? In-Reply-To: <1126038950.944680.39140@z14g2000cwz.googlegroups.com> References: <1125996559.130055.154400@z14g2000cwz.googlegroups.com> <1126038950.944680.39140@z14g2000cwz.googlegroups.com> Message-ID: talin at acm dot org wrote: > I like the decorator idea. Unfortunately, the version of Python I am > using is pre-decorator, and there are various issues involved in > upgrading on Mac OS X (due to the built-in Python 2.3 being used by the > OS itself.) I'll have to look into how to upgrade without breaking too > much... There really aren't any issues. The official 2.4.1 binary installs alongside the built-in 2.3. The executables python{,w,2.4,w2.4} are installed the /usr/local/bin . Under no circumstances should you have to replace the built-in 2.3. Indeed, under no circumstances should you replace it at all. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tjreedy at udel.edu Mon Sep 26 15:33:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Sep 2005 15:33:38 -0400 Subject: Would this be Guido's pen? [OT] References: Message-ID: "Dennis Lee Bieber" wrote in message news:ct2fj19nm53cr7cht5p062piohhhjhtqjs at 4ax.com... > > http://www.empirepens.com/signum_python.html "Each cap in this series is hand covered with genuine python." Am I to understand that they actually mean real python skin, as opposed to a 'genuine' python skin design on whatever material? Is there a European fetish for the real thing? Terry From tarmstrong at gmail.com Fri Sep 30 09:29:01 2005 From: tarmstrong at gmail.com (thomas Armstrong) Date: Fri, 30 Sep 2005 15:29:01 +0200 Subject: 'ascii' codec can't encode character u'\u2013' Message-ID: Hi Using Python 2.3.4 + Feedparser 3.3 (a library to parse XML documents) I'm trying to parse a UTF-8 document with special characters like acute-accent vowels: -------- ... ------- But I get this error message: ------- UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 122: ordinal not in range(128) ------- when trying to execute a MySQL query: ---- query = "UPDATE blogs_news SET text = '" + text_extrated + "'WHERE id='" + id + "'" cursor.execute (query) #<--- error line ---- I tried with: ------- text_extrated = text_extrated.encode('iso-8859-1') #<--- error line query = "UPDATE blogs_news SET text = '" + text_extrated + "'WHERE id='" + id + "'" cursor.execute (query) ------- But I get this error: ------ UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2013' in position 92: ordinal not in range(256) ----- I also tried with: ---- text_extrated = re.sub(u'\u2013', '-' , text_extrated) query = "UPDATE blogs_news SET text = '" + text_extrated + "'WHERE id='" + id + "'" cursor.execute (query) ----- It works, but I don't want to substitute each special character, because there are always forgotten ones which can crack the program. Any suggestion to fix it? Thank you very much. From nil at dev.nul Sun Sep 18 00:51:09 2005 From: nil at dev.nul (Christian Stapfer) Date: Sun, 18 Sep 2005 06:51:09 +0200 Subject: reading files with error References: <20050918015812.GA10421@unpythonic.net> Message-ID: Maurice Ling wrote in message news:mailman.547.1127016906.509.python-list at python.org... > jepler at unpythonic.net wrote: > >>I have written a program to do something similar. My strategy is: >> * use os.read() to read 512 bytes at a time >> * when os.read fails, seek to the next multiple of 512 bytes >> and write '\0' * 512 to the output >>I notice this code doesn't deal properly with short reads, but in my >>experience >>they never happen (because the disk error makes an entire block >>unreadable, and >>a block is never less than 512 bytes) >> >>I use this code on a unix-style system. >> >>def dd(src, target, bs=512): >> src = os.open(src, os.O_RDONLY) >> if os.path.exists(target): >> target = os.open(target, os.O_WRONLY | os.O_APPEND, 0600) >> existing = os.lseek(target, 0, SEEK_END) >> else: >> existing = 0 >> target = os.open(target, os.O_WRONLY | os.O_CREAT, 0600) >> >> total = os.lseek(src, 0, SEEK_END) / bs >> os.lseek(src, existing, SEEK_SET) >> os.lseek(target, existing, SEEK_SET) >> >> if existing: print "starting at", existing >> i = existing / bs >> f = 0 >> lastrem = -1 >> >> last = start = time.time() >> while 1: >> try: >> block = os.read(src, bs) >> except os.error, detail: >> if detail.errno == errno.EIO: >> block = "\0" * bs >> os.lseek(src, (i+1) * bs, SEEK_SET) >> f = f + 1 >> else: >> raise >> if block == "": break >> >> i = i + 1 >> os.write(target, block) >> >> now = time.time() >> if i % 1000 or now - last < 1: continue >> last = now >> >> frac = i * 1. / total >> rem = int((now-start) * (1-frac) / frac) >> if rem < 60 or abs(rem - lastrem) > .5: >> rm, rs = divmod(rem, 60) >> lastrem = rem >> spd = i * 512. / (now - start) / 1024 / 1024 >> sys.stderr.write("%8d %8d %8d %3.1f%% %6d:%02d %6.1fMB/s\r" >> % (i, f, i-f, i * 100. / total, rm, rs, spd)) >> sys.stderr.write("\n") >> >> > Sorry but what are SEEK_END and SEEK_SET? The Python 2.3 documentation seems to specify the *numeric* values of these constants only. But since Python's file objects are "implemented using C's stdio package", you can read http://www.opengroup.org/onlinepubs/009695399/functions/lseek.html Regards, Christian Stapfer From tjreedy at udel.edu Sun Sep 11 15:08:46 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2005 15:08:46 -0400 Subject: Python versus Perl References: <43246da1$0$1290$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: "Michael Sparks" wrote in message news:43246da1$0$1290$ed2619ec at ptn-nntp-reader02.plus.net... > That said, if you do describe it that way, it'd be more accurate to > describe > the python binary as a compiler/runtime rather than interpreter since > it'd > be more accurate. If Java calls its runtime bytecode interpreter a 'runtime' rather than 'interpreter', so can we. Ditto, if applicable, to .NET clr. Still more accurate, I think, is 'intergrated compiler and runtime'. > It strikes me as ironic that python would probably gain more credibility > with some circles if it had two binaries like this, even though it'd be a > step backwards from a usability perspective :-) Yes. The integration is a practical necessity for interactive mode with alternative compile and execute. For batch mode, integration consists of the very nice built-in mini-make. > Personally I agree that any language that is described as interpreted has > an > image issue. However I'm not sure who's problem that is - some people > claim > it's "Python's problem", however personally I'd view as a problem for the > people who buy into "interpretted bad, compiled good" argument. After > all, > they're the ones limiting themselves, and missing out on a whole class of > languages (of which python is just one of course) ! That has been my response. And as a Python programmer, that is the end of it. But as a responder/advocate, I am beginning to accept that the misperception is wide enough to also be a bit my problem. Hence my small effort for a more effective vocabulary. Thanks for your contribution. Terry J. Reedy From i_vincent at hotmail.com Wed Sep 28 02:57:39 2005 From: i_vincent at hotmail.com (Ian Vincent) Date: 28 Sep 2005 07:57:39 +0100 Subject: Spoiler to Python Challenge (help!!!) References: Message-ID: "Terry Reedy" wrote in news:mailman.1027.1127847089.509.python-list at python.org: > > please, line = line[20:-1], etc, is easier to read and understand ;-) Thanks, i'll put that in. From googlenews at tooper.org Thu Sep 1 09:30:41 2005 From: googlenews at tooper.org (tooper) Date: 1 Sep 2005 06:30:41 -0700 Subject: Extend Python In-Reply-To: <1125576741.165568.22390@g14g2000cwa.googlegroups.com> References: <1125576741.165568.22390@g14g2000cwa.googlegroups.com> Message-ID: <1125581441.779857.159380@g47g2000cwa.googlegroups.com> PyQT is using SIP to wrap Qt : looks nice and works great for PyQt which is a quite big wrapping. Never had the occation to use it myself however, except for this. From steve at REMOVETHIScyber.com.au Thu Sep 29 19:21:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 30 Sep 2005 09:21:59 +1000 Subject: attribute error References: <86slvrwhh2.fsf@bhuda.mired.org> <433C4402.6050408@grads.ece.mcmaster.ca> <17212.17749.161555.648218@bhuda.mired.org> Message-ID: On Thu, 29 Sep 2005 15:57:47 -0400, M.N.A.Smadi wrote: > This has nothing to do with how the argument is passed. It is prob > something wrong with str.pop in my python because when i run python and type > import os > import string > x = '1 2 3' > x.pop() > > i get the following error > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'str' object has no attribute 'pop' That's because strings don't have a pop method, just like the error says. Did you read the error? Error messages frequently tell you what the error is. Lists have a pop method. You can't pop from a string. If you try to pop from a string, you will get an error. You tried to pop from a string, and it gave an error. The error told you what you did wrong: you tried to pop from a string. Why are you surprised? Go back to your code. Look at the variable that you are trying to pop from, and notice that it is a string, just like the error message says. Now search back through your code until you find the place where you assign a string to that variable. Don't assign a string to it. Problem fixed. Like I said the first time I answered your question, I think your problem is that you are passing in a single argument string like: "this is a list of commands" instead of a real list like: ["this", "is", "a", "list", "of", "commands"] As I also said the first time I answered this, you may find the split() string method useful for creating that list. (Hint: if x is a string, you call x.split() and get back a list.) For future reference: any time you think you have found a bug in Python, the chances are about 999,999 in a million that you've found a bug in your code. -- Steven. From gene.tani at gmail.com Fri Sep 9 21:39:28 2005 From: gene.tani at gmail.com (gene tani) Date: 9 Sep 2005 18:39:28 -0700 Subject: "grep" database In-Reply-To: <1126287203.938630.98600@g44g2000cwa.googlegroups.com> References: <1126287203.938630.98600@g44g2000cwa.googlegroups.com> Message-ID: <1126316368.002472.177900@g49g2000cwa.googlegroups.com> maybe look Gonzui, LXR, some of the other tools listed here http://www.gnu.org/software/global/links.html Hilbert wrote: > Hello, > > I've heard of a software on linux that creates a recursive database of > text files and then provides an interface for grep-like queries. I'd > like to use it to find procedures/variables in a large code base. > > Any suggestions appreciated. > > Thanks, > Hilbert From gregor.jan at NOSPAM.quick.cz Fri Sep 9 03:33:42 2005 From: gregor.jan at NOSPAM.quick.cz (Jan Gregor) Date: Fri, 09 Sep 2005 09:33:42 +0200 Subject: python script under windows Message-ID: Hello I run python script on another computer and want to "survive" that script after my logout. the script also uses drive mapping to network drive. Can you help me ? Or better is there some info for unix person how to survive with python on windows ;-) thanks, jan gregor From richie at entrian.com Fri Sep 23 08:46:27 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 23 Sep 2005 13:46:27 +0100 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <1127426064.277907.251710@g47g2000cwa.googlegroups.com> <3pgqp0Fagh77U1@individual.net> Message-ID: [amk] > Similar things happen on the catalog SIG: people suggest, or even implement, > an automatic package management system, But bring up the question of whether > it should be called PyPI or Cheeseshop or the Catalog, and *everyone* can make > a suggestion. This is known as the "bike shed effect": http://linuxmafia.com/~rick/lexicon.html#bikeshed -- Richie Hindle richie at entrian.com From ms at cerenity.org Sun Sep 18 17:54:20 2005 From: ms at cerenity.org (Michael Sparks) Date: Sun, 18 Sep 2005 22:54:20 +0100 Subject: Roguelike programmers needed References: <1127023510.646515.8720@g49g2000cwa.googlegroups.com> Message-ID: <432de20d$0$22946$ed2619ec@ptn-nntp-reader01.plus.net> Robert Kern wrote: > Thomas Jollans wrote: >> what exactly is RPG/roguelike etc ? (what debian package provides an >> example?) > > Google is your friend. Often a fair answer, but I'd suggest that the question was fair, especially given the OP was seeking help :-) After all, I read the subject line and simply assumed they were after programmers with roguish qualities. Perhaps to work in the newly formed IT division of the Crimson Permanent Assurance Company. After all, don't forget - #It's Fun to Charter, and Accountant...# ;-) Michael. From grante at visi.com Mon Sep 26 10:24:40 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 26 Sep 2005 14:24:40 -0000 Subject: Simple Dialogs References: <1127500418.970813.321910@g44g2000cwa.googlegroups.com> <1127732262.978778.80400@g47g2000cwa.googlegroups.com> Message-ID: <11jg158imj7q971@corp.supernews.com> On 2005-09-26, neil.fraser at gmail.com wrote: > James Stroud wrote: >> from tkMessageBox import showerror >> showerror('Problem','Program Crashed before Starting') > > Here's a faster method, though not cross-platform: > > import ctypes > ctypes.windll.user32.MessageBoxA(0, "Hello World", "Title", 0x00) Another easy way to do a dialog box: import os os.system('Xdialog --msgbox "Hello World" 0 0') -- Grant Edwards grante Yow! I will establish at the first SHOPPING MALL in visi.com NUTLEY, New Jersey... From http Fri Sep 23 20:41:54 2005 From: http (Paul Rubin) Date: 23 Sep 2005 17:41:54 -0700 Subject: Productivity and economics at software development References: Message-ID: <7xbr2jb8kt.fsf@ruckus.brouhaha.com> Peter Hansen writes: > If you focus on IDEs, your research will have pre-selected only > certain kinds of programmers and teams, and will not necessarily > include the best ones. It wouldn't have occurred to me to say that Ken Iverson (APL), Peter Deutsch (PARC Smalltalk), or Dave Moon (MIT Lisp machine) were any of them slouches. Some of the best programming ever done has gone into IDE's. It would be great if Python had anything of the caliber of those old systems. From bokr at oz.net Fri Sep 2 22:53:52 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 03 Sep 2005 02:53:52 GMT Subject: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type References: <3ErPe.853$sV7.65@newssvr21.news.prodigy.com> <7sJPe.573$MN5.131@newssvr25.news.prodigy.net> <7xy86k3r7n.fsf@ruckus.brouhaha.com> <4314b190.174021119@news.oz.net> <43156165.219034725@news.oz.net> <0ZiRe.67733$Oy2.39610@tornado.tampabay.rr.com> Message-ID: <4318c25c.440465766@news.oz.net> On Wed, 31 Aug 2005 14:16:28 GMT, Ron Adam wrote: [...] > >The problem with negative index's are that positive index's are zero >based, but negative index's are 1 based. Which leads to a non >symmetrical situations. > >Note that you can insert an item before the first item using slices. But >not after the last item without using len(list) or some value larger >than len(list). IMO the problem is that the index sign is doing two jobs, which for zero-based reverse indexing have to be separate: i.e., to show direction _and_ a _signed_ offset which needs to be realtive to the direction and base position. A list-like class, and an option to use a zero-based reverse index will illustrate: >>> class Zbrx(object): ... def __init__(self, value=0): ... self.value = value ... def __repr__(self): return 'Zbrx(%r)'%self.value ... def __sub__(self, other): return Zbrx(self.value - other) ... def __add__(self, other): return Zbrx(self.value + other) ... >>> class Zbrxlist(object): ... def normslc(self, slc): ... sss = [slc.start, slc.stop, slc.step] ... for i,s in enumerate(sss): ... if isinstance(s, Zbrx): sss[i] = len(self.value)-1-s.value ... return tuple(sss), slice(*sss) ... def __init__(self, value): ... self.value = value ... def __getitem__(self, i): ... if isinstance(i, int): ... return '[%r]: %r'%(i, self.value[i]) ... elif isinstance(i, Zbrx): ... return '[%r]: %r'%(i, self.value[len(self.value)-1-i.value]) ... elif isinstance(i, slice): ... sss, slc = self.normslc(i) ... return '[%r:%r:%r]: %r'%(sss+ (list.__getitem__(self.value, slc),)) ... def __setitem__(self, i, v): ... if isinstance(i, int): ... list.__setitem__(self, i, v) ... elif isinstance(i, slice): ... sss, slc = self.normslc(i) ... list.__setitem__(self.value, slc, v) ... def __repr__(self): return 'Zbrxlist(%r)'%self.value ... >>> zlast = Zbrx(0) >>> zbr10 = Zbrxlist(range(10)) >>> zbr10[zlast] '[Zbrx(0)]: 9' >>> zbr10[zlast:] '[9:None:None]: [9]' >>> zbr10[zlast:zlast] = ['end'] >>> zbr10 Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9]) >>> ztop = Zbrx(-1) >>> zbr10[ztop:ztop] = ['final'] >>> zbr10 Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9, 'final']) >>> zbr10[zlast:] "[11:None:None]: ['final']" >>> zbr10[zlast] "[Zbrx(0)]: 'final'" >>> zbr10[zlast+1] '[Zbrx(1)]: 9' >>> zbr10[zlast+2] "[Zbrx(2)]: 'end'" > > >>> a = list('abcde') > >>> a[len(a):len(a)] = ['end'] > >>> a >['a', 'b', 'c', 'd', 'e', 'end'] > > >>> a[-1:-1] = ['last'] > >>> a >['a', 'b', 'c', 'd', 'e', 'last', 'end'] # Second to last. > > >>> a[100:100] = ['final'] > >>> a >['a', 'b', 'c', 'd', 'e', 'last', 'end', 'final'] > >>> a = Zbrxlist(list('abcde')) >>> a Zbrxlist(['a', 'b', 'c', 'd', 'e']) Forgot to provide a __len__ method ;-) >>> a[len(a.value):len(a.value)] = ['end'] >>> a Zbrxlist(['a', 'b', 'c', 'd', 'e', 'end']) lastx refers to the last items by zero-based reverse indexing >>> a[lastx] "[Zbrx(0)]: 'end'" >>> a[lastx:lastx] = ['last'] >>> a Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end']) As expected, or do you want to define different semantics? You still need to spell len(a) in the slice somehow to indicate beond the top. E.g., >>> a[lastx-1:lastx-1] = ['final'] >>> a Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end', 'final']) Perhaps you can take the above toy and make something that works they way you had in mind? Nothing like implementation to give your ideas reality ;-) Regards, Bengt Richter From abkhd at earth.co.jp Sat Sep 24 08:42:30 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 24 Sep 2005 05:42:30 -0700 Subject: How to decompile an exe file compiled by py2exe? References: Message-ID: <1127565750.556586.180160@g44g2000cwa.googlegroups.com> Leo Jay wrote: > Dear All, > > I lost my source code because of my incaution. > so anyone can tell me how to decompile the exe file compiled by py2exe? > > Thanks. > > -- > Best Regards, > Leo Jay In older versions of py2exe (haven't tried it for new ones) I only had to drag the py2exe created file to my zip archiever program window. That somehow got the program to treat the py2exe application as a zip archieve effectively decompressing it right there in the window of the program. This enabled me to extract the files if I wish to do so to any place I want. This is also valid, I noted, for the binary distributions created for windows by the distutils. From skip at pobox.com Wed Sep 14 12:53:55 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 14 Sep 2005 11:53:55 -0500 Subject: improvements for the logging package In-Reply-To: References: <1125935246.425351.260880@z14g2000cwz.googlegroups.com> <20050906172418.GL4377@ActiveState.com> <17182.22978.718108.100126@montanaro.dyndns.org> <20050907171420.GB31649@ActiveState.com> <1126563514.072523.26980@g47g2000cwa.googlegroups.com> <1126655190.914020.106960@g44g2000cwa.googlegroups.com> Message-ID: <17192.21923.291360.286857@montanaro.dyndns.org> >> It does, in the "in-development" version of the documentation. Sorry it >> was not in the 2.4 releases :-( Thomas> Maybe it can be backported to 2.4.2 - is there still time for that? Changed now in CVS. When 2.4.2 is released it should be there. Skip From jgrahn-nntq at algonet.se Thu Sep 8 17:30:56 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 8 Sep 2005 21:30:56 GMT Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga> <431cadd6$0$97134$ed2619ec@ptn-nntp-reader03.plus.net> <7xd5nlx5u4.fsf@ruckus.brouhaha.com> Message-ID: On 06 Sep 2005 14:08:03 -0700, Paul Rubin wrote: > Jorgen Grahn writes: >> I feel the recent SMP hype (in general, and in Python) is a red herring. Why >> do I need that extra performance? What application would use it? > > How many mhz does the computer you're using right now have? When did > you buy it? I'm not a good example -- my fastest computer is a Mac Mini. Come to think of it, last time I /really/ upgraded for CPU speed was when I bought my Amiga 4000/030 in 1994 ;-) My 200MHz Pentium feels a bit slow for some tasks, but most of the time I cannot really tell the difference, and its lack of RAM and disk space is much more limiting. > Did you buy it to replace a slower one? If yes, you must > have wanted more performance. Just about everyone wants more > performance. That's why mhz keeps going up and people keep buying > faster and faster cpu's. I'm not sure that is true, for most people. People keep buying faster CPUs because the slower ones become unavailable! How this works from an economical and psychological point of view, I don't know. > CPU makers seem to be running out of ways to increase mhz. Their next > avenue to increasing performance is SMP, so they're going to do that > and people are going to buy those. Just like other languages, Python > makes perfectly good use of increasing mhz, so it keeps up with them. > If the other languages also make good use of SMP and Python doesn't, > Python will fall back into obscurity. I don't believe that will ever happen. Either of them. My CPU spends almost all its time running code written in C. That code has been written over the last thirty years under the assumption that if there is SMP, it will be taken advantage of on the process level. I cannot imagine anyone sitting down and rewriting all that code to take advantage of concurreny. Thus, I don't believe that SMP and SMP-like technologies will improve performance for ordinary people. Or, if it will, it's because different processes will run concurrently, not because applications become concurrent. Except for some applications like image processing programs, which noone would dream of implementing in Python anyway. New, radical and exciting things don't happen in computing very often. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fredrik at pythonware.com Mon Sep 19 06:22:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Sep 2005 12:22:02 +0200 Subject: execfile eats memory References: Message-ID: Enrique Palomo Jim?nez wrote: > The information will be used no more than 3-4 days a > month and install databases is not allowed. > [...] > Someone suggest me the pickle module. I'll try it and it > works, but pickle dumps is slower than writing the file > with pythonic syntax. (26 seconds vs 6) did you try cPickle instead of pickle? (also make sure that you're using binary pickles). if you only use simple data types, the marshal module can sometimes be faster than cPickle (it's always faster than pickle) > After that, i have a DIC.txt to execfile with it. The application dies there. > The memory grow up till de limit. > Is possible that execfile of a 19 mb file takes more than 600 mb of memory? 15-20 bytes is more than enough; e.g. "*"*1000*1000*600 as for exec'ing huge files, it's not that unlikely that the Python compiler may need 30 bytes per source byte to hold parser trees and byte code structures. to get exact figures, check the peak memory consumption when you parse smaller (i.e. megabyte-sized) parts of your file. From sjmaster at gmail.com Mon Sep 19 18:25:24 2005 From: sjmaster at gmail.com (Steve M) Date: 19 Sep 2005 15:25:24 -0700 Subject: Windows paths, Java, and command-line arguments, oh my! References: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> Message-ID: <1127168724.396911.325020@f14g2000cwb.googlegroups.com> Well, apparently I fried my brain trying to sort this out. There is a typo in my example code in the post but not in my real program. (I know it is a no-no when asking help on c.l.py but I simplified some details from the real code in order not to confuse the issues. Probably backfired by this point.) Below is the post with the error fixed and one sentence added (to clarify why the error in my original post really was not the problem). Thanks for any advice. --- I'm trying to invoke a Java command-line program from my Python program on Windows XP. I cannot get the paths in one of the arguments to work right. The instructions for the program describe the following for the command-line arguments: java -jar sforcedataloader.jar -Dsalesforce.config.dir=CONFIG_DIRECTORY They also give an example: java -Dsalesforce.config.dir=c:\config -jar sforcedataloader.jar If I type the example above at the cmd.exe command line the thing works (assuming I have the config file in c:\config). What doesn't work is these two lines: cmd = r'java -jar sforcedataloader.jar -Dsalesforce.config.dir=c:\config' os.system(cmd) I have tried (not entirely systematically but pretty exhaustively) every combination of backslashes in the cmd string, e.g.: -Dsalesforce.config.dir=c\:\\config -Dsalesforce.config.dir=c:\\config -Dsalesforce.config.dir=c\\:\config -Dsalesforce.config.dir=c\\:\\config etc. No matter what I do, the program outputs that it cannot find the config file. *For at least one variation of the cmd string, I can print the value of cmd and copy/paste it to the command line and the java program works successfully, while for this same cmd string the java program fails when invoked from Python.* I cannot tell whether this is a java thing (why are there three different styles for argument on the same command line? In addition to "-jar xxx" and "-Dxxx=yyy" you can also put "xxx=yyy" for some options... wth?), Windows lame cmd.exe shell (is that program invoked by Python's os.system function?), or something else that is messing up. It drivin me crazy though. (Come to think of it, Windows paths have been a persistent thorn in my side for two years of Python development at my company.) Anybody have any suggestions? p.s. 1. I would like to qualify the claim above that the example works at the command-line. I'm not completely certain exactly which form of invocation was successful at the command line, but at least one of them was and that one definitely didn't work from Python. 2. I have a work-around available to me, which is that the program will look for the configuration file in the current directory if the command-line option isn't specified. I'd much rather be able to specify a directory on the command line, so that I can have multiple simultaneous invocations, and so that I can have the configuration file not be in the directory where the Python program is, or alternatively not have to change my directory (since I don't fully appreciate the implications for other parts of my program - this thing runs asynchronously.) From oyvgi at hotmail.com Thu Sep 15 02:06:48 2005 From: oyvgi at hotmail.com (oyvgi at hotmail.com) Date: 14 Sep 2005 23:06:48 -0700 Subject: "week-year" conversion to date In-Reply-To: References: <1126704361.825633.200680@f14g2000cwb.googlegroups.com> Message-ID: <1126764407.962770.269000@z14g2000cwz.googlegroups.com> Thanks! Both solutions worked perfectly. From brian at sweetapp.com Mon Sep 5 12:08:48 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 05 Sep 2005 18:08:48 +0200 Subject: xmlrcp register classes In-Reply-To: <431c6acc$0$1283$ed2619ec@ptn-nntp-reader02.plus.net> References: <431c6acc$0$1283$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <431C6D90.5050607@sweetapp.com> Sergio Rua wrote: > Server = SimpleXMLRPCServer (('127.0.0.1',8080)) > > Server.register_instance(MyClass1()) > Server.register_instance(MyClass2()) > Server.register_instance(MyClass3()) > > What is seems to happen is that only the last class I register it is the > only one being exported. How can I register all the classes? Thanks. class MyCombinedClass(MyClass1, MyClass2, MyClass3): pass Server.register_instance(MyCombinedClass()) Cheers, Brian From snail at objmedia.demon.co.uk Wed Sep 21 05:25:21 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 21 Sep 2005 10:25:21 +0100 Subject: Would you pls tell me a tool to step debug python program? References: <1126509149.800327.60100@g44g2000cwa.googlegroups.com> <1127241778.491001.309580@f14g2000cwb.googlegroups.com> Message-ID: >Johnny Lee wrote: >> Hi, >> I've met a problem to understand the code at hand. And I wonder >> whether there is any useful tools to provide me a way of step debug? >> Just like the F10 in VC... Not single stepping, but flow tracing, complete with variables, parameters and return values. Python Bug Validator. http://www.softwareverify.com Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From skip at pobox.com Wed Sep 28 18:54:28 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 28 Sep 2005 17:54:28 -0500 Subject: 1 Million users.. I can't Scale!! In-Reply-To: <17211.6223.874504.573767@montanaro.dyndns.org> References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> <17210.62571.387969.713030@montanaro.dyndns.org> <433B0B38.7040406@bellsouth.net> <17211.6223.874504.573767@montanaro.dyndns.org> Message-ID: <17211.7972.510797.222206@montanaro.dyndns.org> Damjan> Is there some python module that provides a multi process Queue? Skip> Not as cleanly encapsulated as Queue, but writing a class that Skip> does that shouldn't be all that difficult using a socket and the Skip> pickle module. Here's a trivial implementation of a pair of blocking queue classes: http://orca.mojam.com/~skip/python/SocketQueue.py Skip From sam at email-scan.com Wed Sep 21 20:08:16 2005 From: sam at email-scan.com (Sam) Date: Wed, 21 Sep 2005 19:08:16 -0500 Subject: Threading, real or simulated? References: Message-ID: Jp Calderone writes: > On Wed, 21 Sep 2005 18:23:33 -0500, Sam wrote: >>I'm using Python 2.3.5 with pygtk 2.4.1, and I'm using the second threading >>approach from pygtk's FAQ 20.6 - invoking "gtk.gdk.threads_init()", and >>wrapping all gtk/gdk function calls with >>gtk.threads_enter()/gtk.threads_leave() >> >>I start a thread, via thread.Threading.start(). The thread then calls a >>particularly time consuming C function, from an extension module. I find >>that when the thread is running the C code, the GUI hangs even though I'm >>not inside the threads_enter/threads_leave territory. >> > > Does the extension module release the GIL? It sounds like it does not. Of course, there are a dozen other mistakes that could be made which would have roughly this symptom. It's difficult to say which is the problem without actually seeing any code. What's the GIL?. The extension module is invoked outside of threads_enter/threads_leave(). >>It looks like thread.Threading() only simulates threading, by having the >>python interpreter multiplex between running threads. Is real threading >>possible, so that I do something time-consuming in the thread, without >>hanging the GUI? >> > > Assuming you mean threading.Thread, this is a native thread. It is not a simulation. Something else is going wrong. Then I must have something locked. Here's what I do: gtk.gdk.threads_init() mainwindow=MainWindow() gtk.threads_enter() gtk.main() gtk.threads_leave() The code in MainWindow.__init__() does this: self.__window=gtk.Window(gtk.WINDOW_TOPLEVEL) self.__window.set_default_size(600, 600) [ some more initialization ] self.__window.show_all() self.__window.connect("delete-event", self.delete_event) self.__window.connect("destroy", self.destroy) t=self.initializationThread() t.packageLayout=packageLayout t.start() Here's the definition of my initializationThread class: class initializationThread(threading.Thread): def run(self): gtk.threads_enter() busy_cursor=gtk.gdk.Cursor(gtk.gdk.WATCH) self.packageLayout.window.set_cursor(busy_cursor) gtk.threads_leave() I do get a busy cursor at this point, so I know that this thread is running. initializationThread.run() continues, as follows: try: sysrep=lpm.getSystemRepository() pkgs=sysrep.getPackages() pkgs.sort() for i in pkgs: icon=sysrep.getManifest(i).header("Icon") gtk.threads_enter() try: if self.packageLayout.window == None: break # Someone was impatient self.packageLayout.addPackage(i, icon) finally: gtk.threads_leave() lpm.getSystemRepository() instantiates an object of an extension-defined type. It's getPackages() method returns a list of objects that are also of an extension-defined type, which I then iterate over. Each iteration invokes the getManifest() method of an extension-defined type. All the stuff between gtk.threads_enter() and gtk.threads_leave() runs pure python code, and should be nearly instantaneous. Furthermore, gtk functions that end up being invoked in the addPackage() method, provide some GUI feedback. Each addPackage() iteration adds a new widget in the main window. Occasionally, there's a noticeable delay, before a new widget appears, because there's a lot on getManifest()'s plate. I get no response from any GUI activity, during the delay. getManifest() gets invoked outside the threads_enter/threads_leave lock, but the GUI is still hanging when that happens. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From sxn02 at yahoo.com Fri Sep 23 14:28:23 2005 From: sxn02 at yahoo.com (Sori Schwimmer) Date: Fri, 23 Sep 2005 11:28:23 -0700 (PDT) Subject: tk_focusNext() revisited Message-ID: <20050923182823.99359.qmail@web50201.mail.yahoo.com> Hello, I am trying to move focus between Tkinter (and other) widgets. A solution similar with my approach was suggested by Eric Brunel at http://mail.python.org/pipermail/python-list/2004-July/229971.html It will generate an error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "ab.py", line 20, in t.bind('', lambda e, t=t: focusNext(t)) File "ab.py", line 12, in focusNext widget.tk_focusNext().focus_set() File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 435, in tk_focusNext return self._nametowidget(name) File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 1006, in nametowidget if name[0] == '.': TypeError: unsubscriptable object I tried to trace the error in Tkinter.py and found that name is a cmdName and it is indeed an unsubscriptable object. It has a string method, and name.string will print a Tk-style widget name, like ".-1121901300". This one can be used to find the next widget to jump to, but later the conversion _nametowidget fails. What are my options? Platform: Gentoo, KDE, Tcl/Tk 8.4, Python 2.4.1 Sorin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rupole at hotmail.com Fri Sep 9 10:12:05 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 9 Sep 2005 10:12:05 -0400 Subject: python script under windows References: Message-ID: <1126275365_1433@spool6-east.superfeed.net> You can use the Task Scheduler to run a script persistently if you don't need the capabilities of the service framework. Roger "Jan Gregor" wrote in message news:dfrdds$l4m$1 at ns.felk.cvut.cz... > Hello > > I run python script on another computer and want to "survive" that > script after my logout. the script also uses drive mapping to network drive. > > Can you help me ? Or better is there some info for unix person how > to survive with python on windows ;-) > > thanks, > jan gregor ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From ggg at zzz.it Fri Sep 30 09:48:44 2005 From: ggg at zzz.it (deelan) Date: Fri, 30 Sep 2005 15:48:44 +0200 Subject: 'ascii' codec can't encode character u'\u2013' In-Reply-To: References: Message-ID: thomas Armstrong wrote: (...) > when trying to execute a MySQL query: > ---- > query = "UPDATE blogs_news SET text = '" + text_extrated + "'WHERE > id='" + id + "'" > cursor.execute (query) #<--- error line > ---- well, to start it's not the best way to do an update, try this instead: query = "UPDATE blogs_news SET text = %s WHERE id=%s" cursor.execute(query, (text_extrated, id)) so mysqldb will take care to quote text_extrated automatically. this may not not your problem, but it's considered "good style" when dealing with dbs. apart for this, IIRC feedparser returns text as unicode strings, and you correctly tried to encode those as latin-1 str objects before to pass it to mysql, but not all glyphs in the orginal utf-8 feed can be translated to latin-1. the charecter set of latin-1 is very thin compared to the utf-8. you have to decide: * switch your mysql db to utf-8 and encode stuff before insertion to UTF-8 * lose those characters that cannot be mapped into latin-1, using the: text_extrated.encode('latin-1', errors='replace') so unrecognized chars will be replaced by ? also, mysqldb has some support to manage unicode objects directly, but things changed a bit during recent releases so i cannot be precise in this regard. HTH. -- deelan, #1 fan of adriana lima! From stefano at pragma2000.com Fri Sep 9 13:10:26 2005 From: stefano at pragma2000.com (Stefano Masini) Date: Fri, 9 Sep 2005 19:10:26 +0200 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: <4321b75f$1@usenet01.boi.hp.com> References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <4321b75f$1@usenet01.boi.hp.com> Message-ID: <4327422405090910104acc06b5@mail.gmail.com> On 9/9/05, djw wrote: > I think, for me, this most important reason is that the stdlib version > of a module doesn't always completely fill the requirements of the > project being worked on. That's certainly why I wrote my own, much > simpler, logging module. In this case, its obvious that the original > author of the stdlib logging module had different ideas about how > straightforward and simple a logging module should be. To me, this just > demonstrates how difficult it is to write good library code - it has to > try and be everything to everybody without becoming overly general, > abstract, or bloated. That's very true. But... ...there are languages (ahem... did I hear somebody say Java? :) that make it so hard to write code, that one usually prefers using whatever is already available even if this means adopting a "style" that doesn't quite match his expectations. To me, it is not clear which is best: a very comfortable programmer with a longer todo list, or an unfomfortable programmer with a short todo list. So far, I've always struggled to be in the first category, but I'm amazed when I look back and see how many wheels I reinvented. But maybe it's just lack of wisdom. :) stefano From dimitri.pater at gmail.com Wed Sep 7 17:56:53 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 7 Sep 2005 23:56:53 +0200 Subject: Python CGI and Firefox vs IE In-Reply-To: <1126116600.586631.277530@g43g2000cwa.googlegroups.com> References: <1126115415.776529.103400@g49g2000cwa.googlegroups.com> <1126116600.586631.277530@g43g2000cwa.googlegroups.com> Message-ID: On 7 Sep 2005 11:10:00 -0700, Jason wrote: > > IE... Yeah, I know what you mean. Here's another one that doesn't work in IE, but it does work in Firefox: canvas = pid.PILCanvas() canvas.drawRect(0,400, 500, 0, fillColor=pid.floralwhite, edgeColor= pid.maroon ) # display stuff f = StringIO.StringIO() canvas.save(f, format="png") # does not work in MSIE, that sucks... return 'data:image/png,' + urllib.quote(f.getvalue()) these are DATA URIs ( http://www.howtocreate.co.uk/wrongWithIE/?chapter=Data%3A+URIs) so do I now have to change my code because most people use IE? Probably I have to :-( Have to come up with a workaround, go back to the old . I'm > about the only one who uses firefox in our facility. > > Thanks for the reply and the link. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident. Arthur Schopenhauer ----- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ido.Yehieli at gmail.com Sat Sep 24 10:52:48 2005 From: Ido.Yehieli at gmail.com (Ido.Yehieli at gmail.com) Date: 24 Sep 2005 07:52:48 -0700 Subject: replacments for stdio? In-Reply-To: References: <1127477278.036977.189230@g44g2000cwa.googlegroups.com> Message-ID: <1127573568.853517.320430@g49g2000cwa.googlegroups.com> some thing platform independent will be preferable... (like a file like interface for TK/Tcl) From davecook at nowhere.net Wed Sep 14 21:43:27 2005 From: davecook at nowhere.net (Dave Cook) Date: Thu, 15 Sep 2005 01:43:27 GMT Subject: O'Reilly book on Twisted References: <87YVe.514$Jr.3739@twister2.libero.it> <1126730213.734243.129900@g43g2000cwa.googlegroups.com> Message-ID: On 2005-09-14, Steve M wrote: > Is this book fully up to date with Twisted 2.0? Yes, according to an email from the author on the twisted-python mailing list > Does the book cover Nevow at all? Doesn't look like it. More info here: http://fettig.net/weblog/2005/06/30/my-book-on-twisted/ http://fettig.net/weblog/ Dave Cook From mweihs at gmx.at Fri Sep 16 10:32:25 2005 From: mweihs at gmx.at (Markus Weihs) Date: Fri, 16 Sep 2005 16:32:25 +0200 Subject: Creating Pie Chart from Python References: <1126797017.338319.215400@z14g2000cwz.googlegroups.com> <432990f9$0$21365$db0fefd9@news.zen.co.uk> Message-ID: Hi! I tried your script and got the following error: Traceback (most recent call last): File "pie_chart.py", line 302, in OnPaint self.OnDraw() File "pie_chart.py", line 336, in OnDraw segment.Draw(self.angle, self.rot, self.explode) File "pie_chart.py", line 46, in Draw glPopMatrix() OpenGL.GL.GLerror: [Errno 1281] invalid value What am I doing wrong? Regards, Markus From frank at chagford.com Mon Sep 12 12:26:57 2005 From: frank at chagford.com (Frank Millman) Date: 12 Sep 2005 09:26:57 -0700 Subject: How to protect Python source from modification In-Reply-To: References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Message-ID: <1126542417.580959.66680@g47g2000cwa.googlegroups.com> Peter Hansen wrote: > Frank Millman wrote: > > I am writing a multi-user accounting/business system. Data is stored in > > a database (PostgreSQL on Linux, SQL Server on Windows). I have written > > a Python program to run on the client, which uses wxPython as a gui, > > and connects to the database via TCP/IP. > > > > The client program contains all the authentication and business logic. > > It has dawned on me that anyone can bypass this by modifying the > > program. As it is written in Python, with source available, this would > > be quite easy. My target market extends well up into the mid-range, but > > I do not think that any CFO would contemplate using a program that is > > so open to manipulation. > > > > The only truly secure solution I can think of would involve a radical > > reorganisation of my program > > Please define what "truly secure" means to you. > Fair question. I am not expecting 'truly' to mean 100% - I know that is impossible. I will try to explain. Here are some assumptions - 1. A system adminstrator is responsible for the system. 2. There is a single userid and password for connecting to the database. This must be stored somewhere so that the client program can read it to generate the appropriate connection string. The users do not need to know this userid and password. 3. Each user has their own userid and password, which is stored in the database in a 'users' table. I use this in my program for authentication when a user tries to connect. 4. The client program can be run from anywhere on the network that has access to the program and to a Python interpreter. [snip] > > But the real answer does depend a lot on *exactly* what kind of security > you want (or, ultimately, what it turns out you really need, once you've > clarified your thinking based on the feedback you do get here). Issues > like: are you more concerned about detecting changes, or in preventing > them in the first place? (the latter is much harder); what is the nature > of software that competes with yours? (is it really any more secure, or > only apparently so? maybe this is just a marketing issue); and is there > any intellectual property that you are trying to protect here, or are > you just interested in avoiding casual disruption of normal operation? > I am not concerned about anyone reading my code - in fact I am looking forward to releasing the source and getting some feedback. My concern is this. I have all this fancy authentication and business logic in my program. If someone wants to bypass this and get direct access to the database, it seems trivially easy. All they have to do is read my source, find out where I get the connection string from, write their own program to make a connection to the database, and execute any SQL command they want. If I move all the authentication and business logic to a program which runs on the server, it is up to the system administrator to ensure that only authorised people have read/write/execute privileges on that program. Clients will have no privileges, not even execute. They will have their own client program, which has to connect to my server program, and communicate with it in predefined ways. I *think* that in this way I can ensure that they cannot do anything outside the bounds of what I allow them. The only problem is that this is very different from the way my program works at present, so it will be quite a bit of work to re-engineer it. If someone can suggest a simpler solution obviously I would prefer it. But if the consensus is that I am thinking along the right lines, I will roll up my sleeves and get stuck in. > -Peter I hope this explains my thinking a bit better. Thanks Frank From fredrik at pythonware.com Fri Sep 23 08:40:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Sep 2005 14:40:47 +0200 Subject: Using distutils 2.4 for python 2.3 References: Message-ID: Noam Raphael wrote: > I want to distribute a package. It's compatible with Python 2.3. > Is there a way to use distutils 2.4 feature package_data, while > maintaining the distribution compatible with python 2.3 ? you can enable new metadata fields in older versions by assigning to the DistributionMetadata structure: try: from distutils.dist import DistributionMetadata DistributionMetadata.package_data = None except: pass setup( ... package_data=... ) From jeff.maitland at gmail.com Thu Sep 1 11:54:56 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Thu, 1 Sep 2005 11:54:56 -0400 Subject: Arguement error In-Reply-To: References: <6829832e050831133030a012f9@mail.gmail.com> Message-ID: <6829832e05090108543287ed85@mail.gmail.com> Found the error. It was not in the code at all it has to do with the fact that the String module has a translate method and it was being used not the one I wrote. Thanks again. On 8/31/05, Terry Reedy wrote: > > > "Jeffrey Maitland" wrote in message > news:6829832e050831133030a012f9 at mail.gmail.com... > Hello folks, > > >I am wondering why I am getting this error. when I try to run a script. > >TypeError: translate() takes at most 3 arguments (10 given) > > Because you apparently gave it more than 3 args. > > >>> str.translate.__doc__ > 'S.translate(table [,deletechars]) -> string\n\nReturn a copy of the > string > S, where all characters occurring in the optional argument deletechars are > removed, and the remaining characters have been mapped through the given > translation table, which must be a string of length 256.' > > >but the thing is the method translate actually accepts 10 arguements. > > Why do you think that? > > Terry J. Reedy > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dalcinl at gmail.com Mon Sep 5 19:57:55 2005 From: dalcinl at gmail.com (Lisandro Dalcin) Date: 5 Sep 2005 16:57:55 -0700 Subject: Online Modification of Python Code In-Reply-To: <1125904440.679016.137720@g44g2000cwa.googlegroups.com> References: <1125904440.679016.137720@g44g2000cwa.googlegroups.com> Message-ID: <1125964675.610753.267890@g44g2000cwa.googlegroups.com> can you send a small example of thing you are trying to do? As Python is *really* dynamic, you can adapt algorithms in many ways... in general, you can change methods, or even class! of almost any object... From david at fielden.com.au Thu Sep 15 08:27:51 2005 From: david at fielden.com.au (Rowdy) Date: Thu, 15 Sep 2005 22:27:51 +1000 Subject: MySQLdb UPDATE does nothing In-Reply-To: <4329633F.7060609@jmsd.co.uk> References: <4329633F.7060609@jmsd.co.uk> Message-ID: <432968C7.7000407@fielden.com.au> John Moore wrote: > Hi, > > I normally work with Java but I'm interested in using Python as well, > particularly for little tasks like doing some massaging of data in a > MySQL database. Below is my first attempt. I'm sure it's inelegantly > written, but my main concern is that the UPDATE sql doesn't actually > work, and I can't understand why. No error is returned, it's just that > the update does not take place. The SQL itself is fine, though - if I > instead write the SQL to a file I can use it from the mysql command line > and it does all the updates just fine. What have I missed? > > John > A similar question was asked back in July, someone posted this: If it's any help, using cursor.execute("set autocommit = 1") before doing anything else works nicely unless you actually need transactions. Rowdy From tjreedy at udel.edu Thu Sep 29 18:55:57 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Sep 2005 18:55:57 -0400 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com><7xbr2dxqqq.fsf@ruckus.brouhaha.com><7xk6h0zxnm.fsf@ruckus.brouhaha.com><7x64skzvas.fsf@ruckus.brouhaha.com><7xll1gvk7w.fsf@ruckus.brouhaha.com><1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> Message-ID: "could ildg" wrote in message news:311b5ce105092908332c12164c at mail.gmail.com... >why is rails written in Ruby Because the several people and groups of people who have written web frameworks in Python used other names. Python on Rails just doesn't have the same alliterative zing. >but not Python since python is such a good language? I have seen mention of 5-10 web frameworks in Python. >This kind of variables can only be modified by the > functions of the class itself. Reading a private variable does not change it. I am sure this covers at least some use cases of private var access. Terry J. Reedy From benji at benjiyork.com Fri Sep 9 08:41:30 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 09 Sep 2005 08:41:30 -0400 Subject: python script under windows In-Reply-To: References: Message-ID: <432182FA.2060201@benjiyork.com> Jan Gregor wrote: > I run python script on another computer and want to "survive" that > script after my logout. Start at http://www.python.org/windows/win32/#NTServices. -- Benji York From news at NOwillmcguganSPAM.com Thu Sep 15 06:34:21 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 15 Sep 2005 11:34:21 +0100 Subject: Create and display an email In-Reply-To: <1126654259.131820.121010@o13g2000cwo.googlegroups.com> References: <1126654259.131820.121010@o13g2000cwo.googlegroups.com> Message-ID: <43294e2d$0$30311$da0feed9@news.zen.co.uk> Adam Endicott wrote: > I've got a wxPython based windows GUI application that takes some input > and creates a PDF file output. At the end, I need to create an email > message with this pdf file attached ready for the user to just hit > "send". I don't want to actually send the email automatically, I just > want to pop up a message in the default mail program that's ready to go > (partially because the person might not be online when the email is > created, this way they could just put it in their Outlook outbox). > > I can't figure out how to do this. I've tried using > webbrowser.open('mailto:...'), which works, except that I can't add an > attachment that way (at least I haven't been successful). And I don't > know any other way to open up a message in the default mail program. > > There has to be something obvious that I'm missing here. Any > suggestions? > I dont think there is anything in the standard library to help you here. Windows has an api called 'MAPI' which does this sort of thing. There may be bindings to it somewhere, or you could create your own with ctypes. I sure you will find something now you know what to google for.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From __peter__ at web.de Fri Sep 9 08:24:46 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2005 14:24:46 +0200 Subject: using metaclass __call__ to replace class instance References: Message-ID: Ksenia Marasanova wrote: > class BasemethodMeta(type): > def?__new__(cls,?class_name,?bases,?new_attrs): > cls?=?type.__new__(cls,?class_name,?bases,?new_attrs) > new_attrs['__metaclass__'].cls?=?cls > return?cls > > def?__call__(self): > return?self.cls.get_foo() Though I'm not sure what you are trying to do, I fear it will get more complicated than necessary. But you do get the desired output if you change your metaclass to class BasemethodMeta(type): def __call__(cls): # the instance of the metaclass already is a class # so you can drop the double indirection return cls.get_foo() Peter From dannoritzer at web.de Thu Sep 8 09:03:49 2005 From: dannoritzer at web.de (Guenter) Date: 8 Sep 2005 06:03:49 -0700 Subject: Video display, frame rate 640x480 @ 30fps achievable? Message-ID: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> Hi, I need to develop an application that displays video 640x480 16-bit per pixel with 30 fps. I would prefer to do that with Python (wxPython) but don't have any experience whether it is possible to achieve that frame rate and still have some resources for other processing left? My development PC would be a Celeron 1 GHz. The final system could be a faster system. I would appreciate if anybody could share some experience in that field. Thanks for any help. Guenter From haircut at gmail.com Fri Sep 9 16:36:04 2005 From: haircut at gmail.com (Adam Monsen) Date: 9 Sep 2005 13:36:04 -0700 Subject: disabling TCP connections, just for one script References: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> <1126296077.445884.313850@z14g2000cwz.googlegroups.com> Message-ID: <1126298164.613718.99460@g44g2000cwa.googlegroups.com> Nice!! Since that works, this also works (any socket operations appear to raise an IOError): import socket socket.setdefaulttimeout(0) Thanks! -Adam -- Adam Monsen http://adammonsen.com/ From peter at engcorp.com Sat Sep 24 10:06:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Sep 2005 10:06:06 -0400 Subject: parsing a date In-Reply-To: <0001HW.BF5AC932001DA4B2F0284550@news.individual.de> References: <0001HW.BF5A26260018E425F0284550@news.individual.de> <0001HW.BF5AC932001DA4B2F0284550@news.individual.de> Message-ID: <04OdncFaFO3RwKjenZ2dnUVZ_s6dnZ2d@powergate.ca> Kalle Anke wrote: > On Fri, 23 Sep 2005 23:01:18 +0200, Larry Bates wrote: > >>but I'm not sure it is "better". I guess it depends >>on what you want to do with them after parsing. > > Sorry, I should have been clearer. I want to parse the date and create a > 'date object' that is a part of larger object (I'm parsing a text file that > represents the larger object and the date is a part of it). > > So my question should probably be: is there a better way to parse the date > and generate the 'date object' than the two step > > w = strptime(d,'%Y-%m-%d') > datetime.date( w[0], w[1], w[2] ) > > Since I'm new to many things in Python I'm trying to learn if there is a > "better" way of doing things. You're still not defining what "better" means to you, so who can say? Perhaps you think a single line would be "better"? datetime.date(*time.strptime(d, '%Y-%m-%d')[:3]) -Peter From jlocc at fau.edu Wed Sep 14 16:04:47 2005 From: jlocc at fau.edu (jlocc at fau.edu) Date: 14 Sep 2005 13:04:47 -0700 Subject: ezPyCrypto Message-ID: <1126728287.603932.256190@o13g2000cwo.googlegroups.com> Hi!! I finally decided to use ezPyCrypto for my project but I can't download it from http://www.freenet.org.nz/ezPyCrypto/ ... Does anyone know of a different mirror? Maybe a similar wrapper? My goal is to encrypt a nine-digit number so that it can be safely used as a student ID number. THIS IS A SCHOOL PROJECT. NO NEED TO KILL NOBODY OVER EXPORT LAWS OR UNSAFE PRACTICES....pleaseeeeeeee!!! Thanks in advance, J From ptmcg at austin.rr.com Thu Sep 1 02:56:49 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 31 Aug 2005 23:56:49 -0700 Subject: graphical or flow charting design aid for python class development? In-Reply-To: <8ckRe.3276$v83.327@newssvr33.news.prodigy.com> References: <8ckRe.3276$v83.327@newssvr33.news.prodigy.com> Message-ID: <1125557809.587367.242230@o13g2000cwo.googlegroups.com> It's not free, but it is pretty cheap considering all it can do. Check out Enterprise Architect (with the free add-in for Python) from www.sparxsystems.com.au. Pro version license is US$180 or so, but they may have a student license for less that you could use. -- Paul From haircut at gmail.com Mon Sep 19 11:53:25 2005 From: haircut at gmail.com (Adam Monsen) Date: 19 Sep 2005 08:53:25 -0700 Subject: style question: anything wrong with super(type(self), self).f() ? Message-ID: <1127145205.959666.10310@o13g2000cwo.googlegroups.com> Is there anything wrong with using something like super(type(self), self).f() to avoid having to hardcode a type? For example: class A(object): def f(self): print "in A.f()" class B(A): def f(self): super(type(self), self).f() obj = A() obj.f() # prints "in A.f()" By "wrong" I mean, is there any reason why this is just a Bad Idea? Seems helpful to me, if I change the name of the 'B' class, I don't have to change super() calls as well. -- Adam Monsen http://adammonsen.com/ From jbperez808 at yahoo.com Mon Sep 19 23:01:06 2005 From: jbperez808 at yahoo.com (jbperez808 at yahoo.com) Date: 19 Sep 2005 20:01:06 -0700 Subject: slicing functionality for strings / Python suitability forbioinformatics In-Reply-To: References: <1127157916.290111.112620@g47g2000cwa.googlegroups.com> <3p8in6F98fduU1@individual.net> Message-ID: <1127183697.246671.284920@g49g2000cwa.googlegroups.com> Great suggestion... I was naively trying to turn the string into a list and slice that which I reckon would be significantly slower. From rkern at ucsd.edu Tue Sep 6 20:28:46 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 06 Sep 2005 17:28:46 -0700 Subject: Last mod date In-Reply-To: <431E3326.3030607@fidelitylodge.com> References: <431E3326.3030607@fidelitylodge.com> Message-ID: Webmaster - Fidelity Lodge #113 wrote: > This is my first post--I'm a Java developer trying to expand my > horizons. I'm trying to figure out how to find out the last > modification date/time for a file. I've found a reference to > *PyOS_GetLastModificationTime *as an Operating System Utility, but I > can't figure out which module I need to import to access it. os.path.getmtime(filename) http://docs.python.org/lib/module-os.path.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tores at stud.cs.uit.no Fri Sep 23 21:26:43 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Sat, 24 Sep 2005 03:26:43 +0200 Subject: Bluetooth References: <1127512737.067466.299070@g49g2000cwa.googlegroups.com> Message-ID: Okei.... I've been doing some research since my first post and now I'm really confused. I'm programming in xp, and found some c++ code out of this world that supposidly should list all available services to a given bluetooth device. This code however where only working with certain bluetooth-devices supported by the Microsoft Bluetooth Stack. If someone out there has any advice/ experience on bluetooth-programming on laptops (preferably in windows) I would appreciate it. Maybe there is some easy-to-grasp tutorials out there using the windows API for bluetooth-programing??? regards tores "Paul Boddie" wrote in message news:1127512737.067466.299070 at g49g2000cwa.googlegroups.com... Tor Erik S?nvisen wrote: > I'm making a server-side solution in Python and need to be able to > communicate through bluetooth. Is there any bluetooth-packages out there > for > python? At the lowest level, you should be able to create sockets for Bluetooth communications (see the socket module's documentation and the source code in Modules/socketmodule.c); for example: from socket import * s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) On Linux, upon binding a device file to the Bluetooth device, you can use things like pySerial to manage the communications; this works with software like t616hack: http://www.nelson.monkey.org/~nelson/weblog/tech/phone/ http://pyserial.sourceforge.net/ Various other tools exist which understand Bluetooth communications, notably the OpenOBEX tools: http://triq.net/obex/ I prefer to work with tools at the higher levels (obexftp to access files, pySerial/t616hack to access messages), but provided your Python distribution is set up correctly, you should be able to work at the lowest levels too. Paul From twic at urchin.earth.li Sat Sep 17 19:39:56 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 18 Sep 2005 00:39:56 +0100 Subject: Wanted: mutable bitmap In-Reply-To: <7xacib9zr6.fsf@ruckus.brouhaha.com> References: <7xacib9zr6.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 17 Sep 2005, it was written: > Tom Anderson writes: > >> One thing that would be rather useful in various bits of programming >> i've done would be a mutable bitmap type. Am i right in thinking >> there's no such thing in the standard library? Is there an >> implementation out there somewhere else? Is there a hack for doing it >> with the stuff that is in the standard library? > > The obvious way is with the array module. *bangs head against keyboard* i've had a niggling feeling i should be paying more attention to that module for months now. yes, it would be very simple to implement a bitset on top of an array of integers. doh. tom -- There is no strange thing. From trentm at ActiveState.com Fri Sep 30 13:07:22 2005 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 30 Sep 2005 10:07:22 -0700 Subject: RELEASED Python 2.4.2 (final) In-Reply-To: <1128068637.3f9ee921d4cfdda045e3a223b29ae699@teranews> References: <1128068637.3f9ee921d4cfdda045e3a223b29ae699@teranews> Message-ID: <20050930170722.GI14354@ActiveState.com> [Fuzzyman wrote] > I had problems updating from activestate 2.4 to activestate 2.4.1 > > I think it was caused by not uninstalling the original. This does mean > that even a *minor* version upgrade is a PITA. To do it cleanly all > extension modules have to be uninstalled and re-installed. > > *sigh* As Steve said, uninstalling ActivePython 2.4 will leave your extensions alone and then installing ActivePython 2.4.1 will install in the same proper places so that all your extensions should just work. Trent -- Trent Mick TrentM at ActiveState.com From qvx3000 at gmail.com Thu Sep 1 16:24:20 2005 From: qvx3000 at gmail.com (qvx) Date: 1 Sep 2005 13:24:20 -0700 Subject: Starting twisted service manually Message-ID: <1125606260.963114.324280@g14g2000cwa.googlegroups.com> I want to start twisted app from another GUI application and not via twistd. It works fine when started via twistd (1 & 2) but not when I try to start it manually (1 & 3) - nothing is listening to 8080 port. # (1) common part from nevow import rend, appserver from twisted.application import service, internet from twisted.internet import reactor class Index(rend.Page): ... # (2) part used when running via twistd application = service.Application("my-app") internet.TCPServer(8080, appserver.NevowSite(Index(r'D:\www'))).setServiceParent(application) # (3) attempt to start the same thing but inside a larger (wxPython) app def run_in_thread(): def runner(): application = service.Application("my-app") internet.TCPServer(8080, appserver.NevowSite(Index(r'D:\www'))).setServiceParent(application) reactor.run(0) thread.start_new_thread(runner, ()) I feel lost in twisted documentation and HOWTOs. Please help! Qvx From fredrik at pythonware.com Fri Sep 9 06:06:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 9 Sep 2005 12:06:20 +0200 Subject: Inconsistent reaction to extend References: Message-ID: Jerzy Karczmarczuk wrote: > Gurus, before I am tempted to signal this as a bug, perhaps > you might convince me that it should be so. it's not a bug, and nobody should have to convince you about any- thing; despite what you may think from reading certain slicing threads, this mailing list is not an argument clinic. > If I type > > l=range(4) > l.extend([1,2]) > > l gives [0,1,2,3,1,2], what else... > > On the other hand, try > > p=range(4).extend([1,2]) > > Then, p HAS NO VALUE (NoneType). (footnote: None is a value in Python. it can be used to represent "no value", but it can also be used for other things) > With append the behaviour is similar. I didn't try other methods, but > I suspect that it won't improve. > > WHY? because you're saving the return value of "extend", not "range", and "extend" returns None. if you split it up like this l = range(4) p = l.extend([1, 2]) it should be obvious that "l" and "p" doesn't necessarily contain the same thing. From rganesan at myrealbox.com Fri Sep 23 10:06:19 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Fri, 23 Sep 2005 19:36:19 +0530 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <1127426064.277907.251710@g47g2000cwa.googlegroups.com> <3pgqp0Fagh77U1@individual.net> Message-ID: >>>>> A M Kuchling writes: > The group of committers is a diverse group of people, and not every one of > them uses a relational database; that effort would be better done on the > DB-SIG mailing list, because the people there presumably do all use an > RDBMS. (Now, if you wanted to include SQLite in core Python, that *would* > be a python-dev topic, and ISTR it's been brought up in the past.) I would definitely love to see SQLite included in core python. I am a Unix systems/networking programmer myself. Just like the fact that everything looks like a database programmers to most database, I've observed that the reverse is true for non database programmers. In other words, most non RDMS normally don't think of a database even the solution screams for a database. I think SQLite does an amazing job in bridging this gap. > Agreed; python-dev has gotten pretty boring with all the endless discussions > over some minor point. Of course, it's much easier and lower-effort to > propose a syntax or nitpick a small point issue than to tackle a big > complicated issue like static typing. You have a point there :-). > Similar things happen on the catalog SIG: people suggest, or even > implement, an automatic package management system, But bring up the > question of whether it should be called PyPI or Cheeseshop or the Catalog, > and *everyone* can make a suggestion. My memory may not be perfect but I remember reading that Python 2.5's focus is libraries and no language changes. If that's correct, I can understand why core python folks are more interested in discussing language features for Python 3000 ;-). Speaking of libraries, I haven't seen many discussions on libraries in python-dev. Is there some other list with more discussions on libraries? Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From swarnapsv at yahoo.co.in Tue Sep 20 13:14:09 2005 From: swarnapsv at yahoo.co.in (swarna pulavarty) Date: Tue, 20 Sep 2005 18:14:09 +0100 (BST) Subject: How to Handle exceptions using OpenerDirector Message-ID: <20050920171409.74646.qmail@web8408.mail.in.yahoo.com> Hi all, I am trying to figure out a way to handle exceptions for error code 4xx , and 5xx 's . I came to know that these can be handled using OpenerDirector class and urllib2 module in Python. I could'nt find the right syntax or examples of how to use these Handlers. Any help is greatly appreciated ! Swarna. --------------------------------- Yahoo! India Matrimony: Find your partner now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sa at almasris.com Sat Sep 24 00:55:34 2005 From: sa at almasris.com (Shahla Almasri) Date: Fri, 23 Sep 2005 23:55:34 -0500 Subject: Problem subclassing (Newbie) Message-ID: Hi, I'm new to Python, so forgive me if I'm missing something obvious here. All what I am trying to do is create a hirarachy of objects (i.e. one that inherits from another). But for somereason my subclasses are not recognizing their superclass! I have the following: class Widget(object): def __init__(self, app, name, loc, width=30, height=50): #some initialization class Button(Widget): def __init__(self, app, label, loc, callback, width=30, height=50): Widget.__init__(self, app, label, loc, width, height) #some initialozation Then I have an instance of class Button called obj. My probelm is that the test isinstance(obj, Widget) resturns False! What is really strange is that even the test issubclass(Button, Widget) returns False!! Obviously I did not achieve the hirarchy I wanted. Any ideas what I could be missing? Thanks a lot! -Shahla From devlai at gmail.com Sat Sep 3 05:24:16 2005 From: devlai at gmail.com (Devan L) Date: 3 Sep 2005 02:24:16 -0700 Subject: 'isa' keyword References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> <1125577823.da914aee91f630e1c5ca0bb07d0fa224@teranews> <1125679294.724013.133350@z14g2000cwz.googlegroups.com> Message-ID: <1125739456.625683.138110@g49g2000cwa.googlegroups.com> talin at acm dot org wrote: > Thanks for all the respones :) I realized up front that this suggestion > is unlikely to gain approval, for reasons eloquently stated above. > However, there are still some interesting issues raised that I would > like to discuss. > > Let me first respond to a few of the comments: > > >What's the difference between this and ``isinstance`` ? > > What's the difference between 'in' and 'has_key()"? 1) Its shorter and > more readable, 2) it can be overridden to mean different things for > different container types. Your analogy doesn't apply to non dictionaries. In any case, nothing stops you from writing your own has_key() method for a different container type. Likewise, if you made an isa keyword, it would just call a method to have the traits you described above. You could write your own method to see if it was an instance of the class, but it would end up being more or less similar to isinstance(). From ed_zeng at yahoo.com Fri Sep 2 18:23:45 2005 From: ed_zeng at yahoo.com (Laguna) Date: 2 Sep 2005 15:23:45 -0700 Subject: Find day of week from month and year In-Reply-To: References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> <1125693378.950355.210830@g49g2000cwa.googlegroups.com> Message-ID: <1125699825.595306.290370@g49g2000cwa.googlegroups.com> Hey Donn, I don't mean to offend anyone here. I was just saying that the other solution is better suited for my problem. I truly appreciate your analysis and suggestions. BTW, I am not a programmer :( and I like the simplest solution whenever possible. Cheers, L From tvrtko.sokolovski at gmail.com Sun Sep 25 04:10:25 2005 From: tvrtko.sokolovski at gmail.com (tvrtko.sokolovski at gmail.com) Date: 25 Sep 2005 01:10:25 -0700 Subject: Poor man's OCR: need performance improvement tips In-Reply-To: References: <1127585677.391112.70130@g49g2000cwa.googlegroups.com> Message-ID: <1127635825.490639.46900@g43g2000cwa.googlegroups.com> Imagine a large matrix with dimensions [W,H], and a lots of smaller matrices with dimensions [p,q1], [p,q1], [p,q2], [p,q1], ... I have to slide a small window [p,q] horizontally over a larger matrix. After each slide I have to compare smaller matrices with the data from larger matrix (as defined by sliding window). I'm currently trying to use other kinds of optimizations (linearize data by columns), but the program no longer works, and it is so hard to debug. But it works very fast :) Here is an example of linearization by columns that i'm currently using : # setup: convert to 1 bit image img = Image.open(file_name) img2 = img.point([0]*255 + [1], "1") # find ocr lines, and for each do ... # extract OCR line region = img2.crop((0, ocrline.base_y-13, width, ocrline.base_y+3)) # h=16 region.load() # clean up upper two lines which should be empty but # sometimes contain pixels from other ocr line directly above draw = ImageDraw.Draw(region) draw.line((0,0,width,0), fill=1) draw.line((0,1,width,1), fill=1) # transpose data so I get columns as rows region = region.transpose(Image.FLIP_LEFT_RIGHT) region = region.transpose(Image.ROTATE_90) ocrline.data = region.tostring() # packs 8 pixels into 1 octet I do the same for known letters/codes (alphabet). Then I compare like this: def recognize (self, ocrline, x): for code_len in self.code_lengths: # descending order code = ocrline.data[x:x+code_len] ltr = self.letter_codes.get(code, None) if ltr is not None: return ltr, code_len # So I can advance x This currently "works" two orders of magnitude faster. From tjreedy at udel.edu Fri Sep 9 14:55:30 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Sep 2005 14:55:30 -0400 Subject: circular import problem References: <1126288774.239916.310020@z14g2000cwz.googlegroups.com> Message-ID: "Learning Python" wrote in message news:1126288774.239916.310020 at z14g2000cwz.googlegroups.com... > An example in the book I didn't understood well > two modules files recursively import/from each other There are past postings available in the archives (via Google) at least, that lucided discuss circular imports. There are also some that recommend "don't do that" and give alternatives. I recommend both. Terry J. Reedy From fredrik at pythonware.com Thu Sep 22 09:38:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Sep 2005 15:38:35 +0200 Subject: How to tell if an exception has been caught ( from inside theexception )? References: <1127384703.19940.8.camel@localhost.localdomain> <4332AF63.8060609@traxon.com> Message-ID: Paul Dale wrote: > I'm writing an exception that will open a trouble ticket for certain > events. Things like network failure. I thought I would like to have it > only open a ticket if the exception is not caught. Is there a way to do > this inside the Exception? As far as I can see there are only two events > called on the exception, __init__ and __del__, both of which will be > called wether or not an exception is caught (right?) > > Am I missing something, or is there a way to do this with exceptions? if you want to trap "uncaught" exceptions, add an except handler to the top level of your program: try: main() except MySpecialException, v: v.open_trouble_ticket() a less convoluted approach would be do to def open_trouble_ticket(exctype, value, traceback): ... try: main() except: open_trouble_ticket(*sys.exc_info()) or, in recent Python versions, import sys def open_trouble_ticket(exctype, value, traceback): ... sys.excepthook = open_trouble_ticket main() From python at rcn.com Thu Sep 29 22:07:19 2005 From: python at rcn.com (Raymond Hettinger) Date: 29 Sep 2005 19:07:19 -0700 Subject: Moronicity Xha Lee, Jargonizer In-Reply-To: References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> Message-ID: <1128046039.929637.94810@f14g2000cwb.googlegroups.com> James Stroud wrote: > There needs to be an email filter that, when a thread is begun by a specific > user . . . it cans every > message in that thread. The tried-and-true solution is both simple and civil, "Don't feed the trolls." Raymond From binarybana at gmail.com Sun Sep 25 20:17:01 2005 From: binarybana at gmail.com (binarybana at gmail.com) Date: 25 Sep 2005 17:17:01 -0700 Subject: Alternatives to Stackless Python? In-Reply-To: <1127610584.900195.112130@g43g2000cwa.googlegroups.com> References: <1127231444.643628.197920@g49g2000cwa.googlegroups.com> <1127438841.532386.73410@g44g2000cwa.googlegroups.com> <1127610584.900195.112130@g43g2000cwa.googlegroups.com> Message-ID: <1127693821.578384.39930@f14g2000cwb.googlegroups.com> Honestly I am not knowledgeable about either option but mainly I was specifically targetting my feature set towards the things that a higher level game engine would need such as the one described here: http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/ Which I guess the main difference that I see between stackless and NanoThreads is the ability to communicate between threads through channels and other methods. This is very important in games where the actors need to communicate among each other to create interactive and interesting gameplay. And perhaps scheduling overhead, memory costs and slow thread creation could be otherh areas where the two differ (but I am unsure). And finally, how good is NanoThreads at non-preemptive multithreading and event-driven control? These are more areas that I see the two possibly differing. Also, Greenlets look really interesting, I will have to evaluate these more closely. From fakeaddress at nowhere.org Fri Sep 2 00:06:08 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 02 Sep 2005 04:06:08 GMT Subject: Sockets: code works locally but fails over LAN In-Reply-To: <1125597092.323375.151570@g44g2000cwa.googlegroups.com> References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> Message-ID: n00m wrote: >>Bryan; > > I tested your code locally (in I*D*L*E) - it works fine! Glad it worked, but I'd still disrecommend IDLE for that version. Threads may live after the program seems to be done (and may still own the port you need). Below is a version that respects ^C to terminate more-or-less cleanly. > And of course I'll test it over LAN but only tomorrow - at work. > See the picture of my IDLE window with output of your code: > http://free.7host02.com/n00b/socket_Br.gif I didn't touch the printing, so it should output the same thing as your version. Looks like you've got some UTF-16 action there, and Python may be able to print it nicer if you use the unicode/codec stuff. -- --Bryan import socket, threading, select sqls_host, sqls_port = '192.168.0.3', 1443 proxy_host, proxy_port = '', 1434 def start_deamon_thread(func, args): """ Run func(*args) in a deamon thread. """ thread = threading.Thread(target=func, args=args) thread.setDaemon(True) thread.start() def sock_copy(s_from, s_to, annotation): while 1: data = s_from.recv(4096) if not data: break s_to.sendall(data) print annotation + data + '\n\n' s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((proxy_host, proxy_port)) s1.listen(5) while 1: s, _, _ = select.select([s1], [], [], 1.0) if s: cn, _ = s1.accept() s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.connect((sqls_host, sqls_port)) start_deamon_thread(sock_copy, (cn, s2, 'VB_SCRIPT:')) start_deamon_thread(sock_copy, (s2, cn, 'SQL_SERVER:')) From ms at cerenity.org Wed Sep 7 15:55:02 2005 From: ms at cerenity.org (Michael Sparks) Date: Wed, 07 Sep 2005 20:55:02 +0100 Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga> <431cadd6$0$97134$ed2619ec@ptn-nntp-reader03.plus.net> <431d4bd3$0$1314$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <431f4589$0$1292$ed2619ec@ptn-nntp-reader02.plus.net> Thomas Bellman wrote: > Michael Sparks writes: >> Similarly, from >> a unix command line perspective, the following will automatically take >> advantage of all the CPU's I have available: >> (find |while read i; do md5sum $i; done|cut -b-32) 2>/dev/null |sort > > No, it won't. At the most, it will use four CPU:s for user code. OK, maybe I should've been more precise. That said, the largest machine I could potentially get access relatively easily to would be a quad CPU machine so if I wanted to be be pedantic, regarding "*I* have available" the idea stands. (Note I didn't say take /best/ advantage - that would require rewriting all the indvidual parts of the pipeline above to be structured in a similar manner or some other parallel approach) You've essentially re-iterated my point though - that it naturally sorts itself out, and does the best fit it can, which is better than none (despite this being a naff example - as I mentioned). Worst case, yes, everything serialises itself. Michael. From tom at thebrownboys.net Thu Sep 22 09:25:32 2005 From: tom at thebrownboys.net (Tom Brown) Date: Thu, 22 Sep 2005 06:25:32 -0700 Subject: How to use writelines to append new lines to an existing file In-Reply-To: <4332A8F6.1020608@gmail.com> References: <4332A8F6.1020608@gmail.com> Message-ID: <200509220625.37695.tom@thebrownboys.net> On Thursday 22 September 2005 05:52, Nico Grubert wrote: > Does f = open('/tmp/myfile', 'w') overwrite the existing file or > does f.writelines('456') replace the first line in the existing file? Here's an excerpt from open.__doc__ The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Tom From agostino.russo at gmail.com Tue Sep 20 16:05:58 2005 From: agostino.russo at gmail.com (ago) Date: 20 Sep 2005 13:05:58 -0700 Subject: Object default value In-Reply-To: <43306858.20003@websafe.com> References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> <43306858.20003@websafe.com> Message-ID: <1127246758.691165.23920@g49g2000cwa.googlegroups.com> The print statement was only for illustrative purposes, when calling varx=myobj I need to receive obj.x as opposed to the instance of obj, but I also need to call vary=myobj.y. Something like that exists for com objects/VB, for instance an excel range object uses value as the default attribute, so that you can write set rng=range(...); x=rng y=rng.value 'x==y z=rng.attributeXYZ From davidstummer at gmail.com Sun Sep 11 11:04:44 2005 From: davidstummer at gmail.com (davidstummer at gmail.com) Date: 11 Sep 2005 08:04:44 -0700 Subject: python callbacks and windows In-Reply-To: <1126261209.412057.142160@o13g2000cwo.googlegroups.com> References: <1126261209.412057.142160@o13g2000cwo.googlegroups.com> Message-ID: <1126451084.782466.196080@g44g2000cwa.googlegroups.com> anybody? From i_vincent at hotmail.com Thu Sep 29 03:22:26 2005 From: i_vincent at hotmail.com (Ian Vincent) Date: 29 Sep 2005 08:22:26 +0100 Subject: Spoiler to Python Challenge (help!!!) References: <200509271042.20695.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote in news:mailman.1088.1127920459.509.python-list at python.org: > >>>> bz2.decompress(eval('"' + user + '"')) > > Sorry about that. I was trying the other as an alternative, > but in fact, it doesn't work. So ignore that. Excellent! Thanks. From deets at nospam.web.de Sun Sep 18 06:00:10 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Sep 2005 12:00:10 +0200 Subject: Brute force sudoku cracker In-Reply-To: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> Message-ID: <3p4s58F8lc12U1@uni-berlin.de> As everyone posts his, I'll do the same :) It uses some constraint based solving techniques - but not too complicated ones. When stuck, it backtracks. So far it never failed me, but I haven't tested it too thouroughly. Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sudoku.py URL: From kyaBey at gmail.com Fri Sep 30 12:13:27 2005 From: kyaBey at gmail.com (kyaBey at gmail.com) Date: 30 Sep 2005 09:13:27 -0700 Subject: getattr Message-ID: <1128096807.903294.293470@g47g2000cwa.googlegroups.com> This question is regarding the __getattr__ function defined for every object. Consider the following example Assume that foo is an instance of class Foo, and the following are references to foo's field "bar" which is an instance of class Bar a) foo.bar b) foo.bar.spam - spam is a member of "bar" I want the above references to be handled by __getattr__. Hence I do not have an entry for the 'bar' in foo.__dict__ Is there any way by which the __getattr__(self,attr) method can determine that in case a) attr == 'bar' is the final component in the reference unlike in case b) where attr=='bar' is NOT the ultimate(final) component of reference and is an intermediate component in the reference. tia From mwm at mired.org Wed Sep 28 18:40:06 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 28 Sep 2005 18:40:06 -0400 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <86y85hp5y7.fsf@bhuda.mired.org> <7xfyrozxf0.fsf@ruckus.brouhaha.com> Message-ID: <86psqsq0jd.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> Note that the quoted article only applies to *writing* attributes. It >> doesn't say anything about needing accessors to *read* a >> variable. This encourages me that the convention I use - adopted from >> Eiffel, where the compiler enforces it - of freeling reading >> attributes, but providing methods to write them - is a right way todo >> things. > > Generally that sounds reasonable. Obviously there are other examples > when (e.g. for security) you have to make sure that variables can't be > read by other classes, e.g. you have a class that stores a capability > (or a password) in an instance variable, and uses it for privileged > operations. If you can't trust the code that shares your address space, you're in a world of hurt for security. Compile-time restrictions don't matter for squat - you need serious restrictions on what the program can do at runtime. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeremy+python at jeremysanders.net Thu Sep 22 15:29:05 2005 From: jeremy+python at jeremysanders.net (Jeremy Sanders) Date: Thu, 22 Sep 2005 20:29:05 +0100 Subject: Classes derived from dict and eval References: Message-ID: On Tue, 20 Sep 2005 13:59:50 -0700, Robert Kern wrote: > globals needs to be a real dictionary. The implementation uses the C > API, it doesn't use the overridden __getitem__. The locals argument, > apparently can be some other kind of mapping. It seems that on Python 2.3 then neither globals or locals accessing by eval calls the __getitem__ member of the dicts. Jeremy From fredrik at pythonware.com Thu Sep 29 10:59:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 16:59:01 +0200 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xzmpwuxd0.fsf@ruckus.brouhaha.com> Message-ID: Steve Holden wrote: > To avoid naming conflicts, Python provides a mechanism (name mangling) > which pretty much guarantees that your names won't conflict with anybody > else's, *even if you subclass a class whose methods use the same name*. as long as you don't cheat, that is: # your code class Secret: def __init__(self): self.__hidden = "very secret value" # my code from yourcode import Secret class Secret(Secret): def gethidden(self): return self.__hidden s = Secret() print s.gethidden() From Vishnu.Mavuram at morganstanley.com Tue Sep 6 14:20:08 2005 From: Vishnu.Mavuram at morganstanley.com (Mavuram, Vishnu (IT)) Date: Tue, 6 Sep 2005 14:20:08 -0400 Subject: Pass pointer from C++ class to Boost Python script ?!!! Message-ID: Hi, Did you get an answer to this posting of yours? What I am trying to do is: struct Sec { ... }; int main(int, char **) { Py_Initialize(); ... Sec *s1 = new Sec(); PyObject *args = Py_BuildValue("(O)", s1); //*** this is where I am having problem ... PyObject* res = PyEval_CallObject( func, args); ... Py_Finalize(); return 0; } Can you please tell me how to get convert my pointer to a valid PyObject*? Thanks, Vishnu Mavuram -------------------------------------------------------- NOTICE: If received in error, please destroy and notify sender. Sender does not waive confidentiality or privilege, and use is prohibited. From alanmk at hotmail.com Tue Sep 6 11:09:31 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 06 Sep 2005 16:09:31 +0100 Subject: Python xml.dom, help reading attribute data In-Reply-To: <1126013682.038129.169860@g43g2000cwa.googlegroups.com> References: <1126013682.038129.169860@g43g2000cwa.googlegroups.com> Message-ID: [Thierry Lam] > Let's say I have the following xml tag: > > 1 > > I can't figure out what kind of python xml.dom codes I should invoke to > read the data 1? Any help please? This is job for xpath. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= from xml import xpath from xml.dom import minidom doc = """1""" mydom = minidom.parseString(doc) #result_nodes = xpath.Evaluate("/para/text()", mydom) #result_nodes = xpath.Evaluate("/para[1]/text()", mydom) result_nodes = xpath.Evaluate("/para[@role='success']/text()", mydom) for ix, r in enumerate(result_nodes): print "result %d: %s" % (ix, r) #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Xpath support is a part of the PyXML package, which you can get from here http://pyxml.sourceforge.net Xpath tutorials from here http://www.zvon.org/xxl/XPathTutorial/General/examples.html http://www.w3schools.com/xpath/ there-are-other-ways-to-do-it-but-i-like-xpath-ly'yrs, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From larry.bates at websafe.com Mon Sep 19 17:44:13 2005 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 19 Sep 2005 16:44:13 -0500 Subject: very high-level IO functions? In-Reply-To: References: Message-ID: It's so easy (using csv module), no need to build in. You can wrap in a class if you want to make even easier. Same can be done for tables from SQL database. import csv fp=open(r'C:\test.txt', 'r') # # test.txt contains: # # "record","value1","value2" # "1","2","3" # "2","4","5" # "3","6","7" table=csv.DictReader(fp) for record in table: # # Record is a dictionary with keys as fieldnames # and values of the data in each record # print "record #=%s, value1=%s, value2=%s" % \ (record['record'],record['value1'],record['value2']) fp.close() -Larry Bates York wrote: > Your are right, a program cannot be smarter than its programmer. However > I need a program to parse any table-format data files offered by user. R > offer such a function, I hope python such a function too. > > -York > > >> While it may "attempt" to recognize the types, it in fact cannot >> be more correct than the programmer. Example: >> >> data="""0X1E04 111""" >> >> That "looks" lile a hex and an int. But wait. What if it is >> instead two strings? >> >> In Python you can easily write a class with a interator that can >> read the data from the file/table and return the PROPER data types >> as lists, tuples, or dictionaries that are easy to manipulate. >> >> -Larry Bates >> >> York wrote: >> >>> Hi, >>> >>> R language has very high-level IO functions, its read.table can read a >>> total .csv file and recogonize the types of each column. write.table can >>> do the reverse. >>> >>> R's MySQL interface has high-level functions, too, e.g. dbWriteTable can >>> automatically build a MySQL table and write a table of R data into >>> it. >>> >>> Is there any python packages do similar things? >>> >>> >>> -York From martin.witte at gmail.com Fri Sep 23 08:09:39 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 23 Sep 2005 05:09:39 -0700 Subject: File processing In-Reply-To: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> References: <1127477266.452792.150450@z14g2000cwz.googlegroups.com> Message-ID: <1127477379.479350.264510@g47g2000cwa.googlegroups.com> The ConfigParser class is designed for this task, see http://docs.python.org/lib/module-ConfigParser.html From piet at cs.uu.nl Fri Sep 2 07:00:22 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 02 Sep 2005 13:00:22 +0200 Subject: Decrypting GPG/PGP email messages References: Message-ID: >>>>> Alessandro Bottoni (AB) wrote: >AB> Of course, I want to be sure that only the allowed people is able to send >AB> such dangerous messages to my server so I will ask my users to encrypt and >AB> digitally sign their messages using Thunderbird, Enigmail and GPG ... What benefit is there in encrypting the messages? It would only prevent people intercepting the message from seeing what's inside, but it won't give you any additional protection on the server. And if somebody can intercept the messages there is a much bigger danger: They could save the message and replay it later. You can't protect against this with encryption (well, with encryption they won't know what they are doing). Neither with a digital signature. Only checking timestamps, keeping track of the messages received and/or a challenge/response system will help in this case. >AB> 1) What would you use to decrypt the messages? The GPG module created by >AB> Andrew Kuchling is declared "incomplete" and "no more maintained" on his >AB> web pages (http://www.amk.ca/python/code/gpg) so I think it is out of the >AB> game. Would you use OpenPGP (http://www.aonalu.net/openpgp/python)? Any >AB> other module? If you only sign, it will be sufficient, but there is a more complete one (including decryption) in http://trac.t7a.org/isconf/file/trunk/lib/python/isconf/GPG.py -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From http Tue Sep 6 03:20:23 2005 From: http (Paul Rubin) Date: 06 Sep 2005 00:20:23 -0700 Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga> <431cadd6$0$97134$ed2619ec@ptn-nntp-reader03.plus.net> <7xirxeso5q.fsf@ruckus.brouhaha.com> Message-ID: <7xslwiu0g8.fsf@ruckus.brouhaha.com> Steve Jorgensen writes: > Given that Python is highly dependent upon dictionaries, I would > think a lot of the processor time used by a Python app is spent in > updating hash tables. That guess could be right or wrong, bus > assuming it's right, is that a design flaw? That's just a language > spending most of its time handling the constructs it is based on. > What else would it do? I don't believe it's right based on half-remembered profiling discussions I've seen here. I haven't profiled CPython myself. However, if tuning the rest of the implementation makes hash tables a big cost, then the implementation, and possibly the language, should be updated to not have to update hashes so much. For example, x.y = 3 currently causes a hash update in x's internal dictionary. But either some static type inference or a specializing compiler like psyco could optimize the hash lookup away, and just update a fixed slot in a table. From gsakkis at rutgers.edu Thu Sep 22 20:13:47 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 22 Sep 2005 20:13:47 -0400 Subject: Newbie regular expression and whitespace question References: <1127419129.027712.252910@g47g2000cwa.googlegroups.com> Message-ID: <1127434477.ad78d3d530903d001e279515d4ebee93@teranews> "googleboy" wrote: > Hi. > > I am trying to collapse an html table into a single line. Basically, > anytime I see ">" & "<" with nothing but whitespace between them, I'd > like to remove all the whitespace, including newlines. I've read the > how-to and I have tried a bunch of things, but nothing seems to work > for me: > > [snip] As others have shown you already, you need to use the sub method of the re module: import re regex = re.compile(r'>\s*<') print regex.sub('><',data) > For extra kudos (and I confess I have been so stuck on the above > problem I haven't put much thought into how to do this one) I'd like to > be able to measure the number of characters between the

&

> tags, and then insert a newline character at the end of the next word > after an arbitrary number of characters..... I am reading in to a > script a bunch of paragraphs formatted for a webpage, but they're all > on one big long line and I would like to split them for readability. What I guess you want to do is wrap some text. Do not reinvent the wheel, there's already a module for that: import textwrap print textwrap.fill(oneBigLongLine, 60) HTH, George From bhoel at despammed.com Tue Sep 27 15:20:15 2005 From: bhoel at despammed.com (=?utf-8?q?Berthold_H=C3=B6llmann?=) Date: Tue, 27 Sep 2005 21:20:15 +0200 Subject: Python 2.4 under WinXP, free VC71 toolkit and VC6 libraries References: <43398685$0$7334$626a14ce@news.free.fr> Message-ID: "F. Petitjean" writes: > Le Tue, 27 Sep 2005 17:48:47 +0200, Berthold H?llmann a ?crit : >> I have wrapped some inhouse libraries for Python. > How ? Directly coding C code ? Depends :-) f2py, directly coding C, SWIG. >> The development team >> uses VC6 and DF6.1 for development of these libraries under WinXP. > DF6.1 is Digital FORTRAN 6.1 ? Yes >> I >> would like to wrap the libraries for Python and use the official Win >> Python from python.org. Now I get a segmentation fault in (access >> violation in NTDLL.DLL). The code used to work on Python 2.3, so I >> am afraid I have a plroblem in mixing the code generated by different >> VC versions. Is this the probable cause of my problem, or should the >> combination work in general (some libraries seem to work). >> >> Kind regards >> Berthold > A possible solution would be to write any VC6 and DF6.1 code to generate > some DLLs (black boxes) and to use these DLLs from Python by using > ctypes, to build your applications. All the CPU intensive code should be > in DLLs and the high level stuff (GUI, presentation, application logic, > ...) could be in python. (GUI with wnd or venster for example). As I understand it, ctypes is not really a solution. The code is about data handling and FE analysis. It has not GUI component. I'm not sure how well ctypes works with Numeric arrays, but I'm sure ctypes does not work on Linux and Solaris, but my code has to. Regards. -- "Es gelten die Regeln der christlichen Seefahrt: Rot und Gr?n markiert das sichere Fahrwasser, Schwarz und Gelb markieren Untiefen und Wracks." Christa Sager, Bundestagsfraktionsvorsitzende B?ndnis 90/Gr?ne From en.karpachov at ospaz.ru Thu Sep 29 14:56:10 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Thu, 29 Sep 2005 22:56:10 +0400 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <20050929182936.50b6ec54.jk@ospaz.ru> Message-ID: <20050929225610.504bd9d5.jk@ospaz.ru> On Thu, 29 Sep 2005 17:03:00 +0200 Fredrik Lundh wrote: > en.karpachov at ospaz.ru wrote: > > > What if the access to that variable was forbidden for reasons you never > > foresaw? What if the class author decide to remove the variable in the next > > version of the class, because it's not an interface, but only a part of the > > class implementation? > > you mean when he breaks into your computer and installs the new version > without you noticing? > > if you think that once you've put private labels on all accidental stuff, nothing > will break during upgrades, you're clearly very new to this thing called pro- > gramming... Do you ever heard of that funny things named "an interface" and "an implementation"? -- jk From durumdara at mailpont.hu Wed Sep 28 07:16:51 2005 From: durumdara at mailpont.hu (durumdara at mailpont.hu) Date: Wed, 28 Sep 2005 13:16:51 +0200 Subject: Python batching on XP In-Reply-To: References: Message-ID: <433A7BA3.7030601@mailpont.hu> Hi ! I have Py 2.3.5, and subprocess is placed in version 2.4. The os.popen is not good, because it is not get return value. I can read the return value, but the message is os dependent (XP, 2k, NT). I create this function. It is not too good, but it is working: def Cmd(cmd,tmpdir="./"): outfn='%s/_out.msg'%tmpdir errfn='%s/_err.msg'%tmpdir post="1>%s 2>%s"%(outfn,errfn) cmd2='%s %s'%(cmd,post) r=os.system(cmd2) f=open(outfn,"r") try: s1=f.read() finally: f.close() f=open(errfn,"r") try: s2=f.read() finally: f.close() s="\n".join([s1,s2]).strip() return (r,s) Anyone have a better idea ? Thanks for it: dd Larry Bates wrote: >You should take a look at the subprocess module >http://www.python.org/dev/doc/devel/lib/module-subprocess.html > >-Larry Bates > >durumdara at mailpont.hu wrote: > > >>Hi ! >> >>I want to write a program that backup some databases in the night. >> >>Pseudo like this: >> >>try: >>if cmd('net stop dbservice'): >> s=c://backup'+str(time.time())+'.zip' >> if cmd('zipit c:\\database '+s): >> if cmd('map drive \\\\backupdrive\\c$ y -user BACKUP -pwd SECRET'): >> if cmd('copy '+s+' y:\\'): >> LogSucc() >>finally: >> cmd('net start dbservice') >> >>I'm trying with os.system() commands. >>But that is printing the result message to the screen, not to a tuple, >>like commands.|getstatusoutput(). >>I need to store this message, because I want to log everything that this >>program do/print; every of the messages. >> >>So: how to I capture the screen, or how to I use >>|commands.|getstatusoutput() to access the Windows batch/cmd commands, >>and get their errors/statuses ? >> >>Please help me ! >> >>Thanks for it: dd >>| >> >> From r2_r2 at hotmail.com Thu Sep 22 01:58:49 2005 From: r2_r2 at hotmail.com (r2_r2 at hotmail.com) Date: 21 Sep 2005 22:58:49 -0700 Subject: Help w/ easy python problem In-Reply-To: <1127367364.763432.85610@o13g2000cwo.googlegroups.com> References: <1127367364.763432.85610@o13g2000cwo.googlegroups.com> Message-ID: <1127368729.351444.311150@g43g2000cwa.googlegroups.com> Actually, it is not a sin curve i need to plot, it is dots running down the page in the shape of a sin curve like this . . . etc... From reinhold-birkenfeld-nospam at wolke7.net Sun Sep 25 15:08:15 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 25 Sep 2005 21:08:15 +0200 Subject: "Re: cElementTree clear semantics" In-Reply-To: References: <3po78hFbdl84U1@individual.net> <3po7i3Fbdl84U2@individual.net> <3po99cFb5tpjU2@individual.net> Message-ID: <3poasvFb9emmU2@individual.net> D H wrote: > Reinhold Birkenfeld wrote: >> D H wrote: >> >>>D H wrote: >>> >>>>Reinhold Birkenfeld wrote: >>>> >>>> >>>>>Well, if I had e.g. a question about Boo, I would of course first ask >>>>>here because I know the expert writes here. >>>>> >>>>>Reinhold >>>> >>>> >>>>Reinhold Birkenfeld also wrote: >>>> > If I had wanted to say "you have opinions? fuck off!", I would have said >>>> >"you have opinions? fuck off!". >>>> >>>> >>>>Take your own advice asshole. >> >> >> And what's that about? > > I think it means you should fuck off, asshole. I think you've made that clear. *plonk* Reinhold PS: I really wonder why you get upset when someone except you mentions boo. From benji at benjiyork.com Sat Sep 24 10:03:03 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 24 Sep 2005 10:03:03 -0400 Subject: Accessing class variable at class creation time In-Reply-To: <3756d975050924030910eb9db2@mail.gmail.com> References: <1127509281.767539.271230@g43g2000cwa.googlegroups.com> <4334AE1C.7070508@benjiyork.com> <3756d975050924030910eb9db2@mail.gmail.com> Message-ID: <43355C97.3080902@benjiyork.com> Jan-Ole Esleben wrote: > That doesn't really give him a way of using the class variable inside a method. Oh! I must have misunderstood the question. I'd like to know more about why the OP wants to do this; a small example would help narrow down the possibilities. -- Benji York From crculver at christopherculver.com Sun Sep 4 22:37:10 2005 From: crculver at christopherculver.com (Christopher Culver) Date: Sun, 04 Sep 2005 21:37:10 -0500 Subject: learning python References: <1125886211.816019.201070@z14g2000cwz.googlegroups.com> Message-ID: <1125887831.3fb3e29f106c8f78f93b86aa1197a085@teranews> "placid" writes: > I was just wondering about good books that teach python (either with > programming or no programming experience at all) ? Or some online > tutorial? Did you even bother doing a web search? "Learn Python" or "Python tutorial" would be enough. Christopher From trentm at ActiveState.com Thu Sep 15 11:29:49 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 15 Sep 2005 08:29:49 -0700 Subject: ddd or eclipse with mod_python In-Reply-To: <1126765291.108775.324560@g43g2000cwa.googlegroups.com> References: <1126765291.108775.324560@g43g2000cwa.googlegroups.com> Message-ID: <20050915152949.GD22838@ActiveState.com> [Sakcee wrote] > Hi > > I am using mod_python for web development, I am in need of some ide , > can i use ddd or eclipse with pydev with mod_python. > > can these ide's handle requests from mod_python and run server side > scripts You should be able to debug with Komodo(*): Using the Python Remote Debugger http://aspn.activestate.com/ASPN/docs/Komodo/3.1/komodo-doc-debugpython.html#Using_the_Python_Remote_Debugger You can get a trial here: www.activestate.com/Komodo/Trial Cheers, Trent (*) Disclaimer: I work on Komodo. -- Trent Mick TrentM at ActiveState.com From jason at jasonmhirst.co.uk Mon Sep 19 04:17:41 2005 From: jason at jasonmhirst.co.uk (JMH) Date: Mon, 19 Sep 2005 09:17:41 +0100 Subject: How am I doing? In-Reply-To: <86slw1znup.fsf@bhuda.mired.org> References: <86slw1znup.fsf@bhuda.mired.org> Message-ID: Thanks for that Mike. I do remember reading about the __main__ in an online tutorial and remember thinking "That's handy!". Totally forgot about that in my own little code so thanks for reminding me. From beliavsky at aol.com Mon Sep 19 17:16:27 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 19 Sep 2005 14:16:27 -0700 Subject: ANN: PyTrilinos (wrapper for parallel linear algebra) Message-ID: <1127164587.066336.92760@g14g2000cwa.googlegroups.com> PyTrilinos is a Python wrapper for the Trilinos linear algebra library. It is described at http://software.sandia.gov/trilinos/packages/pytrilinos/index.html and in more detail in the PDF file at that site. It was just announced on NA Digest. I have not tried it myself. Here are some quotes from the Trilinos site. "The Trilinos Project is an effort to develop and implement robust parallel algorithms using modern object-oriented software design, while still leveraging the value of established numerical libraries such as PETSc, Aztec, the BLAS and LAPACK. It emphasizes abstract interfaces for maximum flexibility of component interchanging, and provides a full-featured set of concrete classes that implement all abstract interfaces." ... "PyTrilinos is a set of Python wrappers for selected Trilinos packages. This allows a python programmer to dynamically import Trilinos packages into a python script or the python command-line interpreter, allowing the creation and modification of Trilinos objects and the execution of Trilinos algorithms, without the need to constantly recompile." From chris.cavalaria at free.fr Tue Sep 13 11:49:10 2005 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 13 Sep 2005 17:49:10 +0200 Subject: PyGTK or wXPython? In-Reply-To: References: Message-ID: <4326f37b$0$24718$636a15ce@news.free.fr> Peter Decker a ?crit : > On 9/13/05, Rod W wrote: > >>I'm just starting out on Python but my primary goal is to provide >>applications with some user interface (GUI). >> >>Can someone point me to a good comparison of whether I should use >>wxPython (with wxGlade I assume) or PyGTK (with Glade I assume)? >> >>I'd prefer open source (not necessarily GPL though) tools. > > > I looked at both, and preferred wxPython's look. I hated its C-like > feeling, with some very un-Pythonic code that failed to hide its C > roots very well, but I used it because the results were so good. > > Since then I've discovered Dabo, which is a complete application > framework, and which wraps wxPython for its UI. Apparently, the > authors of Dabo also didn't like the style of wxPython code, and have > created their own classes that expose a cleaner, much more Pythonic > API. I've been using Dabo for some small GUI apps, and I still can't > believe how much easier it is to create the UI with Dabo than with > plain wxPython. You should definitely check it out if you decide to go > the wxPython route. > There's Wax which is a cleaner pythonic API on top of wxPython. Myself, I would go the PyQT way because the API is very clean and there's one less abstraction layer on top of it. From harlinseritt at yahoo.com Fri Sep 9 07:04:06 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 9 Sep 2005 04:04:06 -0700 Subject: python script under windows References: Message-ID: <1126263846.693277.50420@g47g2000cwa.googlegroups.com> Hi Jan, Unfortunately you will have to register it as a service. I am almost certain there is no other way to do it. However, setting up an executable as a true Windows Service is extremely tedious. You can try this utility that I use. You can get it here: http://www.seritt.org/pub/srvinst13b.exe. I'm probably not supposed to distribute it, but the site and owners that used to host it have gone belly up best that I can tell. As with anything, use it at your own risk. I found it as freeware a few months back. If you want a decent cheap solution, FireDaemon is pretty good. I think it's like 30USD but it does a great job and adds a few extra features. HTH, Harlin Seritt Internet Villa: www.seritt.org From chandra.bangalore at gmail.com Mon Sep 19 10:19:07 2005 From: chandra.bangalore at gmail.com (chand) Date: 19 Sep 2005 07:19:07 -0700 Subject: Removing Warning Messages ............. Message-ID: <1127139547.304510.112570@g14g2000cwa.googlegroups.com> Hi., In my api.py file 'g_opt_list' is defined globally g_opt_list =[[],[],[],[],[],[],[]] when I run the py file, I am getting the Following Error SyntaxWarning: name 'g_opt_list' is used prior to global declaration SyntaxWarning: name 'layers' is used prior to global declaration Please let me know how to remove these warnings. I found that commenting 'g_opt_list' initialisation in "NEW" command removes this warning message. But my requirement is that i want to reset g_opt_list to empty list, whenever "NEW" command is called. Here is the code which gives the error... I have removed most of the unwanted code to reduce the size. Let me know exact reason for this warning and how to remove these warnings.. import os,sys,re,string,math g_opt_list =[[],[],[],[],[],[],[]] SIG_STANDARD_HOME = "/home/chandras/SIGNALLING_STANDARD/ANSI_SS7/" symbols=['(',')','{','}','[',']','.'] reverse_symbols=['<','>','~'] layers=['MTP3','SCCP','IOS','CDTAPM2','CDTAPC2','ISUP','IS-41D-SQA'] GUI_API_COMMAND_LIST = [ "NEW", "ADD_OPTIONAL_PARAM", ] Message_obj = Message() def Process_GUI_Command(arg): global Message_obj global filename out_file = file('/tmp/te.txt', 'w+') if arg[0] == "NEW" : global g_opt_list for i in range(0,len(g_opt_list)): g_opt_list[i] = [] return layerList elif arg[0] == "ADD_OPTIONAL_PARAM" : global g_opt_list global layers global index message_name = "" add_delete_flag = 0 param_name = optional_parameter_name g_opt_list[int(index)].append(optional_parameter_name) def main(): print "####### choice ", if __name__ == '__main__': main() From steve at holdenweb.com Fri Sep 23 06:49:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 23 Sep 2005 11:49:51 +0100 Subject: Anyone else getting posts back as email undeliverable bounces? In-Reply-To: <433346fa.2178291167@news.oz.net> References: <433346fa.2178291167@news.oz.net> Message-ID: I've even tried communicating with postmaster at all relevant domains, but such messages are either bounced or ignored, so I've just filtered that domain out. regards Steve Bengt Richter wrote: > It seems lately all my posts have been coming back to me as bounced emails, > and I haven't emailed them ;-( > > I've been getting bounce messages like (excerpt): > ... > _______________________________________________ > > This is the Postfix program at host deimos.liage.net. > > I'm sorry to have to inform you that your message could not be > be delivered to one or more recipients. It's attached below. > > For further assistance, please send mail to > > If you do so, please include this problem report. You can > delete your own text from the attached returned message. > > The Postfix program > > : Host or domain name not found. Name service error for > name=lindensys.net type=A: Host not found > Reporting-MTA: dns; deimos.liage.net > X-Postfix-Queue-ID: DC5264161 > X-Postfix-Sender: rfc822; bokr at oz.net > Arrival-Date: Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > > Final-Recipient: rfc822; lists at lindensys.net > Action: failed > Status: 5.0.0 > Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error > for name=lindensys.net type=A: Host not found > Received: by deimos.liage.net (Postfix, from userid 126) > id DC5264161; Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > Received: from smtp-vbr5.xs4all.nl (smtp-vbr5.xs4all.nl [194.109.24.25]) > by deimos.liage.net (Postfix) with ESMTP id 79D8340AA > for ; Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > Received: from bag.python.org (bag.python.org [194.109.207.14]) > by smtp-vbr5.xs4all.nl (8.13.3/8.13.3) with ESMTP id j8MNoClb072177 > for ; Fri, 23 Sep 2005 01:50:12 +0200 (CEST) > (envelope-from python-list-bounces+lists=listpreserve.org at python.org) > Received: from bag.python.org (bag [127.0.0.1]) > by bag.python.org (Postfix) with ESMTP id 8C4871E4013 > for ; Fri, 23 Sep 2005 01:50:10 +0200 (CEST) > _________________________________________________ > ... > > > Regards, > Bengt Richter -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From rschroev_nospam_ml at fastmail.fm Tue Sep 6 04:22:39 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 06 Sep 2005 08:22:39 GMT Subject: OpenSource documentation problems In-Reply-To: References: Message-ID: Adriaan Renting wrote: > In my Windows days I realy liked the Borland documentation, it was > way better as the Visual Studio/MSDev docs. Borland C++Builder used > to come with a complete rewrite of the Win32 API docs, next to the > docs of it's own API. Yes, but the two are completely separate. If you press F1 on a misspelled function, it doesn't find the function in its Win32 section and opens its Borland section, even though it's not there either. You have to manually open the Win32 help in that case if that's what you need (e.g. if you don't know the exact name of the function you're looking for). And I think MSDN is more detailed; I almost always use MSDN instead of Builder's builtin Win32 help. I also think that Borland's documentation on general (e.g. STL) and Borland-specific (e.g. __property) C++-language topics isn't as good as it should and could be. > One of the things I realy liked about C++Builder, and haven't found > anywhere else*, is that if you push F1 anywhere in your code, it will > pop up the help of whatever object/class/function/lib your cursor is > sitting on. I've been doing that in Visual Studio since the first version I used, which was 5 IIRC. > No need to hunt google or some awkward CD search, just > press F1 when you don't remember exactly how to call > SetModemParams(). (*I'm not current with the latest MS and Borland > offerings) What I've always done with MSDN: copy the whole thing from CD to HD, and do a minimal install from there. Then the help application can find everything without asking for the CDs. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From sa at almasris.com Sat Sep 24 11:31:23 2005 From: sa at almasris.com (Shahla Almasri) Date: Sat, 24 Sep 2005 10:31:23 -0500 Subject: Problem subclassing (Newbie) Message-ID: I finally figured what I was missing. I forgot to import my Widget class!!! I have imported Tkinter in the module for other GUI related stuff. So Python was testing my Button class against Tkinter's Widget class, and that's why the result was False. It finally made sense :) Thank you Anand and Laszlo for your reply. Cheers, -Shahla > > >Then I have an instance of class Button called obj. My probelm is that > >the test isinstance(obj, Widget) resturns False! > > > You must have a typo somewhere. Please try this little test program. > > >>> class Widget(object): > ... pass > ... > >>> class Button(Widget): > ... pass > ... > >>> b = Button() > >>> isinstance(b,Widget) > True > >>> isinstance(b,Button) > True > >>> issubclass(Widget,Button) > False > >>> issubclass(Button,Widget) > True > >>> > > > > -- From tjreedy at udel.edu Thu Sep 1 17:46:26 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Sep 2005 17:46:26 -0400 Subject: Weekly Python Patch/Bug Summary References: <200509011712.j81HCXHG007703@bayview.thirdcreek.com> Message-ID: "Kurt B. Kaiser" wrote in message news:200509011712.j81HCXHG007703 at bayview.thirdcreek.com... >Patches : 903 open (+551) / 5222 closed (+2324) / 6125 total (+2875) >Bugs : 903 open (-23) / 5222 closed (+45) / 6125 total (+22) Something went awry, as the patch totals did not really rise up to exactly the bug totals ;-) Terry J. Reedy From edhotchkiss at gmail.com Fri Sep 16 17:09:58 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Fri, 16 Sep 2005 17:09:58 -0400 Subject: My First Python Script In-Reply-To: <20050916202914.GB2145@gate2.hazen.net> References: <200509152048.04404.jstroud@mbi.ucla.edu> <20050916202914.GB2145@gate2.hazen.net> Message-ID: Someone else actually got me some help, the end result he hooked me up with was: # function to evaluate all possible IPs def findIPs(): ipFile = open("IPList.txt", 'w') for octet1 in range(256): for octet2 in range(256): for octet3 in range(256): for octet4 in range(256): ipAddress = '%03.d.%03.d.%03.d.%03.d\n' % (octet1, octet2,octet3, octet4) ipFile.write(ipAddress) ipFile.close() # execute the function findIPs() Thanks though, your response helps me understand variables better now.. On 9/16/05, John Hazen wrote: > > * Ed Hotchkiss [2005-09-15 20:36]: > > But then I still get the error with the len(x) statement .. hmm > > Ahh. In the future, it will help us help you, if you make it clear that > there was an error, and *paste the exact error* into your mail. > > For example, I'm guessing the error you got is: > > >>> len(255) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > > > As Robert said, this is because integers don't have a length. > > James' suggestion to use string formatting is probably the "best" > solution, but the formatting codes are fairly daunting for someone never > exposed to them. > > > if len(x) == 1: > > mySet = '00' + str(x) > > elif len(x) == 2: > > mySet = '0' + str(x) > > You know intuitively that strings *do* have length, and you appear to > know how to create a string from an integer. So the easiest > modification to your code to make it work wolud be something like: > > mySet = str(x) > if len(mySet) == 1: > mySet = '00' + mySet > elif len(mySet) == 2: > mySet = '0' + mySet > > Now, this can be made a little more elegant (and generalized) by using > the algorithm "if the string is too short, keep prepending zeros until > it's long enough." > > target_length = 3 > mySet = str(x) > while len(mySet) < target_length: > mySet = '0' + mySet > > But this isn't as efficient as your solution. Once you know about the > interesting ability to multiply strings ("0" * 3 = "000"), you can > create a solution that's general, elegant, and efficient: > > target_length = 3 > mySet = str(x) > mySet = '0' * (target_length - len(mySet)) + mySet > > HTH- > > John > -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: From RayFLau at gmail.com Sat Sep 3 11:14:35 2005 From: RayFLau at gmail.com (KK) Date: 3 Sep 2005 08:14:35 -0700 Subject: Problems with Python for Windows extensions Message-ID: <1125760475.488680.17070@z14g2000cwz.googlegroups.com> the code below is taken from M$ technet as an example on using vb script to do a replace all in word: Const wdReplaceAll = 2 Set objWord = CreateObject("Word.Application") objWord.Visible = True Set objDoc = objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") Set objSelection = objWord.Selection objSelection.Find.Text = "Contoso" objSelection.Find.Forward = True objSelection.Find.MatchWholeWord = True objSelection.Find.Replacement.Text = "Fabrikam" objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll I did a rewrite and made it pythonic: from win32com.client import * wdReplaceAll = 2 objWord = Dispatch("Word.Application") objWord.Visible = True objDoc = objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") objSelection = objWord.Selection objSelection.Find.Text = "Contoso" objSelection.Find.Forward = True objSelection.Find.MatchWholeWord = True objSelection.Find.Replacement.Text = "Fabrikam" objSelection.Find.Execute (Replace = wdReplaceAll) However, the document juz loaded up in word but no action was taken. I am using Word 2003. Any ideas? From robin.cull at gmail.com Wed Sep 14 09:42:58 2005 From: robin.cull at gmail.com (Rubinho) Date: 14 Sep 2005 06:42:58 -0700 Subject: Removing duplicates from a list References: <1126697915.879705.300450@g44g2000cwa.googlegroups.com> Message-ID: <1126705378.787162.120130@g43g2000cwa.googlegroups.com> Peter Otten wrote: > Rubinho wrote: > > > I've a list with duplicate members and I need to make each entry > > unique. > > > > I've come up with two ways of doing it and I'd like some input on what > > would be considered more pythonic (or at least best practice). > > > > Method 1 (the traditional approach) > > > > for x in mylist: > > if mylist.count(x) > 1: > > mylist.remove(x) > > That would be an odd tradition: By tradition I wasn't really talking Python tradition; what I meant was that the above pattern is similar to what would be generated by people used to traditional programming languages. > > >>> mylist = [1, 2, 1, 3, 2, 3] > >>> for x in mylist: > ... if mylist.count(x) > 1: > ... mylist.remove(x) > ... > >>> mylist > [2, 1, 2, 3] # oops! But you're absolutely right, it doesn't work! Oops indeed :) I've gone with Thomas's suggestion above of: mylist=list(set(mylist)) Thanks, Robin From mensanator at aol.com Fri Sep 23 19:10:06 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 23 Sep 2005 16:10:06 -0700 Subject: Help installing Python 2.3 on Win2K In-Reply-To: References: Message-ID: <1127517006.054291.193660@f14g2000cwb.googlegroups.com> D.S. Hein wrote: > I have installed python 2.3 on my Windows 2K laptop and I can run python > from the command prompt. > > I have tried various ways to set PYTHONPATH with the various directories > where I have python programs (i.e. xxxxxx.py) but no matter how I set > PYTHONPATH I keep getting a message that python can't open the python > file. If I try to specify the full pathname by typing: python > c:\Documents and Settings\-rest of path- I get an error message that > python can't open c:\Documents. Put the path inside quotation marks just as you would any other command. C:\>dir C:\documents and settings\a* The system cannot find the file specified. C:\>dir "C:\documents and settings\a*" Volume in drive C is XXXXPXXABA Volume Serial Number is 90C0-740E Directory of C:\documents and settings 07/16/2001 08:40a Administrator 07/29/2005 08:20a All Users 0 File(s) 0 bytes 2 Dir(s) 772,973,568 bytes free > > The ways I have set PYTHONPATH are by directly changing the registry > entry for Python 2.3, by setting the environment variable by > right-clicking on My Computer and by adding set PYTHONPATH=-various > pathnames-. > > I'd be grateful for any guidance on how to organize my system. From tjreedy at udel.edu Fri Sep 2 18:21:00 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Sep 2005 18:21:00 -0400 Subject: To the python-list moderator References: <200508311704.14077.hancock@anansispaceworks.com> <6HZRe.355752$s54.266548@pd7tw2no> Message-ID: "Neil Schemenauer" wrote in message news:6HZRe.355752$s54.266548 at pd7tw2no... > In the future, sending a message to postmaster at python.org is > suggested rather than posting to only to python-list. Thank you information. Since python.org is mostly stuff other than the mailing lists, I did not think of that. Adding it to the CC line for this reply. > What's > happening is that Spambayes is marking the message as UNSURE. The > message that mailman sends to the sender is unfortunate. The > "Message has a suspicious header" notice is misleading because the > user did not have any header in their message that caused it to be > held (at least normally not). Is that hardwired into Spambayes or can it be edited. > I'm not sure why many legitimate messages are being flagged as > UNSURE. I'll look into it. Then my 'misdirected' query will have worked anyway. Thank you. > Hmm, the message should eventually get through since it ends up > getting moderated by a person. My embargoed reply, which I believe I sent Sunday, was released mid-Thursday. > Maybe they are getting overwhelmed and are making some mistakes. Fewer false positives would make life easier for everyone. Perhaps a whitelist of regular and long-terms posters would help. I think most or all of the 4 people who responed 'me too' would also qualify. What still puzzles me is why the spamblocker that embargoed me and others did not catch such obvious spam as Subject: Re: The penis is way too delicate for masturbation (and occasional others like this). If you need a regular c.l.p reader to forward missed spam for addition to the training base, I would volunteer. Terry J. Reedy From cjw at sympatico.ca Fri Sep 9 10:42:33 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 09 Sep 2005 10:42:33 -0400 Subject: Interactive use of Help with class/instance data Message-ID: help(instance.property) gives the same information as help(instance) but help(cls.property) gives information specific to the property. Is this a bug? Colin W. From dify.ltd at gmail.com Sat Sep 17 17:00:45 2005 From: dify.ltd at gmail.com (dify.ltd at gmail.com) Date: 17 Sep 2005 14:00:45 -0700 Subject: disabling TCP connections, just for one script In-Reply-To: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> References: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> Message-ID: <1126990845.367457.306610@g47g2000cwa.googlegroups.com> >From the post I gather that you are looking for a solution under Linux. I don't know much linux, but under Windows you could patch the IAT (import address table) of the running process temporarly to redirect calls to the socket winsock api to a stup function, which simply fails. If you are interested, drop me a letter. From n00m at narod.ru Fri Sep 9 03:00:49 2005 From: n00m at narod.ru (n00m) Date: 9 Sep 2005 00:00:49 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126129942.736374.260770@g44g2000cwa.googlegroups.com> <1126161203.409605.27880@f14g2000cwb.googlegroups.com> <1126196908.479379.22010@z14g2000cwz.googlegroups.com> <1126201801.250692.27750@f14g2000cwb.googlegroups.com> Message-ID: <1126249249.489265.35100@o13g2000cwo.googlegroups.com> Bravo, Bryan! Looks very neat! (pity I can't give it a try in my Py 2.3.4 because of reversed() and sorted() functions) And I've submitted it but got ... TLEs: http://spoj.sphere.pl/status/SUPPER/ Funnily, the exec.time of the best C solution is only 0.06s! PS In my 1st submission I overlooked that your code handles only 1 testcase (there are 10 of them); hence its 0.13s exec. time. PPS This is the code's text I submitted: #!/user/bin/env python from sys import stdin def one_way(seq): n = len(seq) dominators = [n + 1] * (n * 1) # dominators[j] is lowest final value of any increasing sequence of # length j seen so far, as we left-right scan seq. score = [None] * n end = 0 for (i, x) in enumerate(seq): # Binary search for x's place in dominators low, high = 0, end while high - low > 10: mid = (low + high) >> 1 if dominators[mid] < x: low = mid + 1 else: high = mid + 1 while dominators[low] < x: low += 1 dominators[low] = x score[i] = low end = max(end, low + 1) return score def supernumbers(seq): forscore = one_way(seq) opposite = [len(seq) - x for x in reversed(seq)] backscore = reversed(one_way(opposite)) score = map(sum, zip(forscore, backscore)) winner = max(score) return sorted([seq[i] for i in range(len(seq)) if score[i] == winner]) for tc in range(10): _ = stdin.readline() sequence = [int(ch) for ch in stdin.readline().split()] supers = supernumbers(sequence) print len(supers) for i in supers: print i, From max at alcyone.com Tue Sep 13 17:59:44 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 13 Sep 2005 14:59:44 -0700 Subject: Printing w/o newlines inside loops - odd behavior In-Reply-To: <1126648452.814304.139740@g44g2000cwa.googlegroups.com> References: <1126648452.814304.139740@g44g2000cwa.googlegroups.com> Message-ID: <59WdnX2UhoJI1rreRVn-hw@speakeasy.net> Jeffrey E. Forcier wrote: > Doing multiple print statements inside a for loop, using the 'comma at > the end eats the newline' variant, results in zero output until the > loop completes its entire iteration. sys.stdout is line buffered. Put an intervening sys.stdout.flush() in between your prints. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Substance is one of the greatest of our illusions. -- Sir Arthur Eddington From nothingcanfulfill at gmail.com Tue Sep 27 22:59:48 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 27 Sep 2005 19:59:48 -0700 Subject: __call__ in module? References: <1127855953.687066.235740@g43g2000cwa.googlegroups.com> Message-ID: <1127876388.067134.27390@g49g2000cwa.googlegroups.com> My thanks to you and Fredrik Lundh for the quality replies. however much so, I appreciate your moreso descriptive reply. I probably should've been a little more specific in my original query, and have stated that I *did* try it before I posted here asking for help. I was just hoping somebody would be able to prove my test wrong. Oh well, have a good day -Wes From mikael.x.larsson at tele2.se Fri Sep 16 12:10:53 2005 From: mikael.x.larsson at tele2.se (Mikael Larsson) Date: Fri, 16 Sep 2005 18:10:53 +0200 Subject: xml2schema Message-ID: <432AEE8D.3000408@tele2.se> Hi Is there any python tool to generate a schema from xml ?? //Mike From kay.schluehr at gmx.net Tue Sep 20 03:35:13 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Sep 2005 00:35:13 -0700 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <1127201713.955250.39430@g49g2000cwa.googlegroups.com> Fredrik Lundh wrote: > bearophileHUGS at lycos.com wrote: > > > On Slashdot there is a discussion about the future C#3.0: > > http://developers.slashdot.org/developers/05/09/18/0545217.shtml?tid=109&tid=8 > > > > http://msdn.microsoft.com/vcsharp/future/ > > "The extensions enable construction of compositional APIs that > have equal expressive power of query languages in domains such > as relational databases and XML." > > > There are many differences, but it looks a bit more like Python: > > http://download.microsoft.com/download/9/5/0/9503e33e-fde6-4aed-b5d0-ffe749822f1b/csharp%203.0%20specification.doc > > meanwhile, over in python-dev land: > > "Is anyone truly attached to nested tuple function parameters; 'def > fxn((a,b)): print a,b'? /.../ > > Would anyone really throw a huge fit if they went away? I am willing > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > people are up for it." > > I won't get nervous if they will be refused in their poor current state but I would get excited if they will be extended to something becoming close to algebraic data types enabling pattern matching. Maybe it's an irony of the Python development process that it tries to refuse functional programming facilities in just a moment where mainstream languages start to embrace them. Besides C# also VisualBasic gets improved: http://lambda-the-ultimate.org/node/view/967 For the Java platform Scala raises some attention too, after the failure of the Java design team of integrating generics in a clean and comprehensible way with the existing language. Here is Scalas attempt for pattern matching called "case classes": http://scala.epfl.ch/intro/caseclasses.html I do think that gimmicks, syntax permutations and refusals of so called "Python warts" are not sufficient to preserve language attraction in a competing field that tries to make fast progress. Kay From ms at cerenity.org Thu Sep 8 13:56:14 2005 From: ms at cerenity.org (Michael Sparks) Date: Thu, 08 Sep 2005 18:56:14 +0100 Subject: Video display, frame rate 640x480 @ 30fps achievable? References: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> Message-ID: <43207b2e$0$97137$ed2619ec@ptn-nntp-reader03.plus.net> Guenter wrote: > I need to develop an application that displays video 640x480 16-bit per > pixel with 30 fps .... it is possible to achieve that frame rate and still > have some resources for other processing left? Yes. Co-incidentally we've been looking at video playback this week as well. We've been using Pygame with an Overlay surface, and it works fairly well. Initially we're testing with simple IYUV raw video data, and it's a good idea to use a modern video card supported by your OS, but other than that we've not had problems. If you're interested in code, let us know :-) If you end up using the framebuffer device in linux under xorg's X11 (not exactly an ideal setup for video playback anyway!) there is a little oddity that we found, due to SDL underneath, but we've been able to work around that. The system I'm working on normally has that issue, and as a result isn't accelerated and is a 1.6Ghz machine, but can do standard defintion video (720x576) playback happily at >30fps. Normally though most people can offload this to their graphics card so there shouldn't be issues on your 1Ghz machine. Clearly if you're interested in driving that you need to decode some data source to IYUV, but that's a different issue. People have embedded pygame in wxPython before (I don't know how though, I've only seen screenshots of the integration) so although you said wxPython and might've discounted pygame based on that, it might still be suitable for you. Regards, Michael. From dwelch at vcd.hp.com Thu Sep 8 13:46:03 2005 From: dwelch at vcd.hp.com (djw) Date: Thu, 08 Sep 2005 10:46:03 -0700 Subject: Printer List from CUPS In-Reply-To: <1126175587.426865.138130@g14g2000cwa.googlegroups.com> References: <1126175587.426865.138130@g14g2000cwa.googlegroups.com> Message-ID: <4320793d$1@usenet01.boi.hp.com> Mike Tammerman wrote: > Hi, > > I want to get the printer list from CUPS. I found some ways using > > lpstat -p and > http://localhost:631/printers > > but, these ways require some parsing and I am not sure, if the parsing > works all the time. A pythonic way would be very helpful. > > Thanks, > Mike > The HPLIP project (hpinkjet.sf.net) includes a basic CUPS extension module in the src/prnt/cupsext directory. Its pretty rough, but it will return a list of CUPS printers easily enough. I am in the process of rewriting it in Pyrex and hope to include more complete CUPS API coverage. -Don From presentt at gmail.com Wed Sep 7 00:31:52 2005 From: presentt at gmail.com (presentt) Date: 6 Sep 2005 21:31:52 -0700 Subject: ~ after script filename? In-Reply-To: References: <1126065469.212137.264680@g49g2000cwa.googlegroups.com> Message-ID: <1126067512.772173.141580@g47g2000cwa.googlegroups.com> Huh, no ~ on other files when I edit them, but at least I don't have to worry about it. Thanks Aldo. From gerrit at nl.linux.org Sat Sep 24 10:01:49 2005 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 24 Sep 2005 16:01:49 +0200 Subject: Programming languages "national brotherhood week" Message-ID: <20050924140149.GA6644@topjaklont.student.utwente.nl> Hi, I have once seen a variant of "national brotherhood week" with programming languages; 'all the python folk hate alle the perl folk and all the ... hate all the ... and everybody hates Java', or something like that, but I can't find it anymore. Does anyone remember it and is anyone able to find it? It was quite funny, I think it was more than five years ago though. Gerrit. -- Temperature in Lule?, Norrbotten, Sweden: | Current temperature 05-09-24 15:59:53 12.1 degrees Celsius ( 53.9F) | -- Det finns inte d?ligt v?der, bara d?liga kl?der. From skip at pobox.com Thu Sep 29 05:38:34 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 29 Sep 2005 04:38:34 -0500 Subject: A quick c.l.p netiquette question In-Reply-To: <37mzlwcka6.fsf@chiark.greenend.org.uk> References: <37mzlwcka6.fsf@chiark.greenend.org.uk> Message-ID: <17211.46618.713204.171596@montanaro.dyndns.org> Peter> About how short should a program be to be postable to this Peter> newsgroup - in other words, at what length should you stick it on Peter> a web page and post a link? 158 lines is probably not a killer. However, consider what misbehaving news and mail readers are likely to do to the indentation of your script before embedding it in a message. The net being the somewhat less safe place than it used to be, many people may be hesitant to open attachments either. It might well be safer to simply toss it on a personal website and provide a link. Skip From peter at engcorp.com Thu Sep 22 16:51:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Sep 2005 16:51:14 -0400 Subject: Wrapping classes In-Reply-To: References: Message-ID: <35CdnQgRcKzchK7eRVn-2A@powergate.ca> Jeremy Sanders wrote: > Is it possible to implement some sort of "lazy" creation of objects only > when the object is used, but behaving in the same way as the object? > > For instance: > > class Foo: > def __init__(self, val): > """This is really slow.""" > self.num = val > > # this doesn't call Foo.__init__ yet > a = lazyclass(Foo, 6) > > # Foo is only initalised here > print a.num > > What I really want to do is make an object which looks like a numarray, > but only computes its contents the first time it is used. Almost anything is possible in Python, though whether the underlying design idea is sound is a completely different question. (Translation: try the following pseudo-code, but I have my suspicions about whether what you're doing is a good idea. :-) ) class lazyclass(object): '''should probably be called lazyobject though...''' def __init__(self, class_, *args, **kwargs): self.class_ = class_ self.args = args self.kwargs = kwargs self.obj = None def _getnum(self): if self.obj is None: self.obj = self.class_(*args, **kwargs) return self.obj.num num = property(_getnum) Now that "should" do precisely what you've asked for above, though it is obviously very limited in supporting only a single attribute name even though the __init__ method is somewhat generalized. I didn't try testing the code so there could be typos. -Peter From hancock at anansispaceworks.com Fri Sep 9 11:03:40 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 9 Sep 2005 10:03:40 -0500 Subject: Inconsistent reaction to extend In-Reply-To: References: Message-ID: <200509091003.40458.hancock@anansispaceworks.com> On Friday 09 September 2005 08:29 am, Steve Holden wrote: > Yes it is :) That's not an argument! That's just a contradiction. I'm not payin' for this! -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From larry.bates at websafe.com Wed Sep 21 09:38:27 2005 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 21 Sep 2005 08:38:27 -0500 Subject: What am I doing wrong? In-Reply-To: References: Message-ID: <43316253.7050407@websafe.com> You have been bitten by a well known "feature". You used a mutable as default value in your argument list for __init__. See: http://www.nexedi.org/sections/education/python/tips_and_tricks/python_and_mutable_n/view It would be better to write: class structure: def __init__(self, folders = None): self.folders=folders or [] -Larry Bates keithlackey wrote: > I'm relatively new to python and I've run into this problem. > > > DECLARING CLASS > > class structure: > def __init__(self, folders = []): > self.folders = folders > > def add_folder(self, folder): > self.folders.append(tuple(folder)) > > > > Now I try to make an instance of this class > > structure1 = structure() > structure1.add_folder([('foo'),]) > print structure1.folders > > This returns: [('foo',)] > > This works fine. But when I try to make another instance of that class... > > structure2 = structure() > print structure2.folders > > This now also returns: [('foo',)] > Even though I haven't added any folders to this new instance > > What am I doing wrong? > From mark.dufour at gmail.com Mon Sep 12 09:11:53 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Mon, 12 Sep 2005 15:11:53 +0200 Subject: First release of Shed Skin, a Python-to-C++ compiler. Message-ID: <8180ef690509120611513ad8e8@mail.gmail.com> >Obviously, neither the 0 nor the message following should have been >displayed. It's a pity that this assumption was made, but given the short >time the project's been going I can understand it, hopefully Mark will >continue towards greater python compliance :) The latter is certainly my goal. I just haven't looked into supporting exceptions yet, because I personally never use them. I feel they should only occur in very bad situations, or they become goto-like constructs that intuitively feel very ugly. In the 5500 lines of the compiler itself, I have not needed to use a single exception. For example, I prefer to check whether a file exists myself, rather than executing code that can suddenly jump somewhere else. There's probably some use for exceptions, but I don't (want to?) see it. Seeing how often exceptions are used by other people though, it's probably one of the first things I should look into.. :-) thanks! mark. From mwm at mired.org Sat Sep 3 21:46:22 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 03 Sep 2005 21:46:22 -0400 Subject: global interpreter lock References: <86slwymx79.fsf@bhuda.mired.org> <7xoe7kjsag.fsf@ruckus.brouhaha.com> <3dpQe.22$tz6.13@newssvr27.news.prodigy.net> <861x4dy77g.fsf@bhuda.mired.org> <864q98b7k0.fsf@bhuda.mired.org> <43149abd.168178447@news.oz.net> <86ek897bih.fsf@bhuda.mired.org> Message-ID: <86r7c538r5.fsf@bhuda.mired.org> Dennis Lee Bieber writes: > On Wed, 31 Aug 2005 22:44:06 -0400, Mike Meyer declaimed > the following in comp.lang.python: >> I don't know what Ada offers. Java gives you pseudo-monitors. I'm > > From the days of mil-std 1815, Ada has supported "tasks" which > communicate via "rendezvous"... The receiving task waits on an "accept" > statement (simplified -- there is a means to wait on multiple different > accepts, and/or time-out). The "sending" task calls the "entry" (looks > like a regular procedure call with in and/or out parameters -- matches > the signature of the waiting "accept"). As with "accept", there are > selective entry calls, wherein which ever task is waiting on the > matching accept will be invoked. During the rendezvous, the "sending" > task blocks until the "receiving" task exits the "accept" block -- at > which point both tasks may proceed concurrently. Thank you for providing the description. That was sufficient context that Google found the GNAT documentation, which was very detailed. Based on that, it seems that entry/accept are just a synchronization construct - with some RPC semantics thrown in. > As you might notice -- data can go both ways: in at the top of the > rendezvous, and out at the end. > > Tasks are created by declaring them (there are also task types, so > one can easily create a slew of identical tasks). > > procedure xyz is > > a : task; -- not real Ada, again, simplified > b : task; > > begin -- the tasks begin execution here > -- do stuff in the procedure itself, maybe call task entries > end; The problem is that this doesn't really provide any extra protection for the programmer. You get language facilities that will provide the protection, but the programmer has to remember to use them in every case. If you forget to declare a method as protected, then nothing stops two tasks from entering it and screwing up the objects data with unsynchronized access. This should be compared to SCOOP, where trying to do something like that is impossible. Thanks again, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From morrismosseri at gmail.com Sun Sep 4 18:10:43 2005 From: morrismosseri at gmail.com (pythonprogrammer) Date: 4 Sep 2005 15:10:43 -0700 Subject: GETTING IMAGEDATA FROM A BUTTON Message-ID: <1125871843.559395.3300@g14g2000cwa.googlegroups.com> Does anyone know how to get pixeldata from the image of a button without taking a screenshot? From billiejoex at fastwebnet.it Sun Sep 11 19:36:35 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Mon, 12 Sep 2005 01:36:35 +0200 Subject: pinging from within python References: Message-ID: Impacket module can helps you to construct the ip/icmp packet structure, then you can send the packet and wait for the ECHOREPLY by using a RAW_SOCKET. Here's an example: http://oss.coresecurity.com/impacket/ping.py Cheers > I need a simple script to run the ping command with some parameters and be > able to read the return value of the ping function. Any pointers will be > appreciated > > thanks > m.smadi From jeremy+complangpython at jeremysanders.net Fri Sep 23 06:57:07 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 23 Sep 2005 11:57:07 +0100 Subject: Wrapping classes References: <35CdnQgRcKzchK7eRVn-2A@powergate.ca> <3pi37tFa7ibaU1@uni-berlin.de> <4333defe$0$20963$636a15ce@news.free.fr> Message-ID: bruno modulix wrote: > Could it work with a UserDict subclass ? Unfortunately not: Traceback (most recent call last): File "test.py", line 17, in ? print eval("10 * a + b", globals(), l) TypeError: eval() argument 3 must be dict, not instance Thanks Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From anirudhpec at gmail.com Sat Sep 10 14:20:47 2005 From: anirudhpec at gmail.com (anirudh) Date: 10 Sep 2005 11:20:47 -0700 Subject: START YOUR OWN BIZMAKING THOUSANDS USING PAYPAL!!!! Message-ID: <1126376447.287334.25780@z14g2000cwz.googlegroups.com> My own business, making hundreds of thousands of dollars, with little investment, could it be that simple??? Just read this. I don't even have to convince you that this is not a scam...because it makes logical sense how you can earn money through PAYPAL. A little while back, I was browsing through a newsgroup, just like you are now and came across an article similar to this that said you could make thousands of dollars within weeks with only an initial investment of $6.00! So I thought, "Doubt that, this must be a scam", but like most of us, I was curious, so I kept reading. OPRAH WINFREY and an article published in the Wall Street Journal on 10/1/2001 both talk about the birth of PAYPAL, and what it has to offer here is some of it, "PayPal allows people and businesses to use electronic mail to send and receive payments, drawing funds from a sender's credit card, bank account or balance in an account at PayPal. As of Sept. 1, PayPal had 10 million user accounts; it completed transactions totaling $746.9 million for the three months ended June 30, its preliminary prospectus states." Everyone has heard about "PayPal" and, when I came across this concept I knew it would work because, as a member of PayPal, I had already experienced their efficiency and excellent standing. PayPal is the simplest method of making and receiving payments online anyone has ever seen! Anyone with an email address can join, for FREE! Please read further before you go there... You can complete this whole process in less than one hour and you will never forget the day you decided to do so!!! Oh, Did I say FAST? By fast I mean ' the speed of the Internet - fast. Everything is done on the Internet by E-mail. And, if you abide by the rules, it's perfectly legal! Now the article said that you send $1.00 through PayPal to each of the emails stated in the article. You then place your own email address in the bottom of the list at #6, and post the article in at least 200 newsgroups. (There are thousands) No catch, that was it. So after thinking it over, I figured what have I got to lose except $6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it: It follows the same regulations as the mailed chain letters, which according to the Post Office (1-800- 725-2161) is indeed legal! Then I invested the $6.00 and Well GUESS WHAT!!?. Within 7 days, I started getting money in my PayPal account! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $20.00. By the end second week I had made a total over $1,200.00! In the third week I had over $9,500.00 and it's still growing. This is now my fourth week and I have made a total of just over $36,000.00 and it's still coming in rapidly. It's Certainly worth $6.00. Let me tell you how this works and most importantly, why it works? Also, make sure you print a copy of this article NOW, so you can get the information you'll need. REQUIREMENTS: You must have a verified PayPal account. If you do not have an account you can go to http://www.paypal.com/ and follow the instructions to set up a free account. In order to place the initial $6 into your account, you will have to verify your bank account with PayPal (which may take a few days). Or if you want to start right away, use your credit or debit card to make the $6 deposit to Paypal. Paypal guarantees your security when using personal information. They do not release your information to third parties. Very, very secure! Paypal is 100% secure and is used my millions of people world-wide. STEP 1: Send, through PayPal, $1.00 to each e-mail address on the list below. Make the subject of the payment "Email List" and in the comments, write "PLEASE PUT ME ON YOUR EMAIL LIST." By stating this you are creating a mailing list, in which you can use to start a small mailing list company, this will be the basis behind your income. THIS IS ABSOLUTELY LEGAL! 1) mindboggling5 at excite.com 2) mikesmam at gmail.com 3) paladinjames at gmail.com 4) tookie_zazu at rediffmail.com 5) hotmail_biz at rediffmail.com 6) anirudhpec at gmail.com STEP 2: Now take the #1 email off the list that you see above, move the other addresses up (6 becomes 5, 5 becomes 4, etc?.) and add YOUR email address (the one you used to set p your PayPal account) as number 6 on the list. STEP 3: Change anything you need to like the date and spelling, but try to keep this article as close to original as possible. Next, post your amended article to at least 200 newsgroups, message board. (There are approximately 32,000 groups) All you need is 200, but remember, the more you post, the more money you make - as well as everyone else on the list! ---- DIRECTIONS---- HOW TO POST TO NEWSGROUPS, MESSAGE BOARD-- Step 1) You do not need to re-type this entire letter to do your own posting. Simply put your cursor at the beginning of this letter and drag your Cursor to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into the computer memory. Step 2) Open a blank 'notepad' file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name to the list. Step 3) Save your new notepad file as a .txt file. If you want to do your postings in different settings, you'll always have this file to go back to. Step 4) Use Netscape or Internet explorer and try searching for various newsgroups (on-line forums, message boards, chat sites, discussions.) {EX. - you log on any search engine like: metacrawler.com, msn.com, yahoo.com, google.com, altavista.com, excite.com then you search with this subject "web discussion" or "money forum" or "money making message board" or "employment message board" or "money making discussions" or "money making forum" or "business message board" etc. You will find thousands and thousands of message boards. Click one by one then you will find the option post a new message. Step 5) Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done with your first one! Be Honest and it will truly work for you. Congratulations! REMEMBER, THE MORE NEWGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200! That is it You will begin receiving money in your account from around the world within days! JUST MAKE SURE ALL THE ADDRESSES ARE CORRECT. WHY 200 postings? Say I receive only 5 replies (a very low estimate). So then I made $5.00 with my name at #6 on the letter. Each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at # 5 and only 5 persons respond to each of the original 5, this is an additional $25.00 for me. Now those 25 each make 200 minimum posts with my name at #4 and only 5 replies each. This brings in an additional $125.00. Those 125 persons turn around and post the MINIMUM 200 with my name at #3 and receive 5 replies each, I will make an additional $625.00. Ok, now here is the FUN part, each of those 625 people post a MINIMUM of 200 letters with my name at #2 and they receive 5 replies each. That just made me $3,125.00!!! Those 3125 persons will all deliver this message to 200 newsgroups with my name at #1 and if still 5 persons per 200 react, I will receive an additional $15,625.00!! With an investment of only $6.00!! A - M - A - Z - I - N - G - !! NOTE: It works much faster without soliciting or spamming and trying to get higher responses*** !!! With warm wishes, bless you and your loved ones! From Scott.Daniels at Acm.Org Tue Sep 20 10:42:48 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 20 Sep 2005 07:42:48 -0700 Subject: zlib written in python In-Reply-To: References: Message-ID: <43300be2$1@nntp0.pdx.net> Andreas Lobinger wrote: > Aloha, > > is a pure _python_ implementation of the zlib available? > I have broken zlib streams and need to patch the deocder to > get them back. > > Wishing a happy day > LOBI > Check your zlib version: import zlib; print zlib.ZLIB_VERSION There were some fixes you can see described at 'http://www.zlib.net/' that are going into python 2.5. If you can figure it out yourself, you could build an alternative zlib module to either sit beside /DLLs/zlib.pyd or replace it. --Scott David Daniels Scott.Daniels at Acm.Org From TechAlerts at gmail.com Mon Sep 26 08:09:24 2005 From: TechAlerts at gmail.com (Kanthi Kiran Narisetti) Date: 26 Sep 2005 05:09:24 -0700 Subject: good exercises for Beginner Message-ID: <1127736564.520990.3580@g14g2000cwa.googlegroups.com> Hi ALL, I am new to programming and python. In my quest to get good at programming, even when I am able to get through the python tutorials I feel for lack of exercises & examples that emphasises the programming logic skills. The examples are just introduction to particular definition of the concepts. I would appreciate if any one provide me the resources to find such exercise(irrespective of Programming language) , working on which would help to build to skills in programming for problem solving which is more critical. any tutorials or online links and also advise for newbie are highly appreciated Thank You in advance. Kanthi Narisetti From Sebastien.Boisgerault at gmail.com Fri Sep 9 06:40:58 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 9 Sep 2005 03:40:58 -0700 Subject: sys.stdout In-Reply-To: References: <1126255685.873523.293080@o13g2000cwo.googlegroups.com> <1126259024.967722.205860@g44g2000cwa.googlegroups.com> Message-ID: <1126262458.339724.237780@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > S?bastien Boisg?rault wrote: > > > Thanks for your answer. The execution of your example leads to a > > 'aaa' display during 2 secs, before it is erased by the prompt. > > > > This behavior is standard ? The standard output is not supposed > > to *concatenate* the 'aaa' and the '>>>' ? > > what "python shell" are you using, and what platform are you running > it on? The python interpreter is invoked from a bash/konsole session, inside a KDE env.: bash$ python Python 2.4.1 (#4, Sep 8 2005, 19:11:54) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> > here's what I get on a standard Unix console: > > >>> import sys > >>> sys.stdout.write("AAAA") > AAAA>>> sys.stdout.write("BBBB\n") > BBBB > >>> sys.stdout.write("CCCC\nDDDD") > CCCC > DDDD>>> > > Yep. And I hate you for this ;) Cheers, SB From steve at REMOVETHIScyber.com.au Wed Sep 14 08:05:01 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 14 Sep 2005 22:05:01 +1000 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <7xwtlkrs4c.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 14 Sep 2005 01:05:55 -0700, Paul Rubin wrote: > There's a famous paper by John Hughes called "Why Functional > Programming Matters" that (cheap oversimplification) says you should > never modify the value of any variable. So, no increments, not even > for loops (use recursion instead). Which works wonderfully as an academic exercise, but doesn't tend to work so terribly well in the real world where the performance and resource-requirement differences between iteration and recursion can be significant. For instance, try these two simple functions for the nth number in the Fibonacci sequence: def fibr(n): "Recursive version of Fibonacci sequence." if n == 0: return 0 elif n == 1: return 1 else: return fibr(n-1) + fibr(n-2) def fibi(n): "Simple iterative version of Fibonacci sequence." if n == 0: return 0 elif n == 1: return 1 else: Fn2 = 0 Fn1 = 1 for _ in range(2, n+1): s = Fn2 + Fn1 Fn2, Fn1 = Fn1, s return s Try timing how long it takes to generate the 30th Fibonacci number (832040) using both of those algorithms. Now try the 50th. (Warning: the amount of work done by the recursive version increases at the same rate as the Fibonacci sequence itself increases. That's not quite exponentially, but it is fast enough to be very painful.) -- Steven. From nomail at nomail.com Thu Sep 8 11:14:57 2005 From: nomail at nomail.com (Nx) Date: Thu, 08 Sep 2005 23:14:57 +0800 Subject: Installation question References: <431d93ce@127.0.0.1> <1126099236.656545.319500@g43g2000cwa.googlegroups.com> Message-ID: <4320553a@127.0.0.1> Thanks anyway I wished there was a sure step by step approach to get it to work but I can't think of any good solution and I do not want to reinstall a well optimized system if something goes astray. Nx From berthold at despammed.com Tue Sep 27 11:48:47 2005 From: berthold at despammed.com (=?iso-8859-15?q?Berthold_H=F6llmann?=) Date: Tue, 27 Sep 2005 17:48:47 +0200 Subject: Python 2.4 under WinXP, free VC71 toolkit and VC6 libraries Message-ID: I have wrapped some inhouse libraries for Python. The development team uses VC6 and DF6.1 for development of these libraries under WinXP. I would like to wrap the libraries for Python and use the official Win Python from python.org. Now I get a segmentation fault in (access violation in NTDLL.DLL). The code used to work on Python 2.3, so I am afraid I have a plroblem in mixing the code generated by different VC versions. Is this the probable cause of my problem, or should the combination work in general (some libraries seem to work). Kind regards Berthold -- __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From fredrik at pythonware.com Thu Sep 8 07:26:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 8 Sep 2005 13:26:46 +0200 Subject: reading the last line of a file References: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> <1126168591.395956.118840@z14g2000cwz.googlegroups.com><4320046F.1040606@gatwick.westerngeco.slb.com> Message-ID: Fredrik Lundh wrote: > zcat|tail is a LOT faster. and here's the "right way" to use that: from subprocess import Popen, PIPE p1 = Popen(["zcat", filename], stdout=PIPE) p2 = Popen(["tail", "-1"], stdin=p1.stdout, stdout=PIPE) last_line = p2.communicate()[0] (on my small sample, this is roughly 15 times faster than the empty for loop) From twic at urchin.earth.li Mon Sep 26 15:16:01 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 26 Sep 2005 20:16:01 +0100 Subject: Metaclasses, decorators, and synchronization In-Reply-To: References: Message-ID: On Mon, 26 Sep 2005, Jp Calderone wrote: > On Sun, 25 Sep 2005 23:30:21 -0400, Victor Ng wrote: >> You could do it with a metaclass, but I think that's probably overkill. >> >> It's not really efficient as it's doing test/set of an RLock all the >> time, but hey - you didn't ask for efficient. :) > > There's a race condition in this version of synchronized which can allow two > or more threads to execute the synchronized function simultaneously. You could define a meta-lock, and use that to protect the lock-installation action. To avoid bottlenecking on the single meta-lock, you could put a meta-lock in each class, and use that to protect installation of locks in instances of that class. You would, of course, then need a meta-meta-lock to protect those. Also, and more helpfully, you can get a modest speedup by taking out the explicit test for the presence of the lock, and just rely on getting an AttributeError from self._sync_lock.acquire() if it's not there; you could then install the lock in the except suite. tom -- 90% mental, 25% effort, 8% mathematics From tjreedy at udel.edu Wed Sep 28 19:31:18 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2005 19:31:18 -0400 Subject: Fixes since 2.4.2c1? (was: RELEASED Python 2.4.2 (final)) References: <5hkr03-jo6.ln1@nb2.stroeder.com> Message-ID: "Michael Str?der" wrote in message news:5hkr03-jo6.ln1 at nb2.stroeder.com... > Does that differ from 2.4.2c1? On Monday I noticed a crash in the test > suite on a box running Solaris 8. It seems I can build Python 2.4.1 and > run make test there without problems. There were are few additional fixes that Anthony thought were simple enough to release after whatever 'in-house' testing but without a c2 release. > But being busy during the last days I did not have the time to track it > down and report a bug... :-/ Apparently, no one else reported much of anythong either... If necessary, 2.4.3 will come sooner than currently planned. Terry J. Reedy From timr at probo.com Sat Sep 10 02:47:26 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 09 Sep 2005 23:47:26 -0700 Subject: nested tuples References: <3oe39jF5jbvsU1@individual.net> Message-ID: "Luis P. Mendes" wrote: > >I'm trying to solve this problem: > >suppose I'm reading a csv file and want to create a tuple of all those >rows and values, like ((row1value1, row1value2, row1value3),(row2value1, >row2value2, row2value3),..., (rowNvalue1, rowNvalue2, rowNvalue3)) > >I haven't found the way to do it just using tuples. How can I do it? > >Nevertheless, I can solve it like this: >a=[] > >for row in reader: >~ elem = (row[0],row[1],row[2]) >~ a.append(elem) > >which will result in a list of tuples: [(row1value1, row1value2, >row1value3),(row2value1, row2value2, row2value3),..., (rowNvalue1, >rowNvalue2, rowNvalue3)] > >Then, I get what I want with tuple(a). Why? What is it about the list of tuples that you don't like? Philosophically, it's more in line with Guido's separation of list and tuple. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From c at cdot.de Wed Sep 7 08:22:03 2005 From: c at cdot.de (Chris) Date: Wed, 07 Sep 2005 14:22:03 +0200 Subject: __dict__ of object, Was: Regular Expression IGNORECASE differentfor findall and split? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Chris wrote: > > >>but more of a basic question following, I was doing the following before: >> >>method = 'split' # came from somewhere else of course >>result = re.__dict__[method].(REGEX, TXT) >> >>precompiling the regex >> >>r = compile(REGEX) >> >>does give an regex object which has the needed methods >> >>print dir(r) >>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', >>'search', 'split', 'sub', 'subn'] >> >>but how do I evaluate them without explicitly calling them? >> >>result = r.__???MAGIC???__[method](TXT) >> >>obviously I am not a Python pro ;) > > > I really don't understand why you think you have to write > your RE code that way, but the mechanism you're looking > for is getattr: > > result = getattr(r, method)(TXT) > thanks (also to Steven) for the info, that is exactly what i was looking for. reason is that I built a small UI in which the user may choose if he want to do a split, findall (and maybe later others like match or search). So the method name comes in "from the UI". I could of course use if/elif/else blocks but thought getattr should be shorter and easier. I was not really aware of getattr which I was looking for on other occations before... chris From pink at odahoda.de Thu Sep 1 06:49:41 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Thu, 01 Sep 2005 12:49:41 +0200 Subject: Decrypting GPG/PGP email messages References: Message-ID: Alessandro Bottoni wrote: > I know you will shake you head sadly but... I really have to perform such > a suicidal task (even if for a short time and just for internal use). > > I have to send by email (over the open internet) a XML file containing > _system commands_ (yes: the kind of stuff like "rm -dfr /") to a server > and have a Python program sitting on this server, fetching and parsing the > e-mail message and executing the commands (maybe with _root privileges_). > > Of course, I want to be sure that only the allowed people is able to send > such dangerous messages to my server so I will ask my users to encrypt and > digitally sign their messages using Thunderbird, Enigmail and GPG as > described in this very fine tutorial: > > http://goldenspud.com/webrog/archives/2005/03/10/encrypt-encrypt/ > > So far, so good, but I still have a couple of doubts about the server > side: > > 1) What would you use to decrypt the messages? The GPG module created by > Andrew Kuchling is declared "incomplete" and "no more maintained" on his > web pages (http://www.amk.ca/python/code/gpg) so I think it is out of the > game. Would you use OpenPGP (http://www.aonalu.net/openpgp/python)? Any > other module? What about using the command line program via os.pipeX("gpg...")? I've done it this way when I needed to _create_ encrypted mail attachments using python (you'll need different gpg options for decrypting): pipe_in, pipe_out = os.popen2("/usr/bin/gpg -q -r KEYID -s" "--passphrase-fd 0 --batch --no-tty -a -o - -e '%s'" % path_to_temporary_file) pipe_in.write("passphrase") pipe_in.close() # read encrypted file from pipe_out pipe_out.close() > 2) I did not find any mention of _encrypted attachments_ on the Net. Does > anybody know of a tutorial or a guide that explains how to encrypt (with > Thunderbird/Enigmail) and decrypt (with Python) the (ANSI text) files > attached to a email message? I can't help you with Thunderbird. In the worst case, you'll have to encrypt your command file manually and attach the encrypted version to your mail. KMail does have checkboxes for encrypt/sign every attachment separately... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From trapeze.jsg at gmail.com Fri Sep 23 04:52:50 2005 From: trapeze.jsg at gmail.com (trapeze.jsg at gmail.com) Date: 23 Sep 2005 01:52:50 -0700 Subject: Python argv and special characters References: <1127461767.657015.305770@g49g2000cwa.googlegroups.com> Message-ID: <1127465570.425772.162880@o13g2000cwo.googlegroups.com> thanks :-) It seems a little overkill though, is it really the only/best way? From philippe at philippecmartin.com Tue Sep 6 12:27:37 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 06 Sep 2005 16:27:37 GMT Subject: which reg values modified my python installer under windows Message-ID: Hi, I am looking for the reg path that is modified/created by the pyton installer to associate *.pyc with python.exe as I wish to associate *.pyc with pythonw.exe Regards, Philippe From flamesrock at gmail.com Wed Sep 7 23:56:28 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Sep 2005 20:56:28 -0700 Subject: Django Vs Rails In-Reply-To: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> Message-ID: <1126151788.691736.42500@g49g2000cwa.googlegroups.com> Wow- thanks for all of the replies. I'm torn. On the one hand, I'm fluent in Python and love it. On the other, Rails seems to have a brighter future, and is a bit more featureful (at this time.) However the only Ruby I know is what I've already learnt with Python(even though I would like to learn it). How difficult would it be to learn Ruby+Rails, assuming that someone is already skilled with Python? Is it worth it? From lambacck at computer.org Thu Sep 15 17:03:14 2005 From: lambacck at computer.org (Chris Lambacher) Date: Thu, 15 Sep 2005 17:03:14 -0400 Subject: IDE, widget library In-Reply-To: References: Message-ID: <20050915210314.GB25844@computer.org> PyGTK works beatifully on Win32. If you want anything more than the generic GTK widgets on win32 you are going to have to jump through some hoops or not be successful. I tend to hate the GTK file chooser so I am using win32all to get the Native windows one. There is no print dialog and win32all does not help with this. If you want an embedded HTML renderer the only one that I know of is GTKMozEmbed which is a bit of a big beast. WxPython has better support for Win32, but does not have a very pythonic interface. Wax or Dabo may help you out with this. -Chris On Thu, Sep 15, 2005 at 09:39:46PM +0200, Thomas Jollans wrote: > I guess questions like this come all the time here ... well: > > I a looking for a python IDE for gnu/linux that : > - has decent sytax highlighting (based on scintilla would be neat) > - has basic name completition, at least for system-wide modules > - has an integrated debugger > - is open source, or at least free of charge > > an integrated GUI designer would of course be cool, but cannot be > counted as a requirement. > > With that I come to the second question: > What cross-platform GUI libraries are there ? cross-platform meaning > functional and free on (at least) X11 and Win32 > PyQT obviously doesn't count because qt3 is not free on windows. > Tk is ugly. (how well) is Tile supported with python ? > does PyGTK/Glade work on win32 ? > -- > http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Mon Sep 5 14:40:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 Sep 2005 14:40:59 -0400 Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga><431c2f84$1@nntp0.pdx.net> <7xu0gz31ha.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xu0gz31ha.fsf at ruckus.brouhaha.com... > Along with fixing the GIL, I think PyPy needs to give up on this > BASIC-style reference counting and introduce real garbage collection. > Lots of work has been done on concurrent GC and the techniques for it > are reasonably understood by now, especially if there's no hard > real-time requirement. I believe that gc method (ref count versus other) either is now or will be a PyPy compile option. Flexibility in certain implementation details leading to flexibility in host systems is, I also recall, part of their EC funding rationale. But check their announcements, etc., for verification and details. Terry J. Reedy From notmuch at gmail.com Tue Sep 20 20:28:53 2005 From: notmuch at gmail.com (chanchal) Date: 20 Sep 2005 17:28:53 -0700 Subject: python script under windows In-Reply-To: <1127227943.780638.227170@g43g2000cwa.googlegroups.com> References: <1127227943.780638.227170@g43g2000cwa.googlegroups.com> Message-ID: <1127262533.419950.95050@g47g2000cwa.googlegroups.com> typo, the correct command is: c:\>python MyService.py -startup=auto install From darkpaladin79 at hotmail.com Sun Sep 25 19:41:38 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Sun, 25 Sep 2005 19:41:38 -0400 Subject: Carrying variables over from function to function Message-ID: Alright heres my problem. . .Say I want to carry over a variable from one function to another or even another run of the same function. Is that possible? Heres a quick example of what I'm talking about. def abc(): x = 1 y = x + 1 print y def abcd(): y = x + 1 print y abc() abcd() the output would be: >>>abc() 2 >>>abcd() Traceback (most recent call last): File "(stdin)", line 1, in ? File "(stdin)", line 2, in abcd NameError: global name 'x' is not defined >>> See, I want y in the second function to equal 4, carrying the x from the first function over to the next. Is there any way to do this? -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From enleverlesO.OmcO at OmclaveauO.com Thu Sep 29 16:56:26 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Thu, 29 Sep 2005 22:56:26 +0200 Subject: pyMinGW support for Python 2.4.2 (final) is available References: <1127934999.819068.173350@g43g2000cwa.googlegroups.com> <3q0a4bFcj6rfU1@individual.net> <1127937766.926236.320010@o13g2000cwo.googlegroups.com> Message-ID: <433c5663$1$4328$626a14ce@news.free.fr> Hi ! No problem for me, with IE-6 + FlashGet (just to choose right-click + record target) @-salutations Michel Claveau From jzgoda at o2.usun.pl Thu Sep 8 16:27:40 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 08 Sep 2005 22:27:40 +0200 Subject: Python Jabber client? In-Reply-To: <7x1x3zmii2.fsf_-_@ruckus.brouhaha.com> References: <7x1x3zmii2.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin napisa?(a): > Is there such a thing as a general purpose Python Jabber client? I'm > imagining one that uses tkinter. > > A little Googling finds a couple of Jabber protocol libraries written > in Python, a few half-finished projects, and a client> > If there's more than one, does anyone have a favorite? Gajim is most advanced one, if you don't mind GUI. There are also few CLI XMPP/Jabber clients, but most of them is *x-limited. As for libs, there are 2 that are worth of attention: xmpp.py, which has very slow pace of advancement (most current version is available from Gajim svn repo, sigh!) and PyXMPP, which is very limited in usage due to use of libxml, which makes porting to Windows a real PITA. If you want a decent library, get the one from Gajim repo, it is not as standard compliant as PyXMPP (PyXMPP author is a JSF member), but is really and true cross platform. -- Jarek Zgoda http://jpa.berlios.de/ From fredrik at pythonware.com Thu Sep 29 17:41:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 23:41:02 +0200 Subject: python's performance References: <90DEA7ED93F71A4580CEDF76A02682EA03ACA3@torexch.metrigenix.com> <797fe3d405092914194897f1a5@mail.gmail.com> Message-ID: > > Have u been used such camera with PIL before? > > > > im_1= Image.fromstring("I", datasize, buf, 'raw', 'I;16') running on a 700 MHz box: c:\> timeit -s "import Image" -s "data = 1344*1024*2*'x'" "im = Image.fromstring('I', (1344, 1024), data, 'raw', 'I;16')" 10 loops, best of 3: 102 msec per loop running on a 3.0 GHz box: c:\> timeit -s "import Image" -s "data = 1344*1024*2*'x'" "im = Image.fromstring('I', (1344, 1024), data, 'raw', 'I;16')" 10 loops, best of 3: 34.7 msec per loop I somehow doubt that this takes 1 full second on a 2.0 GHz PC. From max at alcyone.com Fri Sep 30 18:42:27 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 30 Sep 2005 15:42:27 -0700 Subject: [Info] PEP 308 accepted - new conditional expressions In-Reply-To: <0qh%e.20023$Ix4.15230@okepread03> References: <3q4ro9Fd770nU3@individual.net> <0qh%e.20023$Ix4.15230@okepread03> Message-ID: Dave Benjamin wrote: > Hooray! After years of arguing over which syntax to use, and finally > giving up since nobody could agree, the Benevolent Dictator did what > only a dictator can do, and just made a damn decision already. > > Thank you, Guido! =) Yes, hear hear. So what made him change his mind? When the debates raged over PEP 308, he seemed pretty dead set against it (at least by proxy) ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The great artist is the simplifier. -- Henri Amiel From siona at chiark.greenend.org.uk Fri Sep 30 11:33:47 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Sep 2005 16:33:47 +0100 (BST) Subject: What python idioms for private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <3f11a$433bf55e$d8c4f6e6$10834@FUSE.NET> Message-ID: Michael Schneider wrote: >I have been coding in C++ since the late 80's and Java since the late 90's. > >I do use private in these languages, with accessors to get at internal >data. > >This has become an ingrained idiom for me. The question is, has it become a purely instinctive idiom, or are you getting real benefit from it? My experience over a similar length of time (well, maybe not quite so long with C++) is that private is far more likely to hinder than help, and that protected is a more sensible state for things which aren't on the public interface. And since working seriously with Python, I've come round to the point of view that the public interface should be defined by what you document it as, and not enforced by language gimmicks. Which is just duck typing from another angle. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tjreedy at udel.edu Mon Sep 12 21:36:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2005 21:36:16 -0400 Subject: which is more 'pythonic' / 'better' ? References: <43256a38$0$4789$da0feed9@news.zen.co.uk> <43257f17$0$27971$636a15ce@news.free.fr> <4325849c$0$525$da0feed9@news.zen.co.uk> <4325a3fe$0$525$da0feed9@news.zen.co.uk> Message-ID: "Will McGugan" wrote in message news:4325a3fe$0$525$da0feed9 at news.zen.co.uk... > You may be right. I always use plural nouns for collections. ditto > To me 'line' would suggest there was just one of them, > so I assumed it was string. I did too. for line in file('skljflask.txt',r): # or similar is a common idiom posted here many times. Terry J. Reedy From baoilleach at gmail.com Mon Sep 19 12:34:06 2005 From: baoilleach at gmail.com (baoilleach at gmail.com) Date: 19 Sep 2005 09:34:06 -0700 Subject: Organising a python project Message-ID: <1127147646.346301.53520@g49g2000cwa.googlegroups.com> Dear all, Can anyone point me to a resource that describes the best way of organising a python project? My project (gausssum.sf.net) is based around a class, and has a GUI that allows 'easy-access' to the methods of the class. What is the best or typical directory structure that allows the easy creation of binary packages for linux and windows, source distributions, etc. Rather than make up my own way, I'd prefer to know if there is a typical python way... Regards, baoilleach From gerrit at nl.linux.org Sun Sep 25 09:24:29 2005 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 25 Sep 2005 15:24:29 +0200 Subject: New-style classes questions In-Reply-To: <3pnbqgFbal03U2@uni-berlin.de> References: <0001HW.BF5C293600279AC3F0284550@news.individual.de> <3pnbqgFbal03U2@uni-berlin.de> Message-ID: <20050925132429.GA19079@topjaklont.student.utwente.nl> Diez B. Roggisch wrote: > > What is the reason for allowing both styles? (backwards compatibility??) > > yes. Note that there is another way to create new-style classes: __metaclass__ = type before the first class definition: >>> class Foo: pass ... >>> type(Foo) >>> __metaclass__ = type >>> class Bar: pass ... >>> type(Bar) I like this. However, perhaps other people reading my source code won't like it, because when they see 'class Foo:', they might expect an old-style class. But it's so much better to type and to read, that I prefer this. Does the Python style guide have any severe penalty for using this? regards, Gerrit. -- Temperature in Lule?, Norrbotten, Sweden: | Current temperature 05-09-25 15:19:47 11.0 degrees Celsius ( 51.9F) | -- Det finns inte d?ligt v?der, bara d?liga kl?der. From rrr at ronadam.com Wed Sep 21 22:31:55 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 22 Sep 2005 02:31:55 GMT Subject: Finding where to store application data portably In-Reply-To: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Tony Houghton wrote: > > I'm using pygame to write a game called Bombz which needs to save some > data in a directory associated with it. In Unix/Linux I'd probably use > "~/.bombz", in Windows something like > "C:\Documents And Settings\\Applicacation Data\Bombz". > > There are plenty of messages in the archives for this group about how to > find the correct location in Windows, but what about Mac OS? There I > don't know the correct location for this sort of thing at all. And there > are other, more obscure systems like RISC OS (it may not have pygame but > it definitely has python). Surely this is something that's crying out > for an official function in os or sys. This works on Win XP. Not sure if it will work on Linux. import os parent = os.path.split(os.path.abspath(os.sys.argv[0]))[0] file = parent + os.sep + '.bombz' Cheers, Ron From peter at engcorp.com Fri Sep 9 08:32:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Sep 2005 08:32:33 -0400 Subject: Video display, frame rate 640x480 @ 30fps achievable? In-Reply-To: <1126268090.385505.210480@g49g2000cwa.googlegroups.com> References: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> <1126220191.485416.32770@f14g2000cwb.googlegroups.com> <1126268090.385505.210480@g49g2000cwa.googlegroups.com> Message-ID: Guenter wrote: > It is a video image coming from a camera over a frame grabber board. > The video from the frame grabber is passed to another board that > performs some processing and when it comes back from that board it > needs to be displayed. The joystick allows to specify some regions of > interest in the image, but any zooming is done by the chip on that > second board. So the application needs only to take the image it gets > from that second board, displays it, handle the joystick input and does > some book keeping of where it is with the joystick position and zoom > factor. Cool! It sounds to me as though Pygame (perhaps embedded in a wxPython app) would be most appropriate. I know it has direct support for joysticks, which I doubt the standard GUI frameworks generally have. (Hmm... no, I'm wrong. At least wxPython does have Joystick support. Check it out in the demo.) -Peter From Michael.Coll-Barth at VerizonWireless.com Mon Sep 26 16:04:17 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Mon, 26 Sep 2005 16:04:17 -0400 Subject: Plotting points to screen Message-ID: <20050926200423.1BEAE1E41A0@bag.python.org> Jason, YMMV = Your Mileage May Vary In other words, how well it works for you depends on a lot of things. You need to determine the suitability for a given task. :) Michael Don't like the legal notice at the end of my email? Too bad, you can stuff it where the sun don't shine. -----Original Message----- From: Jason Sent: Monday, September 26, 2005 3:46 PM To: python-list at python.org Subject: Re: Plotting points to screen One question, that's twice in as many days that someone has said "YMMV". What's it mean!? -- http://mail.python.org/mailman/listinfo/python-list ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From rkern at ucsd.edu Tue Sep 13 19:51:53 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 13 Sep 2005 16:51:53 -0700 Subject: What XML lib to use? In-Reply-To: <54192.64.113.64.209.1126638540.squirrel@mail.scl.ameslab.gov> References: <0001HW.BF4CD7C600321189F0407550@news.individual.de> <54192.64.113.64.209.1126638540.squirrel@mail.scl.ameslab.gov> Message-ID: mekstran at scl.ameslab.gov wrote: > I have also heard excellent things about ElementTree; I haven't used it > myself though (largely because I can't find any resources on doing XML > canonicalization with it). You can use lxml which is an implementation of the ElementTree API using libxml2 and libxslt under the covers for greater standards compliance including c14n. I've been using extensively recently and highly recommend it. http://codespeak.net/lxml -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gmc at serveisw3.net Fri Sep 30 03:19:36 2005 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Fri, 30 Sep 2005 09:19:36 +0200 Subject: PyWin SendMessage In-Reply-To: References: <7jczvrb5.fsf@python.net> Message-ID: <433CE708.4040203@serveisw3.net> g.franzkowiak escribi?: >Thomas Heller schrieb: > > >>"g.franzkowiak" writes: >> >> >> >> >>>Thomas Heller schrieb: >>> >>> >>> >>>>"g.franzkowiak" writes: >>>> >>>> >>>> >>>> >>>> >>>>>Hello everybody, >>>>> >>>>>I've tryed to use an interprocess communication via >>>>>SendMessage on Windows. >>>>>Unfortunately, nothing goes on >>>>> >>>>>######################################################################### >>>>>#! /usr/bin/env python >>>>> >>>>>import win32api, win32ui, win32con >>>>>import struct, array >>>>> >>>>>""" >>>>>typedef struct tagCOPYDATASTRUCT { // cds >>>>> DWORD dwData; >>>>> DWORD cbData; >>>>> PVOID lpData; >>>>>} COPYDATASTRUCT; >>>>>""" >>>>> >>>>>def packCopyData(nNum, sString): >>>>> int_buffer = array.array("L",[nNum]) >>>>> char_buffer = array.array('c', sString) >>>>> int_buffer_address = int_buffer.buffer_info()[0] >>>>> char_buffer_address = char_buffer.buffer_info()[0] >>>>> char_buffer_size = char_buffer.buffer_info()[1] >>>>> copy_struct = struct.pack("pLp", # dword*, dword, char* >>>>> int_buffer_address, >>>>> char_buffer_size, >>>>> char_buffer) >>>>> return copy_struct >>>>> >>>>> >>>>After packCopyData(...) returns, the arrays are destroyed, which will >>>>probably void their contents. You must keep them alive until you don't >>>>need the COPYDATASTRUCT instance any longer. For this kind of stuff, >>>>ctypes may be easier to use than pywin32. >>>> >>>>Thomas >>>> >>>> >>>Hmm, have read something in <> >>>and the script changed to this: >>> >>>#--------------------------------------------------------- >>>#! /usr/bin/env python >>> >>>import win32api, win32ui, win32con, win32gui >>>import struct, array >>> >>> >>>from ctypes import * >> >> >>>""" >>>typedef struct tagCOPYDATASTRUCT { // cds >>> DWORD dwData; >>> DWORD cbData; >>> PVOID lpData; >>>} COPYDATASTRUCT; >>>""" >>> >>>class COPYDATATYPE(Structure): >>> _fields_ = [("nNum", c_ulong), >>> ("szData", c_char_p)] >>> >>>class COPYDATASTRUCT(Structure): >>> _fields_ = [("dwData", c_ulong), >>> ("cbData", c_ulong), >>> ("lpData", POINTER(COPYDATATYPE))] >>> >>># get the window handle >>>hwnd = win32ui.FindWindow(None, "target window") >>> >>># print just for fun >>># ##print hwnd >>> >>># prepare copydata structure for sending data >>>cpyData = COPYDATATYPE(1, '1') >>>cds = COPYDATASTRUCT(c_ulong(1), >>> c_ulong(sizeof(cpyData)), >>> pointer(cpyData)) >>> >>># try to send a message >>>win32api.SendMessage(hwnd, >>> win32con.WM_COPYDATA, >>> 0, >>> pointer(cds)) >>> >>>#--------------------------------------------------------- >>>and the message for the last line is: >>>==> TypeError: an integer is required" >>> >>>This message comes with "pointer(cds)" and with "addressof(cds)" >>> >>> >>That error refers to the first argument - win32ui.FindWindow returns a >>PyCWnd object, which is not accepted by win32api.SendMessage. >>Changing this brings you one step further. win32api.SendMessage accepts >>an integer for the last element, so addressof(cds) should work now. >> >>win32gui.SendMessage is more tolerant in what it accepts as 4th >>argument, according to the error message you get when you try it it >>expects a string, a buffer, or an integer. So you could use addressof() >>or pointer(), what you like best. >> >>Thomas >> >> > >Super, operates :-)) > >My last answer must be in the Nirvana, strange ? > >Ok, only the version with 'addressof' generates a message and I must >play with the data types. The receiver becomes a wrong data formate. >Expect (int=1, char[256]='1\00'), but the int is 0x31 and the string >somewhat. Must play with my data. > >Thanks >gerd > > Hi Gerd, I'm not really sure of, but I think you must use a message value in range of WM_USER or WM_APP so this fact maybe let the receiver window getting bad data... have a look to this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/messagesandmessagequeues/messagesandmessagequeuesreference/messagesandmessagequeuesmessages/wm_user.asp 0 through WM_USER 0x0400 Messages reserved for use by the system. *WM_USER* through 0x7FFF Integer messages for use by private window classes. *WM_APP* through 0xBFFF Messages available for use by applications. 0xC000 through 0xFFFF String messages for use by applications. Greater than 0xFFFF Reserved by the system. I've done the same with PHP GTK and achieved random results sending low Msg values... until used WM_USER and above. Also, in my case only PostMessage work fine... try using both... but expect this doesn't happen with python, Hope it helps. Gonzalo From steve at holdenweb.com Mon Sep 26 03:45:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 26 Sep 2005 08:45:00 +0100 Subject: How to show percentage In-Reply-To: References: <1127411503.211432.250960@g43g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Sen-Lung Chen wrote: > >>Dear All: >> I have a question of show percentage. >>For example ,I want to show the percentage of 1/3 = 33.33% >> >> I use the 1*100/3 = 33 >>it is 33 not 33.33 , how to show the 33.33 % >> Thanks >> > > You should by now know enough answers. The easiest way to ensure that > the result is floating point is to cast it as > > pct = 100.0 * v) / N > > This is guaranteed to work in all past and future Python versions > without setting any options. Then you can format is using the % operator. > > regards > Steve ... apart from the obvious syntax error, that is. Sigh. pct = (100.0 * v) / N regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From gerrit at nl.linux.org Fri Sep 30 06:56:46 2005 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 30 Sep 2005 12:56:46 +0200 Subject: A Moronicity of Guido van Rossum In-Reply-To: <43D1E0B3-6A3B-442E-9BDE-6DBC1A2466A7@ihug.co.nz> References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> <77498FFE-AEC3-4148-A113-E434EE4A4E52@ihug.co.nz> <200509292042.36051.jstroud@mbi.ucla.edu> <43D1E0B3-6A3B-442E-9BDE-6DBC1A2466A7@ihug.co.nz> Message-ID: <20050930105646.GA17540@topjaklont.student.utwente.nl> Tony Meyer wrote: > X-Spambayes-Classification: ham; 0.048 > X-Spambayes-Evidence: '*H*': 0.90; '*S*': 0.00; 'bug.': 0.07; 'flagged': 0.07; > "i'd": 0.08; 'bayes': 0.09; 'from:addr:ihug.co.nz': 0.09; > 'really,': 0.09; 'cc:no real name:2**0': 0.14; > 'from:addr:t-meyer': 0.16; 'from:name:tony meyer': 0.16; > 'obvious,': 0.16; 'spambayes': 0.16; 'subject:Guido': 0.16; > 'trolling,': 0.16; 'regret': 0.82; 'lee,': 0.91; 'viagra': 0.91; > 'mailings': 0.93; 'probability': 0.93 > This is a feature, not a bug. It's the same feature that means that > messages talking about spam on the spambayes mailing list, or the > legitimate mail I get about viagra , get through to me. True. However, most mail to this mailinglist has less than 0.001 spam probability. As you can see, this one had 0.048 - a vast score, almost enough to put it in my unsure box. It seems to be just not hammy enough. It's interesting to see that no none of the foul language words used by Xah Lee ever occurs in any spam I receive - spam is not that stupid. Gerrit. -- Temperature in Lule?, Norrbotten, Sweden: | Current temperature 05-09-30 12:49:54 11.1 degrees Celsius ( 51.9F) | -- Det finns inte d?ligt v?der, bara d?liga kl?der. From jason at jasonmhirst.co.uk Tue Sep 20 08:42:06 2005 From: jason at jasonmhirst.co.uk (Jason) Date: Tue, 20 Sep 2005 13:42:06 +0100 Subject: How am I doing? In-Reply-To: References: <86slw1znup.fsf@bhuda.mired.org> <1127161587.863795.214000@z14g2000cwz.googlegroups.com> Message-ID: Tom Anderson wrote: > On Mon, 19 Sep 2005, Brett Hoerner wrote: > >> Wouldn't the standard idiom be to actually put the code under the >> if-name, and not make a whole new main() function? > > Yes. > > The nice thing about the main() function, though, is that you can do the > most basic argument parsing in the if-block. Like so: > > def powers(n): > m = 1 > while True: > yield m > m = m * n > > def main(n, limit): > for power in powers(n): > if (power > limit): break > print power > > import sys > > if (__name__ == "__main__"): > main(int(sys.argv[1]), int(sys.argv[2])) > > That serves as a sort of documentation on the arguments to the script, and > also makes it easier for other scripts to reuse the main logic of the > program, since they don't have to package parameters up as a string array. > It is more verbose, though. > >> I'm not sure I see the reason behind main(), couldn't that also >> interfere with other modules since main() seems like it might be common, >> not sure how it would work as I'm pretty new to Python myself. > > The two mains would be in different namespaces, so they wouldn't conflict. > >> from script import * > > Don't do that. 'from script import x' is, IMNERHO, bad practice, and 'from > script import *' is exceptionally bad practice. I know a lot of people do, > but that doesn't make it right; namespaces are there for a reason. > > tom > I haven't a clue what all this means, but it looks important ! lol Thanks for the headsup, will take note of what you've said. Incidentally, at work my main programming platform is VisualStudio .Net, and I never import the children of namespaces so hopefully this practice I have will be carried over to Python. From gnb at itga.com.au Mon Sep 19 01:59:23 2005 From: gnb at itga.com.au (Gregory Bond) Date: Mon, 19 Sep 2005 15:59:23 +1000 Subject: Brute force sudoku cracker In-Reply-To: <1127047310.956841.14720@f14g2000cwb.googlegroups.com> References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> <3p4s58F8lc12U1@uni-berlin.de> <1127047310.956841.14720@f14g2000cwb.googlegroups.com> Message-ID: My current solver does 1 level of backtracking (i.e. constant space, and bounded time) only, and it has been able to solve every puzzle I've thrown at it. It's based on the usual logic and book-keeping for the most part. (It also explains how it comes up with each answer step as it goes, which is handy...) Once it gets to the stage where it needs to guess, it arranges all the unknowns then tries them in some arbitary order. It saves the state, applies the guess (square x,y is N) and then re-applies all the logic rules. There are 3 possible outcomes from here: - We've solved it, which is good (this happens surprisingly often....) - We can't solve it using this guess (so ignore this possibility, restore the state & try the next guess) - The Resulting puzzle is badly formed / inconsistant (represented by a python exception, naturally!) In this case, we know the guessed square/number is not valid, so we backtrack (restore the state before we made this guess), remove that possibility (x,y is N) and then apply all the logic rules again. Often times, this is enough to solve, but it usually progreses things a little even if it doesn't solve it. I've not yet found a (9x9) puzzle that this cannot solve. The downside is that it cannot detect cases where there are multiple solutions. From __peter__ at web.de Fri Sep 30 14:32:28 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Sep 2005 20:32:28 +0200 Subject: Duplicating Modules References: <1128103740.931794.136610@o13g2000cwo.googlegroups.com> Message-ID: kimes wrote: > Why don't you do like this.. > > import module > import mudule as module2 >>> import module as a >>> import module as b >>> b is a True You have to remove the module from the cache before the second import: >>> import sys >>> import module as a >>> del sys.modules["module"] >>> import module as b >>> b is a False Peter From Scott.Daniels at Acm.Org Tue Sep 20 17:27:35 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 20 Sep 2005 14:27:35 -0700 Subject: Object default value In-Reply-To: References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> <43306858.20003@websafe.com> <1127246758.691165.23920@g49g2000cwa.googlegroups.com> Message-ID: <43306abf$1@nntp0.pdx.net> James Stroud wrote: > I think you want to overload the assignment operator here. I'm not sure that > is allowed in python (I've never seen it done).... > But I don't think assignment overloading is allowed in python: Exactly correct. Assignment is an operation on a namespace using a new value, and does not involve the former value. Something similar to assignment overloading is possible with properties, but you need to be using object attributes, not names in a module (or function locals). class SomeDemo(object): def _read_foo(self): print 'Reading foo' return self._foo def _write_foo(self, value): print 'Writing foo as %r' % value return self._foo def _del_foo(self): print 'Deleting foo' del self._foo foo = property(_read_foo, _write_foo, _del_foo) obj = SomeDemo() obj.foo = 123 obj.foo += 1 del obj.foo --Scott David Daniels Scott.Daniels at Acm.Org From xah at xahlee.org Sun Sep 4 13:04:02 2005 From: xah at xahlee.org (Xah Lee) Date: 4 Sep 2005 10:04:02 -0700 Subject: os.system(r"ls") prints to screen?? In-Reply-To: References: <1125795750.304104.280660@g49g2000cwa.googlegroups.com> <1125832488.379489.147760@g49g2000cwa.googlegroups.com> Message-ID: <1125853442.491125.17480@g14g2000cwa.googlegroups.com> do you know what the Muses do when a mortal challenged them? And, please tell me exactly what capacity you hold under the official Python organization so that i can calculate to what degree i can kiss your ass or feign mum of your ignorance. Xah xah at xahlee.org ? http://xahlee.org/ Steve Holden wrote: > Seems to me that you'd know more about frenzy than me. Having read many > of your posts it seems to me that they are deliberately calculated to > inflame the reader. > > To be successfully so critical of others you need to demonstrate > superior knowledge and judgment, which your original question revealed > to be lacking. > > To put it another way: "People who live in glass houses shouldn't throw > stones". From notmuch at gmail.com Tue Sep 20 10:52:23 2005 From: notmuch at gmail.com (cg) Date: 20 Sep 2005 07:52:23 -0700 Subject: python script under windows In-Reply-To: References: Message-ID: <1127227943.780638.227170@g43g2000cwa.googlegroups.com> I ran into a similar issue a couple of months back, the solution on Windows is to run it as a service. It is very simple, you need Mark Hammond's Win32 extensions. For path you have to use absolute filepath for all local files and for network drive use the UNC path i.e. \\servername\folder-filename\ . All these steps will let your machine running the program survive logouts after a login. If your machine is part of windows network and there is domain login then in order for it to work after a machine restart you need to goto the Service panel (in Control Panel) find the Python service you registered, right-click and goto its properties, goto the "Log On" panel, select a domain user for "This account" by clicking the Browse button, note the selected user has access to windows domain and admin access to that particular machine. Enter user network password, hit Apply, OK and there u go. All this requires admin access to machine. You can configure a couple of things about the service in the Services panel. The code itself is simple: #------------------------------------------------------------------ import win32service, win32serviceutil class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "MyServiceName" _svc_display_name_ = "A Little More Descriptive" def SvcDoRun(self): #do your stuff here, call your main application code. def SvcStop(self): #the following line is not really needed, basically put here any code that should execute #before the service stops self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) if __name__ == '__main__': win32serviceutil.HandleCommandLine(MyService) #------------------------------------------------------------------ After this if you have python in your path and Win32 extensions installed, goto command prompt and run: c:\> MyService.py -startup=auto install Trying to have your service have Network access after a machine restart is a bit tricky. This thing works but somehow I feel there is more to it. If anyone has a better way, please post. From viridia at gmail.com Thu Sep 1 03:11:46 2005 From: viridia at gmail.com (viridia at gmail.com) Date: 1 Sep 2005 00:11:46 -0700 Subject: Yielding a chain of values In-Reply-To: <1125514778.955076.255950@z14g2000cwz.googlegroups.com> References: <4314bf65.177562962@news.oz.net> <3nk0e4F1snjcU2@individual.net> <4314e9fe.188467011@news.oz.net> <431553db.215568641@news.oz.net> <3nli8nF23ge4U1@individual.net> <1125490081.383463.322120@z14g2000cwz.googlegroups.com> <3nm4n7F26v7eU2@individual.net> <1125514778.955076.255950@z14g2000cwz.googlegroups.com> Message-ID: <1125558706.752900.8180@g43g2000cwa.googlegroups.com> This is why my original proposal used the '*' operator rather than a keyword. The reasoning behind this is as follows: When calling a function, a parameter of the form "*expression" expands to a list of arguments. From the Python reference manual: "If the syntax '*expression' appears in the function call, 'expression' must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments." By (somewhat stretched) analogy, "yield *expression" would "expand" the sequence into a series of multiple yields. Of course, now that yield is an expression (as stated above), you would indeed have to account for the fact that the yield statement used in this way would yield a sequence of values: for x in yield *[ 1, 2, 3 ]: print x So the '*' would not only signal that multiple values were being yielded, but that multiple values are also being returned. -- Talin From reinhold-birkenfeld-nospam at wolke7.net Mon Sep 19 15:43:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 19 Sep 2005 21:43:34 +0200 Subject: slicing functionality for strings / Python suitability for bioinformatics In-Reply-To: <1127157916.290111.112620@g47g2000cwa.googlegroups.com> References: <1127157916.290111.112620@g47g2000cwa.googlegroups.com> Message-ID: <3p8in6F98fduU1@individual.net> jbperez808 at yahoo.com wrote: >>>> rs='AUGCUAGACGUGGAGUAG' >>>> rs[12:15]='GAG' > Traceback (most recent call last): > File "", line 1, in ? > rs[12:15]='GAG' > TypeError: object doesn't support slice assignment > > You can't assign to a section of a sliced string in > Python 2.3 and there doesn't seem to be mention of this > as a Python 2.4 feature (don't have time to actually try > 2.4 yet). Strings are immutable in Python, which is why assignment to slices won't work. But why not use lists? rs = list('AUGC...') rs[12:15] = list('GAG') Reinhold From mwm at mired.org Fri Sep 30 21:35:02 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 30 Sep 2005 21:35:02 -0400 Subject: Will python never intend to support private, protected and public? References: <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7xbr2btv84.fsf@ruckus.brouhaha.com> <7xy85fvxny.fsf@ruckus.brouhaha.com> <86vf0inlt3.fsf@bhuda.mired.org> <7xd5mq9ir9.fsf@ruckus.brouhaha.com> Message-ID: <86wtkym33t.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> So, fool._bar is now clobbered. Nuts, the _bar attribute is broken for >> *every* instance of Fools. According to you, the error must be in >> Fools. Care to point it out? > > Yes, the error is in the "breaker" function, which leaks the private > variable to other classes, Wrong. The bug is in the King class, which is clobbering objects it's not supposed to clobber. Unless your compiler detects and flags passing private variables to external functions all you've got is a convention that you don't pass private variables to external functions. > This is the kind of thing that you'd look for in an audit, so I > don't see your point. So would you audit catch this one: class Fools(object): ... _foo = "my private list of values".split() ... def broken(self): ... return len(self._foo) ... >>> fool = Fools() >>> fool.broken() >>> fool._foo [] Are you going to try and tell me thas using builtin functions on private variables is something you don't allow in your projects? If all you've got is a convention for some of the cases you're trying to catch, then having a compiler enforce private variables isn't fundamentally different from having a convention that you don't touch variables with specific names. It lets the comiler catch more bugs, but doesn't mean that such bugs are suddenly impossible. Of course, there's nothing wrong with catching errors earlier. Might I suggest that you file a change request for pylint (or your favorite error checker) asking that it start issuing warnings for object._variable? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dave at pythonapocrypha.com Fri Sep 9 12:48:40 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 09 Sep 2005 10:48:40 -0600 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: <432742240509090817230df311@mail.gmail.com> References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <432742240509090817230df311@mail.gmail.com> Message-ID: <4321BCE8.30209@pythonapocrypha.com> Stefano Masini wrote: > I wonder how many people (including myself) have implemented their own > versions of such modules, at least once in their pythonic life. I > indeed have my own odict (even same name! :). My own pathutils > (different name, but same stuff). My own validate... and so forth. > > This is just too bad. > There are a few ares where everybody seems to be implementing their > own stuff over and over: logging, file handling, ordered dictionaries, > data serialization, and maybe a few more. > I don't know what's the ultimate problem, but I think there are 3 main reasons: > 1) poor communication inside the community (mhm... arguable) > 2) lack of a rich standard library (I heard this more than once) > 3) python is such an easy language that the "I'll do it myself" evil > side lying hidden inside each one of us comes up a little too often, > and prevents from spending more time on research of what's available. IMO the reason is something similar to #3 (above and beyond #1 and #2 by a long shot). The cost of developing _exactly_ what you need often is (or at least *appears* to be) the same as or lower than bending to use what somebody else has already built. (my wheel reinvention has typically covered config files, logging, and simple HTTP request/response/header processing) > It seems to me that this tendency is hurting python I think it helps on the side of innovation - the cost of exploring new ideas is cheaper than in many other languages, so in theory the community should be able to stumble upon truly great ways of doing things faster than would otherwise be possible. The problem lies in knowing when we've found that really good way of doing something, and then nudging more and more people to use it and refine it without turning it into a bloated one-size-fits-all solution. I think we have half of what we need - people like Fuzzyman coming up with handy modules and then making them available for others to use. But right now it's hard for a developer to wade through all the available choices out there and know which one to pick. Maybe instead of being included in the standard library, some modules could at least attain some "recommended" status by the community. You can't exactly tell people to stop working on their pet project because it's not special or different enough from some other solution, so maybe the solution is to go the other direction and single out some of the really best ones, and hope that the really good projects can begin to gain more momentum. For example, there are several choices available to you if you need to create a standalone Windows executable; if it were up to me I'd label py2exe "blessed by the BDFL!", ask the other tool builders to justify the existence of their alternatives, and then ask them to consider joining forces and working on py2exe instead. But of course I'm _not_ in charge, I don't even know if the BDFL likes py2exe, and it can be really tough knowing which 1 or 2 solutions should receive recommended status. FWIW, RubyOnRails vs all the Python web frameworks is exactly what you're talking about. What makes ROR great has little to do with technology as far as I can tell, it's all about lots of people pooling their efforts - some of them probably not seeing things develop precisely as they'd prefer, but remaining willing to contribute anyway. Many projects (Python-related or not) often seem to lack precisely what has helped Python itself evolve so well - a single person with decision power who is also trusted enough to make good decisions, such that when disagreements arise they don't typically end in the project being forked (the number of times people disagreed but continued to contribute to Python is far higher than the number of times they left to form Prothon, Ruby, and so on). In the end, domain-specific BDFLs and their projects just might have to buble to the top on their own, so maybe the best thing to do is find the project you think is the best and then begin contributing and promoting it. > and I wonder if > there is something that could be done about it. I once followed a > discussion about placing one of the available third party modules for > file handling inside the standard library. I can't remember its name > right now, but the discussion quickly became hot with considerations > about the module not being "right" enough to fit the standard library. I think an extremely rich standard library is both a blessing and a curse. It's so handy to have what you need already there, but as you point out it becomes quite a debate to know what should be added. For one, a module to be added needs to be sufficiently broad in scope and power to be widely useful, but this often breeds complexity (e.g. the logging package added in Py2.3 sure looks powerful, but other than playing around with it for a few minutes I've never used it in a real app because it's a little overwhelming and it seems easier to just use a quickie logging function that does all I need). Having two versions of the standard lib probably wouldn't solve anything - you'd still have debates about what goes in the "lite" version, but you'd also have debates about what to include in the big version - maybe even moreso. -Dave From tprimke at interia.pl Mon Sep 19 10:42:27 2005 From: tprimke at interia.pl (TPJ) Date: 19 Sep 2005 07:42:27 -0700 Subject: Python game coding In-Reply-To: References: <8f6Xe.14083$FW1.371@newsread3.news.atl.earthlink.net> Message-ID: <1127140947.592844.304280@z14g2000cwz.googlegroups.com> OT: > BTW: I wonder if and when someone will use stackless python (...) And what is this stackless python? I have visited it's homepage, but I wasn't able to find any answer. (Well, I have found out, that stackles python is python's implementation that doesn't use C stack, but it tells me nothing...) Is this stackless python faster or slower than CPython? Does anybody know something? From jcribbs at twmi.rr.com Mon Sep 19 20:54:29 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Mon, 19 Sep 2005 20:54:29 -0400 Subject: ANNOUNCE: KirbyBase 1.9 Message-ID: <432F5DC5.90404@twmi.rr.com> KirbyBase is a simple, plain-text, database management system written in Python. It can be used either embedded in a python script or in a client/server, multi-user mode. You use python code to express your queries instead of having to use another language such as SQL. KirbyBase is disk-based, not memory-based. Database changes are immediately written to disk. You can find more information on KirbyBase at: http://www.netpromi.com/kirbybase.html You can download KirbyBase for Python at: http://www.netpromi.com/files/KirbyBase_Python_1.9.zip I would like to thank David Edwards and Pierre Quentel for their contributions to this release. Changes in Version 1.9: -Fixed a bug that can occur on very fast machines when sending data between the client and the server. Thanks to David Edwards for this fix. -Added a method, setDefaultReturnType, that allows you to, set the default return type of results from the select method. The default is still 'list', but you can set it to 'list', 'object', or 'dict'. Thanks to David Edwards for this suggested enhancement. -Added methods addFields and dropFields. These allow you to add new columns to a table and remove existing columns from the table. Thanks to Pierre Quentel for the code for these two enhancements. Jamey Cribbs jcribbs at twmi.rr.com From http Thu Sep 29 04:57:07 2005 From: http (Paul Rubin) Date: 29 Sep 2005 01:57:07 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xfyroe5vh.fsf@ruckus.brouhaha.com> Message-ID: <7x4q84s13w.fsf@ruckus.brouhaha.com> Gregor Horvath writes: > > If you don't want the compiler to make sure your private instance > > variables stay private, then don't declare them that way. You're the > > one asking for less flexibility. > > I want to declare them as private, but want to give the flexibilty to > access them at the users own risk. What else do you want to let users do at their own risk? Treat integers as pointers, like in C? Both are violations of type safety. > Declaring everything as public is nonsene, because there should be a > garanteed stable interface. You could have a "friend" declaration like in C++, if you want to let some class see the private instance variables of another class. I can't think of a single time that I've ever seen a legitimate use of name mangling to reach from one class into another in a Python application (I don't count something like a debugger). If you're got some concrete examples I wouldn't mind looking. From rrr at ronadam.com Mon Sep 19 15:37:03 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 19 Sep 2005 19:37:03 GMT Subject: inspect getsource() minor fix? Message-ID: While playing around with the inspect module I found that the Blockfinder doesn't recognize single line function definitions. Adding the following two lines to it fixes it, but I'm not sure if it causes any problems anywhere else. elif self.indent == 0: raise EndOfBlock, self.last Cheers, Ron C:\Python24\Lib>diff.py inspect.py inspect_.py *** inspect.py Tue Mar 15 13:22:02 2005 --- inspect_.py Mon Sep 19 14:26:26 2005 *************** *** 531,536 **** --- 531,538 ---- raise EndOfBlock, self.last elif type == tokenize.NAME and scol == 0: raise EndOfBlock, self.last + elif self.indent == 0: + raise EndOfBlock, self.last def getblock(lines): """Extract the block of code at the top of the given list of lines.""" def test(t): print '**',t,'**' print "Line:" def f(): pass """ This line shouldn't be visible """ print inspect.getsource(f) print "Block:" def f(): pass pass """This line should not be visible.""" print inspect.getsource(f) import inspect test("before") import inspect_ as inspect test("after") #-- output -- ** before ** Line: def f(): pass """ This line shouldn't be visible """ print inspect.getsource(f) print "Block:" def f(): pass pass Block: def f(): pass pass ** after ** Line: def f(): pass Block: def f(): pass pass From tdelaney at avaya.com Thu Sep 29 17:50:45 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 30 Sep 2005 07:50:45 +1000 Subject: A Moronicity of Guido van Rossum Message-ID: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> Sherm Pendley wrote: > "Matt" writes: > >> OK... your post seems to indicate a belief that everyone else is >> somehow incompetent. > > Xah's just a troll - best to just ignore him. He posts these diatribes > to multiple groups hoping to start a fight. You have to admit though, he's remarkably good at getting past Spambayes. Despite classifying *every* Xah Lee post as spam, he still manages to get most of his posts classified as 0% or 1% spam. It's very annoying - I've maxxed out the rules I can use in Outlook (my work account) so I can't afford to add a specific one to trash his emails... Tim Delaney From apardon at forel.vub.ac.be Fri Sep 30 02:52:50 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Sep 2005 06:52:50 GMT Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> Message-ID: Op 2005-09-29, Bill Mill schreef : > > But, if your users can't figure out that they shouldn't be changing > the variable called t._test__i without expecting side effects, what do > you think of the users of your class? > > Python is for consenting adults. No it is not. Consenting means you had the choice. Python doesn't give you the choice not to consent. Unless of course you write it as a C-extension, then you can hide all you want. -- Antoon Pardon From cipherpunk at gmail.com Mon Sep 5 00:38:48 2005 From: cipherpunk at gmail.com (Robert J. Hansen) Date: 4 Sep 2005 21:38:48 -0700 Subject: mod_python: what's going on here? Message-ID: <1125895128.704350.51270@g47g2000cwa.googlegroups.com> I'm not entirely certain comp.lang.python is the proper newsgroup for mod_python questions, but "comp.lang.python.web" doesn't seem to exist, so... my apologies in advance if this is considered off-topic. I'm attempting to get mod_python 3.1.4/python 2.4.1 working on Apache 2.0.54 running under OS X. Apache was compiled from source with a simple /configure --enable-so --with-mpm=worker ... followed by the make/make install dance. mod_python was almost as simple: ./configure --with-apxs=/usr/local/apache2/bin/apxs \ --with-python=/sw/bin/python2.4 ... followed by the requisite dance. At this point, all's well. The following bits were added to httpd.conf: LoadModule python_module /usr/local/apache2/modules/mod_python.so AddHandler mod_python .py PythonHandler mptest PythonDebug on ... one apachectl restart later, Apache was running fine and serving pages. The version string at the bottom of some static pages listed mod_python as being present, so I reckoned that meant it was all installed all right. However, any attempt to serve a mod_python script, mptest.py, from the test subdirectory results in a 500 Internal Server Error. Nothing gets written to error_log, but access_log confirms the 500 was sent. Does anyone have any experience with mod_python on OS X/Apache environments? Can anyone shed some light on 500s that don't leave traces in the error logs, or what precise incantation I need to make mod_python start serving up scripts? Also, if this is not appropriate for this group, does anyone know of a Python group for which this is more appropriate? From allisfree at gmail.com Wed Sep 14 02:27:59 2005 From: allisfree at gmail.com (JackPhil) Date: Wed, 14 Sep 2005 14:27:59 +0800 Subject: Where is the document of python-mode.el Message-ID: <87psrc4100.fsf@microblue.com> I searched in the python-mode.el, sf.net, python.org, and found nothing Best regards From stephan.diehl at gmx.net Mon Sep 5 13:06:42 2005 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 05 Sep 2005 19:06:42 +0200 Subject: curious about slice behaviour Message-ID: I just found out by accident, that slice indices can be larger than the length of the object. For example >>> 'test'[:50] 'test' >>> 'test'[40:50] '' I'd rather expected to be confronted with an IndexError. (This is actually described in http://docs.python.org/lib/typesseq.html, so my expectation was wrong :)) Does anybody know, why this is preferred to just raising an error? From g.horvath at gmx.at Fri Sep 30 01:28:52 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Fri, 30 Sep 2005 07:28:52 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xek77p2i8.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7xbr2btv84.fsf@ruckus.brouhaha.com> <7x64sjduqk.fsf@ruckus.brouhaha.com> <7xek77p2i8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > Gregor Horvath writes: > >>Real open source live example from yesterdays mailinglists: > > > I don't see any use of name mangling in that example. Someone has a problem and tweaks a private variable as a workaround. No python program will rely by definition on access to privat variables, it just lets the door open, just for the case that the program is not used in steril theoretical environment with a lot of flipcharts but in real dirty live with bugs, version conflicts, changing demands, ill spezifications, crazy public interfaces and so on. -- Greg From R.Brodie at rl.ac.uk Mon Sep 5 09:56:50 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 5 Sep 2005 14:56:50 +0100 Subject: error when parsing xml References: <3o2u75F3vcj4U1@uni-berlin.de> Message-ID: > > I have found that some people refuse to stick to standards, so whenever I > > parse XML files I remove any characters that fall in the range > > <= 0x1f > > > >>= 0xf0 > > Now of what help shall that be? Get rid of all accented characters? > Sorry, but that surely is the dumbest thing to do here - and has > _nothing_ to do with standards! Earlier versions of the Microsoft XML parser accept invalid characters (e.g. most of those < 0x1f). Sadly, you do find files in the wild that need to have these stripped before feeding them to a conforming parser. One can be too enthusiastic about the process, though. From hipertracker at gmail.com Tue Sep 6 08:47:02 2005 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: Tue, 6 Sep 2005 14:47:02 +0200 Subject: Django Vs Rails References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> Message-ID: <4ey7tf62yjpo.140udjsjvbeze$.dlg@40tude.net> Dnia 5 Sep 2005 19:06:51 -0700, flamesrock napisa?(a): > Firstly, this topic is NOT intended for trolling or starting any flame > wars. > > I want to know if anyone has experience with these frameworks, and if > so, how do they compare? Which one do you prefer? Django's ORM does not work with SQL Server (only Postgresql, MySQL and SQlite). it would be problem to use Django for m$ based intranets. Rails has more features, better docs and seems to be more mature than Django. And last but not least, Django has no official release up today. -- JZ From http Fri Sep 30 06:42:32 2005 From: http (Paul Rubin) Date: 30 Sep 2005 03:42:32 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xzmpwuxd0.fsf@ruckus.brouhaha.com> <20050930075313.67b9b676.jk@ospaz.ru> Message-ID: <7xbr2a6dlz.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Still, en.karpachov at ospaz.ru's point that you must know the base classes > is correct. It is *easy* to find them out (NotSoSecret.__bases__ should do > it), but if you don't you are taking a chance that your class name doesn't > clash with one of the bases. It's not easy if the base classes change after you check your code in. You shouldn't need to know about that if it happens. Modularity, remember? From cyril.bazin at gmail.com Thu Sep 29 10:57:58 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Thu, 29 Sep 2005 16:57:58 +0200 Subject: A rather unpythonic way of doing things In-Reply-To: <37irwkc5y8.fsf@chiark.greenend.org.uk> References: <37ll1gci8v.fsf@chiark.greenend.org.uk> <37irwkc5y8.fsf@chiark.greenend.org.uk> Message-ID: "Crypthonic" could be the exact word... On 29 Sep 2005 15:19:11 +0100, Peter Corbett < pcorbett at chiark.greenend.org.uk> wrote: > > Richie Hindle writes: > > > > [Peter] > > > http://www.pick.ucam.org/~ptc24/yvfc.html > > > > [Jeff] > > > Yuma Valley Agricultural Center? > > > Yaak Valley Forest Council? > > > > I went through the same process. My guess is "Yes, Very F'ing Clever." > > Peter? > > You're all thinking about it the wrong way (he says, being cryptic). > > Peter > > -- > A frightful hobgoblin is stalking throughout Europe. > - The Communist Manifesto, 1st English Edition > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From viridia at gmail.com Tue Sep 6 04:49:19 2005 From: viridia at gmail.com (talin at acm dot org) Date: 6 Sep 2005 01:49:19 -0700 Subject: Replacement for lambda - 'def' as an expression? Message-ID: <1125996559.130055.154400@z14g2000cwz.googlegroups.com> I've been reading about how "lambda" is going away in Python 3000 (or at least, that's the stated intent), and while I agree for the most part with the reasoning, at the same time I'd be sad to see the notion of "anonymous functions" go - partly because I use them all the time. Of course, one can always create a named function. But there are a lot of cases, such as multimethods / generics and other scenarios where functions are treated as data, where you have a whole lot of functions and it can be tedious to come up with a name for each one. For example, my current hobby project is implementing pattern matching similar to Prolog in Python. The dispatcher I am making allows you to create "overloaded" versions of a function that take different patterns as their input arguments, so that Simplify( (add, x, y) ) calls a different method than Simplify( (log, x) ) -- in other words, the choice of which code is executed is based on the structure of the tuple that is passed into it. However, in order for this to work, I need to be able to assign a block of Python code to a particular pattern, and having to invent a named function for each pattern is a burden :) Anyway, here's an example, then, of how 'def' could be used: add = def( a, b ): return a + b The lack of a function name signals that this is an anonymous function. The def keyword defines the function using the same syntax as always - the arguments are in parentheses, and are unevaluated; The colon marks the beginning of a suite. In fact, it looks a lot like the existing lambda, with a couple of differences: 1) It uses the familiar "def" keyword, which every Python beginner understands, instead of the somewhat unfamiliar "lambda" 2) The arguments are enclosed in parentheses, instead of a bare tuple followed by a colon, again reiterating the similarity to the normal usage of "def". 3) The statements are a real suite instead of a pseudo-suite - they can consist of multiple lines of statements. Like all statements whose last argument is a suite, you can put the body of the function on a single line: add = def( a, b ): return a + b (If this were Perl, you could also omit the "return", since in Perl the last evaluated expression in the function body is what gets returned if there's no explicit return statement.) What about passing an anonymous function as an argument, which is the most common case? This gets tricky, because you can't embed a suite inside of an expression. Or can you? The most powerful option would be to leverage the fact that you can already do line breaks inside of parentheses. So the "def" keyword would tell the parser to restart the normal indentation calculations, which would terminate whenever an unmatched brace or paren was encountered: a = map( (def( item ): item = do_some_calculation( item ) return item ), list ) The one-liner version looks a lot prettier of course: a = map( (def( item ): return item * item), list ) And it looks even nicer if we switch the order of the arguments around, since you can now use the final paren of the enclosing function call to terminate the def suite. a = map( list, def( item ): return item * item ) Unfortunately, there's no other good way I can think of to signal the end of the block of statements without introducing some radical new language construct. (Besides, if being an expression is good enough for 'yield', why shouldn't def get the same privilege? :) From uche.ogbuji at gmail.com Fri Sep 23 12:27:16 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 23 Sep 2005 09:27:16 -0700 Subject: xml2schema In-Reply-To: <1126992233.041972.132660@f14g2000cwb.googlegroups.com> References: <1126992233.041972.132660@f14g2000cwb.googlegroups.com> Message-ID: <1127492836.769161.79720@g43g2000cwa.googlegroups.com> """ Er, do you mean to generate a Relax NG (or possibly a DTD in fact) from some XML file?? If you do mean this then just think of that how you could generate grammar from some paragraphs of English text... Sorta non-trivial, if possible at all, isn't it? :-) """ Very well put. However, for RELAX NG there is a tool that might work for the OP: Examplotron. See: http://www-128.ibm.com/developerworks/xml/library/x-xmptron/ As I show in that article, you can use Examplotron from any XSLT processor, including one invoked through Python API. -- Uche http://copia.ogbuji.net From nyamatongwe+thunder at gmail.com Fri Sep 30 18:47:57 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 30 Sep 2005 22:47:57 GMT Subject: What encoding is used when initializing sys.argv? In-Reply-To: References: Message-ID: Petr Prikryl: > ... I have discovered that > I do not understand what encoding should be used > to convert the sys.argv into unicode. Martin mentioned CP_ACP. In Python on Windows, this can be accessed as the "mbcs" codec. import sys print repr(sys.argv[1]) print repr(unicode(sys.argv[1], "mbcs")) C:\bin>python glurp.py abc?? 'abc\xdf\x95' u'abc\xdf\u2022' Neil From vincent at visualtrans.de Wed Sep 21 13:32:31 2005 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 21 Sep 2005 19:32:31 +0200 Subject: I am not able to setup pydb2 ! Any help ! References: <1127321226.420209.253360@g43g2000cwa.googlegroups.com> <1127322750.143775.92010@g44g2000cwa.googlegroups.com> Message-ID: "vj" schrieb im Newsbeitrag news:1127322750.143775.92010 at g44g2000cwa.googlegroups.com... | Unfortunately I get another error | | Your DB2 root is: C:\Program Files\IBM\SQLLIB\ | running install | running build | running build_py | creating build | creating build\lib.win32-2.4 | copying DB2.py -> build\lib.win32-2.4 | running build_ext | error: The .NET Framework SDK needs to be installed before building | extensions f | or Python. You need the same compiler Python 2.4 was compiled with to compile CPython extensions from source. Alternatively, you might look into getting some precompiled Windows Binaries for pydb2 (try Googling for them or the pyDB2 mailing list). HTH, -- Vincent Wehren From eric_brunel at despammed.com Wed Sep 14 02:52:58 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 14 Sep 2005 08:52:58 +0200 Subject: Tkinter add_cascade option_add References: Message-ID: On Tue, 13 Sep 2005 22:31:31 -0600, Bob Greschke wrote: > Root.option_add("*?????*font", "Helvetica 12 bold") > > Want to get rid of the "font =": > Widget.add_cascade(label = "File", menu = Fi, font = "Helvetica 12 bold") > > Does anyone know what ????? should be to control the font of the cascade > menus (the labels on the menu bar)? "*Menu*font" handles the part that > drops down, but I can't come up with the menu bar labels part. option_add('*Menu.font', 'helvetica 12 bold') works for me for all sorts of menu items (cascade, commands, checkbuttons, whatever...). What is your platform? There may be a few limitations for menu fonts on Windows. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From http Sun Sep 4 05:03:42 2005 From: http (Paul Rubin) Date: 04 Sep 2005 02:03:42 -0700 Subject: Code for generating validation codes (in images) References: <1125824039.381538.309520@g43g2000cwa.googlegroups.com> Message-ID: <7xzmqt6w7l.fsf@ruckus.brouhaha.com> "morphex" writes: > does anyone of you know of some code I can use to generate validation > code images? > > Those images you can see on various login forms used to prevent bots > for performing a brute-force attack.. http://en.wikipedia.org/wiki/CAPTCHA From no at spam Tue Sep 6 12:15:28 2005 From: no at spam (D H) Date: Tue, 06 Sep 2005 11:15:28 -0500 Subject: Django Vs Rails In-Reply-To: <1125975775.892662.231980@f14g2000cwb.googlegroups.com> References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <1125975775.892662.231980@f14g2000cwb.googlegroups.com> Message-ID: flamesrock wrote: > D H, > 'flamesrock' refers to the Calgary Flames, not the act of flaming. > It was just a joke about your statement and your name. I thought it was obvious enough that a smiley wasn't necessary. I don't care though, flames happen on comp.lang.python all the time. Go with Rails. Django is only like a month old. Unless you are more comfortable using python than ruby. From neil.fraser at gmail.com Mon Sep 26 06:57:43 2005 From: neil.fraser at gmail.com (neil.fraser at gmail.com) Date: 26 Sep 2005 03:57:43 -0700 Subject: Simple Dialogs In-Reply-To: References: <1127500418.970813.321910@g44g2000cwa.googlegroups.com> Message-ID: <1127732262.978778.80400@g47g2000cwa.googlegroups.com> James Stroud wrote: > from tkMessageBox import showerror > showerror('Problem','Program Crashed before Starting') Here's a faster method, though not cross-platform: import ctypes ctypes.windll.user32.MessageBoxA(0, "Hello World", "Title", 0x00) From Scott.Daniels at Acm.Org Tue Sep 20 10:32:41 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 20 Sep 2005 07:32:41 -0700 Subject: Organising a python project In-Reply-To: <432fc735$0$9449$636a15ce@news.free.fr> References: <1127147646.346301.53520@g49g2000cwa.googlegroups.com> <432fc735$0$9449$636a15ce@news.free.fr> Message-ID: <43300983$1@nntp0.pdx.net> bruno modulix wrote: > baoilleach at gmail.com wrote: > >>What is the best or typical directory structure that >>allows the easy creation of binary packages somedir: test/ test_product.py # Really do include tests product.py setup.py Look at distutils documentation. Also read up on "Python Eggs." You might consider doing it as a package under a you-specific name: somedir: yourname: test/ test_product.py # See unittest module __init__.py # can be empty (and often is), also might have a # doc string, author, copyright, and license info # and a line like: __version__ = "0.2" product.py setup.py --Scott David Daniels Scott.Daniels at Acm.Org From steve at holdenweb.com Fri Sep 30 09:15:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 30 Sep 2005 14:15:35 +0100 Subject: Google Not Universal Panacea [was: Re: Where to find python c-sources] In-Reply-To: References: Message-ID: <433D3A77.2030105@holdenweb.com> Tor Erik S?nvisen wrote: > "Erik Max Francis" wrote in message > news:Ab6dnZLcB8e2zqHeRVn-hw at speakeasy.net... > >>Tor Erik S?nvisen wrote: >> >> >>>I need to browse the socket-module source-code. I believe it's contained >>>in the file socketmodule.c, but I can't locate this file... Where should >>>I look? >> >>The source tarball, available on python.org. Are people really too lazy >>to do elementary research on Google? >> >>-- >>Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ >>San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis >> The people are to be taken in very small doses. >> -- Ralph Waldo Emerson > > > Thanks for the answers... And yes, I have searched google! > > > As Pythonistas we can all marvel at the utility of Python, possibly best-known for its many applications at Google. However, I've noticed an increasing number of replies (quite possibly including some from me, so I'm not being holier-than-thou in this respect) of the "sheesh, can't people use Google?" type lately. However, >> Are people really too lazy to do elementary research on Google? goes a bit too far in imputing motives to the enquirer and overlooking the fact that there are some very good reasons for *not* using Google. Since Google and the Python Software Foundation have a relationship (Google are a sponsor member of the Foundation, were one of the sponsors of PyCon DC 2005 and employ some Foundation Board members) and since I am a Board member of the Foundation (there, full disclosure), I hesitate to suggest that Googling can't fulfil every individual's every needs, but the bald fact is it's true. [Thinks: if Google stock tanks today I'm in deep doo-doo here]. Technical people like to pretend there's only technology. The fact that this is demonstrably not true doesn't appear to condition their behaviour very much, and on newsgroups, a bastion of testosterone from the very early days of internetworking (due to network news' tight interlinking with the dial-up UUCP network that used mainly local calls to propagate news and mail), the position is at its worst. Note that we're talking male hormones here, since by and large women don't appear to have embraced the Python community (except perhaps individually, but that's no business of mine). While a snappish "go and look it up on Google" might suffice for a mouthy apprentice who's just asked their thirteenth question in the last half hour, it's (shall we say) a little on the brusque side for someone who only appears on the group last February, and has a history of asking reasonably pertinent though sometimes beginner-level questions. In the real world there are many reasons why people interact, and interactions on c.l.py reflect this diversity. Sometimes it's just (as Americans say) "gathering round the water cooler": it's good to be in touch with a number of other people who have the same technical interest as you, and sometimes you get to say "well done" or interject your own opinion. Other people come here for a sense of affirmation ("I wonder if those Python guys will treat me like a leper if I post on c.l.py?"), amusement ("I wonder what the quote of the week'll be on the python-url"), intelligence (I wonder if the Twisted guys have produces a new version of X recently") and even identity ("I'll argue about everything I can possibly find the minutest hole in so people know that I have a brain and can use it"). Also, many regular readers didn't grow up speaking English (I was tempted to omit those last two words and leave it at that, but I won;'t be quite so extreme today), and so they may not phrase their questions appropriately. For all I know, there may not be that much Google content in Norwegian. In short, this group is a broad church, and those readers with brain s the size of planets should remember that they are just as much in a minority as the readers who appear on the list for the first time this week. The vast majority are here to learn and grow, and I think that's the sort of behaviour we should be encouraging. Google is *very* good at delivering information. I use google.com all the time, and I'm also a Google Earth user. However, we wouldn't be at all happy if Google just stuck a pipe onto our computers and spewed information at them three times as fast as it could be read. Bandwidth on a group like this is precious (which, I recently had to be reminded, is why it's important Not to Feed the Trolls - trolls eat bandwidth up like nobody's business, and pretty soon whole days are taken up by responses to their inanities). As time goes by I find myself more and more likely, getting to the end of a possibly sharp or vindictive response, to simply kill the post and take what pleasure I can from not having shared that particular piece of small-mindedness with the group. In the end our most valuable contributions to groups like this can be the gift of being able to walk away from a fight simply to keep the noise level down. so-now-thank-me-for-not-saying-all-that-crap-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From fredrik at pythonware.com Fri Sep 30 00:42:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 06:42:34 +0200 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com><7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com><20050929182936.50b6ec54.jk@ospaz.ru> <20050929225610.504bd9d5.jk@ospaz.ru> <20050930084128.50c085e9.jk@ospaz.ru> Message-ID: en.karpachov at ospaz.ru wrote: >> > Do you ever heard of that funny things named "an interface" and "an >> > implementation"? >> >> the "shared DLL:s ought to work" school of thought, you mean? > > No, the other way around: my app works when I upgrade libraries it depends > on. yeah, because it's only the visible interface that matters. implementation semantics don't exist. you're clearly very new to this thing called programming... From steve at REMOVETHIScyber.com.au Tue Sep 20 19:10:24 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 21 Sep 2005 09:10:24 +1000 Subject: print there! References: <1127215955.371254.248380@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 20 Sep 2005 14:06:23 +0200, Fredrik Lundh wrote: > Godwin Burby wrote: > >> print 'c:\godwin\bl.csv', >> for i,row in enumerate(reader): >> # inserts or updates the database >> print i, >> This displays on the screen as : >> c:\godwin\bl.csv 1 2 3 4 5 6 7 8 >> ^ >> But i want it to show the above numbers on the same spot denoted by the >> carat character. Can it be done with print statement or any other trick? > > carriage return is your friend: > > filename = 'c:\\godwin\\bl.csv', > for i,row in enumerate(reader): > # inserts or updates the database > print "\r" + filename, i, > print That may not be enough. You may need to flush the print buffer using sys.stout.flush(). -- Steven. From martin at v.loewis.de Sun Sep 11 16:21:44 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 11 Sep 2005 22:21:44 +0200 Subject: unicode, C++, python 2.2 In-Reply-To: References: Message-ID: <432491d8$0$16457$9b622d9e@news.freenet.de> Trond Eivind Glomsr?d wrote: > I am currently writing a python interface to a C++ library. Some of the > functions in this library take unicode strings (UTF-8, mostly) as > arguments. > > However, when getting these data I run into problem on python 2.2 > (RHEL3) - while the data is all nice UCS4 in 2.3, in 2.2 it seems to be > UTF-8 on top of UCS4. UTF8 encoded in UCS4, meaning that 3 bytes of the > UCS4 char is 0 and the first one contains a byte of the string encoding > in UTF-8. > > Is there a trick to get python 2.2 to do UCS4 more cleanly? It's hard to tell from your message what your problem really is, as we have not clue what "these data" are. How do you know they are "nice UCS4" in 2.3? Are you looking at the internal representation at the C level, or are you looking at something else? Do you use byte strings or Unicode strings? You tried to explain what "UTF8 encoded in UCS4" might be, but I'm not sure I understand the explanation: what precise sequence of statements did you use to create such a thing, and what precisely does it look like (what exact byte is first, what is second, and so on)? Regards, Martin From jpopl at interia.pl Mon Sep 12 04:07:13 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Mon, 12 Sep 2005 10:07:13 +0200 Subject: read stdout/stderr without blocking Message-ID: Popen from subprocess module gives me access to stdout, so I can read it. Problem is, that I don't know how much data is available... How can I read it without blocking my program? example: -------------------------------------------------------------------- import subprocess import time command="ls -l -R /" p=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) while (p.poll()==None): print "." r=p.stdout.read() -------------------------------------------------------------------- when you comment out read() - you will notice that loop is working, with read() loop is blocked Of course I don't need to read() inside loop, but... if output is very long (like from "make") and I don't read from stdout - command will block itself! I tried to increase bufsize, but it didn't help. Is there a way to read only available data from stdout/stderr? Is there a way to not block Popen command without reading stdout/stderr? From jaywgraves at gmail.com Mon Sep 26 15:31:59 2005 From: jaywgraves at gmail.com (jay graves) Date: 26 Sep 2005 12:31:59 -0700 Subject: Plotting points to screen References: Message-ID: <1127763119.071302.300810@g44g2000cwa.googlegroups.com> I've used both pygame and PIL for this in the past. (i'm plotting a non-standard 3d data format from a in-house app) Pygame was nice because I put a key handler in to reload the file and do a little zooming/panning and when I wanted to save a particular plot I would just use a screen capture program. Then I upgraded my harddrive and didn't re-install PyGame. The next time I had to plot some data, I tweaked my script to use PIL. I ended up liking this solution better. I could easily create large images (bigger than physical screen which was a limiting factor in PyGame) and used a regular image viewer to pan and shrink/zoom. I had the drawing portions of my script well separated from the data parsing and manipulation so tweaking the script was simple. YMMV, but PIL was the best way for me. ... jay graves From hancock at anansispaceworks.com Fri Sep 16 11:50:40 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 16 Sep 2005 10:50:40 -0500 Subject: Software bugs aren't inevitable In-Reply-To: <432aca29$0$97140$ed2619ec@ptn-nntp-reader03.plus.net> References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <432aca29$0$97140$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <200509161050.40553.hancock@anansispaceworks.com> On Friday 16 September 2005 08:35 am, Michael Sparks wrote: > Steven D'Aprano wrote: > > But there is a difference: writing assembly is *hard*, which is why we > > prefer not to do it. Are you suggesting that functional programming is > > significantly easier to do than declarative? > > But there is a difference: writing assembly is *hard*, which is why we > prefer not to do it. Are you suggesting that object oriented programming is > significantly easier to do than old style imperative? The answer in both cases, is that it depends very much on what you're trying to write. > FWIW, IMO once you've learnt functional programming's idioms it certainly > can be easier and more natural. In particular domains of problem-solving, yes. > The problem is the tools that make things > like recursion efficient aren't available normally in mainstream languages > meaning that most people simply don't get the practice. There's also an assumption here (which I regard as a fallacy), that different models of programming are equally intuitive. Some models, like OOP, draw heavily on experience *outside* the realm of programming (in many cases, you can successfully apply machine-shop experience to a programming problem if the program is object-oriented -- in fact, ISTM, this is the *primary* power of OOP, that it allows you to provide experience from the problem domain to the process of writing a software program to work with that domain). Functional programming (and I am no expert here), seems to me to draw heavily on the problem domain *of* computer science. So naturally, computer scientists think it's brilliant and intuitive. But for those of us who primarily regard computers as tools for solving problems in other domains -- such as image-processing, web-application, handling business transactions, or simulating supernovae -- FP just doesn't seem very natural at all. In fact it seems completely backwards, perverse, and twisted, as if the designer were simply trying to confuse and obfuscate the problem instead of solving it. Or at least, it frequently does. > Essentially it's about expressiveness. Yes, and expressiveness means keeping vocabulary and grammar for different applications, not throwing one out on the basis that it is somehow superior. If you *are* making the latter claim, then the burden is on you to prove that your method is really that much better. > Think of it this way - we normally write left to write, however some > languages read up and down. Neither is inherently better or easier > than the other, but for some things *may* be more expressive. I *really* doubt that, actually. ;-) But I heard what you meant. > If you think about it being about choosing the most clear/expressive way to > describe an algorithm, the argument may become clearer. After all, the > recursive definition of some things is clearer than the non-recursive. Yes. I think all we're claiming is that the reverse is equally true. In addition to this kind of elegance argument, there is also a pragmatic argument that, with existing technology, it is sometimes much more efficient to write an iterative solution than to insist on recursion. Even if it can then be shown for particular cases that a recursive solution that is also efficient exists, and even if it can be proven that, in general, all such efficient iterative solutions have equivalent recursive solutions, it does not defeat the simple point that the obvious iterative solution is faster and more efficient than the obvious recursive solution. Let's not forget that this started with an example of the Fibonacci series. Who in their right mind would *actually* be trying to solve the Fibonacci series for a practical programming application? It's a toy, like the "hello world" program. I have no doubt that I can handle the extra burden of understanding the cleverly structured "efficient recursive" algorithm, versus the alternatives. But I can also see that it *is* more of a burden to understand it -- it causes confusion. Now what happens when the complexity goes up ten-fold, and we add extra bells and whistles to it that theoretical programs usually skip over, and real world programs have in abundance? At that point, I *really* want that core problem to be simple to understand. Ideally, as simple as it can possibly be. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From reinhold-birkenfeld-nospam at wolke7.net Thu Sep 22 18:50:08 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 23 Sep 2005 00:50:08 +0200 Subject: C#3.0 and lambdas In-Reply-To: <1127426064.277907.251710@g47g2000cwa.googlegroups.com> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <1127426064.277907.251710@g47g2000cwa.googlegroups.com> Message-ID: <3pgqp0Fagh77U1@individual.net> Erik Wilsher wrote: > And I think the discussion that followed proved your point perfectly > Fredrik. Big discussion over fairly minor things, but no "big picture". > Where are the initiatives on the "big stuff" (common documentation > format, improved build system, improved web modules, reworking the > standard library to mention a few) Hey, even Ruby is passing us here. This is Open Source. If you want an initiative, start one. Reinhold From eurleif at ecritters.biz Fri Sep 9 16:08:36 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 09 Sep 2005 20:08:36 GMT Subject: using % operator to print possibly unitialized data attributes In-Reply-To: <1126289950.109163.199100@o13g2000cwo.googlegroups.com> References: <1126289950.109163.199100@o13g2000cwo.googlegroups.com> Message-ID: <8ZlUe.1513$Qq1.218776@newshog.newsread.com> Adam Monsen wrote: > class J: > name = '' > value = '' > def __str__(self): > vals = self.__class__.__dict__ > vals.update(self.__dict__) > return 'name="%(name)s" value="%(value)s' % vals This will update the class's attributes with instance attributes when str() is called, which probably isn't what you want. For instance: >>> foo = J() >>> foo.name = "Joe Bloggs" >>> print foo name="Joe Bloggs" value=" >>> bar = J() >>> print bar name="Joe Bloggs" value=" What's wrong with the obvious version: class J(object): name = '' value = '' def __str__(self): return 'name=%r value=%r' % (self.name, self.value) From uche.ogbuji at gmail.com Tue Sep 13 18:03:52 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 13 Sep 2005 15:03:52 -0700 Subject: What XML lib to use? In-Reply-To: <0001HW.BF4CD7C600321189F0407550@news.individual.de> References: <0001HW.BF4CD7C600321189F0407550@news.individual.de> Message-ID: <1126649032.425693.35320@g49g2000cwa.googlegroups.com> """ I'm confused, I want to read/write XML files but I don't really understand what library to use. I've used DOM-based libraries in other languages, is PyXML the library to use? """ There are many options (some say too many): http://www.xml.com/pub/a/2004/10/13/py-xml.html Try out Amara Bindery, if you like: http://uche.ogbuji.net/tech/4suite/amara/ Browsing the manual should let you know whether you like the API: http://uche.ogbuji.net/tech/4suite/amara/manual BTW, lots on Python/XML processing covered in my column, including other options besides Amara: http://www.xml.com/pub/at/24 -- Uche http://copia.ogbuji.net From godoy at ieee.org Thu Sep 15 16:08:52 2005 From: godoy at ieee.org (Jorge Godoy) Date: 15 Sep 2005 17:08:52 -0300 Subject: p2exe using wine/cxoffice References: Message-ID: <871x3qum97.fsf@ieee.org> James Stroud writes: > "better". The only reason I want this functionality is to make my software > available to windoze users--despite their unfortunate ignorance, they are > people too. That's what I always say. +1 QOTW... -- Jorge Godoy From finite.automaton at gmail.com Tue Sep 13 16:53:30 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 13 Sep 2005 13:53:30 -0700 Subject: Windows Python 2.4: Unbuffered flag causes SyntaxError on interactive sessions? References: <1126643211.523525.22220@o13g2000cwo.googlegroups.com> Message-ID: <1126644810.073493.201700@g43g2000cwa.googlegroups.com> Weird. Did you build Python yourself? The 2.4.1 release on python.org is from March 30. I just tried ActiveState's 2.4.1... the same thing happens. From luca.tavoletti at gmail.com Thu Sep 22 10:01:28 2005 From: luca.tavoletti at gmail.com (lux) Date: 22 Sep 2005 07:01:28 -0700 Subject: Stampare su stampante aghi Message-ID: <1127397688.005150.278240@f14g2000cwb.googlegroups.com> Salve a tutti, sono alle prese con delle stampe su stampanti ad aghi... Per stampare puro testo la soluzione pi? gettonata sembra essere f = open("LPT1:") f.write("bla bla") f.close() devo dire che funziona benissimo, ma mi piacerebbe essere slegato falla parallela (sempre meno frequente) e inviare il puro testo da stampare scegliendo una delle stampanti installate sulla macchina senza starmi a preoccupare di come o dove sia configurata (locale, rete, usb, etc). Come posso fare? Grazie, Luca. From http Wed Sep 28 08:06:50 2005 From: http (Paul Rubin) Date: 28 Sep 2005 05:06:50 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: <7x3bnppfad.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Do you know any language that has real private and protected attributes? Java? From lidenalex at yahoo.se Fri Sep 30 10:15:33 2005 From: lidenalex at yahoo.se (Alex) Date: 30 Sep 2005 07:15:33 -0700 Subject: what does 0 mean in MyApp(0) Message-ID: <1128089733.684329.101320@o13g2000cwo.googlegroups.com> I'm looking at a tutorial with the code below from wxPython.wx import * class MyApp(wxApp): def OnInit(self): frame = wxFrame(NULL, -1, "winApp", size = (800,640)) frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() Everything is explained nicely except the zero parameter in MyApp(0). Anybody knows what that zero refers to? Alex From cam.ac.uk at mh391.invalid Thu Sep 1 15:09:46 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 01 Sep 2005 20:09:46 +0100 Subject: Proposal: add sys to __builtins__ Message-ID: What would people think about adding sys to __builtins__ so that "import sys" is no longer necessary? This is something I must add to every script I write that's not a one-liner since they have this idiom at the bottom: if __name__ == "__main__": sys.exit(main(sys.argv[1:])) Additionally, the necessity of "import sys" makes some one-liners a little more unwieldy than they should be--it is surely the module I am missing the most in one-liners. For example, with this proposal, this inelegant one-liner: $ python -c "import sys; print ''.join(sorted(sys.stdin.readlines()))" could be replaced by: $ python -c "print ''.join(sorted(sys.stdin.readlines()))" Since sys is surely the most commonly used module (it is imported in 108 of 188 Python 2.4 stdlib modules on my system, and certainly more than any other module), I would hope few people would be affected by a namespace collision. Other languages (e.g. C#) always make their system namespace available without needing a special import. In short, given the wide use of sys, its unambiguous nature, and the fact that it really is built-in already, although not exposed as such, I think we would be better off if sys were always allowed even without an import statement. -- Michael Hoffman From ol3ta at mindspring.com Thu Sep 22 21:36:52 2005 From: ol3ta at mindspring.com (Wayne Sutton) Date: Thu, 22 Sep 2005 21:36:52 -0400 Subject: What is "self"? Message-ID: <43335c5f$1_4@alt.athenanews.com> OK, I'm a newbie... I'm trying to learn Python & have had fun with it so far. But I'm having trouble following the many code examples with the object "self." Can someone explain this usage in plain english? Thanks, Wayne From fumanchu at amor.org Wed Sep 21 20:00:01 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Sep 2005 17:00:01 -0700 Subject: distutils and decorators References: <43317832.6030600@benjiyork.com> Message-ID: I wrote: > We're trying to get CherryPy 2.1 RC 1 out the door, but setup.py is > giving us some problems. > In our test suite, we want to test a decorator > that we provide. Of course, decorators won't work in Python 2.3 and Benji York replied: > More accurately, the special "@" decorator syntax doesn't work in 2.3. > I would propose that you *do not* want to test the syntax (that's what > the Python test suite is for), but instead test the functionality of the > decorator. Therefore I'd switch to 2.3 compatible syntax instead. Actually, in this case we most definitely want to test 2.4's "@" syntax. The decorator in question is an aliaser, and therefore is one of the few decorators which must be implemented differently for the 2.3-style decoration and the 2.4-style. See the "expose" function at: http://www.cherrypy.org/file/trunk/cherrypy/__init__.py?rev=654 Robert Brewer System Architect Amor Ministries fumanchu at amor.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sat Sep 10 19:20:47 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 10 Sep 2005 16:20:47 -0700 Subject: encryption with python In-Reply-To: References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <87k6hok51e.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <200509101620.47054.jstroud@mbi.ucla.edu> On Saturday 10 September 2005 15:02, Ron Adam wrote: > Kirk Job Sluder wrote: > I would think that any n digit random number not already in the data > base would work for an id along with a randomly generated password that > the student can change if they want. The service provider has full > access to the data with their own set of id's and passwords, so in the > case of a lost id, they can just look it up using the customers name > and/or ssn, or whatever they decide is appropriate. In the case of a > lost password, they can reset it and get another randomly generated > password. > > Or am I missing something? Yes and no. Yes, you are theoretically correct. No, I don't think you have the OP's original needs in mind (though I am mostly guessing here). The OP was obviously a TA who needed to assign students a number so that they could "anonymously" check their publicly posted grades and also so that he could do some internal record keeping. But, I'm thinking no one remembers college here anymore. When I was in college (and when I TA'd) security was kind of flimsy. TAs kept all records of SS#s, etc. (etc. includes birthdays here) in a gradebook (or the rich ones kept them on a 5 1/4" floppy). Grades were reported publicly by full SS#s, usually on a centralized cork-board. That was back in the good-ole-days, before financial fraud was euphemised to "identity theft". When I TA'd several years later, grades were reported by the last n digits of the SS#. Some very security conscious TAs--or was it just me? I think it was just me--solicited pass phrases from each student and grades were reported based on the student generated pass phrase--and not on SS# or the like. These phrases usually came in the form of "Buffs1" or "Kitty1979" (the latter possibly revealing some information about a birthday, perhaps?). Some students didn't submit pass phrases, for whatever reason. I think I did the less convenient of the two most reasonable options, which was to withold reporting the grade to the student until they gave me a phrase. The other option was to use a default pass phrase of the last n digits of the SS#. The idea of combining ID information and encrypting it to create another ID is a quantum leap beyond the primitive "last n digits of the SS#". Does it beat, in theoretical terms, assigning random numbers? No. And it certainly doesn't beat, in theoretical terms, my improved one-time-pad protocol (see my previous email). I challenge even the most capable cryptographer to beat my improved one-time-pad protocol for security (Oh wait, here it is: 1. Destroy Data.) But it is convenient, especially if you discard the original identifying information and store just the hashes. And as far as collisions go, even if a class of 10,000 gives a 1% chance of collision, who is going to TA a class of 10,000 students. If you can promise that kind of enrolment for any department, much less any single class, there is a job in an Economics department waiting for you out there, my friend. So what would be the alternative to ID information generated IDs? Have a 3xDES encrypted database with the SS# and birthday stored as plain-text? Better keep the encryption protocol secret! Oops. Screwed up already. I figured out the encryption protocol: Encrypt database with 3xDES using a secret key. Dang, security through obscurity. All they have to do is to get that secret key and all those records are easily readable. The point is that *something has to be kept secret* for encryption security to work. Theoretically best would be a passphrase, or a passphrase to a really big key. So, perhaps we could modify the algorithm from a few messages back, in order to address the (assumed) *practical* considerations of the OP's original query: import sha def encrypt(x,y, password): def _dosha(v): return sha.new(str(v)+str(password)).hexdigest() return int(_dosha(_dosha(x)+_dosha(y))[5:13],16) So now what is the criticism? That its still a "secret algorithm" because the password is "secret"? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From efrat_regev at yahoo.com Wed Sep 21 02:21:06 2005 From: efrat_regev at yahoo.com (Efrat Regev) Date: Wed, 21 Sep 2005 09:21:06 +0300 Subject: Newbie Question on ctypes Message-ID: <4330f9a7@news.bezeqint.net> Hello, (I apologize in advance if I'm posting to the wrong group. If so, could you please instruct me which is appropriate?) I'm trying to use uTidyLib, HTML-tidy's python binding. When I import tidy Python says it can't import ctypes. Since I'm using FC4, I looked for a FC4 ctypes rpm. All I could find, however, were buildlog errors for ctypes on FC4. My question is, therefore, if I can build ctypes locally. I tried rpm -i python-ctypes-0.9.1-1.rf.src.rpm but that didn't seem to work (python still couldn't import ctypes). Thanks in advance for all answers. I should point out that I'm not an expert in python or linux (in the combination, alas, even less). Thanks, Efrat From martin at v.loewis.de Wed Sep 14 02:13:00 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Sep 2005 08:13:00 +0200 Subject: Static freeze In-Reply-To: References: Message-ID: <4327bf6d$0$19020$9b622d9e@news.freenet.de> Grzegorz Dostatni wrote: > Is there a way to tell freeze to create a statically linked executable? > Freeze commandline does not appear to have that option. I'm sure that in a > day or two I can figure out the Makefile it generates and perhaps > substitute the object files to create what I need, but I'm hoping there is > someone out there who can help me (or at least save me a lot of time). You need two days to figure out the Makefile? Just changing LDFLAGS/LINKFORSHARED should do the trick. Regards, Martin From pipene-news at pu.kielce.pl Tue Sep 20 09:37:22 2005 From: pipene-news at pu.kielce.pl (Artur M. Piwko) Date: Tue, 20 Sep 2005 13:37:22 +0000 (UTC) Subject: QCheckListItem signal question Message-ID: Is there a way to distinguish if QCheckListItem was checked/unchecked or clicked? -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:213B ] [ 15:36:46 user up 10740 days, 3:31, 1 user, load average: 0.06, 0.06, 0.06 ] Grain grows best in shit. From pedro.werneck at terra.com.br Sun Sep 18 12:17:42 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 18 Sep 2005 13:17:42 -0300 Subject: Possible bug in "metaclass resolution order" ? In-Reply-To: <1127029171.838998.113680@o13g2000cwo.googlegroups.com> References: <1126972310.484861.138970@o13g2000cwo.googlegroups.com> <1127029171.838998.113680@o13g2000cwo.googlegroups.com> Message-ID: <20050918131742.4517cdea.pedro.werneck@terra.com.br> On 18 Sep 2005 00:39:31 -0700 "Michele Simionato" wrote: > Remember that given a class C, its metaclass is given by C.__class__, > not by > C.__metaclass__, despite the name. Of course. Seems you think I'm arguing that C.__class__ and __metaclass__ should always be the same. The metaclass is given by C.__class__ after class creation. At the end of the 'class' statement, searching for the 'winner' metatype, dict["__metaclass__"] is supposed to have priority over B.__class__, and this over global __metaclass__. Not only this is the behavior documented on GvR essay but is on the source code I mentioned too. > You argue that in this case an error should be raised, since "errors > should never pass silently". May be. Exactly... and the behaviour is inconsistent. I get an exception when the metaclass is not related to the M_A-M_B hierarchy, like X below, and the same error was supposed to be raised when using M_A or type, which do not follow the same rule of being a "subclass of the metaclasses of all its bases". In fact, I lost a lot of time trying to find an error related to this in my code a few weeks ago. >>> class X(type): pass ... >>> class C(B): __metaclass__ = X ... Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases >>> class C(B): __metaclass__ = M_A ... >>> C.__metaclass__ >>> C.__class__ > You are free to post the bug report and look at the opinions of the > developers. I posted a few hours ago. Thank you. -- Pedro Werneck From bokr at oz.net Mon Sep 5 09:04:31 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 05 Sep 2005 13:04:31 GMT Subject: Job Offer in Paris, France : R&D Engineer (Plone) References: <7xbr37u8ut.fsf@ruckus.brouhaha.com> Message-ID: <431c412e.669539797@news.oz.net> On 05 Sep 2005 03:06:34 -0700, Paul Rubin wrote: >Huron writes: >> Sopinspace, Society For Public Information Spaces (specialized in Web-based >> citizen public debate and collaborative initiatives) is looking for a new >> developer / R&D engineer with strong Plone focus. >> The position is located in Paris, France (11eme). >> >> All details (in french) can be found here : >> http://www.sopinspace.com/company/poste_ing.pdf contact : emploi >> <*at*> sopinspace <-dot-> com > >Since you're posting in English, is there any point in responding >to it in English, and are non-Europeans eligible? It says, "bonne ma?trise de l'anglais ?crit et parl? (toute autre langue sera un plus)" so good mastery of English written and spoken is the main language requirement (stated, that is ;-) But "capacit? de dialoguer avec des usagers non techniques et tous les membres de l'?quipe" probably means French too ;-) Regards, Bengt Richter From edhotchkiss at gmail.com Mon Sep 19 23:41:47 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Mon, 19 Sep 2005 23:41:47 -0400 Subject: Best Encryption for Python Client/Server In-Reply-To: References: <200509191446.15240.jstroud@mbi.ucla.edu> Message-ID: No worries, I apologize for my outburst. I will check out the viability of using an SSH module, or using pyCrypto or something to encrypt the data. Here's my mission: simple P2P class with encryption of whatever type of file is being sent, and authentication via encrypted user name/password. So any type of file or login being sent over the net, any communication between the scripts should be encrypted, regardless of whether it is client/server communication, or file transfer. Now that I've finally stated what I want to do (sorry) Is SSH a good option, or just using sockets with pycrypto? Thanks in advance. -edward -------------- next part -------------- An HTML attachment was scrubbed... URL: From frank at chagford.com Wed Sep 14 02:47:57 2005 From: frank at chagford.com (Frank Millman) Date: 13 Sep 2005 23:47:57 -0700 Subject: How to protect Python source from modification In-Reply-To: References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> <1126539190.828744.78280@g49g2000cwa.googlegroups.com> <1126598437.871654.12270@g49g2000cwa.googlegroups.com> Message-ID: <1126680477.103108.68350@g44g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 13 Sep 2005 01:00:37 -0700, "Frank Millman" > declaimed the following in comp.lang.python: > > > > 2. I am a great believer in 'field-by-field' validation when doing data > > entry, instead of filling in the entire form, submitting it, and then > > being informed of all the errors. I can inform a user straight away if > > they try to do something they are not entitled to. > > > Ensuring a field is numeric (with range checking) or string is one > thing... But if a certain user is not even supposed to see a field, or > only have read-only access, those could be determined at the server side > when generating the form (okay, that was phrased more as a web-page > scheme, but...) Better that low-privilege users never even learn of the > additional data fields rather than be tempted by the "forbidden fruit" > > Food for thought - thanks > > 3. I can cater for the situation where a user may not have permission > > to do something, but they can call a supervisor who can override this. > > I have seen solutions which involve prompting for a password, but this > > has to be programmed in at every place where it might be required. I > > allow the supervisor to enter their userid and password, and my program > > reads in their permissions, which become the active ones until > > cancelled. I create a flashing red border around the window to warn > > them not to forget. > > > I suspect such an override could still be done through the server > side. Not sure of the "programmed in at every place" concern -- it > sounds like just an exception handler with retry (and if it were done > via web forms, it would be the server detecting "no privilege" and > returning the override log-in form). I'd be more concerned that the > override doesn't go away after the transaction is completed... To me, if > a lowly user needs to have a supervisor unlock operations -- and the > supervisor then walks away while the higher privileges are active, it is > a sign of either poor security practices, or a need to grant that user > more privileges. > > Imagine a store where supervisor approval is needed for any check > over a certain amount... You don't want the supervisor to key in their > approval code on a register and walk away leaving that code active (and > letting the clerk then enter dozens of high value checks without calling > for a supervisor). The code should only be active for the completion of > the check approval and then automatically reset to the regular clerk's > mode of operation. > H'mm, more food for thought. The advantage of my approach is that no additional programming is required. I have a very flexible security model, which is entirely user-definable. If any user finds that they are blocked from doing something, they can call anyone who does have that permission, without exiting from their position in the app. The other person can key in their userid and password, perform the required action, and the original user can carry on. You are right that the danger is that the second person forgets to cancel their code. That is why I create a flashing red border. This is how it works from a user perspective. There is a hot-key, Ctrl-U, which can be pressed at any prompt (wxPython makes this easy). If pressed, I pop up a box asking for userid and password. If accepted, I save the original user's permissions, read in the new user's permissions, and create the flashing border. To cancel the setting, the user simply presses Ctrl-U again, and everything is reset. I think this works quite well, so I will run with it for now and see if it causes any problems in practice. Many thanks for the valuable comments. Frank From jpopl at interia.pl Fri Sep 9 07:22:04 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Fri, 09 Sep 2005 13:22:04 +0200 Subject: subprocess solved all my problems Message-ID: In the last week I was working to create script which will read command from socket, call it, return result, stdout, stderr and kill it after timeout. After playing with threads, processes, spawns and popens I found subprocess module. To call command I use following construction: finish=time.time()+self.timeout self.p=subprocess.Popen(self.command,shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE) while (self.p.poll()==None) and (time.time() I am trying to execute a win python script that connects to an AS/400; changes from the native lib to the IFS file system; then, changes to a directory in IFS; gets a file. Any help would be greatly appreciated. I cannot get the script to switch from native to IFS. I get the following error: Traceback (most recent call last): File "C:\Python24\Tools\scripts\ftp400.py", line 9, in ? ftp.cwd(path) File "C:\Python24\lib\ftplib.py", line 494, in cwd return self.voidcmd(cmd) File "C:\Python24\lib\ftplib.py", line 246, in voidcmd return self.voidresp() File "C:\Python24\lib\ftplib.py", line 221, in voidresp resp = self.getresp() File "C:\Python24\lib\ftplib.py", line 214, in getresp raise error_perm, resp ftplib.error_perm: 501 Unknown extension in database file name. here is the script: import ftplib, os filename='' path = "directory" os.chdir('c:\\ftp_jde400') ftp = ftplib.FTP('server', 'user', 'password') ftp.sendcmd('site namefmt 1') ftp.cwd(path) #remotefiles = ftp.nlst() #ftp.retrlines('LIST') #for filename in remotefiles: # file = open(filename, 'wb') # ftp.retrbinary('RETR ' + filename, file.write, 1024) # file.close() ftp.quit() From nyamatongwe+thunder at gmail.com Fri Sep 16 20:24:29 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 17 Sep 2005 00:24:29 GMT Subject: Unicode-aware file shortcuts in Windows In-Reply-To: References: Message-ID: <1nJWe.49481$FA3.30157@news-server.bigpond.net.au> Stanislaw Findeisen: > E:\Documents and Settings\Staszek\Progs\Python-Windows\test_1>cf.py > Traceback (most recent call last): > File "E:\Documents and > Settings\Staszek\Progs\Python-Windows\test_1\cf.py", line 7, in ? > shortcut.Save() > File ">", line 2, in Save > pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, > 'WshShortcut.Save', 'Unable to save shortcut "E:\\Documents and > Settings\\Staszek\\Progs\\Python-Windows\\test_1\\Te\x9a\xed me c\xfd > z\xf3lazcseL\\link do vecer Z\xd3LAKe e\x9a\xed bla.lnk".', None, 0, > -2147024893), None) I see similar problems using WSH so I think the problem is in WScript.Shell, rather than in Python's access to COM. Slightly simplified and with the directory created: C:\bin>cscript ul.wsf Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Start C:\bin\ul.wsf(9, 11) WshShortcut.Save: Unable to save shortcut "C:\Te?? me c? z?lazcseL\link do vecer Z?LAKe e?? bla.lnk". C:\bin>dir c:\T* Volume in drive C has no label. Volume Serial Number is A04B-224D Directory of c:\ 02/06/2005 10:30 PM 67 test.py 17/09/2005 09:56 AM T??? m? ?? ????????? 1 File(s) 67 bytes 1 Dir(s) 7,014,309,888 bytes free C:\bin>dir "c:\T??? m? ?? ?????????" Volume in drive C has no label. Volume Serial Number is A04B-224D Directory of c:\T??? m? ?? ????????? 17/09/2005 09:56 AM . 17/09/2005 09:56 AM .. 0 File(s) 0 bytes 2 Dir(s) 7,014,309,888 bytes free C:\bin> Happy googling. Neil From jbperez808 at yahoo.com Mon Sep 19 22:40:12 2005 From: jbperez808 at yahoo.com (jbperez808 at yahoo.com) Date: 19 Sep 2005 19:40:12 -0700 Subject: slicing functionality for strings / Python suitability forbioinformatics In-Reply-To: References: <1127157916.290111.112620@g47g2000cwa.googlegroups.com> <3p8in6F98fduU1@individual.net> Message-ID: <1127184012.589663.17820@g44g2000cwa.googlegroups.com> Having to do an array.array('c',...): >>> x=array.array('c','ATCTGACGTC') >>> x[1:9:2]=array.array('c','AAAA') >>> x.tostring() 'AACAGACATC' is a bit klunkier than one would want, but I guess the efficient performance is the silver lining here. From steven.bethard at gmail.com Tue Sep 6 17:42:41 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 06 Sep 2005 15:42:41 -0600 Subject: __dict__ of object, Was: Regular Expression IGNORECASE different for findall and split? In-Reply-To: References: Message-ID: Chris wrote: > but more of a basic question following, I was doing the following before: > > method = 'split' # came from somewhere else of course > result = re.__dict__[method].(REGEX, TXT) > > precompiling the regex > > r = compile(REGEX) > > does give an regex object which has the needed methods > > print dir(r) > ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', > 'scanner', 'search', 'split', 'sub', 'subn'] > > but how do I evaluate them without explicitly calling them? > > result = r.__???MAGIC???__[method](TXT) > > obviously I am not a Python pro ;) Use getattr: method = 'split' result = getattr(re.compile(REGEX), method)(TXT) HTH, STeVe From bokr at oz.net Fri Sep 16 15:56:55 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 16 Sep 2005 19:56:55 GMT Subject: 2.3 -> 2.4: long int too large to convert to int References: <11ijsh0h2dec0ed@corp.supernews.com> <11ilnab5b5vsue0@corp.supernews.com> Message-ID: <432b1f2a.1643811836@news.oz.net> On Fri, 16 Sep 2005 14:57:15 -0000, Grant Edwards wrote: [...] > >What I would really, really like are fixed length integer types >so that I can manipulate 8, 16, 32 and maybe 64 bit, 2's >compliment values. I've seen some pretty good "user-space" >pure-python implimentations, but haven't gotten around to using >them in production yet. > >One of the nasty bits in a pure-python approach is that there's >no way to write a literal with a fixed length. For example, >instead of writing 0xf7 to get an 8-bit value and 0x12345789 to >get a 32-bit value, you have to instantiate a class like >Word8(0xf7) and Word32(0x12345678). > >That starts to make things pretty hard to read. > I'm not sure at what point you actually need "fixed width" other than passing to some non-python interface, in which case an interface object could have a suitable property to do the final trimming or padding of bits. Or do you want to define some kind of mathematical space? For specifying bits in literals see my other post in this thread (I think ;-) Regards, Bengt Richter From desparn at wtf.com Mon Sep 5 01:04:41 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Mon, 05 Sep 2005 01:04:41 -0400 Subject: Proposal: add sys to __builtins__ References: Message-ID: "Terry Reedy" wrote in news:mailman.120.1125883780.4249.python-list at python.org: > > "Colin J. Williams" wrote in message > news:JEBSe.55$vN.6924 at news20.bellglobal.com... >> Rick Wotnaz wrote: >>> +1 here. As far as I'm concerned, both os and sys could be >>> special- cased that way. That said, I would guess the >>> likelihood of that happening is 0. >>> >> +1 for both. > > Some people might prefer that math be special cased. Or some > other module. A neutral criterion is needed. > Actually, I don't think it's beyond reason to suggest that any module included with the standard distribution be special-cased in this way. That is, a reference to xxx.func(), without a previous import of xxx *could* be resolvable automatically, at least for those modules that can be found in a standard location. Whether it's a good idea to do so is another question. Offhand, I am not sure why it would be an insanely poor idea. It would mean some funky namespace building and possibly redundant imports, I guess. I'll certainly defer to just about anybody else's opinion as to the difficulty and advisability, but I believe it would be possible to do. Note that I am not saying that a reference to, say, 'argv' should provoke an automatic import. I don't mean that some automatic search for a matching function name should be done through some undefined module chain. I'm talking only about qualified references, like os.path or sys.stderr. As it is, a NameError is generated if the proper import has not been done. At the point of that error, the module name is known. For the programmer to fix the situation, an import statement has to be added to the code and then the code must be rerun. I don't see why it would be impossible to make that happen automatically, provided the module to be imported was recognized (through some undefined magic). I'd think the module would have to be known, because trying to import a nonexistent module -- "import ssy", say (in the event of a typo for "sys") -- would fail, so there would have to be a way to avoid looping on the "ssy.func()" line. Is it worth adding that kind of complexity to execution of a Python program? Probably not. Is it even a good idea to try to make it happen automatically? Possibly not. For one thing, it wouldn't always be the right thing to do. A developer would most likely want to set up the imports properly, and to know when they were not correctly set up instead of having Python fix things quietly. There's a reason why Explicit is better than Implicit. But *could* it be done? I'd think so. -- rzed From pierre.barbier at cirad.fr Thu Sep 29 09:38:03 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 29 Sep 2005 15:38:03 +0200 Subject: User-defined augmented assignment Message-ID: <433beda9$0$7354$626a14ce@news.free.fr> Hello, a discussion began on python-dev about this. It began by a bug report, but is shifted and it now belongs to this discussion group. The problem I find with augmented assignment is it's too complex, it's badly explained, it's error-prone. And most of all, I don't see any use-case for it ! The most common error is to consider that : a += b <==> a.__iadd__(b) when the truth is : a += b <==> a = a.__iadd__(b) which can be very confusing, as the two "a" are not necessarily the same. It then leads to subtle errors like: >>> class A(object): >>> a = 0 >>> a = A() >>> b = A() >>> a.a += 1 >>> A.a += 2 >>> print a.a 1 >>> print b.a 2 Also, the following behavior is pretty confusing : >>> a = [1] >>> b = [a] >>> c = (a,) >>> b[0] += [2] # Ok, no pb >>> print a [1,2] >>> c[0] += [3] Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment >>> print a [1,2,3] Then, in the standard library, there is no use-case of user-defined augmented assignment I could find. Of course, I find the augmented assignement itself very useful ! I use it a lot with immutable objects (strings, numbers, tuples, ...) but I tend to avoid it with mutables, and so it seems in the standard library that uses extensively the "extend" method of lists and very seldom the "+=" operator with lists. And even where the "a+=b" is used, it could be replaced with either "a.extend(b)" or "a = a+b" without bugs. So, what I would suggest is to drop the user-defined augmented assignment and to ensure this equivalence : a X= b <=> a = a X b with 'X' begin one of the operators. Pierre From mahs at telcopartners.com Fri Sep 23 20:03:13 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 23 Sep 2005 17:03:13 -0700 Subject: Wrapping classes In-Reply-To: References: <35CdnQgRcKzchK7eRVn-2A@powergate.ca> Message-ID: Jeremy Sanders wrote: > Colin J. Williams wrote: > > >>Could you not have functions a and b each of which returns a NumArray >>instance? >> >>Your expression would then be something like a(..)+2*b(..). > > > The user enters the expression (yes - I'm aware of the possible security > issues), as it is a scientific application. I don't think they'd like to > put () after each variable name. > > I could always munge the expression after the user enters it, of course. > > Jeremy > Alternatively, you could build your own expression calculator, and initialize the objects if necessary as they are evaluated. If you are happy with Python syntax for your expressiones then the stdlib compiler package is helpful. The example below is not tested beyond what you see. It's a bit verbose, but most of the code is boilerplate. >>> a = 3 >>> b = 4 >>> calc('a * b') using a using b 12 >>> calc('a * b ** (b - a) * "a"') using a using b using b using a 'aaaaaaaaaaaa' >>> calc("0 and a or b") using b 4 >>> calc("1 and a or b") using a 3 >>> calc("1 and a or c") using a 3 >>> calc("0 and a or c") Undefined symbol: c >>> HTH, Michael ----------------- import compiler class CalcError(Exception): def __init__(self,error,descr = None,node = None): self.error = error self.descr = descr self.node = node def __repr__(self): return "%s: %s" % (self.error, self.descr) __str__ = __repr__ class LazyCalc(object): def __init__(self, namespace): self._cache = {} # dispatch table self.context = namespace def visit(self, node,**kw): cls = node.__class__ meth = self._cache.setdefault(cls, getattr(self,'visit'+cls.__name__,self.default)) return meth(node, **kw) def visitExpression(self, node, **kw): return self.visit(node.node) # Binary Ops def visitAdd(self,node,**kw): return self.visit(node.left) + self.visit(node.right) def visitDiv(self,node,**kw): return self.visit(node.left) / self.visit(node.right) def visitFloorDiv(self,node,**kw): return self.visit(node.left) // self.visit(node.right) def visitLeftShift(self,node,**kw): return self.visit(node.left) << self.visit(node.right) def visitMod(self,node,**kw): return self.visit(node.left) % self.visit(node.right) def visitMul(self,node,**kw): return self.visit(node.left) * self.visit(node.right) def visitPower(self,node,**kw): return self.visit(node.left) ** self.visit(node.right) def visitRightShift(self,node,**kw): return self.visit(node.left) >> self.visit(node.right) def visitSub(self,node,**kw): return self.visit(node.left) - self.visit(node.right) # Unary ops def visitNot(self,node,*kw): return not self.visit(node.expr) def visitUnarySub(self,node,*kw): return -self.visit(node.expr) def visitInvert(self,node,*kw): return ~self.visit(node.expr) def visitUnaryAdd(self,node,*kw): return +self.visit(node.expr) # Flow Control def visitAnd(self,node,**kw): for arg in node.nodes: val = self.visit(arg) if not val: return val return val def visitOr(self,node,**kw): for arg in node.nodes: val = self.visit(arg) if val: return val return val # Logical Ops def visitBitand(self,node,**kw): return reduce(lambda a,b: a & b,[self.visit(arg) for arg in node.nodes]) def visitBitor(self,node,**kw): return reduce(lambda a,b: a | b,[self.visit(arg) for arg in node.nodes]) def visitBitxor(self,node,**kw): return reduce(lambda a,b: a ^ b,[self.visit(arg) for arg in node.nodes]) def visitCompare(self,node,**kw): comparisons = { "<": operator.lt, # strictly less than "<=": operator.le,# less than or equal ">": operator.gt, # strictly greater than ">=": operator.ge, # greater than or equal "==": operator.eq, # equal "!=": operator.ne, # not equal "<>": operator.ne, # not equal "is": operator.is_, # object identity "is not": operator.is_not # negated object identity } obj = self.visit(node.expr) for op, compnode in node.ops: compobj = self.visit(compnode) if not comparisons[op](obj, compobj): return False obj = compobj return True # Values def visitCallFunc(self,node,**kw): raise CalcError("Functions not supported", node.node) def visitName(self, node, **kw): """LazyEvaluation""" name = node.name try: val = eval(name, self.context) except NameError: raise CalcError("Undefined symbol",name) except: raise print "using %s" % name # init if necessary here return val def visitConst(self, node, **kw): return node.value # Other def default(self, node, **kw): """Anything not expressly allowed is forbidden""" raise CalcError("Not Allowed", node.__class__.__name__,node) def calc(source, context = None): walker = LazyCalc(context or globals()) try: ast = compiler.parse(source,"eval") except SyntaxError, err: raise try: return walker.visit(ast) except CalcError, err: return err From amk at amk.ca Fri Sep 2 09:10:34 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 02 Sep 2005 08:10:34 -0500 Subject: OpenSource documentation problems References: <4317BEAC.6030804@holdenweb.com> Message-ID: <1LOdnZ2dnZ1qRSK7nZ2dndfShd6dnZ2dRVn-y52dnZ0@speakeasy.net> On Thu, 1 Sep 2005 23:08:18 -0400, Fred L. Drake, Jr. wrote: > Ideally, emails to docs at python.org would result in issues being created > somewhere, simply so they don't get lost. It probably doesn't make sense for > those to land in SourceForge automatically, since then everyone has to read > every plea for a printable version of the documents. As a stop-gap, could we encourage people to record issues on a wiki page? Then someone could periodically look at the page and act on the suggestions there. The problem is that Wikis aren't really newbie-friendly, either; while you don't need to register for the Python wiki any more, many people don't realize the pages are editable. Still, it might be worth a try. --amk From grante at visi.com Tue Sep 13 10:46:12 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 13 Sep 2005 14:46:12 -0000 Subject: read stdout/stderr without blocking References: <11ib4sfhuj94m0b@corp.supernews.com> <11idodoscmns1b9@corp.supernews.com> Message-ID: <11idphkoce2p1d7@corp.supernews.com> On 2005-09-13, Jacek Pop?awski wrote: > Grant Edwards wrote: >> You're right. I must have been remembering the behavior of a >> network socket. Apparently, you're supposed to read a single >> byte and then call select() again. That seems pretty lame. > > I created another thread with single read(), it works, as long > as I have only one PIPE (i.e. stderr is redirected into > stdout). I wonder is it Python limitation or systems one (I > need portable solution)? Not sure what you mean. Here is my test program that blocks on the read(1024) call: #!/usr/bin/python import os,select p = os.popen("while sleep 2; do date; done","r") print p while 1: r,w,e = select.select([p],[],[],1) if r: d = r[0].read(1024) print len(d),repr(d) else: print "timeout" It also blocks if the call is changed to read(). This seems pretty counter-intuitive, since that's not the way read() usually works on pipes. Here's the corresponding C program that works as I expected (read(1024) returns available data): #include #include #include #include unsigned char buffer[1024]; int main(void) { fd_set readfds, writefds, exceptfds; struct timeval tv; FILE *fp; int fd; fp = popen("while sleep 2; do date; done","r"); if (!fp) { perror("popen"); exit(1); } fd = fileno(fp); FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); while (1) { int s; FD_SET(fd,&readfds); tv.tv_sec = 1; tv.tv_usec = 0; s = select(fd+1,&readfds,&writefds,&exceptfds,&tv); if (s==0) printf("timeout\n"); else if (s<0) { perror("select"); exit(2); } else { if FD_ISSET(fd,&readfds) { int n = read(fd,buffer,(sizeof buffer)-1); buffer[n] = '\0'; printf("read %d: '%s'\n",n,buffer); } } } } -- Grant Edwards grante Yow! Does that mean at I'm not a well-adjusted visi.com person?? From larry.bates at websafe.com Fri Sep 23 14:25:34 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 23 Sep 2005 13:25:34 -0500 Subject: CRC16 In-Reply-To: <1127497562.576819.83920@f14g2000cwb.googlegroups.com> References: <1127497562.576819.83920@f14g2000cwb.googlegroups.com> Message-ID: <4334489E.1060208@websafe.com> The first URL back from Google is: http://www.onembedding.com/tools/python/code/crc16.htm Site is Russian, but crc16.py that is listed there has English comments. Maybe you can use some/all of it. -Larry Bates Tuvas wrote: > Anyone know a module that does CRC16 for Python? I have an aplication > that I need to run it, and am not having alot of sucess. I have a > program in C that uses a CRC16 according to CCITT standards, but need > to get a program that tests it with python as well. Thanks! > From ksenia.marasanova at gmail.com Sun Sep 18 13:05:42 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sun, 18 Sep 2005 20:05:42 +0300 Subject: How does f=open('mytext.txt', 'w+') work? In-Reply-To: <1127059911.786742.195010@g43g2000cwa.googlegroups.com> References: <1127059911.786742.195010@g43g2000cwa.googlegroups.com> Message-ID: <130df19305091810056f7cf977@mail.gmail.com> 18 Sep 2005 09:11:51 -0700, Alex : > Rossum's tutorial on Python states: it's "Van Rossum's" :) "van" in a part of the last name, you can't just cut it away in Dutch :) -- Ksenia From rschroev_nospam_ml at fastmail.fm Wed Sep 21 10:55:24 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 21 Sep 2005 14:55:24 GMT Subject: C#3.0 and lambdas In-Reply-To: <43315dd9$0$3051$626a14ce@news.free.fr> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> <43315dd9$0$3051$626a14ce@news.free.fr> Message-ID: Christophe schreef: > Steve Holden a ?crit : > >> Christophe wrote: >> >>> Serhiy Storchaka a ?crit : >>> >>>> Roel Schroeven wrote: >> >> >> [...] >> >>>>> or >>>>> >>>>> def drawline(p1, p2): >>>>> # draw a line from p1[0], p1[1] to p2[0], p2[1] >>>>> foo(p1[0], p1[1]) >>>>> bar(p2[0], p2[1]) >>>> >>>> >>>> >>>> >>>> def drawline(p1, p2): >>>> # draw a line from p1 to p2 >>>> foo(*p1) >>>> bar(*p2) >>>> >>> >>> >>> That one is stupid. I don't see how you can make it work without some >>> global storing the p1 information in foo which I would consider as >>> very ugly code. >> >> >> >> In which case perhaps you should actually try the code. Then once you >> realise it works you can start to figure out why :-). Hint: f(*p1) >> appears as len(p1) separate arguments to the called function. > > > You should also notice that foo knows the starting point of the line but > not the ending point and so it can't draw the line. On the other hand, > bar knows the end point but not the starting point so it can't do the > job either. It was just an example of tuples as arguments to a function and doing something with the values of the tuples in the function itself. Even so, many graphical environments offer MoveTo(x, y) and LineTo(x, y) or equivalents. MoveTo moves some internal cursor to the specified position without drawing a line; LineTo draws a line from the stored cursor position to the specified position and moves the internal cursor to that new position. > And what about a function which computes the line length ? That would have been a better example indeed, since the *p1 trick doesn't work there. def euclidian_distance((x1, y1), (x2, y2)): return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) That's a lot nicer, I think, than this: def euclidian_distance(p1, p2): return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From opengeometry at yahoo.ca Thu Sep 29 16:18:10 2005 From: opengeometry at yahoo.ca (William Park) Date: Thu, 29 Sep 2005 16:18:10 -0400 Subject: Dynamic character substitution. References: Message-ID: John Bausano wrote: > Hello all, > > > > I've been using Ansys which is a commercial FEA package which can be > controlled through its own scripting language they call APDL. Now I'm > trying to write some stand alone code in Python to supplement my current > efforts. > > > > In Ansys I can do something like this. > > > > *do,n,1,3 #loop > through n > > *dim,data%n%,1000,2 #creates variables > arrays data1(1000,2), data2(1000,2).. > > *vread,data%n%,filename%n% #fills arrays with data > from filename1,. I await English translation of the above. -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From enleverlesO.OmcO at OmclaveauO.com Thu Sep 1 06:24:28 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Thu, 1 Sep 2005 12:24:28 +0200 Subject: Open-Office ; Python & Win (plain/text) Message-ID: <4316d762$0$4804$636a15ce@news.free.fr> Open-Office 2.0 b?ta-2 fran?ais pour Windows (en fait, la 1.9.125 ) est sortie. Vous la trouverez l? : http://oootranslation.services.openoffice.org/pub/OpenOffice.org/2.0beta2rc/OOo_2.0beta2_Win32Intel_install_fr.zip Je cite ce lien, car j'ai r?ussi ? piloter Open-Office, depuis Python, avec PyWin32. Vous trouverez ci dessous le script exp?rimental (code "brut" et m?chant ; mais c'est la faisabilit? qui importe ici). Ce script fonctionne avec le fichier Open-office C:\\ootest.odt qui contient : --------------------------------------------------------------------- AAAAAAAAAAAA BBBBBBBBBBB CCCCCCCCCCC 111%TXT1%111 22222222222222 %CADRE1% 333333333333333 4444444444444444 Aaz aze ABC djhevgd fude uftyf ofh efzehiufre hiufre zefoz hfzr hruifh ABC ABC gyuguyg ufg eruzyfgerABCABC efeorzehfzrehiufreh ABC --------------------------------------------------------------------- Recr?ez ce fichier, puis lancez le script ci-dessous. Ensuite, ben... lisez le code-source, et d?brouillez-vous... --- Michel Claveau PS : je poste ce message en HTML, puis en plain/text, pour faciliter les choses. --------------------------------------------------------------------- # -*- coding: cp1252 -*- import win32com.client import time def insertIntoCell( strCellName, strText, objTable): objCellText = objTable.getCellByName( strCellName) objCellCursor = objCellText.createTextCursor() objCellCursor.setPropertyValue("CharColor",16777215) objCellText.insertString(objCellCursor, strText, False) objServiceManager = win32com.client.Dispatch("com.sun.star.ServiceManager") objDesktop = objServiceManager.CreateInstance("com.sun.star.frame.Desktop") args = [] #si nouveau document, ligne suivante #objDocument = objDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args) """ //swriter pour le traitement de texte. //scalc pour le tableur //sdraw pour l'?diteur de dessin //simpress pour l'?diteur de pr?sentation (?quivalent de PowerPoint) //smath pour l'?diteur de formule math?matique //swriter/Global Document document maitre //swriter/web Pour l'?diteur HTML """ #si document existant objDocument = objDesktop.loadComponentFromURL("file:///C:/ootest.odt", "_blank", 0, args) objText = objDocument.GetText() objCursor = objText.createTextCursor() objText.insertString(objCursor, "Vous avez les salutations de PONX.\nCeci est la deuxi?me ligne.\n", 0) objText.insertString(objCursor, "Troisi?me ligne.\n", 0) objText.insertString(objCursor, "4? ligne ????@?.\n\n\n", 0) # Tableau #Cr?e un tableau de 4 colonnes x 4 lignes objTable= objDocument.createInstance( "com.sun.star.text.TextTable") objTable.IsWidthRelative = True objTable.RelativeWidth = 80 # largeur de 80 % objTable.BackColor = 255*256*256+255*256+204 # fond en jaune clair objTable.HoriOrient = 2 # 0 LEFT 1 RIGHT 2 CENTER objTable.initialize(8, 4) # lignes / colonnes #Ins?re la table objText.insertTextContent(objCursor, objTable, 0) #1?re ligne objRows = objTable.getRows() objRow0 = objRows.getByIndex(0) #Couleur de fond objTable.setPropertyValue("BackTransparent", 0) objTable.setPropertyValue("BackColor", 255*256*256+255*256+204) #Autre couleur de fond, pour la premi?re ligne objRow0.setPropertyValue("BackTransparent", 0) objRow0.setPropertyValue("BackColor", 6710932) objRow0.setPropertyValue("IsAutoHeight", False) objRow0.setPropertyValue("Height", 3000) #30 mm #Remplissage 1?re ligne insertIntoCell("A1","FirstColumn",objTable) insertIntoCell("B1","SecondColumn",objTable) insertIntoCell("C1","ThirdColumn",objTable) insertIntoCell("D1","SUM",objTable) #Remplissage suite objTable.getCellByName("A2").setValue(22.5) objTable.getCellByName("B2").setValue(5615.3) objTable.getCellByName("C2").setValue(-2315.7) objTable.getCellByName("D2").setFormula("sum(||)") objTable.getCellByName("A3").setValue(21.5) objTable.getCellByName("B3").setValue(615.3) objTable.getCellByName("C3").setValue(-315.7) objTable.getCellByName("D3").setFormula("sum()") objTable.getCellByName("A4").setValue(121.5) objTable.getCellByName("B4").setValue(-615.3) objTable.getCellByName("C4").setValue(415.7) objTable.getCellByName("D4").setFormula("sum ") #on s?lectionne la colonne C sCell = objTable.createCursorByCellName("C1") sCell.goDown(4, True) sCell.BackColor = 255*256*256+200*256+200 #rouge clair """ ?a ne marche pas (sp?cif OO-2.0 ?) cols = objTable.getColumns() col = cols.getByIndex(2) """ #Couleur des caract?res et ombre objCursor.setPropertyValue("CharColor", 255) objCursor.setPropertyValue("CharShadowed", True) #Saut de paragraphe #The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant objText.insertControlCharacter(objCursor, 0 , False) #Insertion texte objText.insertString(objCursor, " Texte color? - bleu avec ombre\n", False) #Saut de paragraphe (caract?re sp?cial PARAGRAPH_BREAK = 0). objText.insertControlCharacter(objCursor, 0, False) #on repasse en noir, sans ombre objCursor.setPropertyValue("CharColor", 0) objCursor.setPropertyValue("CharShadowed", False) # Attention : ces 4 lignes fonctionnent en invisible. objText.insertString(objCursor, "RRRRRRRRRRR", False) objCursor.goLeft(3, False) objCursor.goLeft(5, True) objCursor.String="+++" objCursor.gotoEndOfParagraph(False) #Saut de paragraphe objText.insertControlCharacter(objCursor, 0, False) #Cr?ation d'un cadre (TextFrame) objTextFrame= objDocument.createInstance("com.sun.star.text.TextFrame") objTextFrame.Width = 10400 # 104 mm largeur #objTextFrame.Height =2000 # 20 mm de haut # ne sert ? rien, le cadre d'agrandit tout seul #Affectation type de cadre (AnchorType.AS_CHARACTER = 1) objTextFrame.setPropertyValue("AnchorType", 1) #insertion du cadre objText.insertTextContent(objCursor, objTextFrame, False) #Lecture du texte du cadre objFrameText= objTextFrame.getText() #Positionnement curseur interne objFrameTextCursor= objFrameText.createTextCursor() #Insertion texte objFrameText.insertString(objFrameTextCursor, "Encore du texte\naaaaaaaaaaaa\nbbbbbbb\nccccc\n", False) objFrameText.insertString(objFrameTextCursor, "\net une autre ligne.", False) objFrameText.insertString(objFrameTextCursor, "AAAAAAAA1\n", False) objFrameText.insertString(objFrameTextCursor, "AAAAAAAA2\n", False) objFrameText.insertString(objFrameTextCursor, "AAAAAAAA3\n", False) objFrameText.insertString(objFrameTextCursor, "AAAAAAAA4\n", False) objFrameText.insertString(objFrameTextCursor, "AAAAAAAA5", False) #Cr?ation d'un cadre (TextFrame) objTextFrame= objDocument.createInstance("com.sun.star.text.TextFrame") objTextFrame.Width = 8000 # 80 mm largeur objTextFrame.setPropertyValue("AnchorType", 1) # on va mettre la cadre ? la place d'autre chose (remplacement) och=objDocument.createSearchDescriptor() och.SearchString="%CADRE1%" och.SearchWords = False #mots entiers seulement ? position=objDocument.findFirst(och) position.String="" # on remplit le cadre objText.insertTextContent(position, objTextFrame, False) objFrameText= objTextFrame.getText() objFrameTextCursor= objFrameText.createTextCursor() objFrameText.insertString(objFrameTextCursor, "1111111\n", False) objFrameText.insertString(objFrameTextCursor, "2222222222\n", False) objFrameText.insertString(objFrameTextCursor, "333333333", False) #couleur texte et sans ombre objCursor.setPropertyValue("CharColor", 255*256*256+0*256+0) objCursor.setPropertyValue("CharShadowed", False) #Insertion texte objText.insertString(objCursor, "\n\n\nThat's all for now !!", False) #recherche et remplacement orempl=objDocument.createReplaceDescriptor() orempl.SearchString="ABC" orempl.ReplaceString="XXXYYYZZZ" orempl.SearchWords = False #mots entiers seulement ? orempl.SearchCaseSensitive = True #sensible ? la casse ? nb = objDocument.replaceAll(orempl) print "Nb remplacements :",nb #recherche, effacement et insertion och=objDocument.createSearchDescriptor() och.SearchString="%TXT1%" och.SearchWords = False #mots entiers seulement ? position=objDocument.findFirst(och) position.String="" #remplacement position.setPropertyValue("CharColor", 255*256*256) #rouge Rouge*256*256 + Vert*256 + Bleu #position.goRight(1, False) objText.insertString(position, "Texte de remplacement", 0) objText.insertString(position, "Texte ajout?", 0) #impression, sauvergarde, sortie objDocument.Print(args) objDocument.storeAsURL("file:///C:/ootest2.odt", args) objDesktop.Terminate() From larry.bates at websafe.com Fri Sep 9 14:04:06 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Sep 2005 13:04:06 -0500 Subject: simple problem with os.rename() parameters - path with spaces In-Reply-To: References: Message-ID: <6oCdnVNf_rbxU7zeRVn-qA@comcast.com> Are you sure the source directory exists and you have rights to rename it? Because the rename works for me. But you may want to look at shutil.move and/or use forward slashes (they work under Windows) -Larry Bates Tom wrote: > I'm having a problem using a path with spaces as a parameter to > os.rename() in a program on WinXP. > > This works fine at the command line (where the folder "c:\aa bb" exists) > >> os.rename( "c\aa bb", "c:\cc dd" ); >> > > But, I can't get it to work in my program, eg. > > print SrcDir > print NewDir > os.rename( SrcDir, NewDir ); > > when I run this I get something like this: > > "e:\\music\\Joni Mitchell\\ogg-8" > "e:\\music.ogg\\Joni Mitchell\\ogg-8" > > Traceback (most recent call last): > File "E:\Music\MoveMusic.py", line 64, in ? > main(); > ... > File "E:\Music\MoveMusic.py", line 49, in Visit > os.mkdir( NewDir ); > OSError: [Errno 22] Invalid argument: '"e:\\music.ogg\\Joni > Mitchell\\ogg-8"' > > I've tried different combinations of single backslash vs. double > backslash, and quoted vs. non-quoted, but it always fails. > > The problem is not specific to os.rename. If I instead use mkdir( > SrcDir ) I get the same problem. > > Thanks, > Tom. > From rbt at athop1.ath.vt.edu Wed Sep 14 11:30:59 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 14 Sep 2005 11:30:59 -0400 Subject: appended crontab entries with py script In-Reply-To: <86zmqgxrps.fsf@bhuda.mired.org> References: <86zmqgxrps.fsf@bhuda.mired.org> Message-ID: <1126711859.13054.8.camel@athop1.ath.vt.edu> On Tue, 2005-09-13 at 23:18 -0400, Mike Meyer wrote: > rbt writes: > > > How can I safely append a crontab entry to a crontab file > > progammatically with Python? > > Well, one way would be to invoke the system crontab utility and use an > "editor" that passes the file to your program, and reads the results > back. > > > I need to handle crontabs that currently have entries and crontabs that > > are empty. Also, I'd like this to work across Linux and BSD systems. > > > > Any pointers? > > I think most Free Unix systems use the Vixie cron, and the non-free > ones have a "crontab" command (do some of them call it cron?) with the > same API. So you're pretty safe using that. > > If you want to assume that you're going to have the vixie cron, you > could dig into it's guts to see what it does for locking, and do that > by hand. > > current_crontab.txt') cur_cron.read() cur_cron.close() fp = file('current_crontab.txt', 'a') print >> fp, "0 * * * * %s/.theft_recovery.py" %home fp.close() load = os.popen('crontab current_crontab.txt') load.read() load.close() From larry.bates at websafe.com Fri Sep 9 09:39:53 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Sep 2005 08:39:53 -0500 Subject: python script under windows In-Reply-To: <1126263846.693277.50420@g47g2000cwa.googlegroups.com> References: <1126263846.693277.50420@g47g2000cwa.googlegroups.com> Message-ID: <432190A9.2000409@websafe.com> Making a Python program into a service isn't all that "tedious". Get a copy of Mark Hammonds "Python Programming on Win32" which contains excellent examples on how to do this. I've written several and after the first one, it is quite easy to do. -Larry Bates Harlin Seritt wrote: > Hi Jan, > > Unfortunately you will have to register it as a service. I am almost > certain there is no other way to do it. However, setting up an > executable as a true Windows Service is extremely tedious. You can try > this utility that I use. You can get it here: > http://www.seritt.org/pub/srvinst13b.exe. I'm probably not supposed to > distribute it, but the site and owners that used to host it have gone > belly up best that I can tell. As with anything, use it at your own > risk. I found it as freeware a few months back. > > If you want a decent cheap solution, FireDaemon is pretty good. I think > it's like 30USD but it does a great job and adds a few extra features. > > HTH, > > Harlin Seritt > Internet Villa: www.seritt.org > From edhotchkiss at gmail.com Sat Sep 17 14:09:16 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Sat, 17 Sep 2005 14:09:16 -0400 Subject: Inserting tuple from text file into database fields Message-ID: So I changed the code a little, still throwing the SQL syntax error. I still cannot seem to identify the problem. # Script to add links from a comma deliminated file to a MySQL database # 9/16/05 import MySQLdb conn=MySQLdb.connect( host="www.freesql.org ", user="edhotchkiss", port=3306, passwd="test1", db="links") cursor = conn.cursor() stmt = "DROP TABLE IF EXISTS links" cursor.execute(stmt) stmt = """CREATE TABLE links ( ID INT NOT NULL, Name TEXT, URL LONGTEXT, Category LONGTEXT, primary key (ID) )""" cursor.execute(stmt) arr=[] inp = open ("sites1.txt","r") #read line into array for line in inp.readlines(): links = map(str, line.split(",")) arr.append(links) cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s) % tuple(links[0:3]) """) cursor.close() conn.close() -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sun Sep 11 15:04:04 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Sep 2005 12:04:04 -0700 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: <432469eb$0$1294$ed2619ec@ptn-nntp-reader02.plus.net> References: <432469eb$0$1294$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1126465444.496471.127140@f14g2000cwb.googlegroups.com> Michael Sparks wrote: > Well, you did say you want help with locating problems. One problem with > this is it doesn't build... I found that I needed both the libgc and libgc-dev packages for my Kubuntu distribution - installing them fixed the include issues that you observed - and it does appear to be the Boehm-Demers-Weiser GC library, yes. The only other issue I observed was the importing of the profile and pstats modules which don't exist on my system, but those imports seemed to be redundant and could be commented out anyway. Paul From donn at u.washington.edu Mon Sep 26 12:15:12 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 26 Sep 2005 09:15:12 -0700 Subject: [RFC] Parametric Polymorphism References: <3pnbmiFbal03U1@uni-berlin.de> Message-ID: In article , Catalin Marinas wrote: ... > Of course, duck-typing is simple to use but the parametric > polymorphism is useful when the types are unrelated. Let's say you > want to implement a colour-print function which should support basic > types like ints and floats as well as lists and dictionaries. In this > case, and thank to the function decorations support, the code would be > clearer. What you're describing (and implementing) is not what I would call parametric polymorphism, though. See http://en.wikipedia.org/wiki/Polymorphism_(computer_science) You're talking about "ad-hoc" polymorphism. Personally, I can't agree that, in principle, this practice makes code clearer. In more common, less formal implementations you get functions like this -- def dosome(cmd): if type(cmd) == StringType: cmd = [cmd] ... Of course the first problem with this that it unnecessarily constrains the input type: if your API supports a string parameter, then in Python you should expect any value to work that supports string operations. This isn't a hypothetical matter, you can see relatively major Python applications have trouble with Unicode for exactly this reason. Secondly, rather than clarify the API, it confuses it. How many programmers will observe this usage and erroneously assume that dosome() _just_ takes a string, when the list parameter may in fact be the more ideal usage? This isn't hypothetical either. Your example is a fine one, and some kind of table to resolve the function according to type of input argument is a good idea. I'm just saying that more general application of this idea is best left to languages like C++. Donn Cave, donn at u.washington.edu From steve at holdenweb.com Wed Sep 21 09:02:02 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Sep 2005 14:02:02 +0100 Subject: C#3.0 and lambdas In-Reply-To: <433155ae$0$2935$626a14ce@news.free.fr> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> Message-ID: Christophe wrote: > Serhiy Storchaka a ?crit : > >>Roel Schroeven wrote: [...] >>>or >>> >>>def drawline(p1, p2): >>> # draw a line from p1[0], p1[1] to p2[0], p2[1] >>> foo(p1[0], p1[1]) >>> bar(p2[0], p2[1]) >> >> >> def drawline(p1, p2): >> # draw a line from p1 to p2 >> foo(*p1) >> bar(*p2) >> > > > That one is stupid. I don't see how you can make it work without some > global storing the p1 information in foo which I would consider as very > ugly code. In which case perhaps you should actually try the code. Then once you realise it works you can start to figure out why :-). Hint: f(*p1) appears as len(p1) separate arguments to the called function. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From fredrik at pythonware.com Mon Sep 5 14:33:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Sep 2005 20:33:30 +0200 Subject: Newbie: Datetime, "Prog. in Win32", and how Python thinks References: Message-ID: Max Yaffe wrote: > 1) H&R import a module "dates' which has been dropped. They use > sec2asc which is also m.i.a. I assume that the code should be adapted > to use module datetime. Is that correct? the dates.py module is part of the financial modeling toolkit that is described in chapter 6 of that book. it's not a standard component. > 2) Is there any list of dead modules & names from previous revs? Is > there any list of currently recommended modules? the library reference should tell you if a module is no longer in use. the various "what's new in python X.Y" documents tell you what's been added and removed. > 3) I was able to import datetime & get a dir(datetime) to work. > Great. But where is the actual code to datetime? I can't find a > module named datetime.py in the library. I grepped for datetime in > the library & found plenty of references to it but no module > definition. Where is it defined? it's a C library. in recent versions of Python, it's linked to the core interpreter. in earlier versions, you'll find it in the "datetime" extension module (datetime.pyd on windows, datetimemodule.so or somesuch on windows) >>> import sys >>> sys.builtin_module_names > 4) How does the python interpreter resolve the statement "import > datatime"? http://effbot.org/zone/import-confusion.htm describes the general approach for modules written in Python; built-in modules are handled before Python scans for external modules. From aahz at pythoncraft.com Tue Sep 13 09:38:27 2005 From: aahz at pythoncraft.com (Aahz) Date: Tue, 13 Sep 2005 06:38:27 -0700 Subject: BayPIGgies: DATE CHANGE September 15, 7:30pm (Google) Message-ID: <20050913133827.GA26586@panix.com> The next meeting of BayPIGgies will be Thurs, September 15 at 7:30pm at Google, Bldg 40, room Temp Tech Talk. You need to go to the lobby of Bldg 43 first to get a badge. Ben Bangert will do "SQLObject & FormEncode, A Practical Introduction" - Using SQLObject to integrity check legacy databases - FormEncodes use for validation and data coercion - Easy web front-ends to databases - Fully abstracted database access for easy portability BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://www.baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The meeting agenda for October 13 and December 8 has been set. We've got some options on the plate for November but haven't settled anything yet. Please send e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From michael at adrhinum.de Fri Sep 9 12:06:28 2005 From: michael at adrhinum.de (Michael Amrhein) Date: Fri, 09 Sep 2005 18:06:28 +0200 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: <4ho8v2-96m.ln1@mahlix.mahome.de> Stefano Masini schrieb: > On 8 Sep 2005 08:24:50 -0700, Fuzzyman wrote: > >>What is pythonutils ? >>===================== >>ConfigObj - simple config file handling >>validate - validation and type conversion system >>listquote - string to list conversion >>StandOut - simple logging and output control object >>pathutils - for working with paths and files >>cgiutils - cgi helpers >>urlpath - functions for handling URLs >>odict - Ordered Dictionary Class > > > Fuzzyman, your post reminded me of something I can't stop thinking > about. Please don't take this as a critique on your work. I place > myself on the same side of yours. > I just wanted to share this thought with everybody had an opinion about it. > > I wonder how many people (including myself) have implemented their own > versions of such modules, at least once in their pythonic life. I > indeed have my own odict (even same name! :). My own pathutils > (different name, but same stuff). My own validate... and so forth. > > This is just too bad. > There are a few ares where everybody seems to be implementing their > own stuff over and over: logging, file handling, ordered dictionaries, > data serialization, and maybe a few more. > I don't know what's the ultimate problem, but I think there are 3 main reasons: > 1) poor communication inside the community (mhm... arguable) > 2) lack of a rich standard library (I heard this more than once) > 3) python is such an easy language that the "I'll do it myself" evil > side lying hidden inside each one of us comes up a little too often, > and prevents from spending more time on research of what's available. > > It seems to me that this tendency is hurting python, and I wonder if > there is something that could be done about it. I once followed a > discussion about placing one of the available third party modules for > file handling inside the standard library. I can't remember its name > right now, but the discussion quickly became hot with considerations > about the module not being "right" enough to fit the standard library. > The points were right, but in some sense it's a pity because by being > in the stdlib it could have had a lot more visibility and maybe people > would have stopped writing their own, and would have begun using it. > Then maybe, if it was not perfect, people would have begun improving > it, and by now we would have a solid feature available to everybody. > > mhm... could it be a good idea to have two versions of the stdlib? One > stable, and one testing, where stuff could be thrown in without being > too picky, in order to let the community decide and improve? > > Again, Fuzzyman, your post was just the excuse to get me started. I > understand and respect your work, also because you put the remarkable > effort to make it publicly available. > > That's my two cents, > stefano Did you take a look at pyPI (http://www.python.org/pypi) ? At least you'd find another odict ... ;-) Michael From peter at engcorp.com Fri Sep 30 07:30:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Sep 2005 07:30:56 -0400 Subject: Help with syntax warnings In-Reply-To: References: <5N-dnZjy3YxqA6HenZ2dnUVZ_tKdnZ2d@powergate.ca> Message-ID: Robert Kern wrote: > Peter Hansen wrote: >>Not sure... what's a "syntax warning"? > > In [1]: SyntaxWarning? > Type: classobj > String Form: exceptions.SyntaxWarning > Namespace: Python builtin > Docstring: > Base class for warnings about dubious syntax. Wow... Python detects "dubious syntax"? And here I thought programming was rather black and white, it's right or it's wrong. (He notes examples such as assigning to None and "unqualified exec is not allowed in function" etc.) I guess I've never accidentally hit one of those. Seems like, if I had, I'd probably want to fix the problem rather than hide it, as with most warnings from C compilers. -Peter From steve at holdenweb.com Sat Sep 3 03:01:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Sep 2005 02:01:31 -0500 Subject: python logo In-Reply-To: <1125730325.391485.7690@z14g2000cwz.googlegroups.com> References: <1125730325.391485.7690@z14g2000cwz.googlegroups.com> Message-ID: <43194A4B.1040307@holdenweb.com> Xah Lee wrote: > i noticed that Python uses various logos: > > http://python.org/pics/pythonHi.gif > http://python.org/pics/PyBanner038.gif > http://python.org/pics/PyBanner037.gif > http://python.org/pics/PythonPoweredSmall.gif > http://wiki.python.org/pics/PyBanner057.gif > > is this some decision that python should use various different logos? > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Yes. -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From flupke at nonexistingdomain.com Mon Sep 26 09:06:02 2005 From: flupke at nonexistingdomain.com (flupke) Date: Mon, 26 Sep 2005 13:06:02 GMT Subject: Module import via sys.path and py2exe In-Reply-To: <2TFYe.2211$Qq1.47151@phobos.telenet-ops.be> References: <9uFYe.2194$rs1.114801@phobos.telenet-ops.be> <2TFYe.2211$Qq1.47151@phobos.telenet-ops.be> Message-ID: <_mSZe.5436$fF1.321644@phobos.telenet-ops.be> flupke wrote: > I forgot to add that if i check the shared.lib py2exe creates, the > program1 dir and subdirs/files are there so they are included in the > package. > > Benedict Hi, i solved it by adding the same import statement to the py2exe setup.py script as in my code: import sys sys.path.append('program1') I'm still not sure though that the way i'm adding the module in the first place is correct but it seems to work okay. Regards, Benedict From haircut at gmail.com Fri Sep 30 01:51:59 2005 From: haircut at gmail.com (Adam Monsen) Date: 29 Sep 2005 22:51:59 -0700 Subject: threads, periodically writing to a process Message-ID: <1128059519.626645.113950@g49g2000cwa.googlegroups.com> I have a program that, when run, (1) does some task, then (2) prompts for input: "Press ENTER to continue...", then repeats for about ten different tasks that each take about 5 minutes to complete. There is no way to disable this prompt. How would I go about writing a Python program that would periodically (say, every 10 seconds or so) send a carriage return--"\r\n" (or whatever the ENTER key sends)--then exit when the subprocess is finished? I guess if I get really into this I'd write something that actually waits for the subprocess to print "Press ENTER to continue..." to standard output, *then* sends "\r\n", but extra carriage returns don't hurt, so the first option is probably viable. This is probably something that Expect could handle pretty easily, but I'm just into learning Python for the time being. -- Adam Monsen http://adammonsen.com/ From bokr at oz.net Wed Sep 7 02:57:10 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 07 Sep 2005 06:57:10 GMT Subject: round function problem References: Message-ID: <431e8d31.820070959@news.oz.net> On Tue, 06 Sep 2005 09:27:48 +0200, mg wrote: >Hi everybody... > >We try to white scripts with Pyrhon 2.4 for an acoustic simulation and >we wrote these follow lines : > > >c = 340 340 is an integer, which is different from 340. >i =j=k= 1 >sum_ = 23 also an integer >table = [] >freq = round((c/2*(sum_)**0.5),2) c/2 is integer/integer, which is not the same as c/2.0 rules all-integer arimetic generally produces integer results, so (unless you import division from __future__) pay attention or write your constants with decimal points even if the values are exact integers. note: >>> 5/2 2 >>> from __future__ import division >>> 5/2 2.5 >print freq >table.append([freq,(i,j,k)]) >print i,j,k,' freq',freq >for item in table: print item > > >The problem is simple. The function 'round' allow to obtain the value >with the specified number of digits after the ",". Then, when the >variable 'freq' is printed, there is no problem; but when freq is set in >the table and the table printed, all the digits are come back. > >Is it a bug or a control behavour ? I don't understand ?!?!?!?!... > Others have pointed out the output formatting and binary representation problems behind your question, but I thought you might not realize the above. Regards, Bengt Richter From MrJean1 at gmail.com Thu Sep 29 19:18:46 2005 From: MrJean1 at gmail.com (MrJean1) Date: 29 Sep 2005 16:18:46 -0700 Subject: Parser suggestion In-Reply-To: <87ek77k4m1.fsf@ieee.org> References: <87ek77k4m1.fsf@ieee.org> Message-ID: <1128035925.974424.76140@g47g2000cwa.googlegroups.com> My recommendation for a project like this would be SimpleParse Some examples are here and /Jean Brouwers From steve at holdenweb.com Wed Sep 21 06:44:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Sep 2005 11:44:04 +0100 Subject: Free seminar on domain-specific modeling In-Reply-To: <7c6fcb4c44a08c78cc2795530b3@news.kolumbus.fi> References: <7c6fcb4c44a08c78cc2795530b3@news.kolumbus.fi> Message-ID: Martijn Iseger wrote: > Hello Steve, > > >>1. Any organisation that can talk about "a leap in productivity of >>400% from Assembler to BASIC" as though nothing occurred in between >>suffers such a total disconnect from computing history that it's hard >>to take other utterances seriously. > > > I believe the point being made by the organization is that during computing > history the most successful shifts in productivity were achieved by similar > shifts in raising the abstraction level on which developers specify solutions. > According to Capers Jones Software Productivity research Fortran is 4.5 times > more productive than Assembler. Looking at chronology I'd say it is not incorrect > to refer to the advent of compilers as a leap. > Neither would I. I was simply pointing out that BASIC wasn't the next thing after assembly language. Even before Fortran there were a whole bunch of what were usually called "autocodes", one of the more popular ones in Britain at least being EMA (extended Mercury autocode. So it wasn't really a leap, more a sequence of steps. I could promote nuclear weapons as being a quantum leap above rock-throwing (millions of percent more kill efficiency), but I'd be falsifying the picture by omitting depressing centuries of weapons development in doing so. Most BASICs weren't compiled languages anyway: BASIC's primary feature was the introduction of interactive execution modes and immediate edit/run cycling. The addition of compilation to machine code is a relatively recent phenomenon for (only some) BASICs, unlike other high-level languages. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From roccomoretti at hotpop.com Fri Sep 30 12:14:18 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 30 Sep 2005 11:14:18 -0500 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7x64sjduqk.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7xbr2btv84.fsf@ruckus.brouhaha.com> <7x64sjduqk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I don't know of a single program that's actually relying on the > non-enforcement. I've asked for examples but have only gotten > theoretical ones. As far as I can tell, the feature is useless. I'd like to turn the question around on you - can you come up with an instance where the non-enforcement has tripped someone up? Is there a bug you can point to that would have been prevented if Python enforced private member semantics? From pierre.barbier at cirad.fr Mon Sep 12 09:17:05 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon, 12 Sep 2005 15:17:05 +0200 Subject: which is more 'pythonic' / 'better' ? In-Reply-To: <43256a38$0$4789$da0feed9@news.zen.co.uk> References: <43256a38$0$4789$da0feed9@news.zen.co.uk> Message-ID: <43257f17$0$27971$636a15ce@news.free.fr> Will McGugan a ?crit : > gabor wrote: > >> hi, >> >> there are 2 versions of a simple code. >> which is preferred? >> >> >> === >> if len(line) >= (n+1): >> text = line[n] >> else: >> text = 'nothing' >> === >> >> >> === >> try: >> text = line[n] >> except IndexError: >> text = 'nothing' >> === >> >> >> which is the one you would use? > > > I would actualy use the following for this particular case.. > > text = line[n:n+1] or 'nothing' ... and you would get either a list of one element or a string ... I think you wanted to write : text = (line[n:n+1] or ['nothing'])[0] However, I wouldn't use that because it is hard to read ... you have to know Python in great detail to know that: 1 - is the expressions "line[i:j]", i and j are replaced with "len(line)" if they are greater than "len(line)" 2 - so if n > len(line), then line[n:n+1]" == len[len(line):len(line)] == [] (it is not evident that line[n:n+1] can give an empty list ...) 3 - empty list evaluate to "False" 4 - the "or" operator returns the first argument evaluating to "true" So, in the end, you use 3 side-effects of Python in the same small expression ... (1, 2 and 4) > > But in general I think it is best to use exceptions like that only where > you expect the code to _not_ throw the exception the majority of times. > Otherwise the simple condition is better. Although I expect there is not > much difference either way.. > > > Will McGugan > -- > http://www.kelpiesoft.com What I would do is the following: - if this happen in a loop, I would, if possible, remove any test and catch the exception outside the loop ! - otherwise, I would go for the test, as it is more straitforward to read. Pierre From percivall at gmail.com Fri Sep 23 18:23:46 2005 From: percivall at gmail.com (Simon Percivall) Date: 23 Sep 2005 15:23:46 -0700 Subject: Accessing class variable at class creation time References: <1127509281.767539.271230@g43g2000cwa.googlegroups.com> Message-ID: <1127514226.931403.223390@z14g2000cwz.googlegroups.com> It might be that I'm complicating something easy here, but I immediately thought of import sys class A: X = 2 def F(): f = sys._getframe().f_back print f.f_locals["X"] F() From megafrenzy at gmail.com Thu Sep 22 18:32:35 2005 From: megafrenzy at gmail.com (megafrenzy) Date: 22 Sep 2005 15:32:35 -0700 Subject: Noobie Starting New Project References: <1127354244.568745.296000@g47g2000cwa.googlegroups.com> <1127384606.385567.54810@g47g2000cwa.googlegroups.com> Message-ID: <1127428355.429083.174880@g43g2000cwa.googlegroups.com> Well, I'm not too worried about the serial communications aspect, I've developed perhaps a dozen different RS-232, 422, 485, and even SPI, CANBUS interfaces in the past year for embedded systems. And also, the Subaru protocol is easier than OBDII, no need to change the baud to 5, its fixed at 4800 8 N 1 and you can make it faster with a simple command. Although I did not make it clear, my real questions were with Python's graphics. There are so many GUI options and I wasn't sure which one would be the best. I'm thinking that pyCard would be the easiest for me to pickup, from what I heard on the Python411 podcasts. But based on my hardware, could I expect screen refresh rates that can match the update rate of the serial port? I'm thinking 10-20 updates per sec would be the max I could get out of the serial port, depending on the max baud rate (currently undocumented/unknown but at least 38.4k) I could set it to. And for plotting, there are pleanty of plotting/charing options out there. I wanted to get some input on what I could use. I'm looking at matplotlip and gnuplot, but there are so many others. From jbattat at cfa.harvard.edu Wed Sep 21 17:13:54 2005 From: jbattat at cfa.harvard.edu (jbattat at cfa.harvard.edu) Date: 21 Sep 2005 14:13:54 -0700 Subject: PyEphem on winXP Message-ID: <1127337234.547710.160890@f14g2000cwb.googlegroups.com> Hi, I'm a (sort of) newbie to python and would like to install the PyEphem extension to Python. I'm using Python 2.4 I obtained PyEphem from: http://rhodesmill.org/brandon/projects/pyephem.html When i ran python setup.py install my error was: "error: Python was built with version 7.1 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed" Browsing this group led me to the following URL where I could get (for free) the Visual C++ Toolkit 2003: http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-49FD-9CB0-4BFA122FA91B&displaylang=en However I still see the same error when running python setup.py install. I know that Visual C++ Toolkit 2003 is the same as version 7.1, but is this the same as Visual Studio 7.1? If so, can Visual Studio 7.1 be obtained for free? If not, is there a workaround? I've seen suggestions in the group that you can recompile Python 2.4 using MinGW or some other c compiler. I'd be willing to do that, but do not know how to go about recompiling python. Advice on this would also be helpful. Thanks, James From could.net at gmail.com Wed Sep 14 09:01:52 2005 From: could.net at gmail.com (could ildg) Date: Wed, 14 Sep 2005 21:01:52 +0800 Subject: How can I find all the dependencies of a py? Message-ID: <311b5ce10509140601fe2e886@mail.gmail.com> when I run a.py, it uses b.py,c.py.... and a.py uses x.py,y.py.... How could I find all the modules that a.py and all of its imported modules? Is there any built in functions or any tools to do this? Thank you~, I really want to know it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Thu Sep 15 17:29:59 2005 From: http (Paul Rubin) Date: 15 Sep 2005 14:29:59 -0700 Subject: working with VERY large 'float' and 'complex' types References: <7xll1z78gi.fsf@ruckus.brouhaha.com> Message-ID: <7xll1yow88.fsf@ruckus.brouhaha.com> Mikael Olofsson writes: > > print 'z = %.5fE%d' % (10.**c, m) > > Nice approach. We should never forget that we do have mathematical > skills beside the computers. But, shouldn't you switch c and m in the > last row? Yeah, doh. c=characteristic, m=mantissa. From michaels at rd.bbc.co.uk Wed Sep 7 05:47:22 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Wed, 07 Sep 2005 10:47:22 +0100 Subject: Python versus Perl References: Message-ID: Dieter Vanderelst wrote: > Dear all, > > I'm currently comparing Python versus Perl to use in a project that > involved a lot of text processing. I'm trying to determine what the > most efficient language would be for our purposes. I have to admit > that, although I'm very familiar with Python, I'm complete Perl noob > (and I hope to stay one) which is reflected in my questions. > > I know that the web offers a lot of resources on Python/Perl > differences. But I couldn't find a satisfying answer to my questions: > > 1 - How does the speed of execution of Perl compares to that of > Python? Much of a muchness in my experience.(Qualitative, not quantative) > 2 - Regular Expressions are a valuable tool in text processing. I have > noticed that Regular Expressions are executed very fast in Python. > Does anybody know whether Python executes RE faster than Perl does? > 3 - In my opinion Python is very well suited for text processing. Does > Perl have any advantages over Python in the field of textprocessing > (like a larger standard library maybe). These two are related. If you're writing code and you expect to be using *a lot* of regular expression [*] type code then you may find perl more convenient. [*] That /might/ suggest you're taking the wrong approach mind you... Python, for me, tends to be more readable, both immediately after writing and if I go back to a year later - for maintenance, extension etc. Personally I like both languages for day in day out use, but these days tend to choose python if I think I'm likely to want to modify or extend the code. With the exception being where I'm doing heavy text processing work that I think will be more maintainable in perl, or I'm really sure I won't have to maintain it. (eg quick and dirty scripts) One side effect of perl usage though is that due to them being easy to use and convenient, they can get over used. (Rather than thinking "what's the best way of solving this problem", people can end up thinking "What regular expression can solve this problem" - which isn't ideal) Your comment """I'm complete Perl noob (and I hope to stay one) """ would suggest to me that if you really feel that way, stay that way :-) (Though personally I do like learning new programming languages, since you get more idioms and tools under your belt that way.) > I hope somebody can answer my questions. Of course, every remark and > tip on Python/Perl in texprocessing is most welcome. In case you're not aware there's the book "Text Processing in Python" by David Mertz, which is available online in a "free as in beer" form which might be of use if you decide python instead of perl. Michael. -- Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From fredrik at pythonware.com Sun Sep 25 04:24:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 25 Sep 2005 10:24:13 +0200 Subject: Most direct way to strip unoprintable characters out of a string? References: <1127599437.e4ab33f8d8f65cbcfb07427b68e97909@teranews> <1127632577.e5813e979598f2b9b2af5afda5a88b85@teranews> Message-ID: George Sakkis wrote: > No there's not a stripUnprintable in a standard module AFAIK, and > that's a good thing; if every little function that one might ever wanted > made it to the standard library, the language would be overwhelming. ...and if there was a stripUnprintable function in the standard library that was based on C's mostly brain-dead locale model, US programmers would produce even more web applications that just don't work for non- US users... ("sanitizing" HTML data by running filters over encoded 8-bit data is hardly ever the right thing to do...) From alessandro.bottoni at infinito.it Tue Sep 13 03:55:39 2005 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Tue, 13 Sep 2005 07:55:39 GMT Subject: PyGTK or wXPython? References: Message-ID: <%BvVe.998$m56.33493@twister1.libero.it> Rod W wrote: > I'm just starting out on Python but my primary goal is to provide > applications with some user interface (GUI). > > Can someone point me to a good comparison of whether I should use > wxPython (with wxGlade I assume) or PyGTK (with Glade I assume)? > > I'd prefer open source (not necessarily GPL though) tools. > > Rod Both the wxWidgets and the GTK web sites have some good comparison sheet and/or a "why I should use this platform" page. Many reviews and articles can be found on the web by searching for "PyGTK wxPython comparison" or "Python GUI toolkits". Anyway, the main difference between PyGTK and wxPython is the type of GUI that is generated on Windows. PyGTK uses the Windows porting of GTK and has its own Look&Feel (similar to Gnome, I could say). wxPython, like wxWidgets, uses the native MFC widgets and have the same Look&Feel of any other MFC application (indistiguishable from any other native Windows app). On Linux, PyGTK and wxPython are equivalent because both use GTK for rendering the GUI. (I do not use/program/own any McOS system, so I cannot tell you anything about the Apple Platform). Beside this, wxPython (and wxWidgets) is often told to be more complete, better documented and better supported than GTK/PyGTK. HTH ----------------------------------- Alessandro Bottoni From steve at holdenweb.com Mon Sep 12 11:42:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Sep 2005 16:42:42 +0100 Subject: Launching Python programs from Linux shell script In-Reply-To: <1126533765.007072.257980@g43g2000cwa.googlegroups.com> References: <1126279887.147197.170670@g43g2000cwa.googlegroups.com> <1126533765.007072.257980@g43g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > Thanks! How do you add Python in Linux to the path? Similar to > setting environment variables in Windows. I want to be able to type > "python" when I'm in any directory to launch the interpreter. Thanks! > You will (or should) have a shell intialisation file variously called .profile, .bashrc or several other possible names. Consult your shell documentation (or ask another user who knows) to find out which. You will need to add a line which typically reads something like export PATH=$PATH:/path/to/directory/containing/python making the obvious substitution of the correct path. Interestingly I couldn't quickly formulate a Google search specifically containing Python, but a search for unix add to path gives the quite helpful http://www.ee.surrey.ac.uk/Teaching/Unix/unix8.html as its first result. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Mon Sep 19 16:08:19 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Sep 2005 22:08:19 +0200 Subject: Removing Warning Messages ............. In-Reply-To: <1127139547.304510.112570@g14g2000cwa.googlegroups.com> References: <1127139547.304510.112570@g14g2000cwa.googlegroups.com> Message-ID: <432f1203$0$3733$626a14ce@news.free.fr> chand a ?crit : > Hi., > > In my api.py file 'g_opt_list' is defined globally > g_opt_list =[[],[],[],[],[],[],[]] > > when I run the py file, I am getting the Following Error > > SyntaxWarning: name 'g_opt_list' is used prior to global declaration > SyntaxWarning: name 'layers' is used prior to global declaration > > Please let me know how to remove these warnings. By fixing your code From peck at spss.com Fri Sep 23 11:16:01 2005 From: peck at spss.com (Peck, Jon) Date: Fri, 23 Sep 2005 10:16:01 -0500 Subject: NaN Vs None Message-ID: <5CFEFDB5226CB54CBB4328B9563A12EE02B701BF@hqemail2.spss.com> In choosing a way to represent a value of "no information" for a float, would it be better to use NaN or None? None has the advantage of standard behavior across platforms, but NaN seems to propagate more easily - at least on Windows. For example, NaN+1 = NaN but None+1 raises an exception. Thanks in advance for any advice. Jon K Peck (Kim) peck at spss.com 312-651-3435 233 S Wacker Dr Chicago, IL 60606 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pruebauno at latinmail.com Thu Sep 1 16:21:24 2005 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 1 Sep 2005 13:21:24 -0700 Subject: Improving my text processing script References: <1125500982.664278.83810@g47g2000cwa.googlegroups.com> <1125557140.740041.102790@g44g2000cwa.googlegroups.com> Message-ID: <1125606084.772356.221030@z14g2000cwz.googlegroups.com> Paul McGuire wrote: > match...), this program has quite a few holes. > > What if the word "Identifier" is inside one of the quoted strings? > What if the actual value is "tablename10"? This will match your > "tablename1" string search, but it is certainly not what you want. > Did you know there are trailing blanks on your table names, which could > prevent any program name from matching? Good point. I did not think about that. I got lucky because none of the table names had trailing blanks (google groups seems to add those) the word identifier is not used inside of quoted strings anywhere and I do not have tablename10, but I do have "dba.tablename1" and that one has to match with tablename1 (and magically did). > > So here is an alternative approach using, as many have probably > predicted by now if they've spent any time on this list, the pyparsing > module. You may ask, "isn't a parser overkill for this problem?" and You had to plug pyparsing! :-). Thanks for the info I did not know something like pyparsing existed. Thanks for the code too, because looking at the module it was not totally obvious to me how to use it. I tried run it though and it is not working for me. The following code runs but prints nothing at all: import pyparsing as prs f=file('tlst'); tlst=[ln.strip() for ln in f if ln]; f.close() f=file('plst'); plst=f.read() ; f.close() prs.quotedString.setParseAction(prs.removeQuotes) identLine=(prs.LineStart() + 'Identifier' + prs.quotedString + prs.LineEnd() ).setResultsName('prog') tableLine=(prs.LineStart() + 'Value' + prs.quotedString + prs.LineEnd() ).setResultsName('table') interestingLines=(identLine | tableLine) for toks,start,end in interestingLines.scanString(plst): print toks,start,end From livin at Wed Sep 14 18:29:21 2005 From: livin at (livin) Date: Wed, 14 Sep 2005 15:29:21 -0700 Subject: Example Script to parse web page links and extract data? Message-ID: I'm hoping someone knows of an example script I can see to help me build mine. I'm looking for an easy way to automate the below web site browsing and pull the data I'm searching for. Here's steps it needs to accomplish... 1) login to the site (windows dialog when hitting web page) *optional* 2) Choose menu link from ASP page (script shows/hides menu items depending on mouseover) *optional* 3) Basic Search Form and enter zip code or city to pull all the data. 4) After search, table shows many links (hundreds sometimes) to the actual data I need. Links are this format... 5) Each link opens new window with table providing required data. The URLs that each href opens is this... http://armls.marketlinx.com/Roster/Scripts/Member.asp?PubID=AA059 where the PubID is record I need. Table format looks like this: 6 Alaze
Mark
MA142
Banker Success Realty
COLD56 From chris.cavalaria at free.fr Fri Sep 9 07:43:40 2005 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 09 Sep 2005 13:43:40 +0200 Subject: Inconsistent reaction to extend In-Reply-To: References: Message-ID: <43217403$0$10786$626a14ce@news.free.fr> Antoon Pardon a ?crit : >>Because creating a new list is potentially very time-consuming and >>expensive of memory. Imagine you have a list of 100,000 large objects, and >>you want to add one more object to it. The way Python works is that append >>and extend simply add that new object to the end of the existing list. The >>way you imagined it would work would require Python to duplicate the >>entire list, all 100,000 large objects, plus the extra one. > > > This has nothing to do with the need to create a new list. > > The extend method could just have returned self. Just as sort and reverse could > have done so. This would have made it possible to do things like the following: > > lst.sort().reverse() > > instead of having to write: > > lst.sort() > lst.reverse() This was done on purpose to avoid a second class of problems. The one where you forget that reverse modifies the list in place. That second class of problems was deemed more dangerous because it works without immediate errors. From duncan.booth at invalid.invalid Sat Sep 17 07:01:41 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Sep 2005 11:01:41 GMT Subject: Dictionary sorting problem References: <1126899106.189220.209940@o13g2000cwo.googlegroups.com> <432b2032$0$11071$e4fe514c@news.xs4all.nl> <432b6439.1661489986@news.oz.net> Message-ID: Bengt Richter wrote: > or tell sorted what to do ;-) > > >>> original= { > ... 'hello':135, > ... 'goodbye':30, > ... 'lucy':4, > ... 'sky':55, > ... 'diamonds':239843, > ... 'yesterday':4 } > >>> list(sorted(original.iteritems(), None, lambda t:t[1], True)) > [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30), > ('yesterday', 4), ('lucy',4)] or a slight variation on this theme which just gives you the keys in value order rather than the tuples: >>> for k in sorted(original, key=original.get, reverse=True): print k, original[k] diamonds 239843 hello 135 sky 55 goodbye 30 yesterday 4 lucy 4 From programmer.py at gmail.com Fri Sep 30 19:05:15 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 30 Sep 2005 18:05:15 -0500 Subject: [Info] PEP 308 accepted - new conditional expressions In-Reply-To: References: <3q4ro9Fd770nU3@individual.net> Message-ID: On 9/30/05, Sam wrote: > Reinhold Birkenfeld writes: > > > Hi, > > > > after Guido's pronouncement yesterday, in one of the next versions of Python > > there will be a conditional expression with the following syntax: > > > > X if C else Y > > > > which is the same as today's > > > > (Y, X)[bool(C)] > > What's wrong with "C ? X:Y"? > > Aside from ":" being overloaded? > First thing that comes to my mind is that it is more C-ish (read cryptic) than pythonic (read elegant and understandable). jw From peter at engcorp.com Fri Sep 23 18:47:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Sep 2005 18:47:00 -0400 Subject: Single type for __builtins__ in Py3.0 In-Reply-To: References: <43aa6ff7050923075512175c41@mail.gmail.com> Message-ID: Collin Winter wrote: > On 9/23/05, Fredrik Lundh wrote: >>__builtins__ is a CPython implementation detail. why not just let it >>be an implementation detail, and refrain from using it? it's not that >>hard, really. > Given, but I fail to see why it can't be a consistent implementation > detail. After my own encounter with __builtins__, I now know that I > should use __builtin__ instead. However, the docs never mention this. http://docs.python.org/lib/module-builtin.html > The only way you'd know that __builtin__ is preferred is by searching > the list archives, something you're not likely to do unless you're > already having a problem. > > If it's decided to leave things they way they are, at the very least > the docs should be amended to indicate that users shouldn't be > touching __builtins__. If anyone has a suggestion as to where this > kind of thing might best fit (tutorial, library reference, language > reference?), I'd be happy to write a patch for the docs. User are clearly told in various places that names with leading and trailing double underscores are *special*, and at least by implication they are not to be used without a good understanding of what they are. You certainly shouldn't have found any docs telling you to use __builtins__ that way. http://www.google.ca/search?q=site%3Apython.org+__builtin__ is a pretty quick way of finding the above docs, and while doing the same search with __builtins__ admittedly finds lots of mailing list archives where people have the same misconception as you did, it doesn't take one past the second page of results before you'll be right back at a post by Fredrik pointing out the same mistake. :-) -Peter From grante at visi.com Mon Sep 26 13:41:01 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 26 Sep 2005 17:41:01 -0000 Subject: ncurses programming References: Message-ID: <11jgcldn4c7823d@corp.supernews.com> On 2005-09-26, Sinan Nalkaya wrote: > hi, i want to use ncurses library in python i`ve found proper > library for that, PyNcurses. then i searched for some > documentation about ncurses programming, i only found that web > site ; http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/ > this howto is nice but seems to me, this is for experienced > ncurses programmers who have just migrated to python so i dont > understand anything from examples and howto. what should i do > ? firstly should i learn ncurses programmin on C then migrate > to python? thanks. Here's an introductory page: http://gnosis.cx/publish/programming/charming_python_6.html If what you want to do is fairly simple. the "newt" libarary might worth looking at. It's very light-weight, easy to use, and has a bunch of built-in widget types (text entry boxes, radio buttons, progress bars, message boxes, etc). It's main restriction when compated to something like ncurses/forms is that newt's windows are "stacked" and the user can only interact with the top one. Newt was originally developed by RedHat for their text-mode installer and sysadmin tools that were written in Python. The documents are a bit sparse and sometimes out-of-date, but there are a few decent example programs in the source distro. The Python newt library module is called "snack", so be careful not to get get confused with the sound library of the same name. It's available for most Linux distros and requires the "slang" library. If your distro doesn't have a pre-built newt library you can get it from here: http://www.python.org/pyvault/SRPMS/repodata/repoview/newt-0-0.52.0-3.html -- Grant Edwards grante Yow! Imagine--a WORLD at without POODLES... visi.com From misterwang at gmail.com Thu Sep 1 10:24:26 2005 From: misterwang at gmail.com (Peter Wang) Date: 1 Sep 2005 07:24:26 -0700 Subject: Python doc problems example: gzip module References: <1125477977.072146.298670@g47g2000cwa.googlegroups.com> <1125481348.490681.271200@g47g2000cwa.googlegroups.com> Message-ID: <1125584666.568728.279750@g49g2000cwa.googlegroups.com> >> Constructor for the GzipFile class, which simulates most of the methods >> of a file object, with the exception of the readinto() and truncate() > > yeah, blab blab blab. what the fuck are you talking about? So, how to > use it? um... presumably you type "zippedfile = GzipFile(...)" and depending on whether you are creating a new file, or extracting an existing GzipFile. the documentation says: > The new class instance is based on fileobj, which can be a regular file, a > StringIO object, or any other object which simulates a file. It defaults to > None, in which case filename is opened to provide a file object." so i guess in your case you would want to do "zippedfile = GzipFile("myfile.gz")". >> When fileobj is not None, the filename argument is only used to be >> included in the gzip file header, which may includes the original >> filename of the uncompressed file. It defaults to the filename of >> fileobj, if discernible; otherwise, it defaults to the empty string, >> and in this case the original filename is not included in the header. > > what the fuck?? when you "gzip -d myfile.gz", the resultant output name might not be "myfile". The uncompressed name can be stored in the gzip header, and so if you provide both a fileobj argument and a filename argument to the GzipFile constructor, it will use fileobj for the data stream and just place filename into the header (as opposed to opening the file "filename"). >> The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', >> depending on whether the file will be read or written. The default is >> the mode of fileobj if discernible; otherwise, the default is 'rb'. If >> not given, the 'b' flag will be added to the mode to ensure the file is >> opened in binary mode for cross-platform portability. > > discernible? so, what the fuck are exactly these modes? can't you > describe them concretely? these are the same modes that are used in just about every single programming language when it comes to opening files. these modes are described in the Python tutorial and in the core Python documentation about files and file I/O. It should not be surprising, therefore, that GzipFile, which "simulates most of the methods of a file object", should have the same semantics when it comes to file modes. it is actually quite shocking to me that someone with 10 years of computing experience would not know what "rb" and "rb" mean in the context of opening files in a programming language. >> Calling a GzipFile object's close() method does not close fileobj, >> since you might wish to append more material after the compressed data. >> This also allows you to pass a StringIO object opened for writing as >> fileobj, and retrieve the resulting memory buffer using the StringIO >> object's getvalue() method. > > huh? append more material? pass a StringIO? and memory buffer? you see, not everyone who uses GzipFile will be decompressing files. sometimes they will be *compressing* file data. in this case, it's very possible that they want to compress data going over a network stream, or embed some gzipped into the middle of their own file format. GzipFile doesn't make any assumptions about what the user is going to do with the gzipped data or the file object that the Gzip module is writing into/reading from. > Motherfucking 90% of programers using this module really just want to > compress or decompress a file. I disagree. I think a whopping (non-motherfucking) 100% of programmers using this module want to compress or decompress file data. If someone just wants to decompress a file, wouldn't they just do: import os os.system("gzip -d filename.gz") The GzipFile module is meant to be used by folks who want to gzip or gunzip file data in a programmatic function. It's not meant to be a drop-in, shell-scripting replacement for the gzip command. -peter From saint.infidel at gmail.com Fri Sep 9 18:10:36 2005 From: saint.infidel at gmail.com (infidel) Date: 9 Sep 2005 15:10:36 -0700 Subject: error processing variables In-Reply-To: References: Message-ID: <1126303836.272718.24660@z14g2000cwz.googlegroups.com> > import shutil > > #variables > s = shutil > > toHPU = "/etc/sysconfig/network/toHPU.wifi" > wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d" > toAnyWifi = "/etc/sysconfig/network/toAny.wifi" > wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88" > > > def toHPU(): > > > s.copy2(toHPU,wlan) > s.copy2(toAnyWifi,wired) > > #end > > #execute function > toHPU() Your problem is that the def statement reassignes the name "toHPU" to a function instead of a string. So when the code runs, you're passing a function object to s.copy2. From billiejoex at fastwebnet.it Sat Sep 10 06:37:34 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Sat, 10 Sep 2005 12:37:34 +0200 Subject: execute commands and return output References: Message-ID: Thank you for your help but I'm searching a different way. Moreover it doesn't work always (for exaple: try a 'dir' command). Because of I'm implementing a remote shell the [[os.popen('command').read()]] rapresents the best for me because it can also accepts arguments direclty (for example: os.popen('netstat -a -n -o').read() and this is a great advantage. I was looking at sys.stdout and sys.stderr. Can they be helpful? Cheers > Use subprocess: > > from subprocess import Popen, PIPE > proc = Popen(['command', 'arg', 'arg'], stdout=PIPE, stderr=PIPE) > return_code = proc.wait() > if return_code == 0: > print "Success:\n%s" % proc.stdout.read() > else: > print "Failure %s:\n%s" % (return_code, proc.stderr.read()) From steve at REMOVETHIScyber.com.au Mon Sep 12 07:53:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 12 Sep 2005 21:53:15 +1000 Subject: which is more 'pythonic' / 'better' ? References: Message-ID: On Mon, 12 Sep 2005 12:52:52 +0200, gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? > > > === > if len(line) >= (n+1): > text = line[n] > else: > text = 'nothing' > === > > > === > try: > text = line[n] > except IndexError: > text = 'nothing' > === > > > which is the one you would use? Personally, I would use either. You say po-ta-to, I say pot-at-o. try...except... blocks are quick to set up, but slow to catch the exception. If you expect that most of your attempts will succeed, then the try block will usually be faster than testing the length of the list each time. But if you expect that the attempts to write the line will fail more frequently, then testing will be quicker. You will need to do your own testing before hand to find the exact cut-off, and expect that cut-off to vary according to the Python implementation and version. But a rough rule of thumb is, if you expect your code to fail more often than succeed, then test first, otherwise catch an exception. -- Steven. From theller at python.net Tue Sep 6 02:29:02 2005 From: theller at python.net (Thomas Heller) Date: Tue, 06 Sep 2005 08:29:02 +0200 Subject: py2exe 0.6.1 released References: Message-ID: Bugs writes: > Thomas Heller wrote: >> Changes in this release: >> * py2exe can now bundle binary extensions and dlls into the >> library-archive or the executable itself. This allows to >> finally build real single-file executables. >> The bundled dlls and pyds are loaded at runtime by some special >> code that emulates the Windows LoadLibrary function - they are >> never unpacked to the file system. >> > > Wow, that is fantastic Thomas, congratulations! > > So far, I've only seen where Thinstall has been able to accomplish > this and at STEEP licensing cost, not free and open-source like py2exe! At least there is (or was) a shareware tool named PEBundle, which promised to do something similar. Haven't used it myself, though. > Can this technology be applied to other platforms? Hehe. No idea - I don't know enough about shared libraries. > Could this all be modified in such a way that other scripting > languages could take advantage of your bundling technology? Maybe, but I don't use other scripting languages. But doesn't tcl have a pretty advanced packer? And perl? > Thanks! You're welcome, Thomas From kay.schluehr at gmx.net Mon Sep 26 04:52:21 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 26 Sep 2005 01:52:21 -0700 Subject: Parametric Polymorphism References: Message-ID: <1127724741.393921.105990@g43g2000cwa.googlegroups.com> Catalin Marinas wrote: > Hi, > > Sorry if this was previously discussed but it's something I miss in > Python. I get around this using isinstance() but it would be cleaner > to have separate functions with the same name but different argument > types. I think the idea gets quite close to the Lisp/CLOS > implementation of methods. Guido himself addressed multimethods in his Artima blog: http://www.artima.com/weblogs/viewpost.jsp?thread=101605 See also the subsequent discussion about subtyping problems. Kay From anton.vredegoor at gmail.com Sun Sep 18 08:41:50 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 18 Sep 2005 05:41:50 -0700 Subject: Brute force sudoku cracker In-Reply-To: <3p4s58F8lc12U1@uni-berlin.de> References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> <3p4s58F8lc12U1@uni-berlin.de> Message-ID: <1127047310.956841.14720@f14g2000cwb.googlegroups.com> Diez B. Roggisch wrote: > As everyone posts his, I'll do the same :) It uses some constraint based > solving techniques - but not too complicated ones. When stuck, it > backtracks. So far it never failed me, but I haven't tested it too > thouroughly. Thanks to all for sharing. I like to program sudoku and review such code. So below here is my current file, I think it uses some techniques not yet posted here. It also has a difficult 16x16 puzzle which I know to be solvable (barring typing mistakes) but which my file can't solve before I get tired of waiting, this might draw some heavyweights in the ring :-) I have also read the sudoku wiki page: http://en.wikipedia.org/wiki/Sudoku which was very helpfull and interesting (especially the link to Knuths paper about dancing links was nice, even though I think (but maybe wrongly so) that we don't need dancing links now that we've got sets, but it's still a very very interesting paper) I think the first important step is to realize that some variations have fewer values so that it is possible to reduce the search space early. Currently I'm exploring ideas about contigengies as explained in the wiki above which seems promising, but I haven't found a nice way to implement them yet. Maybe an easy optimization would be to find values that don't come up often and choose variations containing those. And maybe I should switch to an approach that has possibility values inside the cells instead of computing them on the fly each time, that could make contigency elimination easier. Anton from __future__ import generators from sets import Set as set problem1 = ['063000700','000690008','900007002', '002010080','050806090','090070200', '600100003','700045000','009000140'] problem2 = ['030009007','010080000','000100090', '004905006','020000010','500607400', '050001000','000040020','700500030'] problem3 = ['030500810','000760090','400000000', '043905006','010000070','600801930', '000000009','090086000','061002080'] problem4 = ['004530080','060009000','900000005', '000800350','000000000','027006000', '800000007','000300040','090072600'] X =[' 1 0 0 0 0 12 0 10 11 7 6 0 0 4 0 0', ' 0 7 0 0 15 13 0 0 0 0 2 0 0 8 0 0', ' 3 0 0 0 4 0 0 0 0 5 0 12 0 16 0 0', ' 0 0 14 2 0 9 0 0 0 0 1 0 0 0 0 0', '10 15 0 1 0 0 0 2 0 16 0 0 3 0 0 0', '12 0 0 3 0 0 15 0 0 13 0 4 0 1 9 5', ' 5 0 11 0 7 0 8 0 0 0 0 0 0 15 0 0', ' 7 13 0 16 0 0 0 6 0 0 0 14 0 10 0 0', ' 0 0 13 0 11 0 0 0 10 0 0 0 1 0 12 0', ' 0 0 7 0 0 0 0 0 0 3 0 16 0 14 0 13', '16 8 0 0 14 0 5 0 0 15 0 0 4 0 0 6', ' 0 0 0 9 0 0 4 0 1 0 0 0 2 0 0 7', ' 0 0 0 0 0 16 0 0 0 0 8 0 10 5 0 0', ' 0 0 4 0 12 0 6 0 0 0 16 7 0 0 0 14', ' 0 0 6 0 0 1 0 0 0 0 12 13 0 0 11 0', ' 0 0 15 0 0 8 11 3 2 0 9 0 0 0 0 1'] problem5 = [row.split() for row in X] class State: def __init__(self,solved,unsolved): self.solved = solved self.unsolved = unsolved self.size = int((len(solved)+len(unsolved))**.25) def choiceset(self,x,y): "the set of possible choices for an empty cell" sz = self.size res = set(range(1,sz*sz+1)) r,c = x/sz*sz,y/sz*sz for (i,j),v in self.solved.iteritems(): if x == i or y == j or (r<=i References: <1126708775.608076.106850@g43g2000cwa.googlegroups.com> Message-ID: <43285730$0$21365$db0fefd9@news.zen.co.uk> Alan Meyer wrote: > I'm not aware of such a thing. > > I stand ready to be corrected, but I think Python would not be a > good language for writing search engines. In the ones I've written > for custom projects - in C or PL/1, it has been necessary to > perform very high speed operations on highly compressed binary > structures - which is not Python's forte. > > You might be able to put a Python interface over an engine written > in another language. Wasn't Google's first search engine actualy written in Python? Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From fredrik at pythonware.com Fri Sep 30 04:04:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 10:04:44 +0200 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com><7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com><7xzmpwuxd0.fsf@ruckus.brouhaha.com> <20050930075313.67b9b6 76.jk@ospaz.ru> <20050930091126.0c81580c.jk@ospaz.ru> Message-ID: en.karpachov at ospaz.ru wrote: > So you have read every line of the python std library, I guess? yes, but that's irrelevant. in python, you don't need the source to find hidden stuff. finding out is a matter of writing a very small program, or tinkering at the interactive prompt for a couple of seconds. are you even aware that you're posting to a Python group ? From tjreedy at udel.edu Thu Sep 29 17:55:21 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Sep 2005 17:55:21 -0400 Subject: PDF Viewer References: <20050929102501.43567.qmail@web35006.mail.mud.yahoo.com> Message-ID: "Pepe Pena" wrote in message news:20050929102501.43567.qmail at web35006.mail.mud.yahoo.com... Google 'python pdf library' and the third hit is www.reportlab.org/rl_toolkit.html Terry J. Reedy From kreedz at gmail.com Wed Sep 21 11:37:39 2005 From: kreedz at gmail.com (Kreedz) Date: 21 Sep 2005 08:37:39 -0700 Subject: wxPython Notebook crash when pressing alt key In-Reply-To: References: <1127311253.582981.277380@z14g2000cwz.googlegroups.com> Message-ID: <1127317059.085252.161500@g47g2000cwa.googlegroups.com> I have written the "import wx" in my message. You press F key while holding down Alt while focusing on the tab? Python 2.4.1, wxPython 2.6.1.0 From haircut at gmail.com Wed Sep 14 18:31:45 2005 From: haircut at gmail.com (Adam Monsen) Date: 14 Sep 2005 15:31:45 -0700 Subject: strptime() doesn't recognize BST as a valid timezone Message-ID: <1126737105.373660.147170@g14g2000cwa.googlegroups.com> I'm unable to parse the following date string using time.strptime(): "Wed Sep 14, 2005 5:07 PM BST" Format: "%a %b %d, %Y %I:%M %p %Z" I tried changing the locale and using time.tzset(), but no luck. Is there anyone in London (or some other BST location) that would try running the following code? import time date_str = "Wed Sep 14, 2005 5:07 PM BST" format = "%a %b %d, %Y %I:%M %p %Z" time.strptime(date_str, format) I get: "ValueError: time data did not match format: ..." NOTE: there is a workable solution to getting this date into the proper timezone ('Europe/London'), but I'm still unable to parse the 'BST' part, even after setting the locale to en_GB.utf8 and the timezone to 'Europe/London'. Here's a solution to "zoning" naive date strings: http://snipurl.com/hoqz (full url: http://groups.google.com/group/comp.lang.python/browse_frm/thread/ce4909280561458b/ ). I did notice that the Python docs mention %Z is deprecated, so http://snipurl.com/hoqz is possibly the best solution available for now. Thoughts? -- Adam Monsen http://adammonsen.com/ From http Thu Sep 1 23:02:58 2005 From: http (Paul Rubin) Date: 01 Sep 2005 20:02:58 -0700 Subject: Bug in string.find References: <1124160882.554543.75730@g43g2000cwa.googlegroups.com> <3ErPe.853$sV7.65@newssvr21.news.prodigy.com> <7sJPe.573$MN5.131@newssvr25.news.prodigy.net> <7xy86k3r7n.fsf@ruckus.brouhaha.com> <4314b190.174021119@news.oz.net> Message-ID: <7xaciwp3x9.fsf@ruckus.brouhaha.com> Ron Adam writes: > All of the following get the center 'd' from the string. > > a = 'abcdefg' > print a[3] # d 4 gaps from beginning > print a[-4] # d 5 gaps from end > print a[3:4] # d > print a[-4:-3] # d > print a[-4:4] # d > print a[3:-3] # d > print a[3:2:-1] # d These are symetric?! > print a[-4:-5:-1] # d > print a[3:-5:-1] # d > print a[-4:2:-1] # d +1 QOTW From titus at caltech.edu Sun Sep 11 02:05:12 2005 From: titus at caltech.edu (C. Titus Brown) Date: Sat, 10 Sep 2005 23:05:12 -0700 Subject: ANNOUNCE: twill 0.7.2 Message-ID: ANNOUNCING twill v0.7.2. twill is a simple Web scripting language built on top of Python and John J. Lee's 'mechanize'. It's designed for automated testing of Web sites, but it should prove useful for anybody who needs to interact with Web sites (especially those using logins and cookies) on the command line or via a script. twill is a reimplementation of Cory Dodt's PBP. A twill script looks like this: # go to the /. login page go http://slashdot.org/login.pl # fill in the form fv 1 unickname test fv 1 upasswd test submit # ok, there's no such account ;). show error HTML. show --- This is the third public release of twill, version 0.7.2. (Tagline: "no obvious bugs") I'm still looking for general feedback on usability, as well as suggestions on additional use cases. Download directly here: http://darcs.idyll.org/~t/projects/twill-0.7.2.tar.gz Documentation is online at http://www.idyll.org/~t/www-tools/twill.html --- Miscellaneous details: twill is implemented in Python and uses pyparsing and mechanize. In addition to the existing simple command language, twill can easily be extended with Python. twill also provides a fairly simple and well-documented wrapper around mechanize. twill scripts can be recorded with maxq, although scripts may require some hand tweaking at the moment. See the twill documentation for more information. twill does not understand JavaScript, I'm sorry to say. --- Notable bug fixes and features: * save_html and HTTP debugging commands; * fixed extend_with bugs; * updated pyparsing to 1.3.2; * first PyPi release; From apardon at forel.vub.ac.be Mon Sep 5 03:47:34 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Sep 2005 07:47:34 GMT Subject: 'isa' keyword References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> Message-ID: Op 2005-09-03, Steve Holden schreef : >> >> I don't see how it can reasonably said that STK has >> "message-passing" but other OOPLs don't. Consider these code >> fragments: >> >> Smalltalk: >> receiver selector: argument >> >> C++ or Java: >> receiver.selector(argument); >> >> Python: >> receiver.selector(argument) >> >> PHP: >> $receiver->selector($argument) >> >> (I'm not sure if the last one is right since I've not done much OO >> stuff in PHP) >> >> These all mean essentially the same thing so how can one be "message >> passing" and the others not? >> > Sorry, they don't all mean "essentially the same thing" at all. It seems > to me you are looking at SmallTalk in entirely too superficial a light. > In SmallTalk, control structures aren't syntactic primitives, they are > also examples of message-passing, so code blocks are sent as messages to > objects. That doesn't seem that important to me. Should python eventually acquire annonymious blocks, python could do the same. > Python eschews such obscurity and (IMHO) gains clarity by so > doing. But that is, of course, a matter of opinion. > > Also, remember that just because two expressions in different languages > "mean the same thing "doesn't mean they are implemented using the same > techniques. But it is the meaning, that defines the language, not the implementation. So if two expression mean the same thing, they are essentially the same thing. > I would contend (if backed into a corner) that there is a significant > difference between passing the arguments 3 and 4 to a "+" operator > (which is what Python and most other languages implementing standard > ideas of operator precedence do) and sending the message "+ 4" to the > integer 3 (which is effectively what SmallTalk does). Again you are looking at an implemantation detail, not at the meaning. And you are wrong about python. In python you don't pass 3 and 4 to the "+" operator. You select the __add__ method of the integer 3 which you give the argument 4. Yes I know this is a bit simplified. > Of course, I realise that you can argue that the two are equivalent in > the sense that they perform the same computation. But SmallTalk's choice > led to the loss of operator precedence, which is something that is > pretty fundamental to mathematics. Smalltalk could have solved that without any significant change in implementation. Should smalltalk have decided that mathematic expression were just syntactic sugar for messages passed to object, a solution like in python could have been possible. e.g. the arithmetic methods could have been called: @add, @sub, @mul, @div. An expression like 3 + 4 * 5 could then first internally be translated into 3 @add (4 @mul 5) and thus would be treated just as the expression 3 + (4 * 5) is treated now in smalltalk. This has nothing to do with the choice in paradigma, but with the choice of how much syntactix sugar you are willing to allow on top of your paradigma. > Also Python allows much more > flexibility by hard-wiring operators and allowing alternatives to be > considered (if the left operand doesn't have an "__add__" method then > try to use the right operand's "__radd__" method). SmallTalk doesn't > have any parallel to this that I can think of. Smalltalk assumes that there is some total order in the number class systems, and that classes that are low in this relation can be converted to a class that is higher. So when you implement an arithmetic class, you should decide where your class belongs and then when you implement an operator, you should first check to see the argument is not higher classified, if it is you should convert your object to the same class and send the converted object the same method and argument. It is not as flexible as python, but it mostly worked. -- Antoon Pardon From skip at pobox.com Wed Sep 21 09:48:23 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 21 Sep 2005 08:48:23 -0500 Subject: /usr/lib/python2.3/site-packages/_mysql.so: undefined symbol: mysql_rollback In-Reply-To: References: <17195.13247.913110.672774@montanaro.dyndns.org> <17195.14104.513491.861563@montanaro.dyndns.org> Message-ID: <17201.25767.315482.245370@montanaro.dyndns.org> thomas> There is no libmysql, but I've got no idea where it is: Sorry, libmysqlclient.so is the right beastie. So, look in libmysqlclient.so for a mysql_rollback function (using the nm command). Is it possible you have a _mysql.so file that was built with MySQL 4.x include files but is now linking against MySQL 3.x shared objects? That's just a guess, but MySQL became more transaction-aware in the 3.x->4.x transition. I would guess mysql_rollback is available in 4.x but not 3.x. Actually, a better place to ask would be on the help forum for the mysql-python project at Sourceforge: http://sourceforge.net/projects/mysql-python Andy Dustman, the author, is generally quite quick to respond. Skip From andreas.zwinkau at googlemail.com Tue Sep 27 02:21:57 2005 From: andreas.zwinkau at googlemail.com (beza1e1) Date: 26 Sep 2005 23:21:57 -0700 Subject: What tools are used to write and generate Python Library documentation. In-Reply-To: References: Message-ID: <1127802117.122807.281040@o13g2000cwo.googlegroups.com> Do you think of pydoc? Just make comments in your code this way: def add10(x): """this function adds ten to the given variable""" Then save this into add.py and now (in the same directory): pydoc add Voila, your documentation. From rkern at ucsd.edu Tue Sep 27 02:39:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 26 Sep 2005 23:39:51 -0700 Subject: What tools are used to write and generate Python Library documentation. In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > I have a module I'd like to document using the same style... http://docs.python.org/doc/doc.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From viridia at gmail.com Thu Sep 1 03:52:54 2005 From: viridia at gmail.com (talin at acm dot org) Date: 1 Sep 2005 00:52:54 -0700 Subject: 'isa' keyword Message-ID: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> Although I realize the perils of even suggesting polluting the Python namespace with a new keyword, I often think that it would be useful to consider defining an operator for testing whether or not an item is a member of a category. Currently, we have the 'in' operator, which tests for membership within a container, and that works very well -- in particular, it allows such membership tests to be expressed in very natural way. So for example, whereas in C++ I always have to say: if (dependencies.find( name ) != dependencies.end()) in Python I can simply say: if name in dependencies: ...which is much more readable and intuitive. At the same time, however, I recognize that there is a logical difference between membership in a container, and membership in a category. For example, although a bear is a member of the class of mammals, it doesn't make as much to say "if bear in mammal". Similarly, you wouldn't want to use the 'in' keyword as a replacement for isinstance(), i.e. "if name in str". I propose the word 'isa' because the term 'isa hierarchy' is commonly used to indicate a tree of types. So the syntax would look like this: if bear isa mammal: if name isa str: (I suppose it would look prettier to put a space between "is" and "a", but there are many obvious reasons why you don't want "a" to be a keyword!) The "isa" operator would of course be overloadable, perhaps by an accessor functions called __isa__, which works similarly to __contains__. The potential uses for this are not limited to isinstance() sugar, however. For example: if image isa gif: elif image isa jpeg: elif image isa png: In this case, we're not testing for object identity (which tests if two variables are referring to the same object), or even object equivalence (which tests of two objects are of equal value), nor are we testing for membership within a container -- instead we're testing for membership with a type hierarchy, where 'type' can be defined to mean whatever the programmer wants. Of course, at this point, I am sure that someone will point out that I should be using method overloading and inheritance rather than explicit testing of types. However, try writing an efficient __cmp__ function solely by method overloading -- or any other function that deals with more two object argument, where the action to be taken depends on the combination of types of both arguments. This can be solved with multi-method dispatch, but such methods are complex, non-standard, and have somewhat dubious performance characteristics. Its generally faster and simpler to dispatch based on the type of one of the arguments, and then test the types of the other arguments. From rkern at ucsd.edu Fri Sep 9 05:49:41 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 09 Sep 2005 02:49:41 -0700 Subject: sys.stdout In-Reply-To: <1126259024.967722.205860@g44g2000cwa.googlegroups.com> References: <1126255685.873523.293080@o13g2000cwo.googlegroups.com> <1126257573.719356.151770@z14g2000cwz.googlegroups.com> <1126259024.967722.205860@g44g2000cwa.googlegroups.com> Message-ID: S?bastien Boisg?rault wrote: > Tiissa, > > Thanks for your answer. The execution of your example leads to a > 'aaa' display during 2 secs, before it is erased by the prompt. > > This behavior is standard ? The standard output is not supposed > to *concatenate* the 'aaa' and the '>>>' ? FWIW: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.write('AAAA') AAAA>>> sys.stdout.write('BBBB\n') BBBB >>> -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From simonwittber at gmail.com Sun Sep 4 23:49:06 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 4 Sep 2005 20:49:06 -0700 Subject: Magic Optimisation Message-ID: <1125892146.709749.45740@g49g2000cwa.googlegroups.com> Hello People. I've have a very tight inner loop (in a game app, so every millisecond counts) which I have optimised below: def loop(self): self_pool = self.pool self_call_exit_funcs = self.call_exit_funcs self_pool_popleft = self.pool.popleft self_pool_append = self.pool.append check = self.pool.__len__ while check() > 0: task = self_pool_popleft() try: task.next() except StopIteration: self_call_exit_funcs(task) return self_pool_append(task) This style of optimisation has shaved _seconds_ from my iteration cycle, esp. when I have many registered tasks, so this style of optimisation is very important to me. However, it is very ugly. Does anyone have any tips on how I could get this optimisation to occor magically, via a decorator perhaps? Sw. From mxywp at 126.com Wed Sep 7 17:25:36 2005 From: mxywp at 126.com (Xiangyi) Date: Wed, 7 Sep 2005 14:25:36 -0700 Subject: bug in numarray? Message-ID: <000901c5b3f2$b2b6d030$5c0a030a@PANDA> Hi, there, I got the following segmentation fault. > from numarray import * > a = zeros((5,100), Float64) > b = kroneckerproduct(a, identity(12)) > segmentation fault If I use a = zeros((5,100)), everything is fine. Kind of weird! Can someone help me figure it out? BTW, the python version is 2.4.1 and numarray 1.3.2 Many thanks! Xiangyi > > -- > http://mail.python.org/mailman/listinfo/python-list > From bram at geenspam.sara.nl Tue Sep 13 08:13:44 2005 From: bram at geenspam.sara.nl (Bram Stolk) Date: Tue, 13 Sep 2005 14:13:44 +0200 Subject: using filedescriptors in SIGINT signal handler Message-ID: <1126613624.454535@blaat.sara.nl> Hello, I catch SIGINT signals with a handler. In the handler, I use fd's to write some data to a child process. Is this valid? Because the data never arrives, and I wonder what I'm doing wrong. Can filedescriptors still be used when you're in the signal handling of SIGINT? Thanks, Bram From jstroud at mbi.ucla.edu Wed Sep 21 18:31:28 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 21 Sep 2005 15:31:28 -0700 Subject: Object default value In-Reply-To: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com> Message-ID: <200509211531.28566.jstroud@mbi.ucla.edu> On Tuesday 20 September 2005 12:31, ago wrote: > Is it possible to have a default value associated python objects? I.e. > to flag an attribute in such a way that the assignment operator for the > object returns the default attribute instead of the object itself, but > calls to other object attributes are properly resolved? (I don't think > so, but I am not sure) I was thinking about this last night and it seemed an interesting problem. I thought you might want to change the way you look at it, using the python equivalent to type casting (maybe its called "coercing", sorry for my poor command of python vocabulary). I have overridden __int__ and __float__ for this example. You might want to look into __coerce__. This should have the behavior you desire while having the explicit syntax expected of good python code. Inheriting from list allows you to use a stack-like behavior you described in a previous email. You can further modify __getattribute__, __setattribute__, __delattribute__, etc. Overriding __iter__ gives you the history in "correct" order, but may begin to embark on a non-intuitive interface--you be the judge. I think this is about as close as you can get in python to what you are thinking (don't know the oldest python version this is backwards compatible with): py> class Thing(list): ... def __init__(self, start_value): ... list.__init__(self) ... self.append(start_value) ... def __setattr__(self, anattr, aval): ... if (anattr == 'top'): ... self.append(aval) ... else: ... list.__setattr__(self, anattr, aval) ... def __getattr__(self, anattr): ... if (anattr == 'top'): ... return self[-1] ... elif (anattr == 'old'): ... try: ... return self[-2] ... except IndexError: ... raise NameError, "No old value yet" ... else: ... list.__getattr__(self, anattr) ... def __iter__(self): ... return list.__iter__(self[::-1]) ... def __int__(self): ... return int(self.top) ... def __float__(self): ... return float(self.top) ... def __str__(self): ... return str(self.top) ... py> athing = Thing(5) # should init with a reasonable value py> athing.top # __getattr__ 5 py> int(athing) # __int__ 5 py> print athing # __str__ 5 py> float(athing) # __float__ 5.0 py> athing.top = 4 # __setattr__ py> print athing 4 py> athing.old # __getattr__ 5 py> athing.top = 42 # __setattr__ py> [x for x in athing] # __iter__ [42, 4, 5] py> y = float(athing) # closest you can get to assignment overloading py> print y # y is a float 42.0 py> athing # Thing inherits from list, so you get list.__repr__() here [5, 4, 42] Here it is without the prompts: class Thing(list): def __init__(self, start_value): list.__init__(self) self.append(start_value) def __setattr__(self, anattr, aval): if (anattr == 'top'): self.append(aval) else: list.__setattr__(self, anattr, aval) def __getattr__(self, anattr): if (anattr == 'top'): return self[-1] elif (anattr == 'old'): try: return self[-2] except IndexError: raise NameError, "No old value yet" else: list.__getattr__(self, anattr) def __iter__(self): return list.__iter__(self[::-1]) def __int__(self): return int(self.top) def __float__(self): return float(self.top) def __str__(self): return str(self.top) -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From digitalsuicide at gmail.com Thu Sep 29 11:10:49 2005 From: digitalsuicide at gmail.com (dataw0lf) Date: Thu, 29 Sep 2005 09:10:49 -0600 Subject: A Moronicity of Guido van Rossum In-Reply-To: <200509291657.28985.mail@tuxipuxi.org> References: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> <200509291657.28985.mail@tuxipuxi.org> Message-ID: <433C03F9.4030908@gmail.com> Michael Goettsche wrote: > Assuming you want to reach people to convince them your position is right, why > don't you try that in proper language? "moron" occured 7 times in your not > too long text, that doesn't let you look like a tech moron or a math moron, > but just like a moron. Actually, an angry moron, due to the use of the expletive 'fuck' 4 times in said text. -- Joshua Simpson -- dataw0lf.org Lead Network Administrator/Engineer Aero-Graphics Inc. jsimpson at aero-graphics.com From Tommy.Ryding at gmail.com Mon Sep 5 07:42:41 2005 From: Tommy.Ryding at gmail.com (Tommy.Ryding at gmail.com) Date: 5 Sep 2005 04:42:41 -0700 Subject: Controlling memory allocation In-Reply-To: <1125871034.660265.208150@g43g2000cwa.googlegroups.com> References: <1125871034.660265.208150@g43g2000cwa.googlegroups.com> Message-ID: <1125920561.351388.315390@o13g2000cwo.googlegroups.com> Hello. I have done the thing you are requesting. You can easily create your own memory pool and have Python to use it. I added some rows to Pyconfig.h: #ifdef malloc #undef malloc #endif /*malloc*/ #define malloc Python_malloc Then I have some overhead in my own Python_malloc(size_t nBytes) From ptmcg at austin.rr.com Thu Sep 15 20:01:39 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Sep 2005 17:01:39 -0700 Subject: Looking for a database. Sugestions? In-Reply-To: References: Message-ID: <1126826997.926805.301680@g14g2000cwa.googlegroups.com> SQLite is very easy to get started with. I loaded up a 9 Mb file of process data and the performance was pretty good after I indexed on the join columns (increased db file size to 15Mb). Supports transactions, cursors, typed data. I *think* it is thread-safe, but I'm not positive. But it's great as a simple embedded SQL database. -- Paul From gh at ghaering.de Fri Sep 30 09:42:27 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 30 Sep 2005 15:42:27 +0200 Subject: Zope3 Examples? In-Reply-To: References: Message-ID: <433D40C3.2010707@ghaering.de> Markus Wankus wrote: > [...] Thanks for the reply - maybe I'll give it another shot. I'm currently > demoing Snakelets. Quite a turn in the opposite direction, but small > and super-easy to get going with. [...] I also found Snakelets a pleasure to use and chose it for implementing a clan homepage in early 2005. I'm still very interested in the Python/Web/RDBMS field and tried to follow the developments since then. I didn't actually build anything real, only played a little bit with CherryPy and the megaframeworks built upon, Subway and TurboGears. If I had to choose again, I'd use TurboGears, despite the fact that it's very young and still developing. -- Gerhard From grante at visi.com Thu Sep 29 15:12:20 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Sep 2005 19:12:20 -0000 Subject: xml.sax removing newlines from attribute value? References: <11joa6r22k79340@corp.supernews.com> Message-ID: <11jof4kpir8je24@corp.supernews.com> On 2005-09-29, Fredrik Lundh wrote: >> I'm using xml.sax to parse the "datebook" xml file generated >> by QTopiaDesktop. When I look at the xml file, some of the >> attribute strings have newlines in them (as they are supposed >> to). >> >> However, when xml.sax passes the attributes to my >> startElement() method the newlines seem to have been deleted. >> >> How do I get the un-munged element attribute values? > > newlines as in chr(10) rather than ? Yup, Looks that way. > if so, the only way is to avoid XML: > > http://www.w3.org/TR/REC-xml/#AVNormalize I can't quite find it in the BNF, but I take it that chr(10) isn't really allowed in XML attribute strings. IOW, the file generate by Trolltech's app is broken. > if the "yes, I know, but I have good reasons" approach is okay > with you, I didn't define the file or write the program that generated it. It's claimed to be "xml", and I'm just trying to parse it. > and you're big enough to defend yourself against the > XML-Is-The-Law crowd, you can use a "sloppy" XML parsers such > as sgmlop to deal with your files: > > http://effbot.org/zone/sgmlop-index.htm Good to know for future reference. For now, I think I'll just live with the way it works. Everything basically works, except some strings don't display quite "right". My current app treats the file as read-only. If I ever get around to modifying data and writing it back, I'll probably have to deal with the newline issue at that point. -- Grant Edwards grante Yow! When this load is at DONE I think I'll wash visi.com it AGAIN... From tjreedy at udel.edu Fri Sep 9 17:14:11 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Sep 2005 17:14:11 -0400 Subject: Question about consistency in python language References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> <1126247836.678936.233170@o13g2000cwo.googlegroups.com> Message-ID: "Kay Schluehr" wrote in message news:1126247836.678936.233170 at o13g2000cwo.googlegroups.com... > On the other hand there exists no sorted() method for tuples or lists > like join() for strings but it is implemented as a function in Python24 > that returns a new sorted container. I consider this as an > inconsistency across builtin types. The sorted function is not a list method because it is not only a list function or even only a tuple and list function or even only a string, tuple, list, array, or dict function. Its input is **any** iterable. The only way to have it both be general and a method would be to have an iterable type and to require that all iterables inherit from that type to reap the benefit of being an iterable. All the itertools functions are also functions and not methods of a hypothetical iterable type. 'Iterable' is a duck type and hence functions thereof must be functions and not methods. Terry J. Reedy From fredrik at pythonware.com Mon Sep 5 12:22:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Sep 2005 18:22:28 +0200 Subject: Getting the bytes or percent uploaded/downloaded through FTP? References: <1125931880.415786.40880@g47g2000cwa.googlegroups.com> <1125933423.728878.146270@g49g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > The only way I can think of to get the size of the file you're about to > download is using the FTP object's .dir() method. If you have the Tools > directory (standard on Windows, with source on other platforms) you can > take a look at the ftpmirror script - a fairly recent version can be seen at > > http://weblog.cs.uiowa.edu/python-2.3.1/Tools/scripts/ftpmirror.py to handle arbitrary servers, you also need a flexibel LIST response parser; see: http://cr.yp.to/ftpparse.html python bindings: http://c0re.23.nu/c0de/ftpparsemodule/ and http://effbot.org/downloads/#ftpparse From rkern at ucsd.edu Wed Sep 7 17:41:18 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 07 Sep 2005 14:41:18 -0700 Subject: bug in numarray? In-Reply-To: <000901c5b3f2$b2b6d030$5c0a030a@PANDA> References: <000901c5b3f2$b2b6d030$5c0a030a@PANDA> Message-ID: Xiangyi wrote: > Hi, there, > > I got the following segmentation fault. > >>from numarray import * >>a = zeros((5,100), Float64) >>b = kroneckerproduct(a, identity(12)) >>segmentation fault > > If I use a = zeros((5,100)), everything is fine. Kind of weird! > Can someone help me figure it out? BTW, the python version is 2.4.1 and > numarray 1.3.2 Works for me on OS X using Python 2.4.1 and the latest CVS numarray. Please try with the latest CVS numarray, and if it still doesn't work, then please ask again on the numpy-discussion list. http://lists.sourceforge.net/lists/listinfo/numpy-discussion -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From hal at thresholddigital.com Thu Sep 29 01:46:51 2005 From: hal at thresholddigital.com (Hal Vaughan) Date: Thu, 29 Sep 2005 01:46:51 -0400 Subject: Will Python Be Good For This Type Of Project? Message-ID: I'm self taught and most of what I've been working on for the past several years has been entirely in Perl and Java. I've noticed that I can code about 5 times faster in Perl than Java, in part because I feel like whenever I want to do something in Java, I have to create an object, do a few preperatory things, then do what I need, but in Perl, I just call the routine. Java, however, does much better at cross platform apps, especially if I need a GUI (I find Swing easy to use). I need to write a setting editor which basically consists of a GUI with a lot of checkboxes, radio buttons, and option select lists. I originally had something to do this in Javascript, but Javascript was not strong enough to let me create data structures to keep track of the data. I had to store it in 3d arrays, which was hard to keep up with. I was planning on writing the new setting editor in Java for several reasons, including the ability to create my own objects to store groups of settings. I also can write it so it'll run on a computer by itself, or as an applet with very little extra work. That's a benefit, since it means it can be run from anywhere through a Java enabled browser and a username and password. It can also be run on a system where it's been installed without using a browser (either way, it reads and writes the settings from a URL). Someone on a mailing list I'm on has suggested that I look into Python, and use Jython to compile it. I see that I can write applications and applets in Python (but I haven't seen references to being able to write one application just once and have it work as both). I also know Python is a higher level than Java (a few people I know say it's almost like writing pseudo code). At this time I don't know Python (I've looked at some sample code and I'm still getting used to loops and if statements without closing braces!). What I'm trying to determine is 1) if it's relatively easy to write a program to work as an application AND an applet (depending on how it's called), 2) If it'll handle the networking to read what amounts to web pages full of setting info and write that back in POST statements without problems from the user's point of view and easily from the programmer's point of view, 3) What coding time and difficulty is like in Python compared to, most specifically, Java and Perl, 4) Is it easy for me to interface Java and Python classes seamlessly, and 5) (I realize only I can answer this for sure, but opinions and experience of others would be a help!) Is Python easy enough and fast enough to code in that it'd be worth me taking time to learn it and doing the project Python instead of Java? Any help, thoughts, comments, and such are appreciated! Thank you! Hal From xah at xahlee.org Sun Sep 4 07:14:48 2005 From: xah at xahlee.org (Xah Lee) Date: 4 Sep 2005 04:14:48 -0700 Subject: os.system(r"ls") prints to screen?? In-Reply-To: References: <1125795750.304104.280660@g49g2000cwa.googlegroups.com> Message-ID: <1125832488.379489.147760@g49g2000cwa.googlegroups.com> Steve Holden wrote: > This is all pretty basic stuff. Perhaps you should stop your verbal > assault on the computer science community and start to learn the > principles of what you are doing. is this a supressed behavior that a human animal can finally instinctively and justifiably release at another in a group frenzy? Xah xah at xahlee.org ? http://xahlee.org/ From catalin.marinas at gmail.com Sun Sep 25 07:18:21 2005 From: catalin.marinas at gmail.com (Catalin Marinas) Date: Sun, 25 Sep 2005 12:18:21 +0100 Subject: [RFC] Parametric Polymorphism References: <3pnbmiFbal03U1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > google for gnosis utils and multimethods to see a more "oldfashioned" > implementation. I now remember to have seen it but it requires a lot of typing to achieve it and you would call a different function name from the one you define, reducing the code clarity. > But your approach certainly is interesting - however, The idea is not new. Lisp/CLOS implements the defmethod macro which creates a generic function (i.e. a dispatcher) with the same name as the function you define: http://www.lisp.org/HyperSpec/Body/mac_defmethod.html. Actually, the defmehod macro is the base for implementing object polymorphism. > I _rarely_ need such functionality. Ususally duck-typing suits me > well. Of course, duck-typing is simple to use but the parametric polymorphism is useful when the types are unrelated. Let's say you want to implement a colour-print function which should support basic types like ints and floats as well as lists and dictionaries. In this case, and thank to the function decorations support, the code would be clearer. Another use case is to extended the functionality of a class using functions but you cannot easily modify the class or create a subclass (the objects are generated by some factory implemented in a third-party library). Of course, you might be able to get around this but parametric polymorphism could reduce the written code. This idea only needs an optimised (and deterministic) implementation for the best parameter match based on subclass-superclass relations. It can also be extended to implement polymorphism based on the parameter values (something people tried to do in C++ with complicated templates but, well, only at compilation time, with obvious drawbacks). -- Catalin From martijn at metacase.com Wed Sep 21 03:34:59 2005 From: martijn at metacase.com (Martijn Iseger) Date: Wed, 21 Sep 2005 07:34:59 +0000 (UTC) Subject: Free seminar on domain-specific modeling References: Message-ID: <7c6fcb4c42e18c78caf408cb141@news.kolumbus.fi> > if you don't understand the "silver bullet" reference, you're not > qualified to use phrases like "makes software development 5-10 times > faster". You could reverse that as well: http://www.dsmforum.org From barnesc at engr.orst.edu Thu Sep 15 02:16:01 2005 From: barnesc at engr.orst.edu (barnesc at engr.orst.edu) Date: Wed, 14 Sep 2005 23:16:01 -0700 Subject: Builtin classes list, set, dict reimplemented via B-trees Message-ID: <1126764961.432911a1bd436@webmail.oregonstate.edu> Nifty, Tim Peters responded to my e-mail. I must've said something interesting. Cool, a PyCelebrity! >[barnesc at engr.orst.edu] >> ... >> I've gotten bored and went back to one of my other projects: >> reimplementing the Python builtin classes list(), set(), dict(), >> and frozenset() with balanced trees (specifically, counted B-trees >> stored in memory). >> >> In short, this allows list lookup, insertion, deletion in O(log(N)) >> time. It allows the set and dictionary types to be maintained in >> order, and insert/lookup/remove operations here take O(log(N)) time >> as well. Getting the k least or k greatest elements takes >> O(log(N)+k) time. > >Note that BTrees for Python have been part of ZODB for many years: > > Section 5.3, _BTrees Package_ > http://www.zope.org/Wikis/ZODB/FrontPage/guide/node6.html > >If you install ZODB, you can use its BTrees as in-memory data >structures without using any of the rest of ZODB. If you want to >persist them, great, that's what ZODB is for. > >Note that ZODB's are really B+ trees, so iterating over the smallest k >takes O(k) time. As an extension to Python's mapping protocol, the >keys/values/items/iterkeys/itervalues/iteritems methods also accept >optional lower and upper bounds on the keys to return. > >A gotcha: For scalability in multiprocess database apps, ZODB's >BTrees do not store their size. As a result, len(a_ZODB_BTree) takes >time linear in the number of elements. Thanks for the link! >> ... >> So my question is: are there any other *practical* applications of a >> B-tree based list/set/dict ? > >Yes. > >> In other words, is this module totally worth coding, > >That's a different question entirely ;-) > >> or is it just academic wankery and theoretical flim flam ? :) > >It's probably not a way to get rich quick. > Well, the Tim Peters PyCelebrity experience was fun, but not quite as exhilarating as advertised. I'm not sure what to say. Did I get my money's worth? There were no s, even a little sarcasm. I guess, overall, yeah it was cool, it was worthwhile, it was fun, man, it was a life-changing moment! Thanks for tuning in to PyCelebrity weekly. We're always glad to be part of your inexplicable existence in The Hostile And Indifferent Universe (Incorporated). Contributions come from hackers like you! Reporting live from Python-list, this is...Connelly Barnes. Next up: Startling photographs show that Guido van Rossum was KIDNAPPED BY ALIENS in 1990! Rumor has it that his superhuman language design skills are really due to neuroimplanted nanotube processors! From chris.stromberger at gmail.com Wed Sep 7 19:02:18 2005 From: chris.stromberger at gmail.com (chris) Date: 7 Sep 2005 16:02:18 -0700 Subject: Need help with C extension module In-Reply-To: References: <1126131877.351395.64850@f14g2000cwb.googlegroups.com> Message-ID: <1126133396.686688.160760@o13g2000cwo.googlegroups.com> Any tips on what the pyrex should look like for my example? From maksim.kasimov at gmail.com Mon Sep 5 11:26:50 2005 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Mon, 05 Sep 2005 18:26:50 +0300 Subject: logging into one file problem Message-ID: hello in my modules, I'm using logging module, doing thus (there is a few modules): in module1.py: hdl = logging.StreamHandler() fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger('module1') log.addHandler(hdl) In script, which is uses these modules, I'm doing in a similar way: in script.py: hdl = logging.StreamHandler() fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger('script') log.addHandler(hdl) Than, to direct all output into one log-file I'm doing like this: script.py >> script.log 2>&1 All works as expected - all output in one file (script.log), but only until syslog will rotate script.log, than output to log-file stops. How to avoid this situation? i can't using something like this: hdl = logging.FileHandler('script.log') because modules are used in other scripts, and log output of each application must be in different files. and doing in script.py like this: module.hdl = hdl module.log = log will works, but it is very inconvenient, because in main script, i'm not importing all the modules (some modules imported by other modules). thanks for help. Python 2.2.3 FreeBSD -- Best regards, Maksim Kasimov mailto: maksim.kasimov at gmail.com From benji at benjiyork.com Thu Sep 8 08:42:26 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 08 Sep 2005 08:42:26 -0400 Subject: Construct raw strings? In-Reply-To: References: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> Message-ID: <432031B2.6030100@benjiyork.com> Peter Hansen wrote: > Benji York wrote: > >> It's not join that's getting you, it's the non-raw string >> representation in path_to_scan. Use either 'd:\test_images' or >> 'd:\\test_images' instead. > > Benji, you're confusing things: you probably meant r'd:\test_images' > in the above Doh! I did indeed. Thanks for the backup. -- Benji York From jepler at unpythonic.net Fri Sep 2 23:15:55 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Fri, 2 Sep 2005 22:15:55 -0500 Subject: Problems with os.system In-Reply-To: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> References: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> Message-ID: <20050903031555.GD26572@unpythonic.net> On Fri, Sep 02, 2005 at 01:45:42PM -0700, alexLIGO wrote: > Can I force python to execute the program on the bash? What can > I do? os.system() is a wrapper on system(3), which invokes /bin/sh. If you want to use a different shell, you can use os.spawnv(os.P_WAIT, '/bin/bash', ['bash', '-c', command]) or even avoid the use of a shell altogether: os.spawnvp(os.P_WAIT, 'myprogram', ['myprogram', '-arg1', 'arg2']) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steven.bethard at gmail.com Sat Sep 10 19:46:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 10 Sep 2005 17:46:40 -0600 Subject: [pyparsing] make sure entire string was parsed Message-ID: How do I make sure that my entire string was parsed when I call a pyparsing element's parseString method? Here's a dramatically simplified version of my problem: py> import pyparsing as pp py> match = pp.Word(pp.nums) py> def parse_num(s, loc, toks): ... n, = toks ... return int(n) + 10 ... py> match.setParseAction(parse_num) W:(0123...) py> match.parseString('121abc') ([131], {}) I want to know (somehow) that when I called match.parseString(), there was some of the string left over (in this case, 'abc') after the parse was complete. How can I do this? (I don't think I can do character counting; all my internal setParseAction() functions return non-strings). STeVe P.S. FWIW, I've included the real code below. I need to throw an exception when I call the parseString method of cls._root_node or cls._root_nodes and the entire string is not consumed. ---------------------------------------------------------------------- # some character classes printables_trans = _pp.printables.translate word_chars = printables_trans(_id_trans, '()') syn_tag_chars = printables_trans(_id_trans, '()-=') func_tag_chars = printables_trans(_id_trans, '()-=0123456789') # basic tag components sep = _pp.Literal('-').leaveWhitespace() alt_sep = _pp.Literal('=').leaveWhitespace() special_word = _pp.Combine(sep + _pp.Word(syn_tag_chars) + sep) supp_sep = (alt_sep | sep).suppress() syn_word = _pp.Word(syn_tag_chars).leaveWhitespace() func_word = _pp.Word(func_tag_chars).leaveWhitespace() id_word = _pp.Word(_pp.nums).leaveWhitespace() # the different tag types special_tag = special_word.setResultsName('tag') syn_tag = syn_word.setResultsName('tag') func_tags = _pp.ZeroOrMore(supp_sep + func_word) func_tags = func_tags.setResultsName('funcs') id_tag = _pp.Optional(supp_sep + id_word).setResultsName('id') tags = special_tag | (syn_tag + func_tags + id_tag) def get_tag(orig_string, tokens_start, tokens): tokens = dict(tokens) tag = tokens.pop('tag') if tag == '-NONE-': tag = None functions = list(tokens.pop('funcs', [])) id = tokens.pop('id', None) return [dict(tag=tag, functions=functions, id=id)] tags.setParseAction(get_tag) # node parentheses start = _pp.Literal('(').suppress() end = _pp.Literal(')').suppress() # words word = _pp.Word(word_chars).setResultsName('word') # leaf nodes leaf_node = tags + _pp.Optional(word) def get_leaf_node(orig_string, tokens_start, tokens): try: tag_dict, word = tokens word = cls._unescape(word) except ValueError: tag_dict, = tokens word = None return cls(word=word, **tag_dict) leaf_node.setParseAction(get_leaf_node) # node, recursive node = _pp.Forward() # branch nodes branch_node = tags + _pp.OneOrMore(node) def get_branch_node(orig_string, tokens_start, tokens): return cls(children=tokens[1:], **tokens[0]) branch_node.setParseAction(get_branch_node) # node, recursive node << start + (branch_node | leaf_node) + end # root node may have additional parentheses cls._root_node = node | start + node + end cls._root_nodes = _pp.OneOrMore(cls._root_node) From steve at REMOVETHIScyber.com.au Tue Sep 13 14:31:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 14 Sep 2005 04:31:40 +1000 Subject: Simplifying imports? References: <1126580971.076107.314490@o13g2000cwo.googlegroups.com> Message-ID: On Mon, 12 Sep 2005 20:09:31 -0700, chapolim-colorado wrote: > I like to keep my classes each in a separate file with the same name of > the class. The problem with that is that I end up with multiple imports > in the beginning of each file, like this: > > from foo.Bar import Bar > from foo.Blah import Blah > from foo.Zzz import Zzz > > What I'd like to do would be to replace it all by a single line: > > from foo.* import * > > Of course, that doesn't work, but is there a way to do something like > that? "Doctor, it hurts when I do this." "Then don't do that." If putting one class per file causes you pain, then don't put one class per file. The idea of packages is to make things easier for you, not harder -- if you are having to fight the import mechanism, then perhaps you need to rethink your design. eg if you have a good reason for requiring one class per file, then one possible work around would be to define a single "header" module containing all those "from foo.Bar import Bar" statements, and then in your actual module(s) call "from header import *". Watch out for circular imports though. -- Steven. From claudio.grondi at freenet.de Tue Sep 27 16:28:53 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 27 Sep 2005 20:28:53 -0000 Subject: Getting a number out of a string References: <1127844971.471405.172860@g47g2000cwa.googlegroups.com> Message-ID: <3pthagFc5q6eU1@individual.net> what about: >>> lst = [digit for digit in '06897'] >>> lst ['0', '6', '8', '9', '7'] Claudio schrieb im Newsbeitrag news:1127844971.471405.172860 at g47g2000cwa.googlegroups.com... > I'm trying to extract single digit number from a string. > > t[1] = '06897' > > I want to get the 7, 9,8 & 6 seperated out to use but can't find a way > to split out the single characters. > > Thanks > From rkern at ucsd.edu Wed Sep 7 22:08:13 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 07 Sep 2005 19:08:13 -0700 Subject: Manging multiple Python installation In-Reply-To: References: Message-ID: Andy Leszczynski wrote: > Jeremy Jones wrote: > >>Andy Leszczynski wrote: >> >>Download the source, untar, cd to the new directory, run: >> >>./configure --prefix=/opt/mypython >>make >>make install > > Is there any way to pass the prefix to the "make install"? Is passing it to the configure script a problem? > Why "make" > depends on that? I think that parts of the configuration depend on knowing the ultimate installation location. Specifically, you might have problems building extension modules using distutils. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From donn at u.washington.edu Fri Sep 16 13:58:40 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 16 Sep 2005 10:58:40 -0700 Subject: Odd behavior with os.fork and time.sleep References: <1126888834.712275.91470@f14g2000cwb.googlegroups.com> Message-ID: In article <1126888834.712275.91470 at f14g2000cwb.googlegroups.com>, "Yin" wrote: > I am writing a script that monitors a child process. If the child > process dies on its own, then the parent continues on. If the child > process is still alive after a timeout period, the parent will kill the > child process. Enclosed is a snippet of the code I have written. For > some reason, unless I put in two time.sleep(4) commands in the parent, > the process will not sleep. Am I forgetting something? Any reasons > for this strange behavior? ... > signal.signal(signal.SIGCHLD, chldhandler) If you can possibly revise your design to avoid the need for this, by all means do so. The SIGCHLD signal interrupts functions like sleep(), and that's what you're seeing: the parent process didn't return to its sleep after handling the signal. What's worse, it affects other functions in a similar way, such as I/O. Try to read some input from the terminal, instead if sleeping, and you should crash with an EINTR error. Makes it harder to write a reliable program, when you're inviting such trouble. So far this is a low level UNIX issue that isn't peculiar to Python, but Python adds to the difficulties just in the general awkwardness of signal handling in an interpreted language, where handlers may execute somewhat later than you would expect from experience with lower level languages. And then if you decide to add threads to the mix, there are even more issues as signals may be delivered to one thread and handled in another, etc. If you're dispatching on I/O, for example with select, you can use an otherwise unused pipe to notice the child fork's exit -- close the parent's write end right away, and then when the pipe becomes readable it must be because it closed on child exit. Donn Cave, donn at u.washington.edu From ptmcg at austin.rr._bogus_.com Sat Sep 24 03:37:23 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 24 Sep 2005 07:37:23 GMT Subject: Config parser module References: <1127489369.091513.206040@g49g2000cwa.googlegroups.com> Message-ID: wrote in message news:1127489369.091513.206040 at g49g2000cwa.googlegroups.com... > Hi all > I am a newbie and I just saw a ongoing thread on Fileprocessing which > talks abt config parser. > I have writen many pyhton program to parse many kind of text files by > using string module and regex. But after reading that config parser > thread I feel stunned. > > Can somebody tell me some intro info how to parse huge data (most of > them are input data to application softwares like nastran, abaqus etc) > > Recently I saw a great work by John on Nastran file parser (i am still > trying to understand the program, > http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ > > An example of dat may be like this, (part of) > (say point id coordinateSysNo x,y,z ...) > GRID 1 12478.0 0.0 256.75 1 > GRID 2 12357.25 0.0 256.75 1 > GRID 3 12357.25 0.0 199.0 1 > (say Elementtype id property point1 point 2 point3 point4 etc) > CQUAD4 7231 21 5691 5700 5701 56920.0 > > CQUAD4 7232 21 5692 5701 5702 56930.0 > > CQUAD4 7233 21 5693 5702 5703 56940.0 > > the data file is very complex if i consider all complexities) > > Is is possible to use config parser module insome way for this. I also > have few perl parser (for some part for some particular tasks) and now > changing them to python. (I feel perl regex combination is very easy to > learn and very powerfull) > > Any information will be appreciated. > > -jiro > Here's some sample code that might give you some ideas. -- Paul data = """\ GRID 1 12478.0 0.0 256.75 1 GRID 2 12357.25 0.0 256.75 1 GRID 3 12357.25 0.0 199.0 1 CQUAD4 7231 21 5691 5700 5701 56920.0 CQUAD4 7232 21 5692 5701 5702 56930.0 CQUAD4 7233 21 5693 5702 5703 56940.0 """ class Node(object): def __init__(self,s): self.__dict__.update( zip(self.getInitVarNames(), s.split()) ) def __str__(self): return "%s %s" % (self.__class__.__name__, self.__dict__) class GridNode(Node): def getInitVarNames(self): return "id,x,y,z,other".split(',') class Cquad4Node(Node): def getInitVarNames(self): return "id,p1,p2,p3,p4,other".split(',') # define mapping of leading keyword to class name typeNodeClassMap = { "GRID" : GridNode, "CQUAD4" : Cquad4Node, } def makeNode(s): nodeType,nodeArgs = s.split(" ",1) nodeClass = typeNodeClassMap[nodeType] return nodeClass( nodeArgs ) for line in data.split("\n"): if line: n = makeNode(line) print n From renting at astron.nl Wed Sep 14 04:09:00 2005 From: renting at astron.nl (Adriaan Renting) Date: Wed, 14 Sep 2005 10:09:00 +0200 Subject: read stdout/stderr without blocking Message-ID: Please note that popen uses pipes, which are block devices, not character devices, so the writes will be done in blocks instead of characters/lines, (you can only read something _after_ the application at the other end of the pipe has done a flush or written 8192 bytes. When reading from a pty like pexpect does, your read will not block until the stdio block buffer is filled. Maybe using popen is your problem? The FAQ of Pexpect explains the problem very clearly. >>>Jacek Pop*awski 09/13/05 4:36 pm >>> |Grant Edwards wrote: |>You're right. I must have been remembering the behavior of a |>network socket. Apparently, you're supposed to read a single |>byte and then call select() again. That seems pretty lame. | |I created another thread with single read(), it works, as long as I have | only one PIPE (i.e. stderr is redirected into stdout). |I wonder is it Python limitation or systems one (I need portable solution)? -- http://mail.python.org/mailman/listinfo/python-list From news at NOwillmcguganSPAM.com Tue Sep 27 14:32:35 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Tue, 27 Sep 2005 19:32:35 +0100 Subject: Getting a number out of a string In-Reply-To: <3pthagFc5q6eU1@individual.net> References: <1127844971.471405.172860@g47g2000cwa.googlegroups.com> <3pthagFc5q6eU1@individual.net> Message-ID: <4339904b$0$21316$db0fefd9@news.zen.co.uk> Claudio Grondi wrote: > what about: > >>>>lst = [digit for digit in '06897'] >>>>lst > > ['0', '6', '8', '9', '7'] Or.. >>> list('06897') ['0', '6', '8', '9', '7'] Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From fredrik at pythonware.com Wed Sep 7 05:36:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 7 Sep 2005 11:36:15 +0200 Subject: Reading in external file - error checking and line numbers... References: <1126083162.994845.20850@z14g2000cwz.googlegroups.com> Message-ID: Hugh Macdonald wrote: > I'm writing a tool at the moment that reads in an external file (which > can use any Python syntax) > > At the moment, I'm reading the file in using: > > scriptLines = open(baseRippleScript).read() > exec scriptLines > > However, if I raise an exception in my main code, in a function that is > called from the external script, the stack trace just has: > > File "", line 8, in ? > > Ideally, I'd want to be able to avoid throwing exceptions and would > like to, from my main code, print out an error that included the script > name (easily accessible) and the line number (less easily accessible). exec compile(scriptLines, baseRippleScript, "exec") (but in this case, you might as well use the "execfile" built-in) From http Tue Sep 27 20:55:53 2005 From: http (Paul Rubin) Date: 27 Sep 2005 17:55:53 -0700 Subject: Overhead of individual python apps References: <1127859117.870343.96740@g44g2000cwa.googlegroups.com> <4339DF2F.6010701@websafe.com> Message-ID: <7xu0g6ovs6.fsf@ruckus.brouhaha.com> Larry Bates writes: > Several apps using 4Mb each shouldn't be very much memory (maybe > 20Mb at most). You didn't say how much memory was in your machine, > but 256Mb of memory will cost you no more than $50. Not really > worth a lot of effort. That is bogus reasoning. I can't add 256mb to the machine I'm typing on right now for any amount of money, let alone $50. It's an older laptop, it's maxed out at 512 meg, and I can't add any more to it, period. An even older laptop that I still use from time to time is maxed out at 72 meg. And my Sharp Zaurus (Linux handheld) has 32 meg and is not expandable. If Python claims to be a lightweight language, it should not present any obstacles to running on machines of that class. It's already slightly annoying that Python can't run well in an 8 meg Palm Pilot, since there were many Common Lisp implementations that ran tolerably in less memory than that. From johnnyandfiona at hotmail.com Thu Sep 15 22:40:39 2005 From: johnnyandfiona at hotmail.com (Johnny Lee) Date: 15 Sep 2005 19:40:39 -0700 Subject: No newline using printf In-Reply-To: References: <1126831050.903747.13040@z14g2000cwz.googlegroups.com> Message-ID: <1126838439.109477.4790@g14g2000cwa.googlegroups.com> Roy Smith wrote: > > For closer control over output, use the write() function. You want > something like: > > import sys > for i in range(3): > sys.stdout.write (str(i)) here is the output of my machine: >>> import sys >>> for i in range(3): ... sys.stdout.write(str(i)) ... 012>>> Why the prompt followed after the output? Maybe it's not as expected. From peter at commonlawgov.org Sun Sep 25 16:28:04 2005 From: peter at commonlawgov.org (Peter) Date: Sun, 25 Sep 2005 13:28:04 -0700 Subject: Struggling with basics In-Reply-To: References: Message-ID: <43370854.5090505@commonlawgov.org> Jason wrote: >A week ago I posted a simple little hi-score routine that I was using to >learn Python. > >I've only just managed to examine the code, and the responses that >people gave, and I'm now seriously struggling to understand why things >aren't working correctly. > >At present my code is as follows... > >import random >import bisect > >class HiScores: > def __init__(self,hiScores): > self.hiScores=[entry for entry in hiScores] > > def showScores(self): > for score,name in self.hiScores: > score=str(score).zfill(5) > print "%s - %s" % name,score > > > def addScore(self,score,name): > score.zfill(5) > bisect.insort(self.hiScores,(score,name)) > if len(self.hiScores)==6: > self.hiScores.pop() > > def lastScore(self): > return self.hiScores[-1][0] > >def main(): > >hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] > > a=HiScores(hiScores) > print "Original Scores\n---------------" > a.showScores() > > while 1: > newScore=str(random.randint(0,10000)) > if newScore > a.lastScore(): > print "Congratulations, you scored %s " % newScore > name=raw_input("Please enter your name :") > a.addScore(newScore,name) > a.showScores() > >if __name__=="__main__": > main() > > >My first problem (lack of understanding of course) is that if I run the >above, I get an error saying: > > print "%s - %s" % name,score >TypeError: not enough arguments for format string > > >Now I understand what it's saying, but I don't understand why. > >If I change the code to read: > >print "%s - %n" % name, score (thinking of course that ah-ha, score is >numeric) then I get the same error. > >The only way for the program to run is to simply have > >print name,score (or print score,name) > > This is because 'print' is accepting 'score' as a seperate argument, not the formatting, as you want it to. Try 'print "%s - %s" % (name, score)' > >The final part that's simply not working correctly is that the entire >program isn't sorting the data. > >If I run the program and get a score of, say, 6789, then when I add my >name, nothing is entered. I have changed the clause that deletes (pops) >the last array if the array count is 6 and seen what figures are being >entered into the array. > >Sure enough they are going in the array, and they are being sorted, but >they are only being sorted AFTER the 00000 of the initial array creation. > >I'm pretty sure it's to do with comparing a string against an integer >but can't for the life of me see where to force the comparrison to check >against two integers. > > > Humm. This is a harder problem. I will copy this text into JEdit to highlight the text and see if i cannot find the problem. >Apologies for going over old ground and if I'm not understanding, I'm >getting there honest ;) > > > HTH, Peter From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue Sep 6 20:58:58 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 06 Sep 2005 20:58:58 -0400 Subject: Proposal: add sys to __builtins__ References: Message-ID: In article , Rick Wotnaz wrote: > You're right that there is no necessity for such a change. I was > not actually talking about importing *any* module in every case, > but rather about importing, say, 'sys' when, for example, sys.argv > appeared in the code and no import had been specified. I think I must have missed that post; I will go back and look at it. However, while I'm here, how would your proposal deal with code like this: import foobar # ... some while later ... def f( ... ): ... global foobar, sys sys = foobar ... # ... some while even later ... f( ... ) sys.wallaby("Fear and loathing!") In particular, we have no import of sys, but the name "sys" is meaningful as a local alias for a different module. I'm not saying you couldn't deal with this, but it rules out some of the more obvious ways of detecting and automatically handling this kind of substitution. Naturally, you might well ask, "why would you do such a fool thing?" To this I can only respond: "Never underestimate the ingenuity of fools." -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From bathing at gmail.com Fri Sep 16 08:19:50 2005 From: bathing at gmail.com (A. L.) Date: 16 Sep 2005 05:19:50 -0700 Subject: How to clear screen in Python interactive shell mode? In-Reply-To: References: <1126844313.379059.207200@z14g2000cwz.googlegroups.com> Message-ID: <1126873190.116295.260320@g44g2000cwa.googlegroups.com> I have tested it under windows python console, and it works. Thank you very much. From fuzzyman at gmail.com Wed Sep 14 04:18:28 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Sep 2005 01:18:28 -0700 Subject: CGIHTTPServer, popen3, and windoze In-Reply-To: <1126467156.398627.275750@f14g2000cwb.googlegroups.com> References: <1126467156.398627.275750@f14g2000cwb.googlegroups.com> Message-ID: <1126685908.318114.194910@f14g2000cwb.googlegroups.com> Fuzzyman wrote: > Hello all, > > I may well post this a a bug on Monday (after testing with Python 2.3) > - but I thought I'd post here to see if anyone has any ideas. > Hmm... testing on Python 2.3 I *don't* have the same problem - but it's very frustrating under Python 2.4 (different machine). I wonder what else is different ? Fuzzyman http://www.voidspace.org.uk/python > The basic problem is that under Python 2.4 (and windoze XP SP2) > CGIHTTPServer isn't passing the CGI environment variables to scripts it > runs. > > I've checked that the environment variables all exist in os.environ > before the subprocess is launched using popen3. > > I've *also* checked that when I launch a test subprocess using popen3 > myself, environment variables *are* passed on - so I'm a bit > confused... > > I wonder if anyone can shed any light on this behavior ? > > All the best, > > > Fuzzyman > http://www.voidspace.org.uk/python > > P.S. I've also patched CGIHTTPServer so that it can handle paths wih > spaces and CGIs in subdirectories of the 'cgi-bin' folder. I'll > *suggest* these changes to the maintainers - but my tests were on the > original version. From peter at engcorp.com Tue Sep 6 15:21:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Sep 2005 15:21:12 -0400 Subject: which reg values modified my python installer under windows In-Reply-To: References: <1126024996.916146.200370@o13g2000cwo.googlegroups.com> Message-ID: Philippe C. Martin wrote: > I forgot to mention that I want to do it automatically from my application's > installer. Calling the "assoc" and "ftype" commands is one approach. Try them with the existing settings to see how standard Python sets them up: c:\> assoc .py .py=Python.File c:\> ftype Python.File ... Use "assoc /?" or "ftype /?" for help. -Peter From kay.schluehr at gmx.net Fri Sep 9 02:37:16 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Sep 2005 23:37:16 -0700 Subject: Question about consistency in python language In-Reply-To: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> Message-ID: <1126247836.678936.233170@o13g2000cwo.googlegroups.com> lechequier at gmail.com wrote: > Let's say I define a list of pairs as follows: > >>l = [('d', 3), ('a', 2), ('b', 1)] > > Can anyone explain why this does not work? > >>h = {}.update(l) > > and instead I have to go: > >>h = {} > >>h.update(l) > to initialize a dictionary with the given list of pairs? > > when an analagous operation on strings works fine: > >>s = "".join(["d","o","g"]) > > Seems inconsistent. If you define >>> sep = "" >>> sep.join(["d","o","g"]) "dog" >>> sep '' sep is preserved and a new "dog" string is generated. Since sep is immutable there is no way to manipulate it inplace. On the other hand there exists no sorted() method for tuples or lists like join() for strings but it is implemented as a function in Python24 that returns a new sorted container. I consider this as an inconsistency across builtin types. Consistent would be following usage pattern: >>> l = [1,3,2] >>> l.sorted() [1,2,3] # new sorted list >>> l.sort() # sort list inplace >>> l.appended(4) # new extended list [1,2,3,4] >>> l.append(4) # appends an element to the same list >>> l [1,2,3,4] Preserving the naming convention we would have >>> "".joined(["d","o","g"]) "dog" Kay From tismer at stackless.com Wed Sep 28 21:05:44 2005 From: tismer at stackless.com (Christian Tismer) Date: Thu, 29 Sep 2005 03:05:44 +0200 Subject: Alternatives to Stackless Python? In-Reply-To: References: <1127231444.643628.197920@g49g2000cwa.googlegroups.com> <1127438841.532386.73410@g44g2000cwa.googlegroups.com> Message-ID: <433B3DE8.40905@stackless.com> Peter Hansen wrote: > simonwittber at gmail.com wrote: > >>>I found LGT http://lgt.berlios.de/ but it didn't seem as if the >>>NanoThreads module had the same capabilites as stackless. >> >>What specific capabilities of Stackless are you looking for, that are >>missing from NanoThreads? > > > While I can't speak for the OP, isn't it the case that the threadlets in > Stackless (sorry, don't know what they are really called) are true > threads in the sense of being able to switch contexts no matter how far > down in a set of nested calls they might be? And that NanoThreads are > simply generators, which means you can switch contexts only at the top > level, with a yield statement? > > I don't know what the OP wants, but I could imagine that would be a > pretty fundamental difference (if I'm right about Stackless). You are. -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From no at spam Fri Sep 16 10:38:28 2005 From: no at spam (D H) Date: Fri, 16 Sep 2005 09:38:28 -0500 Subject: Rendering HTML In-Reply-To: <1126863962.886966.158460@o13g2000cwo.googlegroups.com> References: <1126863962.886966.158460@o13g2000cwo.googlegroups.com> Message-ID: Harlin Seritt wrote: > I am looking for a module that will render html to console but > formatted much like one might see with Lynx. Is there such a module > already out there for this? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52297 From peter at engcorp.com Thu Sep 8 09:19:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Sep 2005 09:19:39 -0400 Subject: Video display, frame rate 640x480 @ 30fps achievable? In-Reply-To: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> References: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> Message-ID: Guenter wrote: > I need to develop an application that displays video 640x480 16-bit per > pixel with 30 fps. > > I would prefer to do that with Python (wxPython) but don't have any > experience whether it is possible to achieve that frame rate and still > have some resources for other processing left? My development PC would > be a Celeron 1 GHz. The final system could be a faster system. At the very least, you should be looking at Pygame instead, as wxPython is not really intended for that kind of thing. Whether or not you can manage the desired frame rate depends entirely on what you will be displaying... a single pixel moving around, full-screen video, or something in between? ;-) See for example http://mail.python.org/pipermail/python-list/2002-May/106546.html for one first-hand report on frame rates possible with Pygame (whether it's accurate or not I don't know). -Peter From nil at dev.nul Fri Sep 9 00:43:13 2005 From: nil at dev.nul (Christian Stapfer) Date: Fri, 9 Sep 2005 06:43:13 +0200 Subject: Help! Python either hangs or core dumps when calling C malloc References: <1126198290.288644.247510@o13g2000cwo.googlegroups.com> <1126199525.752904.254930@z14g2000cwz.googlegroups.com> <1126203439.152057.78210@o13g2000cwo.googlegroups.com> Message-ID: "Lil" wrote in message news:1126203439.152057.78210 at o13g2000cwo.googlegroups.com... >I already double checked my C code. It runs perfectly fine in C without > any errors. So in my python program, I added a pdb.set_trace() > and step through the program and it did not dump. But when i took out > the tracing, the core dump came back. "sigh" Check your program for _uninitialized_variables_. (Just a guess: but what other side-effect than changing the values of uninitialized variables - and the program's timing, of course - might the stepping through with a debugger have?) Regards, Christian From grante at visi.com Mon Sep 5 23:08:30 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 06 Sep 2005 03:08:30 -0000 Subject: Python compiled? References: Message-ID: <11hq21eb0uerpfa@corp.supernews.com> On 2005-09-05, Fredrik Lundh wrote: > distributing DLLs have been a solved problem for at least > 15-20 years... There are days when some poeple might disagree with that. ;) -- Grant Edwards grante Yow! LOOK!!! I'm WALKING at in my SLEEP again!! visi.com From rkern at ucsd.edu Sun Sep 4 17:55:13 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 04 Sep 2005 14:55:13 -0700 Subject: How to integrate an array? In-Reply-To: References: Message-ID: Tom Kaz wrote: [I wrote:] (please attribute quotes) >>Do each function separately. The routine that scipy.integrate.quad uses >>adapts to the local conditions of the function (when the function is >>flat, it uses fewer samples; when steep, more). > > It's not so easy to do it separately. I want to integrate function that > includes linalg.expm - as you see calculation the function is quite > expensive. I understand, but the good integration algorithms really do need to evaluate each dimension separately. If you can bear algorithms that only use samples from fixed intervals, then you can use the functions romb(), simps(), or trapz() in scipy.integrate. BTW, a better place to ask scipy questions would be the scipy mailing list. http://scipy.net/mailman/listinfo/scipy-user -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fredrik at pythonware.com Mon Sep 19 04:31:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Sep 2005 10:31:48 +0200 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > On Slashdot there is a discussion about the future C#3.0: > http://developers.slashdot.org/developers/05/09/18/0545217.shtml?tid=109&tid=8 > > http://msdn.microsoft.com/vcsharp/future/ "The extensions enable construction of compositional APIs that have equal expressive power of query languages in domains such as relational databases and XML." > There are many differences, but it looks a bit more like Python: > http://download.microsoft.com/download/9/5/0/9503e33e-fde6-4aed-b5d0-ffe749822f1b/csharp%203.0%20specification.doc meanwhile, over in python-dev land: "Is anyone truly attached to nested tuple function parameters; 'def fxn((a,b)): print a,b'? /.../ Would anyone really throw a huge fit if they went away? I am willing to write a PEP for their removal in 2.6 with a deprecation in 2.5 if people are up for it." From simonwittber at gmail.com Mon Sep 5 01:40:46 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 4 Sep 2005 22:40:46 -0700 Subject: Magic Optimisation References: Message-ID: <1125898846.475495.65730@g14g2000cwa.googlegroups.com> Psyco actually slowed down the code dramatically. I've fixed up the code (replaced the erroneous return statement) and uploaded the code for people to examine: The test code is here: http://metaplay.dyndns.org:82/~xerian/fibres.txt These are the run times (in seconds) of the test file. without psyco: 0.00294482 0.03261255 0.06714886 0.87395510 with psyco.full(): 0.00446651 0.05012258 0.15308657 11.23493663 From stephen.thorne at gmail.com Wed Sep 14 23:09:07 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 15 Sep 2005 13:09:07 +1000 Subject: "optimizing out" getattr In-Reply-To: <1126752404.059093.216270@g43g2000cwa.googlegroups.com> References: <1126752404.059093.216270@g43g2000cwa.googlegroups.com> Message-ID: <3e8ca5c805091420094f5e1926@mail.gmail.com> On 14 Sep 2005 19:46:44 -0700, Daishi Harada wrote: > Hi, > > I'd like to get the 'get2' function below to > perform like the 'get1' function (I've included > timeit.py results). Do you have profiling results that show that a significant percentage of your programs time is being spent inside this function? If you don't, then you're wasting your time doing unnecessery optimisation. -- Stephen Thorne Development Engineer From severa at sophia.dtp.fmph.uniba.sk Mon Sep 19 05:05:04 2005 From: severa at sophia.dtp.fmph.uniba.sk (severa at sophia.dtp.fmph.uniba.sk) Date: Mon, 19 Sep 2005 11:05:04 +0200 (CEST) Subject: How to write this iterator? Message-ID: Given a list of iterators, I'd like to have a new one that would cyclically walk over the list calling the next() method of the iterators (removing any iterator which is exhausted). It should also support adding a new iterator to the list; it should be added in front of the current position (so that it's called only after all the others). This is what I was able to write with my zero python skills (self.iters is the list of iterators, self.i is the index of the iterator that should be used next). Is there a nicer/more pythonic solution, maybe using generators? class Liter(object): def __init__(self, *iters): self.i=0 self.iters=[iter(x) for x in iters] def append(self,what): self.iters.insert(self.i,what) def __iter__(self): return self def next(self): while True: try: result=self.iters[self.i].next() except StopIteration: del self.iters[self.i] except IndexError: if len(self.iters) is 0: raise StopIteration else: self.i=0 else: self.i+=1 return result From alessandro.bottoni at infinito.it Thu Sep 29 03:43:22 2005 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Thu, 29 Sep 2005 07:43:22 GMT Subject: c/c++ and python References: <1127978190.737988.89990@g47g2000cwa.googlegroups.com> Message-ID: Mattia Adami wrote: > Hi to all! > I have a little problem. I want to develop an application in c/c++ that > creates a window with gtk+ accordinly to the information on a xml file. > The funcions that are called for manage the event should be written in > python. I don't know how to do it, can you help me? Is it possible? > Thanks a lot! Yes, it is possible. Most likely, you will have to embed a Python interpreter in your app. Have a look at the Extending&Embedding section of the Python manual. As an alternative, you can use your C++ code as an extension of Python (a module). Again, have a look at the Extending&Embedding section of the Python manual. BTW: are you aware of the existence of PyGTK and wxPython? HTH ----------------------------------- Alessandro Bottoni From nick at craig-wood.com Tue Sep 13 02:00:09 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Sep 2005 06:00:09 GMT Subject: Premature wakeup of time.sleep() References: Message-ID: Erich Schreiber wrote: > In the Python Library Reference the explanation of the time.sleep() > function reads amongst others: > > > The actual suspension time may be less than that requested because > > any caught signal will terminate the sleep() following execution > > of that signal's catching routine. Also, the suspension time may > > be longer than requested by an arbitrary amount because of the > > scheduling of other activity in the system. > > I don't understand the first part of this passage with the premature > wakeup. What signals would that be? If someone sent your process a signal. Say you pressed CTRL-C - that generates the INT signal which python translates to the KeyboardInterrupt exception - and which does interrupt the sleep() system call. This probably isn't happening to you though. > In the logs I see a about 1% of the wake-up delays beeing negative > from -1ms to about -20ms somewhat correlated with the duration of the > sleep. 20 minute sleeps tend to wake-up earlier then sub-second > sleeps. Can somebody explain this to me? Sleep under linux has a granularity of the timer interrupt rate (known as HZ or jiffies in linux-speak). Typically this is 100 Hz, which is a granularity of 10ms. So I'd expect your sleeps to be no more accurate than +/- 10ms. +/- 20ms doesn't seem unreasonable either. (Linux 2.4 was fond of 100Hz. Its more configurable in 2.6 so could be 1000 Hz. Its likely to be 100 Hz or less in a virtual private server.) I'm not sure the best way of finding out your HZ, here is one (enter it all on one line) start=`grep timer /proc/interrupts | awk '{print $2}'`; sleep 1; end=`grep timer /proc/interrupts | awk '{print $2}'`; echo $(($end-$start)) Which prints a number about 1000 on my 2.6 machine. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fredrik at pythonware.com Mon Sep 5 17:03:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Sep 2005 23:03:35 +0200 Subject: Python compiled? References: Message-ID: "billiejoex" wrote: > I know the great advanteges deriving by using interpretation too, I appreciate it very much (I'm newbie in Python and the > interpeter really helps me out in many situations), but a 'pure' interpretated language needs obligatorily an interpreter and > (sorry for repeating) this could be a problem for distribution (imho). Python is a compiled language; the Python source code you write is compiled to byte codes, which are executed by a virtual machine. on windows, that virtual machine consists of a DLL. distributing DLLs have been a solved problem for at least 15-20 years... From jegenye2001 at gmail.com Mon Sep 12 12:17:17 2005 From: jegenye2001 at gmail.com (jegenye2001) Date: 12 Sep 2005 09:17:17 -0700 Subject: Ctypes Install in Linux References: <1126541371.379893.295950@g43g2000cwa.googlegroups.com> Message-ID: <1126541837.832917.172740@g14g2000cwa.googlegroups.com> Most likely you're trying to do this as a non-root user and /usr/local/lib/python2.4/site-packages must be writable only with root privileges. If you cannot go root on that machine then you could just install the package in some directory you can write to and add the directory name to your PYTHONPATH environment variable. Cheers, Miklos -- Software development: Python,Zope,Plone,PDF,XML,MivaScript http://www.jegenye.com From steve.horsley at gmail.com Thu Sep 15 17:02:58 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Thu, 15 Sep 2005 22:02:58 +0100 Subject: MySQLdb UPDATE does nothing In-Reply-To: References: <4329633F.7060609@jmsd.co.uk> Message-ID: Rowdy wrote: >> A similar question was asked back in July, someone posted this: > > > If it's any help, using > > cursor.execute("set autocommit = 1") > > before doing anything else works nicely unless you actually need > transactions. > Or, as I found out yesterday, cursor.execute('commit') afterwards. Steve From paul at subsignal.org Mon Sep 5 04:00:53 2005 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Mon, 05 Sep 2005 10:00:53 +0200 Subject: Python Digest authentication against MS MapPoint In-Reply-To: <1125905255.678514.298590@g14g2000cwa.googlegroups.com> References: <1125905255.678514.298590@g14g2000cwa.googlegroups.com> Message-ID: trapeze.jsg at gmail.com wrote: [problem with digest auth] sorry for giving such a generic advice, but I'd capture the headers of the C# app and compare with the urllib version line by line. Try to reproduce the exact header with python (except the response and cnonce of course). Maybe IIS has its own "version" of rfc2617. hth Paul From rkern at ucsd.edu Sat Sep 10 17:32:19 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 10 Sep 2005 14:32:19 -0700 Subject: calling command line programs? In-Reply-To: References: Message-ID: Yevgeniy (Eugene) Medynskiy wrote: > Hi all, > > This is probably a very newbie question, but after searching google and > docs @ python.org I can't find an answer, so maybe someone would be able > to help? http://docs.python.org/lib/module-subprocess.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From EP at zomething.com Fri Sep 2 01:31:45 2005 From: EP at zomething.com (EP) Date: Thu, 1 Sep 2005 21:31:45 -0800 Subject: Python doc problems example: gzip module In-Reply-To: <1125477977.072146.298670@g47g2000cwa.googlegroups.com> References: <1125477977.072146.298670@g47g2000cwa.googlegroups.com> Message-ID: <20050901213145.1868588739.EP@zomething.com> "Xah Lee" wrote: > today i need to decompress > since i'm familiar with what the fuck > Fuck the > I just need to decompress that fucking doc whatever fuck Is it just me or, do you suppose, with so much unnecessary "f" word, this is not a post at all, but a cleverly encoded message to fellow unsavory characters. The "f"'s are just enough to thwart (ahem,lesser!) intellects from critically analyzing the text. And as far as I can tell, there was no real content in the post. Could the position of the f words be the key to the encrypted message? I need to enlist the help of smarter minds to decode the message - I have zero experience in this, but I am sure there are minds bright enough on this list to crack the XL posts. Here's all I could get going, trying to see if there was something in the name itself (but clearly the below is kindergarten level, at best) >>> eName="xahlee" >>> def fName(name="", offset=0, p=1): newName="".join([chr(ord(c)+ offset -(26*((ord(c)+offset)>122))) for c in name]) if p==1: print newName return newName >>> for i in range(0,26): nn=fName(name,i) xahlee ybimff zcjngg adkohh belpii cfmqjj dgnrkk ehosll fiptmm gjqunn hkrvoo ilswpp jmtxqq knuyrr lovzss mpwatt nqxbuu orycvv pszdww qtaexx rubfyy svcgzz twdhaa uxeibb vyfjcc wzgkdd Certainly this one caught my eye ("rubfyy") - Ruby with the f-you acronym inside it! Sorry, folks, its been a long week and I need to decompress. EP From steve at REMOVETHIScyber.com.au Fri Sep 23 08:34:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 23 Sep 2005 22:34:35 +1000 Subject: Sniffing Text Files References: Message-ID: On Fri, 23 Sep 2005 01:20:49 -0300, David Pratt wrote: > Hi. I have files that I will be importing in at least four different > plain text formats, one of them being tab delimited format, a couple > being token based uses pipes (but not delimited with pipes), another > being xml. There will likely be others as well but the data needs to be > extracted and rewritten to a single format. The files can be fairly > large (several MB) so I do not want to read the whole file into memory. Why ever not? On modern machines, "several MB" counts as small files. Let your operating system worry about memory, at least until you get to really big (several hundred megabytes) files. > What approach would be recommended for sniffing the files for the > different text formats. In no particular order: (1) Push the problem onto the user: they specify what sort of file they think it is. If they tell your program the file is XML when it is in fact a CSV file, your XML importer will report back that that the input file is a broken XML file. (2) Look at the file extension (.xml, .csv, .txt, etc) and assume that it is correct. If the user gives you an XML file called "data.csv", you can hardly be blamed for treating it wrong. This behaviour is more accepted under Windows than Linux or Macintosh. (3) Use the Linux command "file" to determine the contents of the file. There may be equivalents on other OSes. (4) Write your own simple scanner that tries to determine if the file is xml, csv, tab-delimited text, etc. A basic example: (Will need error checking and hardening) def sniff(filename): """Return one of "xml", "csv", "txt" or "tkn", or "???" if it can't decide the file type. """ fp = open(filename, "r") scores = {"xml": 0, "csv": 0, "txt": 0, "tkn": 0} for line in fp.readlines(): if not line: continue if line[0] == "<": scores["xml"] += 1 if '\t' in line: scores["txt"] += 1 if ',' in line: scores["csv"] += 1 if SOMETOKEN in line: scores["csv"] += 1 # Pick the best guess: L = [(score, name) for (name, score) in scores.items()] L.sort() L.reverse() # L is now sorted from highest down to lowest by score. best_guess = L[0] second_best_guess = L[0] if best_guess[0] > 10*second_best_guess[0]: fp.close() return best_guess[1] fp.close() return "???" Note that the above code really isn't good enough for production work, but it should give you an idea how to proceed. Hope that helps. -- Steven. From mwm at mired.org Thu Sep 15 20:23:59 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 15 Sep 2005 20:23:59 -0400 Subject: brain cramp: emulating cgi.FieldStorage References: <1126793506.904795.222000@g49g2000cwa.googlegroups.com> Message-ID: <86k6hhj1wg.fsf@bhuda.mired.org> "Chris Curvey" writes: > I can't be the first person to want to do this, but I also can't seem > to find a solution. (Perhaps my Google skills are poor today.) How > can I emulate cgi.FieldStorage() for my unit tests so that I don't have > to put a web server in the way? > > what I'd like to do is something like > > fs = cgi.FieldStorage() > fs["foo"] = "bar" > functionToBeTested(fs) > > Any hints/leads/suggestions? QUERY_STRING="var1=val1&var2=val2&var3=val3" REQUEST_METHOD="GET" python mycgiprogram.py Similar hacks work for POST if you want to store a test query in a file. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From josef.cihal at irm.at Mon Sep 5 07:26:32 2005 From: josef.cihal at irm.at (Josef Cihal) Date: Mon, 5 Sep 2005 13:26:32 +0200 Subject: Problem with: urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Message-ID: Hi, I get an error, when I am trying to download URL with using Cookies. Where is the Problem? Thank u very much for all ideas!!! sincerely Josef import os, cookielib, urllib2 cj = cookielib.MozillaCookieJar() os.environ["http_proxy"] = "http://proxy.irm.at:1234" os.environ['HOME']= r"C:\tmp\COOKIE" # cj.load(os.path.join(os.environ["HOME"], "cookies.txt")) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://brokerjet.ecetra.com/at/news/?/") Traceback (most recent call last): File "", line 1, in ? File "C:\Programme\Python24\lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Programme\Python24\lib\urllib2.py", line 376, in _open '_open', req) File "C:\Programme\Python24\lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Programme\Python24\lib\urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Programme\Python24\lib\urllib2.py", line 996, in do_open raise URLError(err) urllib2.URLError: From pydecker at gmail.com Tue Sep 13 11:34:42 2005 From: pydecker at gmail.com (Peter Decker) Date: Tue, 13 Sep 2005 11:34:42 -0400 Subject: PyGTK or wXPython? In-Reply-To: References: Message-ID: On 9/13/05, Rod W wrote: > I'm just starting out on Python but my primary goal is to provide > applications with some user interface (GUI). > > Can someone point me to a good comparison of whether I should use > wxPython (with wxGlade I assume) or PyGTK (with Glade I assume)? > > I'd prefer open source (not necessarily GPL though) tools. I looked at both, and preferred wxPython's look. I hated its C-like feeling, with some very un-Pythonic code that failed to hide its C roots very well, but I used it because the results were so good. Since then I've discovered Dabo, which is a complete application framework, and which wraps wxPython for its UI. Apparently, the authors of Dabo also didn't like the style of wxPython code, and have created their own classes that expose a cleaner, much more Pythonic API. I've been using Dabo for some small GUI apps, and I still can't believe how much easier it is to create the UI with Dabo than with plain wxPython. You should definitely check it out if you decide to go the wxPython route. -- # p.d. From fredrik at pythonware.com Wed Sep 7 03:56:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 7 Sep 2005 09:56:39 +0200 Subject: dict and __cmp__() question References: <1126078954.485637.172070@g47g2000cwa.googlegroups.com> Message-ID: "Alex" wrote: > But what are those with double underscore? For instance __cmp__(...)? > > I tried >>>> D.cmp('a','b') make that cmp('a', 'b') methods that start and end with "__" are implementation hooks: http://docs.python.org/ref/specialnames.html __cmp__ is used by cmp(a, b) and other operations that need to compare things (unless "rich comparision" hooks are defined; see http://docs.python.org/ref/customization.html ) other common hooks are __init__ (called after construction), __len__ (called to determine the length of a sequence), __getitem__ (called to fetch an item from a container), and a few others. see the documentation for details. From mwm at mired.org Tue Sep 27 20:34:45 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 27 Sep 2005 20:34:45 -0400 Subject: Human readable number formatting References: <1127862406.11827.2.camel@localhost.localdomain> Message-ID: <863bnqqbbu.fsf@bhuda.mired.org> Alex Willmer writes: > When reporting file sizes to the user, it's nice to print '16.1 MB', > rather than '16123270 B'. This is the behaviour the command 'df -h' > implements. There's no python function that I could find to perform this > formatting , so I've taken a stab at it: > > import math > def human_readable(n, suffix='B', places=2): > '''Return a human friendly approximation of n, using SI prefixes''' > prefixes = ['','k','M','G','T'] > base, step, limit = 10, 3, 100 > > if n == 0: > magnitude = 0 #cannot take log(0) > else: > magnitude = math.log(n, base) > > order = int(round(magnitude)) // step > return '%.1f %s%s' % (float(n)/base**(order*step), \ > prefixes[order], suffix) > > Example usage >>>> print [human_readable(x) for x in [0, 1, 23.5, 100, 1000/3, 500, > 1000000, 12.345e9]] > ['0.0 B', '1.0 B', '23.5 B', '100.0 B', '0.3 kB', '0.5 kB', '1.0 MB', > '12.3 GB'] > > I'd hoped to generalise this to base 2 (eg human_readable(1024, base=2) > == '1 KiB' and enforcing of 3 digits at most (ie human_readable(100) == > '0.1 KB' instead of '100 B). However I can't get the right results > adapting the above code. > > Here's where I'd like to ask for your help. > Am I chasing the right target, in basing my function on log()? I wouldn't have done it that way, but that's not worth very much. Can you use the log() variation to change form proper scientific units to the CS powers-of-two variation? if not, I would do it this way: def human_readable(n, suffix = 'B', places = 2): prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E'] top = 10 ** places index = 0 n = float(n) while abs(n) > top: n /= 10 index += 1 return '%.1f %s%s' % (n, prefixes[index], suffix) > Does this function already exist in some python module? humanize_number is a cross-platform C library function, about 150 lines of code. It uses the loop I gave above. It might be worthwhile to swipe the code (it's BSD-licensed), wrap it, and submit a PR to add it to the standard library - just so you get properly tested code. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mtammerman at gmail.com Tue Sep 6 09:12:25 2005 From: mtammerman at gmail.com (Mike Tammerman) Date: 6 Sep 2005 06:12:25 -0700 Subject: execute commands independantly Message-ID: <1126012345.854708.314210@g14g2000cwa.googlegroups.com> Hi, I am trying to execute an executable or a pyton script inside my program. I looked at the subprocess and os module. But all the functions in these modules blocks my application. What I want to do is run the subprocess without any concern. I don't care of its return type or child signals. Just start and let it run independantly. Thanks, Mike From rasmussen.bryan at gmail.com Thu Sep 22 05:38:25 2005 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Thu, 22 Sep 2005 11:38:25 +0200 Subject: python image library TIFF Message-ID: <3bb44c6e050922023867f3550c@mail.gmail.com> Hi does anyone have any experience using the Python Image library to determine if a Tiff is in the G4 or G3 codec? From timr at probo.com Fri Sep 2 03:14:01 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 02 Sep 2005 00:14:01 -0700 Subject: reg email packages work References: Message-ID: praba kar wrote: > > I am working in web based email system project. >Here I try to build email message >from scratch. I used below code to build email >message > > msg = email.MIMEBase('text','html') > msg['Return-Path'] = user+'@'+domain > msg['Date'] = formatdate(localtime=1) > msg['Subject'] = subject > msg['From'] = from_name > msg['To'] = to > msg['Cc'] = cc > msg.set_payload("Body of the email messagge") > fh = os.popen('/bin/sendmail %s'% (eachid),'w') > fh.write(msg.as_string()) > fh.close() > >This code will build plain email message properly. No, it doesn't. It builds an HTML message (see the very first line). If you supply plain text to this as the body of the message, all the lines will be concatenated together, which sounds a lot like what you are seeing. If you are not feeding HTML as the body, change the fist line to ('text','plain'). -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tim.peters at gmail.com Sat Sep 10 23:12:53 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 10 Sep 2005 23:12:53 -0400 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> Message-ID: <1f7befae05091020122bbc0da9@mail.gmail.com> [Bryan Olson, on the problem at http://spoj.sphere.pl/problems/SUPPER/ ] > I never intended to submit this program for competition. The > contest ranks in speed order, and there is no way Python can > compete with truly-compiled languages on such low-level code. > I'd bet money that the algorithm I used (coded in C) can run > with the winners. I also think I'd wager that the Python version > outright trumps them on code size. Oh, it's not that bad . I took a stab at a Python program for this, and it passed (3.44 seconds). It just barely made it onto the list of "best" solutions, which I also guess is ranked by elapsed runtime. The Java program right above it took 2.91 seconds, but ate more than 27x as much RAM ;-) I didn't make any effort to speed this, beyond picking a reasonable algorithm, so maybe someone else can slash the runtime (while I usually enjoy such silliness, I can't make time for it at present). I'll include the code below. Alas, without access to the input data they use, it's hard to guess what might be important in their data. On my home box, chewing over random 100,000-element permutations took less than a second each (including the time to generate them); I'm pretty sure they're using slower HW than mine (3.4 GHz P5). > My first version bombed for the zero-length sequence. That was a > mistake, sorry, but it may not be one of their test-cases. I > wonder how many of the accepted entries would perform properly. No idea here, and didn't even think about it. Notes: the `all` returned by crack() is a list such that all[i] is list of all (index, value) pairs such that the longest increasing subsequence ending with `value` is of length i+1; `value` is at index `index` in the input permutation. The maximal LISs thus end with the values in all[-1]. findall() iterates backwards over `all`, to accumulate all the values that appear in _some_ maximal LIS. There's clearly wasted work in findall() (if someone is looking for an algorithmic point to attack). Curiously, no use is made of that values are integers, outside of input and output; any values with a total ordering would work fine in crack() and findall(). """ # http://spoj.sphere.pl/problems/SUPPER/ def crack(xs): from bisect import bisect_right as find smallest = [] all = [] n = 0 for index, x in enumerate(xs): i = find(smallest, x) if i == n: smallest.append(x) all.append([(index, x)]) n += 1 else: all[i].append((index, x)) if x < smallest[i]: smallest[i] = x return all def findall(all): constraints = all[-1] allints = [pair[1] for pair in constraints] for i in xrange(len(all) - 2, -1, -1): survivors = [] for pair in all[i]: index, value = pair for index_limit, value_limit in constraints: if index < index_limit and value < value_limit: survivors.append(pair) allints.append(value) break constraints = survivors return sorted(allints) def main(): import sys while 1: n = sys.stdin.readline() if not n: break n = int(n) perm = map(int, sys.stdin.readline().split()) assert n == len(perm) supers = findall(crack(perm)) perm = None # just to free memory print len(supers) print " ".join(map(str, supers)) if __name__ == "__main__": main() """ From mwm at mired.org Tue Sep 20 22:07:31 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 20 Sep 2005 22:07:31 -0400 Subject: re.search experts needed on fqdn stripping.. References: <1127260618.929425.175440@g14g2000cwa.googlegroups.com> <1127261825.860781.201690@o13g2000cwo.googlegroups.com> Message-ID: <86wtlbmavw.fsf@bhuda.mired.org> "rh0dium" writes: > After thinking about it for a bit longer i simplified it but still have > the same problem.. > > e =[] > hosts = [ "poundcake.fpdn.com", "scorpion.fpdn.com", "loghost", > "scorpian", "localhost", "lan" ] > > ignore = [ "localhost", "loghost", "timehost", "mailhost" ] > > for host in hosts: > sn = re.split( "\.", host) This should be host.split("."). > if not sn[0] in ignore: > e.append(host) > ignore.append(sn[0]) > print e > > But this STILL gives me some problems.. > ['poundcake.nsc.com', 'scorpion.fqdn.com', 'scorpian', 'lan'] > > Nope - OK I am an idiot - try spelling idiot.. Can I take it that you saw that "scorpion" is not the same as "scorpian"? BTW, if you're using 2.4 and don't care about portability, I'd make ignore a set instead of a list. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gene.tani at gmail.com Wed Sep 14 12:57:00 2005 From: gene.tani at gmail.com (gene tani) Date: 14 Sep 2005 09:57:00 -0700 Subject: Python Search Engine app In-Reply-To: <1126708775.608076.106850@g43g2000cwa.googlegroups.com> References: <1126708775.608076.106850@g43g2000cwa.googlegroups.com> Message-ID: <1126717020.320168.218910@g43g2000cwa.googlegroups.com> Yes, there's a bunch. Google for "query parser" + python, "porter stemming" "stopwords" "text indexer". Maybe lucene has some python bindings, hmm? Harlin Seritt wrote: > Hi, > > Is anyone aware of an available open-source/free search engine app > (something similar to HTDig) written in Python that is out there? > Googling has turned up nothing. Thought maybe I'd mine some of you > guys' minds on this. > > thanks, > > Harlin Seritt > Internet Villa: www.seritt.org From rapp at acm.org Sun Sep 11 15:34:13 2005 From: rapp at acm.org (rapp at acm.org) Date: 11 Sep 2005 12:34:13 -0700 Subject: ANNOUNCE: SMC - State Machine Compiler v. 4.2.0 Message-ID: <1126467253.684991.244790@g43g2000cwa.googlegroups.com> SMC - The State Machine Compiler v. 4.2.0 Requires: Java 1.4.1 SE (Standard Edition) or better. Download: http://sourceforge.net/projects/smc Home Page: http://smc.sourceforge.net ================================================================= What's New? ================================================================= + Added C, Perl and Ruby language generation. + Added method valueOf(int stateId) to Java, C# and VB.Net to allow developers to hand-serialize and deserialize state machines. ================================================================= Bug fixes ================================================================= + (C#) Removed extraneous "bool loopbackFlag = false" line from Default state transitions. + (C#) Added "Trace.Listeners.Add(myWriter)" line when generating debug code. By not having this line it prevented debug output from being outuput. + Corrected parser abend when a transition was missing an endstate. ================================================================= What is SMC? ================================================================= SMC takes a state machine description (stored in a .sm file) and generates State pattern classes in a target language (C++, Java, Tcl, VB.Net, C# and Python are currently supported). SMC is a console-based app written in Java which means SMC can run anywhere Java (1.4.1 or better) can run. The download package includes an example directory showing how SMC can used with C++, Java, Tcl (requires [incr Tcl] package), VB.Net, C# and Python. The examples range from trivial to GUI apps. ================================================================= How can I learn more? ================================================================= At http://smc.sourceforge.net. You can access the SMC Programmer's Manual there as well. While you're there, check out the SMC demo applet at http://smc.sourceforge.net/SmcDemo.htm. ================================================================= Where can I get it? ================================================================= SMC and the Programmer's Manual can be downloaded from http://sourceforge.net/projects/smc. You can also use this website to: + Ask questions (via the Public Forum's Help discussion) + Submit a bug. + Join a mailing list. + Access SMC documentation. + Access SMC's source code in the CVS repository. (Note: in order to make full use of SourceForge capabilities, you must be a SourceForge member. If you are not a member, head over to http://sourceforge.net/account/register.php and sign up. SourceForge membership is free - no money, no requirements and NO SPAM! Membership has its benefits.) If you have any problems, surf over to http://sourceforge.net/forum/forum.php?forum_id=27865 and report the problem. I will try and answer you via the Help forum as quickly as I can. Enjoy! Charles Rapp From prasad.c.iyer at capgemini.com Fri Sep 30 09:27:04 2005 From: prasad.c.iyer at capgemini.com (Iyer, Prasad C) Date: Fri, 30 Sep 2005 18:57:04 +0530 Subject: Overloading __init__ & Function overloading Message-ID: I am new to python. I have few questions a. Is there something like function overloading in python? b. Can I overload __init__ method Thanks in advance regards prasad chandrasekaran --- Cancer cures smoking -----Original Message----- From: python-list-bounces+prasad.c.iyer=capgemini.com at python.org [mailto:python-list-bounces+prasad.c.iyer=capgemini.com at python.org] On Behalf Of python-list-request at python.org Sent: Friday, September 30, 2005 6:36 PM To: python-list at python.org Subject: Python-list Digest, Vol 24, Issue 455 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message. From g.franzkowiak at onlinehome.de Thu Sep 29 10:04:06 2005 From: g.franzkowiak at onlinehome.de (g.franzkowiak) Date: Thu, 29 Sep 2005 16:04:06 +0200 Subject: PyWin SendMessage Message-ID: Hello everybody, I've tryed to use an interprocess communication via SendMessage on Windows. Unfortunately, nothing goes on ######################################################################### #! /usr/bin/env python import win32api, win32ui, win32con import struct, array """ typedef struct tagCOPYDATASTRUCT { // cds DWORD dwData; DWORD cbData; PVOID lpData; } COPYDATASTRUCT; """ def packCopyData(nNum, sString): int_buffer = array.array("L",[nNum]) char_buffer = array.array('c', sString) int_buffer_address = int_buffer.buffer_info()[0] char_buffer_address = char_buffer.buffer_info()[0] char_buffer_size = char_buffer.buffer_info()[1] copy_struct = struct.pack("pLp", # dword*, dword, char* int_buffer_address, char_buffer_size, char_buffer) return copy_struct # get the window handle hwnd = win32ui.FindWindow(None, "special window") # print just for fun print hwnd cds = packCopyData(1, '1') print cds # try to send it a message win32api.SendMessage(hwnd, win32con.WM_COPYDATA, 0, cds) ######################################################################### The last parameter shut be an integer, but I think it must be a pointer ? Any experience or a tip for me ? gf From jbperez808 at yahoo.com Mon Sep 19 22:28:33 2005 From: jbperez808 at yahoo.com (jbperez808 at yahoo.com) Date: 19 Sep 2005 19:28:33 -0700 Subject: slicing functionality for strings / Python suitability for bioinformatics In-Reply-To: <3p8in6F98fduU1@individual.net> References: <1127157916.290111.112620@g47g2000cwa.googlegroups.com> <3p8in6F98fduU1@individual.net> Message-ID: <1127183312.980391.197930@z14g2000cwz.googlegroups.com> right, i forgot about that... From ed at leafe.com Sat Sep 17 15:27:35 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 17 Sep 2005 15:27:35 -0400 Subject: MySQLdb - create table problem In-Reply-To: References: <003801c5bb10$f505b530$6401a8c0@JSLAPTOP> <5084DCE4-5F08-4429-9A66-6806881B38AE@leafe.com> Message-ID: <9E4905A3-FDB2-47D0-99D7-89E28DCB84B1@leafe.com> On Sep 17, 2005, at 3:04 PM, Ed Hotchkiss wrote: > There is no oreilly in the code ... I still get an error, any other > ideas? sorry ... Strange; can you explain where the text quoted (reilly, Python, Archive, http:// python.oreilly.com/archive.html) came from, then? Also I noticed in another message on the list (this one drifted off-list, due to the poor choice of Reply-To: setting by the list admins; I'm moving it back) that you had another error: cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s) % tuple(links[0:3]) """) This should be: cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s)""", links[0:3] ) You don't even need to cast the args into a tuple when you use MySQLdb's parameter handling. It will automatically add quotes to any string values, and will automatically escape any problematic characters, such as single quotes, semi-colons, etc. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From cowie.rob at gmail.com Mon Sep 19 17:26:29 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 19 Sep 2005 14:26:29 -0700 Subject: Barcode Recognition Message-ID: <1127165189.682069.155760@g43g2000cwa.googlegroups.com> I'd like to be able to take a bitmapped image and identify and decode any barcodes present within it. Does anyone know of an existing module for accomplishing this task? Is there any effort to add this functionality to the Python Imaging Library? Can anyone give me an idea of how diffucult an undertaking this is for someone with no image processing experience? Cheers, Rob Cowie From jpopl at interia.pl Thu Sep 8 07:26:29 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Thu, 08 Sep 2005 13:26:29 +0200 Subject: killing thread after timeout In-Reply-To: References: Message-ID: Bryan Olson wrote: > First, a portable worker-process timeout: In the child process, > create a worker daemon thread, and let the main thread wait > until either the worker signals that it is done, or the timeout > duration expires. It works on QNX, thanks a lot, your reply was very helpful! > If we need to run on Windows (and Unix), we can have one main > process handle the socket connections, and pipe the data to and > from worker processes. See the popen2 module in the Python > Standard Library. popen will not work in thread on QNX/Windows, same problem with spawnl currently I am using: os.system(command+">file 2>file2") it works, I just need to finish implementing everything and check how it may fail... One more time - thanks for great idea! From fredrik at pythonware.com Thu Sep 29 01:15:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 07:15:31 +0200 Subject: byte code generated under linux ==> bad magic number under References: <9A45247F1AEBB94189B16E7083981F93016A4DF2@INDIAEXCH.gmi.domain> Message-ID: Shobha Rani wrote: (I think more people might read your posts if you skip the HTML stuff; if you insist on HTML, you could at least use a reasonable color) > How byte code is generated? For example when we run the java > program then the compiler generates the byte code? > How the byte code is generated for the source code(java)? the section "Compiled Python Files" in the tutorial explains this: http://docs.python.org/tut/node8.html byte code is portable between platforms, but it's not portable between different major Python releases (2.4.2 can run 2.4.1 bytecodes, but not 2.3 bytecodes, etc). From http Fri Sep 2 21:57:33 2005 From: http (Paul Rubin) Date: 02 Sep 2005 18:57:33 -0700 Subject: Find day of week from month and year References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> <7xzmqvnu2e.fsf@ruckus.brouhaha.com> <1125693964.021011.111040@f14g2000cwb.googlegroups.com> Message-ID: <7xek86oquq.fsf@ruckus.brouhaha.com> Peter Hansen writes: > (And, if I were "optimizing", I would of course dispense with the > dynamic creation of the static table upon every execution of > expiration(), and move it outside the function.) Replacing it with a tuple might be enough for that. From martin at v.loewis.de Fri Sep 30 18:19:17 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Oct 2005 00:19:17 +0200 Subject: What encoding is used when initializing sys.argv? In-Reply-To: References: Message-ID: <433db9e5$0$11622$9b622d9e@news.freenet.de> Petr Prikryl wrote: > I know about the rejected attempt to implement > sys.argvu. Still, how the sys.argv is filled? What > encoding is used when parsing the cmd line internally? > To what encoding is it converted when non ASCII > characters appear? Python does not perform any conversion whatsoever. It has a traditional main() function, with the char *argv[] argument. So if you think that the arguments are inherently Unicode on your system, your question should be "how does my operating system convert the arguments"? That, of course, depends on your operating system. "MS Windows environment" is not precise enough, since it also depends on the specific incarnation of that environment. On Windows 9x, I believe the command line arguments are "inherently" *not* in Unicode, but in a char array. On Windows NT+, they are Unicode, and Windows (or is it the MS VC runtime?) converts them to characters using the CP_ACP code page. Kind regards, Martin From varghjarta at gmail.com Wed Sep 14 07:36:27 2005 From: varghjarta at gmail.com (=?ISO-8859-1?Q?Varghj=E4rta?=) Date: Wed, 14 Sep 2005 13:36:27 +0200 Subject: some advice about Python GUI apps In-Reply-To: <1126697171.226696.234550@g44g2000cwa.googlegroups.com> References: <1126697171.226696.234550@g44g2000cwa.googlegroups.com> Message-ID: I'm not sure but wouldn't the simplest(perhaps) solution be to store a reference to all the dialogs you open up in a mapped array of some kind (dictionary) and whenever you are going to open up a dialog you check if it already exists a key matching whatever id you choose. If it exists then use the window refernce in there to make it go to front, else make a new, shove it in there with an id(key) of some kind and display it. Perhaps I misunderstood the question though. On 14 Sep 2005 04:26:11 -0700, mitsura at skynet.be wrote: > Hi, > > I am writing a program in Python and I am using wx.Python for the GUI. > I have no prior GUI and Python experience so that's why I turn to the > specialists for aid. > Basically, my app is a wx.tree object with items. You can click on each > item and set some properties of the item (Pydata). To set the > properties of an item you click on the item and then a 'Set item > properties' window pops up. > However, I am looking for a way that you can only open 1 property > window per item. If I click on an item the 'Set item properties' > windows open but when I return to the tree window and select the same > item, I can open an additional 'set properties' window. This leads to > all kind of C++ errors because these properties windows seems to > interfere for some reason. I don't have enough OO/Python/GUI knowledge > yet to fully understand what actually happens. > Basically, what I want is that when you want to open an items property > window and the window is alread open that in stead of opening a new > window, the window the is already open pops to the foreground. Any > ideay how I can implement this. > > Another solution would be to start the properties windows in a > 'synchronous' mode, meaning that if this window is open, that you can't > manipulate the tree window anymore (~like in Word when you open the > 'open file' window, you can't edit your doc until you this window is > closed again). > > I hope this makes some sense. > > Any help much appreciated. > > Kris > > Ps.: any refs to good OO/Python GUI books are also welcome (or URLs) > > -- > http://mail.python.org/mailman/listinfo/python-list > From eddie at holyrood.ed.ac.uk Wed Sep 14 10:04:00 2005 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 14 Sep 2005 14:04:00 +0000 (UTC) Subject: "week-year" conversion to date References: <1126704361.825633.200680@f14g2000cwb.googlegroups.com> Message-ID: oyvgi at hotmail.com writes: >I was wondering if it there is an "easy" way to get the dd-mm-yyyy from >ww-yyyy. >I would like to get, for example the first day (date-month-year) in the >week i specify. Found plenty of ways to go th other way, but none that >give me the reverse. >Idealy I would like both the beginning date/time and the end date/time >of the specified week, but if i can just get a hold one of the or some >other defined time in this week i could probably work out the rest. >This is in Python :-) >dd = day in month >mm = month >yyyy = year >ww = week # >Thanks for any and all help. >>> import mx.DateTime >>> d=mx.DateTime.DateTime(1992)+mx.DateTime.RelativeDateTime(weeks=15) >>> d >>> d=mx.DateTime.DateTime(1992)+mx.DateTime.RelativeDateTime(weeks=51) >>> d Eddie From mfranklin1 at gatwick.westerngeco.slb.com Wed Sep 28 05:00:32 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 28 Sep 2005 10:00:32 +0100 Subject: about install wxPython in Redhat Linux AS 4 In-Reply-To: <4e307e0f0509280128503e5e24@mail.gmail.com> References: <4e307e0f0509280128503e5e24@mail.gmail.com> Message-ID: Leo Jay wrote: > Dear All, > > I'd like to install wxPython in my Redhat AS 4, > I have downloaded both > wxPython-common-gtk2-unicode-2.6.1.0-fc2_py2.4.i386.rpm and > wxPython2.6-gtk2-unicode-2.6.1.0-fc2_py2.4.i386.rpm packages from > www.wxpython.org. > > After I installed these two packages successfully, what should i do now? > > i tried to import wx in python, but python just returned an error: > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named wx > > Anyone can help me, please? > > Thanks > > > -- > Best Regards, > Leo Jay Leo, I don't have AS 4 but fedora core 4 has wx in it's YUM repositories I assume RedHat has too, so perhaps you need to use the officially sanctioned version. If you want to use the latest and greatest then you will most likely need to build them from source (which means installing the -devel packages for python & GTK) Martin From xnews2 at fredp.lautre.net Thu Sep 8 05:47:11 2005 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 08 Sep 2005 09:47:11 GMT Subject: Job Offer in Paris, France : R&D Engineer (Plone) References: Message-ID: Peter Hansen said : > I can't let that pass. :-) I believe it was well established in posts > a few years ago that while the programming-language equivalent of > Esperanto is clearly Python, "Volapuke" was most definitely > reincarnated as *Perl*. Sorry -- I've been reading c.l.py daily for quite some time, but I must have skipped that particular thread :-) Of volap?k I know only the name, so if that was the consensus here, then it's certainly true... -- YAFAP : http://www.multimania.com/fredp/ From chris.cavalaria at free.fr Wed Sep 21 08:51:20 2005 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 21 Sep 2005 14:51:20 +0200 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <433155ae$0$2935$626a14ce@news.free.fr> Serhiy Storchaka a ?crit : > Roel Schroeven wrote: > >> Fredrik Lundh schreef: >> >>> meanwhile, over in python-dev land: >>> >>> "Is anyone truly attached to nested tuple function parameters; 'def >>> fxn((a,b)): print a,b'? /.../ >>> >>> Would anyone really throw a huge fit if they went away? I am willing >>> to write a PEP for their removal in 2.6 with a deprecation in 2.5 if >>> people are up for it." >> >> >> I for one would not like to see that disappear. I like being able to >> write, for example: >> >> def drawline((x1, y1), (x2, y2)): >> # draw a line from x1, y1 to x2, y2 >> foo(x1, y1) >> bar(x2, y2) >> >> instead of >> >> def drawline(p1, p2): >> x1, y1 = p1 >> x2, y2 = p2 >> # draw a line from x1, y1 to x2, y2 >> foo(x1, y1) >> bar(x2, y2) >> >> or >> >> def drawline(p1, p2): >> # draw a line from p1[0], p1[1] to p2[0], p2[1] >> foo(p1[0], p1[1]) >> bar(p2[0], p2[1]) > > > def drawline(p1, p2): > # draw a line from p1 to p2 > foo(*p1) > bar(*p2) > That one is stupid. I don't see how you can make it work without some global storing the p1 information in foo which I would consider as very ugly code. From hancock at anansispaceworks.com Tue Sep 27 03:15:26 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 27 Sep 2005 02:15:26 -0500 Subject: PEP 350: Codetags In-Reply-To: <7xirwnxkcq.fsf@ruckus.brouhaha.com> References: <7xirwnxkcq.fsf@ruckus.brouhaha.com> Message-ID: <200509270215.26352.hancock@anansispaceworks.com> On Monday 26 September 2005 10:25 pm, Paul Rubin wrote: > > I really doubt you'll find much agreement for this (the compiler > > should enforce it) position. The 'fewer conventions are better' > > position might enjoy more support, but doesn't strike me as > > particularly Pythonic (e.g. compare whitespace in Python and C). > > It's ok if the enforcement isn't strict. In this case, of course, it wouldn't be the compiler, but rather automatic documentation tools that enforce the convention (i.e. they will choke and/or not generate correct documentation if the convention is not followed. The PEP specifically mentions a validating application (check that codetags are correct). Nevertheless, enforcement does occur. This is the same situation as with docstring conventions (fields in epydoc for example, or using restructured text). By having a PEP convention for this sort of thing, it becomes easier for such applications to be written. Doesn't that qualify as "non-strict enforcement"? -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tzot at sil-tec.gr Tue Sep 6 16:31:27 2005 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 06 Sep 2005 23:31:27 +0300 Subject: simple question: $1, $2 in py ? References: <3o2mfcF3t26kU1@uni-berlin.de> Message-ID: On Mon, 05 Sep 2005 12:54:35 +0200, rumours say that "Diez B. Roggisch" might have written: >> >> As far as I understand there's no $1, $2... etc stuff right ? > >Yes - but there is sys.argv > >Try this > > >import this >print sys.argv I believe this last line should be: print this.__builtins__['__import__']('sys').argv -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From bokr at oz.net Tue Sep 27 23:55:04 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 28 Sep 2005 03:55:04 GMT Subject: PEP 350: Codetags References: <4338bc2f.2535976150@news.oz.net> Message-ID: <433a10e0.2623193773@news.oz.net> On Tue, 27 Sep 2005 18:53:03 +0100, Tom Anderson wrote: >On Tue, 27 Sep 2005, Bengt Richter wrote: > >> 5) Sometimes time of day can be handy, so maybe <2005-09-26 12:34:56> >> could be recognized? > >ISO 8601 suggests writing date-and-times like 2005-09-26T12:34:56 - using >a T as the separator between date and time. I don't really like the look >of it, but it is a standard, so i'd suggest using it. > I knew of the ISO standard, but I don't really like the "T" connector either. Why couldn't they have used underscore or + ? Oh well. I guess you are right though. >Bear in mind that if you don't, a black-helicopter-load of blue-helmeted >goons to come and apply the rubber hose argument to you. Nah, ISO 8601 is not a DRM standard. Regards, Bengt Richter From n00m at narod.ru Thu Sep 8 13:53:54 2005 From: n00m at narod.ru (n00m) Date: 8 Sep 2005 10:53:54 -0700 Subject: List of integers & L.I.S. In-Reply-To: <1126201801.250692.27750@f14g2000cwb.googlegroups.com> References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126129942.736374.260770@g44g2000cwa.googlegroups.com> <1126161203.409605.27880@f14g2000cwb.googlegroups.com> <1126196908.479379.22010@z14g2000cwz.googlegroups.com> <1126201801.250692.27750@f14g2000cwb.googlegroups.com> Message-ID: <1126202034.179605.96260@g43g2000cwa.googlegroups.com> PS: I've still not read 2 new posts. From rkern at ucsd.edu Fri Sep 2 15:31:48 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 02 Sep 2005 12:31:48 -0700 Subject: Find day of week from month and year In-Reply-To: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> Message-ID: Laguna wrote: > Hi Gurus, > > I want to find the expiration date of stock options (3rd Friday of the > month) for an any give month and year. I have tried a few tricks with > the functions provided by the built-in module time, but the problem was > that the 9 element tuple need to be populated correctly. Can anyone > help me out on this one? mx.DateTime provides a RelativeDateTime constructor that handles things like this. http://www.egenix.com/files/python/mxDateTime.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jgrahn-nntq at algonet.se Tue Sep 6 12:32:20 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 6 Sep 2005 16:32:20 GMT Subject: Python compiled? References: <1125951529.838575.107200@z14g2000cwz.googlegroups.com> Message-ID: On Mon, 5 Sep 2005 22:48:19 +0200, billiejoex wrote: >> there are "noob" questions and there are uneducated questions, yours >> are of the latter ( actually yours are STATEMENTS not questions ), and >> just trolling for what it is worth, if you would take the time to read >> what Python is and why it is you would not be asking these "questions". > > I'm really sorry man. I didn't wanted to be uneducated, believe me. > I wrote fastly, I'm new in Python and probably for my language problems I > didn't expressed concepts properly. I didn't think they were uneducated, they were good questions. At least if one understands that the problem is that the /end user/ percieves a problem. I hope people are less hesitant to install "interpreted" applications today than they were ten years ago. I also believe it's better to convince the end user to install Python before installing the application[1], rather than to try to sneak in an interpreter with py2exe or something -- an interpreter which the end user cannot update, manage or use for other things. /Jorgen [1] Might be hard to convince people who have ever installed a Java interpreter -- when I do that on Windows, I usually break at least one existing Java application, and I usually get a whole lot of useless desktop icons, a funny thing in the system tray, etc. -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From severa at sophia.dtp.fmph.uniba.sk Fri Sep 2 10:48:16 2005 From: severa at sophia.dtp.fmph.uniba.sk (severa at sophia.dtp.fmph.uniba.sk) Date: Fri, 2 Sep 2005 16:48:16 +0200 (CEST) Subject: why no user-def. attributes? Message-ID: I appologize in advance for stupid question, which is: why are user-defined attributes not allowed for builtin types? [I guess I undestand why *instances* cannot have them (e.g. then every dict would have a dict which would have a dict..), but this is a different question] I can imagine several answers, so I put here those that don't seem satisfactory to me :) 1. You can subclass, eg. class my_int(int): pass and then do whatnot, like my_int.__getitem__=some_vicious_function Here the problem is just that it's easier to write 4 than my_int(4), or "ha" than my_string("ha") etc. 2. You would probably want to add new methods, so why don't you define a function and then write e.g. dowhatIwant([1,2,3]) instead of [1,2,3].dowhatIwant() That's OK, except for the convenience of special methods like __add__ or __iter__ 3. It would lead to a confusing code Oops, maybe I shouldn't have written this one.. Anyway, please let me know the true reason (which is perhaps technical) Best whishes Paul From deets at nospam.web.de Mon Sep 19 11:59:07 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Sep 2005 17:59:07 +0200 Subject: Python game coding In-Reply-To: <1127140947.592844.304280@z14g2000cwz.googlegroups.com> References: <8f6Xe.14083$FW1.371@newsread3.news.atl.earthlink.net> <1127140947.592844.304280@z14g2000cwz.googlegroups.com> Message-ID: <3p85iaF93qn5U1@uni-berlin.de> TPJ wrote: > OT: > > >>BTW: I wonder if and when someone will use stackless python (...) > > > And what is this stackless python? I have visited it's homepage, but I > wasn't able to find any answer. (Well, I have found out, that stackles > python is python's implementation that doesn't use C stack, but it > tells me nothing...) > > Is this stackless python faster or slower than CPython? Does anybody > know something? The important thing is that the explicit modelling of the call-stack allows for running interpreters to be pickled - and thus stopped, persisted, reloaded and restarted. That is especially useful in comlex AI-code or e.g. workflow environments. The big difference is that you can _code_ as if you were always running and totally neglect the persistence and reentering issues. Diez From vel.accel at gmail.com Sat Sep 24 18:16:52 2005 From: vel.accel at gmail.com (D.Hering) Date: 24 Sep 2005 15:16:52 -0700 Subject: Poor man's OCR: need performance improvement tips In-Reply-To: <1127599160.757090.136780@o13g2000cwo.googlegroups.com> References: <1127585677.391112.70130@g49g2000cwa.googlegroups.com> <1127594820.721640.302800@g14g2000cwa.googlegroups.com> <1127599160.757090.136780@o13g2000cwo.googlegroups.com> Message-ID: <1127600212.456341.286950@z14g2000cwz.googlegroups.com> I thought I should correct and clarify the use of EMSL (even though this isn't specific toward your request, qvx.) http://esml.itsc.uah.edu/index.jsp It's more for data format recognition and conversion. Here's a description from the site. The sw was developed for earth science, but is very useful for any domain. ESML is an interchange technology that enables data (both structural and semantic) interoperability with applications without enforcing a standard format. Users can write external files using ESML schema to describe the structure of the data file. Applications can utilize the ESML Library to parse this description file and decode the data format. As a result, software developers can now build data format independent applications utilizing the ESML technology. Furthermore, semantic tags can be added to the ESML files by linking different domain ontologies to provide a complete machine understandable data description. This ESML description file allows the development of intelligent applications that can now understand and "use" the data. From stefano at pragma2000.com Sat Sep 10 01:55:24 2005 From: stefano at pragma2000.com (Stefano Masini) Date: Sat, 10 Sep 2005 07:55:24 +0200 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: <4321BCE8.30209@pythonapocrypha.com> References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <432742240509090817230df311@mail.gmail.com> <4321BCE8.30209@pythonapocrypha.com> Message-ID: <43274224050909225557a3a861@mail.gmail.com> On 9/9/05, Dave Brueck wrote: > shot). The cost of developing _exactly_ what you need often is (or at least > *appears* to be) the same as or lower than bending to use what somebody else has > already built. That's right. But as you say, this is _often_ the case, not always. One doesn't necessarily need to "bend" too much in order to use something that's available out there. If we're talking about simple stuff, like ordered dictionaries, file system management, ini files roundtripping, xml serialization (this one maybe is not that trivial...), I don't think you would have to come to big compromises. I myself reinvented these wheels a few times in different projects, because I wasn't happy with the way I reinvented the first time, then I eventually found some code written by someone else that was _exactly_ the same as my last attempt, my most evolved and "perfect", my prescioussss :), if it wasn't even better. Separate paths of evolution that converged to the same solution, because the problem was simple to begin with. Under this light, it seems to me that I wasted a lot of time. If odict was in the stdlib I wouldn't have bothered writing it. And yet, this code is not available in the stdlib. Sometimes it's not even trivial to be googled for. Plus, if you think of a python beginner, what's the chance that he's gonna say: naa, this code in the library sucks. I'm gonna search google for another ini file round tripper. Whatever is available there, he's gonna use, at least in the beginning. Then he will soon figure out that it indeed sucks, and at that point there's a chance that he'll say: man... _python_ sucks! I cannot even round trip an ini file with the same module! That's why I say this lack of a centralized, officially recommended code repository maybe is hurting python. I agree that building library code is hard because it has to be both correct and simple. But, again, there's a lot of useful stuff not the library, that's simple in the start so it's just a matter of writing it correctly. If the semantics can be different, just provide a couple of alternatives, and history will judge. It would be great if there was a section in the Python manual like this: "Quick and Dirty: Commonly needed tricks for real applications" 1. odict 2. file system management 3. xml (de)serialization 4. ... Each section would describe the problem and list one or a few recommended implementations. All available under __testing_stdlib__. Appoint somebody as the BDFL and make the process of updating the testing stdlib democratic enough to allow for more evolution freedom than the stable stdlib. If such a "quick and dirty" section existed, I think it would also become a natural randevouz point for innovators. If one invented a new cool, simple and useful module, rather than just publishing it in his own public svn repository, he would feel comfortable to start a discussion on the python-testing-stdlib mailing list suggesting to include it in the "quick and dirty" section of the manual. The manual is the primary resource that every python programmer makes use of, expecially beginners. But it is so official that no one would ever dare suggesting to include something in it. If the Vaults of Parnassus were listed in there (maybe a bit trimmed and evaluated first ;) a beginner would have immediate access to the most common tricks that one soon faces when it comes to writing real applications. I'm talking wildly here... I'm quite aware of how simplistic I made it. Just throwing an idea. What do you think? stefano From bill.pursell at gmail.com Sun Sep 4 07:40:03 2005 From: bill.pursell at gmail.com (bill) Date: 4 Sep 2005 04:40:03 -0700 Subject: documentation error Message-ID: <1125834003.482688.273630@g14g2000cwa.googlegroups.com> >From 3.2 in the Reference Manual "The Standard Type Hierarchy": "Integers These represent elements from the mathematical set of whole numbers." The generally recognized definition of a 'whole number' is zero and the positive integers. That is to say, -1 is not a whole number. The documentation ought to replace "whole numbers" with "integers". From tgraber_us at yahoo.com Tue Sep 13 12:03:51 2005 From: tgraber_us at yahoo.com (Tim G.) Date: 13 Sep 2005 09:03:51 -0700 Subject: FTP Error: Windows AS/400 Message-ID: <1126627431.665577.103390@o13g2000cwo.googlegroups.com> I am trying to use Win Python to ftp files from an AS/400 IFS directory down to my Windows machine. I seem to get stuck when I am trying to send a command to the AS/400 to switch file systems from native to IFS and then to issue a cd to my folder. I get the error below. If anyone has had experience trying to ftp from a 400, I would greatly appreciate any info on the topic. Code: import ftplib, os filename='' path = "jde7333" os.chdir('c:\\ftp_jde400') ftp = ftplib.FTP('test400') ftp.login('oneworld', 'onew0r1d') #ftp.sendcmd('quote site namefmt 1') ftp.sendcmd('site namefmt 1') ftp.cwd(path) #remotefiles = ftp.nlst() #ftp.retrlines('LIST') #for filename in remotefiles: # file = open(filename, 'wb') # ftp.retrbinary('RETR ' + filename, file.write, 1024) # file.close() ftp.quit() Error: Traceback (most recent call last): File "C:\Python24\Tools\scripts\ftp400.py", line 10, in ? ftp.cwd(path) File "C:\Python24\lib\ftplib.py", line 494, in cwd return self.voidcmd(cmd) File "C:\Python24\lib\ftplib.py", line 246, in voidcmd return self.voidresp() File "C:\Python24\lib\ftplib.py", line 221, in voidresp resp = self.getresp() File "C:\Python24\lib\ftplib.py", line 214, in getresp raise error_perm, resp ftplib.error_perm: 501 Unknown extension in database file name. From gandalf at designaproduct.biz Thu Sep 22 13:09:25 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Thu, 22 Sep 2005 19:09:25 +0200 Subject: Indexed variables In-Reply-To: <19551.1127406845@www41.gmx.net> References: <19551.1127406845@www41.gmx.net> Message-ID: <4332E545.5000509@designaproduct.biz> >a1=a2=0 > >def f(x): > if x == a1: > a1 = a1 + 1 > elif x == a2: > a2 = a2 + 1 > > >Now if I call f with f(a2) only a1, of course, is incremented because the >if-clause does only check for the value of the input and the values of a1 >and a2 are identical. > >So how do I define the function such as to discrimate wheter I call it by >f(a1) or f(a2) ? > > What you are trying to do is to create a function with a side effect. (Side effect is when a function changes its environment. The environment of a function is everything that is not local to that function, plus the actual parameters and I/O devices.) If you really want to change an actual parameter inside an object, then you should use a mutable object. In Python, there are two kinds of objects: mutable and immutable. Immutable objects cannot change their value. Integers are immutable. The object zero will always be zero. You can add another integer to it, but it will create another object, while the zero object will remain zero. There are other immutable objects. For example, tuples are immutable. >>>t = (1,2,3) This object is an immutable tuple. You cannot change its value. Mutable objects can change their values. For example, lists are mutable. >>>L = [1,2,3] Usually, mutable objects have methods to change their value. >>>L.append(4) >>>print L [1,2,3,4] So if you really want to create a function with a side effect, do something like this: >>> >>> a1 = [0] >>> a2 = [0] >>> >>> >>> def f(x): ... if x is a1: ... a1[0] += 1 ... elif x is a2: ... a2[0] += 1 ... >>> a1 [0] >>> f(a1) >>> a1 [1] >>> a2 [0] >>> But please note that having side effect is generally considered harmful. Please read the tutorial, these things are explained quite well. http://docs.python.org/tut/tut.html Best, Les From sherm at dot-app.org Thu Sep 29 13:53:30 2005 From: sherm at dot-app.org (Sherm Pendley) Date: Thu, 29 Sep 2005 13:53:30 -0400 Subject: A Moronicity of Guido van Rossum References: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> <1128013745.763757.144280@g44g2000cwa.googlegroups.com> <1128015868.201617.153240@g14g2000cwa.googlegroups.com> Message-ID: "Matt" writes: > OK... your post seems to indicate a belief that everyone else is > somehow incompetent. Xah's just a troll - best to just ignore him. He posts these diatribes to multiple groups hoping to start a fight. sherm-- -- Cocoa programming in Perl: http://camelbones.sourceforge.net Hire me! My resume: http://www.dot-app.org From alain.paschoud at fastcom.ch Thu Sep 15 03:23:46 2005 From: alain.paschoud at fastcom.ch (Alain Paschoud) Date: Thu, 15 Sep 2005 09:23:46 +0200 Subject: Python in C integration and WxPython Message-ID: Hi all, I made a small dialog in WxPython. I can run the python script with a double-click or through command line, and everything goes fine (dialog appears, which means that wx module has been found). Then, I decided to write a C program (under Windows, with Cygwin) that will read my script (through PyRun_SimpleFile() function) and run it. But the system doesn't find the wx module to import... Traceback (most recent call last): File "Dialog.py", line 2, in ? import wx ImportError: No module named wx How can I say to my program where to search for this module ? I tried to set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything. More generally : Does a C program that embedded python run an external executable (interpreter), or does it only load libraries ? Thank you very much for any help on this topic. Best regards. From brianc at temple.edu Wed Sep 7 17:07:42 2005 From: brianc at temple.edu (brianc at temple.edu) Date: Wed, 7 Sep 2005 17:07:42 -0400 Subject: Best dbm to use? Message-ID: I'm creating an persistant index of a large 63GB file containing millions of peices of data. For this I would naturally use one of python's dbm modules. But which is the best to use? The index would be created with something like this: fh=open('file_to_index') db=dbhash.open('file_to_index.idx') for obj in fh: db[obj.name]=fh.tell() The index should serve two purposes. Random access and sequential stepped access. Random access could be dealt with by the hash table ability for example: fh.seek(db[name]) obj=fh.GetObj() However, I may want to access the i'th element in the file. Something like this: fh.seek(db.GetElement(i)) obj=fh.GetObj() This is where the hash table breaks down and a b-tree would serve my purpose better. Is there a unified data structure that I could use or am I doomed to maintaining two seperate index's? Thanks in advance for any help. -Brian From mwm at mired.org Sun Sep 18 20:09:44 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 18 Sep 2005 20:09:44 -0400 Subject: Announce: open 0.2 - a unix application launcherr Message-ID: <86aci92a0n.fsf@bhuda.mired.org> "open" is designed to provide Unix users with a single tool for dealing with the multitude of applications that deal with data files. Without open - or something like it - every time a user wants to look at a file, they have to figure out what type the file is and which application on their path can open that file, and then invoke that application with the appropriate arguments. Likewise, every application that uses external applications has it's own database of file types and applications. Applications developers have to choose a format for the database, write code to parse it, and provide a GUI for editing it. This not only represents a duplication of effort, but requires the user to tell every application how to deal with each type of file, meaning they have to learn multiple different tools for dealing with this information. "open" was designed to solve these problems. If the user wants to open a file, they just invoke "open" on it. To edit it, they just invoke "open -c edit" (or "edit" if they've installed it that way). Open will figure out which application they want to use for this, and arrange that it gets called appropriately. If open can't find an application, it'll ask the user to choose one, and save that choice for future reference. For applications, open provides an API that takes care of the entire problem. There's no need to parse a configuration file, provide facilities for editing the configuration file, ensure the consistency of the configuration file, or any such thing. The application merely hands the file name to "open", and "open" does the rest. Further, the API is one that any program that has to deal with external applications already deals with - launching an external application on a file. So users can start getting the benefit of using "open" even if none of the applications they have installed know about it - all they have to do is tell each application to use "open" for everything. Hopefully, applications will start checking for and using "open" as an external viewer by default, removing even that burden from the user. The benefits to the user are multifold. They only have to learn one interface for configuring the invocation of external programs. If they install a new foo viewer, and decide they want to use that for viewing foos everywhere, they only have to change it in one place - the "open" database. Users can quit worrying about "What application opens this file" at the command line. Well, most of the time. Instead, they just do "open ", and let open sort it out. It's not got it's own web page yet - and little or no documentation. Download the tarball from http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From edhotchkiss at gmail.com Sun Sep 18 17:53:40 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Sun, 18 Sep 2005 17:53:40 -0400 Subject: tuples and mysqldb tables Message-ID: I have used fetchall() to insert the values from a table into a tuple. anywhere from 0 - ? many rows could be in this tuple, so it is a row within a row. How do I use a loops to iterate through the nested tuple, and assign the tuples integers and strings to variables, ugh :P The Tables data is like this: +---------------------------------------------------------------------------------------------------------------------+ | ID (INT) | Protocol (TEXT) | Name (LONGTEXT) Description (LONGTEXT) | +---------------------------------------------------------------------------------------------------------------------+ import MySQLdb import sys # find out what this ports function is ---- def grabPortInfo(port): try: conn=MySQLdb.connect( host="www.freesql.org ", user="portnumbers", port=3306, passwd="*********", db="portnumbers") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) print "\n\n WTF!? - portnumbers MySQL DB didn't open" sys.exit (1) # ------------------ cursor = conn.cursor() stmt = "SELECT * FROM portnumbers WHERE port=%i" %port cursor.execute(stmt) numrows = int(cursor.rowcount) if numrows == 0: print "port # not found in database" elif numrows >= 1: result = cursor.fetchall() print len(result) # break tuple into strings with output myPort = port myProtocol = result[0|3] myName = result[0|4] myDescription = result[0|5] print "PORT # | PROTOCOL | PORT NAME | PORT DESCRIPTION " print myPort, myProtocol, myName, myDescription cursor.close() conn.close() # end function ------------- grabPortInfo(22) -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Fri Sep 2 15:39:52 2005 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Sep 2005 14:39:52 -0500 Subject: OpenSource documentation problems In-Reply-To: <1f7befae05090207522914e0c3@mail.gmail.com> References: <4317BEAC.6030804@holdenweb.com> <7xzmqwkvu8.fsf@ruckus.brouhaha.com> <1f7befae05090207522914e0c3@mail.gmail.com> Message-ID: <17176.43656.961487.140632@montanaro.dyndns.org> Tim> [Paul Rubin] >> Until not that long ago, it was possible to submit sf bugs without >> being logged into sf. Why did that change? Tim> To reduce tracker spam, to reduce tracker vandalism, and to make it Tim> possible to contact submitters when needed. Also, "not that long ago" must mean different things for different people. I think we've required logins for three years or more. Skip From n00m at narod.ru Thu Sep 1 12:36:48 2005 From: n00m at narod.ru (n00m) Date: 1 Sep 2005 09:36:48 -0700 Subject: Code run from IDLE but not via double-clicking on its *.py In-Reply-To: <1125579678.705228.172970@f14g2000cwb.googlegroups.com> References: <1125402893.124342.54690@g47g2000cwa.googlegroups.com> <1125425945.667967.181000@g49g2000cwa.googlegroups.com> <1125478316.530781.315540@g44g2000cwa.googlegroups.com> <1125490472.670850.247240@g49g2000cwa.googlegroups.com> <1125509322.964828.27510@o13g2000cwo.googlegroups.com> <1125579678.705228.172970@f14g2000cwb.googlegroups.com> Message-ID: <1125592608.894215.186670@g43g2000cwa.googlegroups.com> Dennis; Richie; >That sounds impossible, so I must be misunderstanding something. YOU - BOTH - UNDERSTAND ME ABSOLUTELY RIGHT! >1. >Start a new Command Prompt via Start / Programs / Accessories / Command >Prompt (or the equivalent on your machine) >2. >Type the following: d:\python23\python d:\python23\socket6.py [Enter] >3. Double-click your .vbs file in Windows Explorer. >Now what does the python Command Prompt say? It says... NOTHING! It just DISAPPEARS! JUST FOR TO MAKE SURE I put in the same directory (Python's root) testme.py file with this simplest content: print 'ONE' print 'TWO' print 'THREE' Then I run it EXACTLY the same way as I run socket6.py: D:\>python23\python d:\python23\testme.py [Enter] ONE TWO THREE D:\> AND OF COURSE CONSOLE WINDOW DID NOT CLOSE AFTER THAT ! BUT IT REALLY DISAPPEARS IN CASE OF socket6.py ! (but only AFTER I double-click my .vbs file in Windows Explorer) From steve at ferg.org Tue Sep 27 13:29:11 2005 From: steve at ferg.org (Steve) Date: 27 Sep 2005 10:29:11 -0700 Subject: installing cx_Oracle on Unix/Solaris Message-ID: <1127842151.524686.11780@g14g2000cwa.googlegroups.com> I'm posting this message here, so that someone googling here will be able to find it. I was having problems installing cx_Oracle on Solaris. The build would fail with a message: > ld: fatal: file /apps/oracle/prod/9.2/lib/libclntsh.so: wrong ELF class: ELFCLASS64 I found the solution on Grig Gheorghiu's blog. Grig had similar problems when installing on UNIX, specifically AIX. You can find his very useful report on how he solved the problem, here: http://agiletesting.blogspot.com/2005/05/installing-and-using-cxoracle-on-unix.html and also here: http://agiletesting.blogspot.com/2005/07/installing-python-241-and-cxoracle-on.html To put matters in a nutshell, Oracle 9i installs the 64-bit libraries in $ORACLE_HOME/lib and the 32-bit libraries in $ORACLE_HOME/lib32. Since setup.py is looking by default in $ORACLE_HOME/lib, it finds the 64-bit libraries and it fails. The trick (at least for me) was to change "lib" to "lib32" in my ORACLE_HOME environment setting, and in setup.py. MUCH thanks to Grig for his useful blog! From juicy_killa at hotmail.com Wed Sep 28 07:55:21 2005 From: juicy_killa at hotmail.com (accolades) Date: 28 Sep 2005 04:55:21 -0700 Subject: Pythonwin crashes Message-ID: <1127908521.577030.24100@g43g2000cwa.googlegroups.com> Does anyone else have a problem with Pythonwin crashing after running a python script with graphics libraries? Whenever I use Pythonwin to run a PyGame or PyOgre script, Pythonwin crashes when the script exits. I know it's probably because the Pythonwin interpreter can't read from the console once the graphics mode has been changed, but has anyone discovered a workaround? I'd like to know if this problem is specific to my machine, or if others have witnessed this. Thanks Tim From lidenalex at yahoo.se Fri Sep 9 08:48:26 2005 From: lidenalex at yahoo.se (Alex) Date: 9 Sep 2005 05:48:26 -0700 Subject: is interactive mode same as calculator mode? Message-ID: <1126270106.178712.262520@g43g2000cwa.googlegroups.com> Loking at Rossum's tutorial I've seen that he sometimes uses the expression "interactive mode" and sometimes "calculator mode". Or these concepts same? I've made the following assertion. "When Python prompts for the next command with the primary prompt ">>> ", the interpreter is said to be in an interactive mode, or in a calculator mode. In interactive mode, the Python interpreter acts as a simple calculator: you can type an expression at it and it will write back the value of that expression." Is this correct or incorrect? Alex From fredrik at pythonware.com Fri Sep 30 12:21:12 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 18:21:12 +0200 Subject: getattr References: <1128096807.903294.293470@g47g2000cwa.googlegroups.com> Message-ID: kyaBey at gmail.com wrote: > Is there any way by which the __getattr__(self,attr) method can > determine that in > case a) attr == 'bar' is the final component in the reference unlike in > case b) where attr=='bar' is NOT the ultimate(final) component of > reference and is an intermediate component in the reference. no. if you want to control further accesses, your __getattr__ has to return a proxy object, and use a suitable syntax to get the final value. From root at smtp.imst.de Wed Sep 28 10:54:17 2005 From: root at smtp.imst.de (root) Date: Wed, 28 Sep 2005 16:54:17 +0200 Subject: Virus in your Mail to empire.support Message-ID: <200509281454.j8SEsH8Y019475@smtp.imst.de> The VirusCheck at the IMST generated the following Message: V I R U S A L E R T Our VirusCheck found a Virus (W32/Netsky-Q) in your eMail to "empire.support". This eMail has been deleted ! Now it is on you to check your System for Viruses This System is running with Linux and Amavis (www.amavis.org). :-) From steven.bethard at gmail.com Thu Sep 22 13:59:18 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 22 Sep 2005 11:59:18 -0600 Subject: Writing a parser the right way? In-Reply-To: <1127410048.578692.97810@f14g2000cwb.googlegroups.com> References: <1127300661.440587.287950@g47g2000cwa.googlegroups.com> <1127306797.658461.264950@g44g2000cwa.googlegroups.com> <1127323058.667034.43540@g49g2000cwa.googlegroups.com> <1127410048.578692.97810@f14g2000cwb.googlegroups.com> Message-ID: <0b-dnXgYtNlrba_eRVn-sg@comcast.com> beza1e1 wrote: > Verbs are the tricky part i think. There is no way to recognice them. > So i will have to get a database ... work to do. ;) Try the Brill tagger[1] or MXPOST[2]. STeVe [1] http://www.cs.jhu.edu/~brill/code.html [2] ftp://ftp.cis.upenn.edu/pub/adwait/jmx/jmx.tar.gz From nospam at jollans.com Sat Sep 24 04:07:55 2005 From: nospam at jollans.com (Thomas Jollans) Date: Sat, 24 Sep 2005 10:07:55 +0200 Subject: How to decompile an exe file compiled by py2exe? In-Reply-To: References: Message-ID: Leo Jay wrote: > Dear All, > > I lost my source code because of my incaution. > so anyone can tell me how to decompile the exe file compiled by py2exe? > > Thanks. > > -- > Best Regards, > Leo Jay If you find a program that de-compiles exe to python, it will most likely use very ugly, c-like python because a microchip is no python interpreter. This is based on the assumption that py2exe really generates a pure exe and not an exe that interprets bytecode python. be that the case, it may yield decent results, but ugly nontheless. It might better to re-write it... From larry.bates at websafe.com Fri Sep 30 10:09:24 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 30 Sep 2005 09:09:24 -0500 Subject: Overloading __init__ & Function overloading In-Reply-To: References: Message-ID: <433D4714.9050808@websafe.com> I may be reading this question different than Fredrik. This example is with old-style classes. class baseclass: def __init__(self, arg): # # Do some initialization # def method1(self, arg): # # baseclass method goes here # class myclass(baseclass): def __init__(self, arg): # # This method gets called when I instantiate this class. # If I want to call the baseclass.__init__ method I must # do it myself. # baseclass.__init__(arg) def method1(self, arg): # # This method would replace method1 in the baseclass # in this instance of the class. # myObj=myclass(arg) I could be way off base, but maybe it will help. -Larry Bates Iyer, Prasad C wrote: > I am new to python. > > I have few questions > a. Is there something like function overloading in python? > b. Can I overload __init__ method > > Thanks in advance > > > > regards > prasad chandrasekaran > > > > > > > > > > > > > > > > > > > > > --- Cancer cures smoking > -----Original Message----- > From: python-list-bounces+prasad.c.iyer=capgemini.com at python.org > [mailto:python-list-bounces+prasad.c.iyer=capgemini.com at python.org] On > Behalf Of python-list-request at python.org > Sent: Friday, September 30, 2005 6:36 PM > To: python-list at python.org > Subject: Python-list Digest, Vol 24, Issue 455 > > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message. > From flupke at nonexistingdomain.com Thu Sep 22 18:03:42 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 22 Sep 2005 22:03:42 GMT Subject: Module import via sys.path and py2exe In-Reply-To: <9uFYe.2194$rs1.114801@phobos.telenet-ops.be> References: <9uFYe.2194$rs1.114801@phobos.telenet-ops.be> Message-ID: <2TFYe.2211$Qq1.47151@phobos.telenet-ops.be> flupke wrote: > Hi, > > i have a program with is built like this: > startup.py > dir1/__init__.py > dir1/file1.py > dir2/__init__.py > dir2/file2.py > dir3/__init__.py > dir3/file3.py > > The program works but now i want to add the functionality into an > existing program 2. This is program 2: > > program2.py > program2dir1/__init__.py > program2dir1/file4.py > > When i copy the directories over i get this situation: > > program2.py > program2dir1/__init__.py > program2dir1/file4.py > program1/__init__.py > program1/dir1/__init__.py > program1/dir1/file1.py > program1/dir2/__init__.py > program1/dir2/file2.py > program1/dir3/__init__.py > program1/dir3/file3.py > > However, i need to specify this in program2.py or i can't use the files > 1-3: > import sys > sys.path.append('program1') > import program1.dir1.file1 as f1 > > Then i can use the functionality of the first program in the second. > > Now for my questions: > > 1. Is this the correct way or is there an easier/more logical sollution. > Now all __init__.py file are empty > > 2. As said this works but when i make a standalone of program2 it > doesn't find any of the program1 files: > Traceback (most recent call last): > File "start.py", line 20, in ? > File "windows\windowmain.pyo", line 59, in ? > File "program1\__init__.pyo", line 2, in ? > File "program1\dir1\__init__.pyo", line 1, in ? > File "program1\dir1\file1.pyo", line 28, in ? > ImportError: No module named dir2.file2 > > dir2.file2 is imported in file1.py as import dir2.file2. > So something in my setup script is wrong. How can i make sure all file > of program1 are also added? > > Excerpt of setup.py > ... > py_modules=['start'], > packages=['database','dialogs','export','graphics','localutils','windows'], > ... > If i specify program1 as module or as package or program1.dir1 and so on > doesn't seem to help. > > Any ideas? > > Thanks > Benedict I forgot to add that if i check the shared.lib py2exe creates, the program1 dir and subdirs/files are there so they are included in the package. Benedict From bill.mill at gmail.com Thu Sep 22 14:31:55 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 22 Sep 2005 14:31:55 -0400 Subject: How to show percentage In-Reply-To: <1127411503.211432.250960@g43g2000cwa.googlegroups.com> References: <1127411503.211432.250960@g43g2000cwa.googlegroups.com> Message-ID: <797fe3d4050922113179348154@mail.gmail.com> You need to convert 1 or 3 to a float. How about: >>> def pct(num, den): return (float(num)/den) * 100 ... >>> pct(1, 3) 33.333333333333329 Peace Bill Mill bill.mill at gmail.com On 22 Sep 2005 10:51:43 -0700, Sen-Lung Chen wrote: > Dear All: > I have a question of show percentage. > For example ,I want to show the percentage of 1/3 = 33.33% > > I use the 1*100/3 = 33 > it is 33 not 33.33 , how to show the 33.33 % > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > From bokr at oz.net Mon Sep 19 01:22:09 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 19 Sep 2005 05:22:09 GMT Subject: Possible bug in "metaclass resolution order" ? References: <1126947879.528826.150440@f14g2000cwb.googlegroups.com> Message-ID: <432e3f55.1848653933@news.oz.net> On Sat, 17 Sep 2005 12:41:09 -0300, Pedro Werneck wrote: >On 17 Sep 2005 02:04:39 -0700 >"Simon Percivall" wrote: > >> Have you read the "Metaclasses" part of "Unifying types and classes in >> Python 2.2"? (http://www.python.org/2.2.3/descrintro.html#metaclasses) > >Yes, I read. Have you read and understood my message ? :) > >A class B, subclass of class A, with a metaclass M_A should have M_A or >a subclass of it as metaclass. If you try with anything else, you get a >TypeError exception as expected. OK. But if you try with 'type', nothing >happens. > >Python 2.4.1 (#1, Sep 16 2005, 17:47:47) >[GCC 3.3.4] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> class M_A(type): pass >... >>>> class A: __metaclass__ = M_A >... >>>> class B(A): __metaclass__ = type >... >>>> B.__class__ > >>>> B.__metaclass__ > > FWIW, I think __metaclass__ can be any callable, but it seems to be the first argument to type.__new__ that invokes the checking and type(name, bases, cdict) seems to have the same effect as type.__new__(type, name, bases, cdict). Maybe there has to be a "real" class on the mro, and type isn't one, or it's a wild card ;-) I haven't really grokked the error message's true meaning, not having dealt with metaclass conflict before. Not ready today, sorry ;-) >>> class M_A(type): pass ... >>> class A: __metaclass__ = M_A ... >>> def foo(*args): print args; return 'silliness' ... >>> def foo(cname, cbases, cdict): ... print 'cname, cbases:', cname, cbases ... print 'cdict:', cdict ... mt = type('M_B',(type,),{}) ... print 'mt:', mt ... print 'mt.mro(mt):', mt.mro(mt) ... print 'mt.__new__:', mt.__new__ ... something = mt.__new__(mt, cname, cbases, cdict) ... print 'something:', something ... return something ... >>> class B(A): __metaclass__ = foo ... cname, cbases: B (,) cdict: {'__module__': '__main__', '__metaclass__': } mt: mt.mro(mt): [, , ] mt.__new__: Traceback (most recent call last): File "", line 1, in ? File "", line 8, in foo TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases >>> def bar(cname, cbases, cdict): ... print 'cname, cbases:', cname, cbases ... print 'cdict:', cdict ... mt = type ... print 'mt:', mt ... print 'mt.mro(mt):', mt.mro(mt) ... print 'mt.__new__:', mt.__new__ ... something = mt.__new__(mt, cname, cbases, cdict) ... print 'something:', something ... return something ... >>> class B(A): __metaclass__ = bar ... cname, cbases: B (,) cdict: {'__module__': '__main__', '__metaclass__': } mt: mt.mro(mt): [, ] mt.__new__: something: >>> And the something returned, whatever it is, if no checking is triggered by normal use, gets bound to the class name, e.g., >>> class C(A): __metaclass__ = lambda *a:('silly', 'result') ... >>> C ('silly', 'result') Regards, Bengt Richter From kay.schluehr at gmx.net Fri Sep 16 02:38:41 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Sep 2005 23:38:41 -0700 Subject: Self reordering list in Python References: Message-ID: <1126852721.347855.278870@g14g2000cwa.googlegroups.com> Laszlo Zsolt Nagy wrote: > Hello, > > Do you know how to implement a really efficient self reordering list in > Python? (List with a maximum length. When an item is processed, it > becomes the first element in the list.) I would like to use this for > caching of rendered images. I wonder why you don't use a dictionary? The only time I used a move-front algorithm I stored algorithms and had to evaluate a condition to select the correct algo. That means no constant search key was available for accessing the correct one. In case of an image list I would implement a self-ordering list if I have to do some pattern recognition in order to select the correct image. Holding a reference as a search key a Python hash-table will always have a better average time complexity no matter which language is used to implement move-front. In either way I'd use Python as an implementation language. Kay From rschroev_nospam_ml at fastmail.fm Thu Sep 8 06:34:05 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 08 Sep 2005 10:34:05 GMT Subject: Manging multiple Python installation In-Reply-To: References: Message-ID: Jeremy Jones wrote: > Andy Leszczynski wrote: >> >>Is there any way to pass the prefix to the "make install"? Why "make" >>depends on that? >> >>A. >> > > What does it matter? If you *could* pass it to make, what does that buy > you? I'm not a make guru, but I'm not sure you can do this. Someone > else better versed in make will certainly chime in if I'm wrong. But I > think make just looks at the Makefile and does what it's going to do. > If you want different behavior, you edit the Makefile or you get the > Makefile created differently with configure. That way you could install to a different directory without having to rebuild the whole thing. I don't think that uses case happens very often, but I've certainly encountered it (not in relation to Python though). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From erik.wilsher at gmail.com Fri Sep 23 00:52:03 2005 From: erik.wilsher at gmail.com (Erik Wilsher) Date: 22 Sep 2005 21:52:03 -0700 Subject: C#3.0 and lambdas In-Reply-To: <3pgqp0Fagh77U1@individual.net> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <1127426064.277907.251710@g47g2000cwa.googlegroups.com> <3pgqp0Fagh77U1@individual.net> Message-ID: <1127451123.579807.254870@g43g2000cwa.googlegroups.com> Python developement is discussed, decided and usually developed within the members of python-dev. Have you seen any discussions about xml-literals in python-dev lately? From swarnapsv at yahoo.co.in Tue Sep 13 19:54:30 2005 From: swarnapsv at yahoo.co.in (swarna pulavarty) Date: Wed, 14 Sep 2005 00:54:30 +0100 (BST) Subject: retrieve data using FTP in Python Message-ID: <20050913235431.72662.qmail@web8401.mail.in.yahoo.com> Hi all, I am new to this Python group and to Python . I need to retrieve data from an arbitrary URL and save it to a file. Can anyone tell me how to retrieve "any" data using FTP modules in Python ? And also, Can you suggest me some books and online references to get familiar with Python and especially FTP modules in Python ? Your help is appreciated ! Swarna. --------------------------------- Yahoo! India Matrimony: Find your partner now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From edreamleo at charter.net Mon Sep 12 13:10:22 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 12 Sep 2005 12:10:22 -0500 Subject: ANN: Leo 4.3.2 beta 1 Message-ID: <9EiVe.10770$tc7.1710@fe03.lga> Leo 4.3.2 beta 1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 To learn about Leo, see: http://webpages.charter.net/edreamleo/intro.html The highlights of 4.3.2: ----------------------- - Improved Leo's documentation: - A tutorial introduction to Leo: http://webpages.charter.net/edreamleo/intro.html - A 5-minute guide to programming with Leo: http://webpages.charter.net/edreamleo/intro.html#quick-start-for-programmers - The new rst3 plugin creates .html and .tex files from reStructuredText embedded in Leo files. Any node of the source outline may contain options for the rst3 plugin, which makes this plugin much more useful and flexible than the previous rst plugins. All of Leo's documentation was created using this plugin from sources in LeoDocs.leo. For full documentation for rst3 see: http://webpages.charter.net/edreamleo/rstplugin3.html - The spellpyx (spell checking) plugin is now much easier to use. - The vim and openWith plugins now use Python's subprocess module if it is present. - Improved the Pretty Printing command. - The usual assortment of bug fixes. Edward K. Ream -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From dw-google.com at botanicus.net Thu Sep 22 09:05:27 2005 From: dw-google.com at botanicus.net (David Wilson) Date: 22 Sep 2005 06:05:27 -0700 Subject: Looking for system/network monitoring tool written in Python In-Reply-To: <86k6ham0aw.fsf@bhuda.mired.org> References: <86k6ham0aw.fsf@bhuda.mired.org> Message-ID: <1127394327.610348.302390@f14g2000cwb.googlegroups.com> See http://pynms.sourceforge.net/ Also see Google. :) David. From free.condiments at gmail.com Thu Sep 22 22:16:11 2005 From: free.condiments at gmail.com (Sam Pointon) Date: 22 Sep 2005 19:16:11 -0700 Subject: What is "self"? References: <43335c5f$1_4@alt.athenanews.com> Message-ID: <1127441771.760704.152500@g14g2000cwa.googlegroups.com> self is the class instance that the bound function being called belongs to. This example should illustrate a bit. class Foo(object): def __init__(self, value): self.value = value # so the Foo instance now has an attribute, value def get_value(self): return self.value # This gets the previously-set value attribute of the Foo instance bar = Foo(42) baz = Foo('101010') print bar.get_value() #Note that the self argument is implicit since this is a bound method. print print baz.get_value() The output is (or should be, as this is untested): 42 101010 From apardon at forel.vub.ac.be Wed Sep 14 06:58:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Sep 2005 10:58:44 GMT Subject: round() wrong in Python 2.4? References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Message-ID: Op 2005-09-13, Robert Kern schreef : > Jeremy Sanders wrote: >> Nils Grimsmo wrote: >> >>>Why did round() change in Python 2.4? >> >> It the usual floating point representation problem. 0.0225 cannot be >> represented exactly: > > That's not what he's asking about. He's asking why his Python 2.3 rounds > 0.0225 *up* to 0.023 while his Python 2.4 rounds *down* to 0.022. It's > the change in behavior that he's concerned with and isn't just the usual > floating point problem. I would say the usual floating point problem is involved. Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down. 0.0225 isn't representable and it happens that the actual number you get differ. Now which number python should choose when it is fed 0.0225, I don't know. But expressing the different behaviour as a change in round, suggest that the O.P. would be wise to learn about floating point problems -- Antoon Pardon From gsakkis at rutgers.edu Tue Sep 20 12:25:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 20 Sep 2005 12:25:08 -0400 Subject: How to write this iterator? References: <1127218070.804214.275090@g47g2000cwa.googlegroups.com> Message-ID: <1127233517.5d14e4cf8cf010fc03a3f73c01050e33@teranews> "Jordan Rastrick" wrote: > I've written this kind of iterator before, using collections.deque, > which personally I find a little more elegant than the list based > approach: Nice, that's *much* more elegant and simple ! Here's the class-based version with append; note that interleave is modified to put back the popped iterator before yield, otherwise append doesn't work properly: from collections import deque class Interleave(object): """Iterator that cycles over one or more iterables, yielding one item from each iterable at a time. Once an iterable is exhausted, it is removed from the cycle. This iterator is exhausted when all participating iterables are exhausted. >>> it = Interleave("abc","12345","XY") >>> list(it) ['a', '1', 'X', 'b', '2', 'Y', 'c', '3', '4', '5'] >>> list(it) [] """ def __init__(self, *iterables): iters = self.__iters = deque(map(iter, iterables)) def generator(): while iters: it = iters.popleft() try: next = it.next() except StopIteration: continue else: iters.append(it) yield next self.__this_iter = generator() def append(self,iterable): """Adds an iterable to the existing cycle of iterables. The given iterable is added in front of the current position in the cycle so that it's called only after all the others. >>> example = Interleave("abc", "12345") >>> [example.next() for i in range(3)] ['a', '1', 'b'] >>> example.append("XY") >>> list(example) ['2', 'c', 'X', '3', 'Y', '4', '5'] """ self.__iters.append(iter(iterable)) def __iter__(self): return self def next(self): return self.__this_iter.next() if __name__ == '__main__': import doctest doctest.testmod() From rrr at ronadam.com Wed Sep 21 21:45:42 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 22 Sep 2005 01:45:42 GMT Subject: Question About Logic In Python In-Reply-To: References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Ah, that's a good example, thanks, except I notice you didn't actually > cast to bool in them, eg: (min < value < max) * value It wasn't needed in these particular examples. But it could be needed if several comparisons with 'and' between them are used. It just seems odd to me that: 3 and 2 and 1 -> 1 1 and 2 and 3 -> 3 But that may be because I learned boolean algebra as part of an electronics logic (computer tech) course dealing with gates in the early 80's. >>In boolean math it is useful to add and subtract. >> >>> a = b = True >> >>> a + b >>2 # Non boolean result. > I presume you mean Boolean algebra by "Boolean math". I have to disagree > with you there. It is *not* useful to do addition, subtraction, > multiplication or division in Boolean algebra. .... (clip) Yes, but not quite as strict as True BA would be and not with the strict type checking other languages have. > I'm not saying that it can't be useful to treat Booleans as if they were > the integers 0 and 1, but in mathematics Booleans are abstract values > distinct from the integers (even when they use the symbols 0 and 1) and > the concept "True plus True is two" is meaningless. > > It is useful to read the comments here: > > http://www.python.org/doc/2.3/whatsnew/section-bool.html Thanks and the PEP link from there was useful too. > eg "Python's Booleans were not added for the sake of strict type-checking. > A very strict language such as Pascal would also prevent you performing > arithmetic with Booleans, and would require that the expression in an if > statement always evaluate to a Boolean result." It doesn't need to be that strict. But a few changes could resolve and reduce the chance of errors especially for beginners, while not limiting more advanced uses. These would be Python 3k changes most likely if at all. 1. 'and', 'or', and 'not' always return bool values. Lots of discussion on this one already. From the look of it, I don't think it will change. But Guido seemed to suggest its possible with the addition of a trinary operation. But even with that it wouldn't be done any time soon. 2. bool == value to be the same as bool == value.__nonzero__() By doing this comparisons with Bool types will match the behavior of if conditions without restricting if to strictly bools. 3. Math with bools as both arguments should return bools. This wouldn't prevent adding bools and ints, or doing other operations on them. But bools would remain bool types until an operation with a non bool type. True * True -> True instead of 1 True * False -> False instead of 0 False * True -> False instead of 0 False * False -> False instead of 0 True * 10 -> 10 False * 10 -> 0 True * 0 -> 0 True + True -> True instead of 2 **changed** True + False -> True instead of 1 False + True -> True instead of 1 False + False -> False instead of 0 True + 1 = 2 False + 0 = 0 -True -> False instead of -1 **changed** -False -> True instead of 0 **changed** 1-True -> 0 1-False -> 1 2-True -> 1 2-False -> 2 True-1 -> 0 False-1 -> -1 Notice there is only three places above where the change would be significantly different than now. All other cases would just exchange True of 1 or False for 0. Some operation would need a trinary operation in place of the current and/or. person.name = (if name then name else 'default name') Not my favorite syntax, but I can live with it. It might be possible to have a short form. person.name = (name else 'default name') >>Should bool type act like bools as expressed here? >> >> http://www.ee.surrey.ac.uk/Projects/Labview/boolalgebra/ > > That is only one possible Boolean algebra, the simplest one. Strictly > speaking, Booleans aren't limited to two values. See > http://en.wikipedia.org/wiki/Boolean_algebra for more detail. I look at those earlier and was surprised at how complex some Boolean algebra concepts were. Interesting though, and I'll probably go back and study it a bit more. > Python's bools aren't Booleans. They are merely aliases for 0 and 1. Yes, and according to the PEP they were introduced to help reduce errors. ;-) Cheers, Ron From drochom at googlemail.com Thu Sep 15 11:33:49 2005 From: drochom at googlemail.com (drochom) Date: 15 Sep 2005 08:33:49 -0700 Subject: Removing duplicates from a list In-Reply-To: <1126796020.723737.124730@g47g2000cwa.googlegroups.com> References: <1126697915.879705.300450@g44g2000cwa.googlegroups.com> <1126706415.609072.92570@o13g2000cwo.googlegroups.com> <1126793332.635421.18630@g44g2000cwa.googlegroups.com> <1126794488.141927.9990@g49g2000cwa.googlegroups.com> <1126796020.723737.124730@g47g2000cwa.googlegroups.com> Message-ID: <1126798429.926312.25050@g43g2000cwa.googlegroups.com> thanks, nice job. but this benchmark is pretty deceptive: try this: (definition of unique2 and unique3 as above) >>> import timeit >>> a = range(1000) >>> t = timeit.Timer('unique2(a)','from __main__ import unique2,a') >>> t2 = timeit.Timer('stable_unique(a)','from __main__ import stable_unique,a') >>> t2.timeit(2000) 1.8392596235778456 >>> t.timeit(2000) 51.52945844819817 unique2 has quadratic complexity unique3 has amortized linear complexity what it means? it means that speed of your algorithm strongly depends on len(unique2(a)). the greater distinct elements in a the greater difference in execution time of both implementations regards przemek From miki.tebeka at zoran.com Thu Sep 1 07:36:47 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 1 Sep 2005 14:36:47 +0300 Subject: py2exe and output executable name Message-ID: <20050901113647.GO2656@zoran.com> Hello All, Is there a way to tell py2exe to create an executable with arbirary name? Currently the executable name is the script name with .exe suffix. Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From fakeaddress at nowhere.org Wed Sep 14 04:18:41 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 14 Sep 2005 08:18:41 GMT Subject: Builtin classes list, set, dict reimplemented via B-trees In-Reply-To: References: Message-ID: barnesc at engr.orst.edu wrote: > Hi again, > > Since my linear algebra library appears not to serve any practical > need (I found cgkit, and that works better for me), I've gotten bored > and went back to one of my other projects: reimplementing the Python > builtin classes list(), set(), dict(), and frozenset() with balanced > trees (specifically, counted B-trees stored in memory). [...] > So my question is: are there any other *practical* applications of a > B-tree based list/set/dict ? In other words, is this module totally > worth coding, or is it just academic wankery and theoretical flim > flam ? :) B-trees are specifically designed for disk storage. Seeking to a page takes much longer than reading a page of several kilobytes. B-trees read the keys for a many-way comparison in one seek. For in-memory comparison-based dictionaries, Red-Black trees, AVL trees, 2-3 trees, or skip-lists, are a better choice. -- --Bryan From JustinStraube at notmymailbox.com Sun Sep 4 17:27:42 2005 From: JustinStraube at notmymailbox.com (Justin Straube) Date: Sun, 04 Sep 2005 16:27:42 -0500 Subject: how to do this? In-Reply-To: <9cvSe.3820$3R1.2590@fe06.lga> References: <9cvSe.3820$3R1.2590@fe06.lga> Message-ID: <1yJSe.14785$aR1.2931@fe07.lga> Thanks Steve and Peter, these two methods are a lot of help. Ill have to play with each in my actual app to find which works best. I found more info on trace_variable() at http://effbot.org/tkinterbook/variable.htm and also some more info on events and bindings at http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm Justin From martijn at metacase.com Wed Sep 21 01:50:05 2005 From: martijn at metacase.com (Martijn Iseger) Date: Wed, 21 Sep 2005 05:50:05 +0000 (UTC) Subject: Free seminar on domain-specific modeling References: Message-ID: <7c6fcb4c414d8c78ca098e94860@news.kolumbus.fi> > Martijn Iseger wrote: > >> Domain-specific modeling makes software development 5-10 times faster >> than approaches based on UML or MDA. It accelerates development and >> reduces complexity by automatically generating full code from >> higher-abstraction design models. >> > Wow, look everyone! A silver bullet! > Before slashing down in ignorance - educate yourself on www.dsmforum.org. After that: feel free to comment. I will make you look a lot more intelligent Peter Hansen. From mwh at python.net Fri Sep 9 04:30:02 2005 From: mwh at python.net (Michael Hudson) Date: Fri, 09 Sep 2005 08:30:02 GMT Subject: Possible improvement to slice opperations. References: <0BZSe.13427$xl6.12703@tornado.tampabay.rr.com> Message-ID: Ron Adam writes: > Magnus Lycka wrote: >> Ron Adam wrote: [...] >>> REVERSE ORDER STEPPING >>> ---------------------- >>> When negative steps are used, a slice operation >>> does the following. (or the equivalent) >>> >>> 1. reverse the list >>> 2. cut the reversed sequence using start and stop >>> 3. iterate forward using the absolute value of step. >> I think you are looking at this from the wrong perspective. >> Whatever sign c has: >> For s[a:b:c], a is the index for the first item to include, >> b is the item after the last to include (just like .end() in >> C++ iterators for instance), and c describes the step size. > > Yes, and that is how it "should" work. But.... > > With current slicing and a negative step... > > [ 1 2 3 4 5 6 7 8 9 ] > -9 -8 -7 -6 -5 -4 -3 -2 -1 -0 > > r[-3:] -> [7, 8, 9] # as expected > r[-3::-1] -> [7, 6, 5, 4, 3, 2, 1, 0] # surprise > > The seven is include in both cases, so it's not a true inverse > selection either. Did you read what Magnus said: "a is the index for the first item to include"? How could r[-3::x] for any x not include the 7? Cheers, mwh -- Windows 2000: Smaller cow. Just as much crap. -- Jim's pedigree of operating systems, asr From matthewleslie at [EDITME-HOTMAIL].com Thu Sep 22 13:30:10 2005 From: matthewleslie at [EDITME-HOTMAIL].com (Matt Leslie) Date: Thu, 22 Sep 2005 18:30:10 +0100 Subject: Python installation root directory problem References: Message-ID: Further diggingappears to show this is an instance of the problem documented here: http://tinyurl.com/82dt2 Running msiexec with logging revealed the following lines: MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property X MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property TARGETDIR MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property DLLDIR MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property USERNAME MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property COMPANYNAME MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property SOURCEDIR MSI (s) (48:F8) [18:15:47:990]: Ignoring disallowed property ROOTDRIVE Values were not being passed from the UI to the actual installation script as they were untrusted. This can be resolved as described in the link above by using SecureCustomProperties. I have therefore submitted this to the sourceforge bug tracker. Matt "Matt Leslie" wrote in message news:dgujtr$rlm$1 at news.ox.ac.uk... > Hi, > > I am trying to install python 2.4.1 on a windows XP machine. Whether I > choose to install 'for me' or 'for all users, and no matter where I select > as the root directory, the installer always puts the python root in C:\, > which is obviously a bit messy. > > I am running this instalaltion as a slightly restricted non-administrative > user, but I can create the C:\Python24 directory that I specified in the > installation program and put files in it, so I do not think this can be > the reason the installer fails. I have uninstalled python and deleted all > references to it in the registry, then reinstalled, and experienced the > same effect. > > Does anyone have any ideas what this might be? > > Thanks, > Matt > > From wierob at gmx.de Mon Sep 5 04:48:49 2005 From: wierob at gmx.de (Robert Wierschke) Date: Mon, 05 Sep 2005 10:48:49 +0200 Subject: Python Doc Problem Example: os.system In-Reply-To: <1125879393.873803.6790@g14g2000cwa.googlegroups.com> References: <1125879393.873803.6790@g14g2000cwa.googlegroups.com> Message-ID: Xah Lee schrieb: > Python Doc Problem Example: os.system > > Xah Lee, 2005-09 > > today i'm trying to use Python to call shell commands. e.g. in Perl > something like > > output=qx(ls) > > in Python i quickly located the the function due to its > well-named-ness: > > import os > os.system("ls") > > > however, according to the doc > http://www.python.org/doc/2.4/lib/os-process.html the os.system() > returns some esoteric unix thing, not the command output. The doc > doesn't say how to get the output of the command. > The os.popen(...) function will return a file like object, so you can use a read() - method of these object to get the called programms output. hope that helps - I' m very new to python The documentation may be not well for all circumstances but the fine thing is: the documentation is part of the code itself - inform of the docstrings - and this is a very good approach. The bad thing is the person who wrote the docstring was documenting his/her own code and not code of other programmers. From fakeaddress at nowhere.org Sun Sep 11 19:43:15 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 11 Sep 2005 23:43:15 GMT Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> Message-ID: Tim Peters wrote: > [Bryan Olson, on the problem at > http://spoj.sphere.pl/problems/SUPPER/ > ] > >>I never intended to submit this program for competition. The >>contest ranks in speed order, and there is no way Python can >>compete with truly-compiled languages on such low-level code. >>I'd bet money that the algorithm I used (coded in C) can run >>with the winners. I also think I'd wager that the Python version >>outright trumps them on code size. > > Oh, it's not that bad . I took a stab at a Python program for > this, and it passed (3.44 seconds). [...] > I didn't make any effort to speed this, beyond picking a reasonable > algorithm, so maybe someone else can slash the runtime Hmmm ... I used the Theta(n lg n) algorithm ... how the heck... Aha! The 'bisect' module changed since last I looked. It still has the Python implementation, but then the last few lines say: # Overwrite above definitions with a fast C implementation try: from _bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect except ImportError: pass Binary-search is the inner-loop in this algorithm. I wrote my own binary-search, so I was executing Theta(n lg n) Python statements. Tim's use of bisect means that his inner-loop is in C, so he does Theta(n) Python statements and Theta(n lg n) C statement. The key to fast Python: use a good algorithm, and keep the inner loop in C. -- --Bryan From mekstran at scl.ameslab.gov Thu Sep 1 16:44:36 2005 From: mekstran at scl.ameslab.gov (Michael Ekstrand) Date: Thu, 1 Sep 2005 15:44:36 -0500 Subject: Add lists to class? Message-ID: <6234b28fda337c24884d04c14426e2e0@scl.ameslab.gov> On Sep 1, 2005, at 3:18 PM, BBands wrote: > Something like: > > class master: > def __init__(self, list): > self.count = len(list) > for line in list: > self.line = [] # obviously this doesn't work No, but this does: class master: def __init__(self, lst): for line in list: setattr(self, line, []) From library reference section 2.1, Built-In Functions: --8<-- setattr( object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123. --8<-- - Michael From sybrenUSE at YOURthirdtower.com.imagination Fri Sep 16 11:21:03 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 16 Sep 2005 17:21:03 +0200 Subject: Wrapper module for Linux shared lib References: <1126882155.941208.240150@g49g2000cwa.googlegroups.com> Message-ID: Ernesto enlightened us with: > What's the best resource for finding out how to write a wrapper > module for a shared library file *.so* in Linux? The extension documentation on the python website. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From martijn at metacase.com Thu Sep 22 02:07:37 2005 From: martijn at metacase.com (Martijn Iseger) Date: Thu, 22 Sep 2005 06:07:37 +0000 (UTC) Subject: Free seminar on domain-specific modeling References: Message-ID: <7c6fcb4c4b338c78d6c3639a15d@news.kolumbus.fi> Hello Michael, > The alternate point is that during computing history, many, many, many > promises were made for many, many, many, technologies based on the > same principle of raising the abstraction level. Many, many, many of > those technologies promised much and failed to deliver on their claims > when used beyond the people inventing/using those technologies. True, DSM however is not so much a new method for develping software. It's been used since the early 1990ies as far as I know and seen many sccessful implementations of it in varying sectors of industry: From mobile phones (Nokia uses it to develop the software running in all their phones) to IP switching platforms (Lucent), CRM systems, pacemakers, home automation systems, J2EE-based B2B portals (insurance industry), car infotainment systems (Audi A6), messaging systems (USAF), enterprise apps on smartphones (Nokia series60), Tooling industry and many more. Success with DSM depends on several factors like a common platform used for developing applications or variants of applications and the presence of domain-expertise: That leaves out one-time projects. > One thing is relatively clear - your approach appears to include a > graphical approach to systems building. Personally I suspect that the > fact people are able to engage other parts of their brain when > building these systems beyond linguistic is the real reason you see > benefits, rather than actually the specific thing that led to the > visual approach being possible. It is actually based on the graphical approach. The important thing I see here is that specific instances of this approach are defined by a company's expert developer instead of by a standards-body or a vendor, this puts the expert in the driver-seat so to say, he/she gets the ability to formalize (changing) development practices in his/her problem domain for the rest of the (less experienced) developers to follow automatically. Instead of adopting a one-size-fits-all approach companies/developers get to tailor the approach to the specific needs of their unique problem domain. It does not eliminate coding but attempts to minimize the need for it and leave it to the people who are really good at it. > (On a sad note it looks like you're reinvented how hardware is > designed and made, but not made the intuitive leap :-/ ) I suppose you mean software here? It seems I fail to make the "leap" towards understanding what you mean with this, feel free to elaborate. Regards, Martijn From steve at holdenweb.com Thu Sep 1 21:39:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Sep 2005 20:39:14 -0500 Subject: 'isa' keyword In-Reply-To: References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> Message-ID: phil hunt wrote: > On 1 Sep 2005 00:52:54 -0700, talin at acm dot org wrote: > >>The "isa" operator would of course be overloadable, perhaps by an >>accessor functions called __isa__, which works similarly to >>__contains__. The potential uses for this are not limited to >>isinstance() sugar, however. For example: >> >> if image isa gif: >> elif image isa jpeg: >> elif image isa png: > > > What's wrong with: > > if image.isa(gif): > elif image.isa(jpeg): > elif image.isa(png): > > In short, I see no need to add further complexity to Python's > grammar. > > It could be argued of course, that an OOPL should allow methods to > be sent with a grammar: > > receiver selector argument > > (which is almost what Smalltalk does), but you're not arguing for > that (and I'm not sure it would work with the rest of python's > grammar). > Even if it did it might mangle operator precedence in the same way SmallTalk did, which I always felt was one of the least attractive features" of the language. I don't think a change to a message-passing paradigm would necessarily benefit Python at this stage. Some people are still under the misapprehension that message-passing is a fundamental of object-oriented programming because of Smalltalk, but they are wrong. The addition of an "isa" operator would be an unnecessary addition of pure syntactic sugar. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From __peter__ at web.de Sun Sep 4 04:10:33 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Sep 2005 10:10:33 +0200 Subject: discarded iterator.next() at interactive global scope doesn't bump interator?? References: <431a9953.561032291@news.oz.net> Message-ID: Bengt Richter wrote: [it.next() appears to be a noop in the interactive interpreter] > I guess it could be in the read-eval-print loop Indeed: >>> for i in range(5): ... 42 ... 42 42 42 42 42 Whereas: >>> for i in range(5): ... None >>> Every line with an expression that doesn't evaluate to None is echoed. Therefore it.next() and print it.next() look the same when repr(it.next()) == str(it.next()). No bug :-) Peter From mitsura at skynet.be Wed Sep 14 07:26:11 2005 From: mitsura at skynet.be (mitsura at skynet.be) Date: 14 Sep 2005 04:26:11 -0700 Subject: some advice about Python GUI apps Message-ID: <1126697171.226696.234550@g44g2000cwa.googlegroups.com> Hi, I am writing a program in Python and I am using wx.Python for the GUI. I have no prior GUI and Python experience so that's why I turn to the specialists for aid. Basically, my app is a wx.tree object with items. You can click on each item and set some properties of the item (Pydata). To set the properties of an item you click on the item and then a 'Set item properties' window pops up. However, I am looking for a way that you can only open 1 property window per item. If I click on an item the 'Set item properties' windows open but when I return to the tree window and select the same item, I can open an additional 'set properties' window. This leads to all kind of C++ errors because these properties windows seems to interfere for some reason. I don't have enough OO/Python/GUI knowledge yet to fully understand what actually happens. Basically, what I want is that when you want to open an items property window and the window is alread open that in stead of opening a new window, the window the is already open pops to the foreground. Any ideay how I can implement this. Another solution would be to start the properties windows in a 'synchronous' mode, meaning that if this window is open, that you can't manipulate the tree window anymore (~like in Word when you open the 'open file' window, you can't edit your doc until you this window is closed again). I hope this makes some sense. Any help much appreciated. Kris Ps.: any refs to good OO/Python GUI books are also welcome (or URLs) From oliver.andrich at gmail.com Thu Sep 8 16:18:12 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Thu, 8 Sep 2005 22:18:12 +0200 Subject: Python Jabber client? In-Reply-To: <7x1x3zmii2.fsf_-_@ruckus.brouhaha.com> References: <7x1x3zmii2.fsf_-_@ruckus.brouhaha.com> Message-ID: <6f7b52d0509081318204e034d@mail.gmail.com> Hi Paul, take this one. http://xmpppy.sourceforge.net/ It is used inside gajim, my favorite jabber client. http://gajim.org/ It works like a charm. And I am also using xmpppy for some monitoring tools, that alert our admins. Best regards, Oliver -- Oliver Andrich --- http://roughbook.de/ From llemmens at gmx.net Tue Sep 27 18:38:23 2005 From: llemmens at gmx.net (Lucas Lemmens) Date: Wed, 28 Sep 2005 00:38:23 +0200 Subject: Silly function call lookup stuff? References: Message-ID: On Tue, 27 Sep 2005 13:56:53 -0700, Michael Spencer wrote: > Lucas Lemmens wrote: >> Dear pythonians, >> >> I've been reading/thinking about the famous function call speedup trick >> where you use a function in the local context to represent a "remoter" >> function to speed up the 'function lookup'. >> >> "This is especially usefull in a loop where you call the function a >> zillion time" they say. >> >> I think this is very odd behavior. >> >> Why isn't the result of the first function-lookup cached so that >> following function calls don't need to do the function-lookup at all? >> > I guess because the function name may be re-bound between loop iterations. > Are there good applications of this? I don't know. Yuk I'd hate that. I think it would be extremely rare. Would the myLocalFunc = hisRemoteFunc optimization break in such a case? If not then why not auto-add a local hisRemoteFunc that points to the remote hisRemoteFunc to the local context when hisRemoteFunc is executed for the first time. > >> And if the context changes (an import-statement say) reset the cached >> 'function-lookups'. > > In general an object doesn't know what names are bound to it and there are > many ways besides an import statement of binding/re-binding, so "if the > context changes" is easier said than done. > My guess (but I'm not a python programmer) is that context changes would be the odd case. So optimizing for not having them ... > >> This way any function would only need to be looked up once. >> >> L. >> > Would you apply this optimization to all lookups in outer scopes, or just > callables? Why? ;-) Hmmm callables have probably the highest chance of being recalled. > > Michael From aahz at pythoncraft.com Sat Sep 10 13:16:23 2005 From: aahz at pythoncraft.com (Aahz) Date: 10 Sep 2005 10:16:23 -0700 Subject: OpenSource documentation problems References: <20050903040959.7EBB.3.NOFFLE@dieschf.news.arcor.de> <86zmql28fv.fsf@bhuda.mired.org> Message-ID: In article , Michael Ekstrand wrote: >On Fri, 09 Sep 2005 18:16:36 -0400 >Mike Meyer wrote: >> >> You need a better browser. Mine - at least on Unix - have an option to >> dump textareas into text files, invoke my favorite editor on them, and >> then read the file back in when the editor exits. Assuming i'm not >> running the browser in that editor in the first place. > >Which browser might this be? I am curious. Lynx -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From bokr at oz.net Sun Sep 11 18:14:41 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 11 Sep 2005 22:14:41 GMT Subject: python callbacks and windows References: <1126261209.412057.142160@o13g2000cwo.googlegroups.com> Message-ID: <4324a196.1218507851@news.oz.net> On 9 Sep 2005 03:20:09 -0700, davidstummer at gmail.com wrote: >I was wondering if anyone could point me to an example. Currently i >have a c++ program which calls and c++ dll (i created both). The dll >uses SendMessage to pass messages back to the calling .exe, and the >.exe process the messages in it's Windows Procedure function >WindProc(). > This sounds like your main program is ordinary C++ GUI and the dll could be anything, but you probably cause it to be loaded and initialized at least from the GUI main prog, maybe just by automatic dependency loading. It is not clear whether you have a lot of code and would like to use python for some aspect of processing special messages, or whether you have a tentative start in C++ for an application you'd rather develop entirely in python. What you want to do next will probably depend on what you have. >What i want is to receive these messages ( the contents of each message >will be plain text), in python using a callback (i think this is what i >need). I would guess that if you want to use windows messages, it might be easiest to receive them in the main message loop and to recognize the special messages there (vs all the standard windows stuff) and at that point call from C++ to python to process the plain text contents. The question is what do you want to get back, and what side effects and state-ful processing might you want to do, and if there is state, do you want to maintain it in python or C++, and how to you want to access from the other side if you need to. Calling from C++ to python and vice versa is discussed in the docs re extensions and embedding etc. (See http://python.org/doc/ links to "Extending and Embedding" and "Python/C API") > >I don't know whether (or if it's possible) to implement the windows >procedure and stuff in python, eliminating the need for the .exe >altogether. Have you looked at tkinter? It will let you make a GUI that runs under windows, and then you can code in python. > >or should i do it the other way, to add a callback function in python, >and for the windows procedure in the .exe to call this python callback? > >in any case, some simple code examples would be great. > I would suggest downloading the python sources zip or tgz in addition to the standard installation (which presumably you already have). The reason is that the sources contain a demo subdirectory with useful examples of what can be done with tkinter (and other stuff as well). Some of it could stand to be updated to take advantage of current python, but you can run the demo examples and modify them to learn a lot about what can be done. Regards, Bengt Richter From rrr at ronadam.com Wed Sep 21 22:14:57 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 22 Sep 2005 02:14:57 GMT Subject: Finding where to store application data portably In-Reply-To: References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> <4331af69$0$15056$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Steven D'Aprano wrote: > On Wed, 21 Sep 2005 20:07:54 +0100, Tony Houghton wrote: > > >> > I wish the Linux Standard Base folks would specify that settings files >> > should all go into a subdirectory like ~/settings rather than filling up >> > the home directory with cruft. That was acceptable in the days when >> > people >> > only looked at their files with ls, but in these days of GUI file >> > managers, it is ridiculous that there are more than 100 dot files and >> > directories in my home directory. >> >>Don't all file managers have an option to hide files beginning with '.'? > > > I don't want to hide them. I just don't want them in my face when I open > my home directory. +1 This has been a gripe of mine on windows as well, and hiding files (or extensions) is definitely not the answer. Personally I think hidden files do more harm than good. It's not a substitute for good file management, and it not an acceptable alternative to good security either. Cheers, Ron From mekstran at iastate.edu Thu Sep 29 10:34:40 2005 From: mekstran at iastate.edu (Michael Ekstrand) Date: Thu, 29 Sep 2005 09:34:40 -0500 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7x4q84s13w.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7x4q84s13w.fsf@ruckus.brouhaha.com> Message-ID: <200509290934.42587.mekstran@iastate.edu> On Thursday 29 September 2005 03:57, Paul Rubin wrote: > I can't think of a single time that I've ever seen a legitimate use > of name mangling to reach from one class into another in a Python > application (I don't count something like a debugger). If you're got > some concrete examples I wouldn't mind looking. I've done it in one project, my YaPIE library (http://sourceforge.net/projects/yapie). But it's kinda ugly, and probably not the right way to do things, and I don't even use the library myself anymore (it grew out of frustration with some XML parsing issues, before I did a little Java and learned to use SAX). -Michael From jeffrey.schwab at rcn.com Wed Sep 28 21:58:15 2005 From: jeffrey.schwab at rcn.com (Jeff Schwab) Date: Wed, 28 Sep 2005 21:58:15 -0400 Subject: 1 Million users.. I can't Scale!! In-Reply-To: References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> <17210.62571.387969.713030@montanaro.dyndns.org> <433B0B38.7040406@bellsouth.net> Message-ID: skip at pobox.com wrote: > Jeff> How many are more than "a few?" > > I don't know. What can you do today in commercial stuff, 16 processors? > How many cores per die, two? Four? We're still talking < 100 processors > with access to the same chunk of memory. For the OP's problem that's still > 10,000 users per processor. Maybe that's small enough, but if not, he'll > need multiple processes across machines that don't share memory. Sure, multiple machines are probably the right approach for the OP; I didn't mean to disagree with that. I just don't think they are "the only practical way for a multi-process application to scale beyond a few processors," like you said. For many (most?) applications in need of serious scalability, multi-processor servers are preferable. IBM has eServers available with up to 64 processors each, and Sun sells E25Ks with 72 processors apiece. I like to work on those sorts of machine when possible. Of course, they're not right for every application, especially since they're so expensive. From fredrik at pythonware.com Wed Sep 21 08:53:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Sep 2005 14:53:20 +0200 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> Message-ID: Christophe wrote: > > def drawline(p1, p2): > > # draw a line from p1 to p2 > > foo(*p1) > > bar(*p2) > > > > That one is stupid. I don't see how you can make it work without some > global storing the p1 information in foo which I would consider as very > ugly code. if you cannot see how that can work, you clearly haven't done much graphics programming in your days... From fredrik at pythonware.com Thu Sep 1 11:09:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Sep 2005 17:09:27 +0200 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> Message-ID: Rocco Moretti wrote: > Something a simple as allowing doc bugs to be submitted from a webform > w/o login would reduce the barrier to contribute. - Increasing the size > of the "About" text wouldn't hurt either. (To be honest, I've never > noticed that text before, and it never occurred to me look at the > "About" page for information on error reports.) the useredit approach I'm using over at the librarybook site works pretty well. for example, if you go to http://effbot.org/librarybook/mailbox.htm and click "suggest changes" at the bottom, you can edit the page source, preview the changes, and generate a patch when you're done, all without signing up or logging in. (unfortunately, Python's documentation is written in LaTeX, using a rather advanced tool chain to get from sources to HTML, so the librarybook approach won't really work "out of the box") From grisha at apache.org Mon Sep 19 21:55:04 2005 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Mon, 19 Sep 2005 21:55:04 -0400 Subject: ANNOUNCE: Mod_python 3.2.2 Beta Message-ID: <20050919214954.S45391@grisha.dyndns.org> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the 3.2.2 Beta release mod_python. Version 3.2.2b of mod_python features several new functions and attributes providing better access to apache internals, file-based sessions and other session improvements, as well as many bug fixes and various performance and security improvements. A detailed description of the changes is available in Appendix A of the mod_python manual, also available here: http://www.modpython.org/live/mod_python-3.2.2b/doc-html/node97.html Beta releases are NOT considered stable and usually contain bugs. This release is intended to solicit widespread testing of the code. We strongly recommend that you try out your existing applications and experiment with new features in a non-production environment using this version and report any problems you may encounter so that they can be addressed before the final release. Preferred method of reporting problems is the mod_python user list mod_python at modpython.org. Mod_python 3.2.2b is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit http://www.modpython.org/ Regards, Grisha Trubetskoy and the Apache mod_python team. From pinard at iro.umontreal.ca Fri Sep 23 12:15:29 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 23 Sep 2005 12:15:29 -0400 Subject: NaN Vs None In-Reply-To: <5CFEFDB5226CB54CBB4328B9563A12EE02B701BF@hqemail2.spss.com> References: <5CFEFDB5226CB54CBB4328B9563A12EE02B701BF@hqemail2.spss.com> Message-ID: <20050923161529.GA10441@phenix.progiciels-bpi.ca> [Peck, Jon] > In choosing a way to represent a value of "no information" for a > float, would it be better to use NaN or None? None has the advantage > of standard behavior across platforms, but NaN seems to propagate more > easily ? at least on Windows. [...] What I do for these things is creating a Missing type which behaves like a number, that is, it has all __FUNCTION__ magic required by numbers. I then create either a single missing constant or very few such missing constants, in which case each one representing a particular way or flavor of a missing number (unknown, not applicable, uncomputable, etc.) The magic functions for Missing should know how to combine the few missing constants with numbers, and with other missing constants, for returning the "proper" one. It's easier with only one missing constant. You also need to take care of comparisons and logical operators on missing values. My usual convention is that missing values propagate within booleans and behave like False when tested. Sometimes, I also need "missing" strings. That's more difficult to implement, because of the numerous string methods and ramifications. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From http Tue Sep 6 04:27:31 2005 From: http (Paul Rubin) Date: 06 Sep 2005 01:27:31 -0700 Subject: python profiling, hotspot and strange execution time References: <1125995101.301148.158900@g47g2000cwa.googlegroups.com> Message-ID: <7xwtlu4n4c.fsf@ruckus.brouhaha.com> cournape at gmail.com writes: > I have some scientific application written in python. There is a > good deal of list processing, but also some "simple" computation such > as basic linear algebra involved. I would like to speed things up > implementing some of the functions in C. So I need profiling. Why don't you use numarray for the linear algebra? From twic at urchin.earth.li Sun Sep 25 17:48:26 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 25 Sep 2005 22:48:26 +0100 Subject: Struggling with basics In-Reply-To: References: Message-ID: On Sun, 25 Sep 2005, Jason wrote: > A week ago I posted a simple little hi-score routine that I was using to > learn Python. > > I've only just managed to examine the code, and the responses that people > gave, and I'm now seriously struggling to understand why things aren't > working correctly. Others have dealt with the string printing problem, so i'll leave that. The problem with the sorting is that you're not consistent about how scores are represented - are they strings or integers? At present, you sometimes use one and sometimes the other, with the result that the sort basically pukes all over you. To fix this, pick one type (hint: integers), and use that consistently. I'll show you how to do that below (although it's not exactly hard). Oh, and i'm a picky git, so i'm going to point out some other flaws in the code! > At present my code is as follows... > > import random > import bisect > > class HiScores: > def __init__(self,hiScores): > self.hiScores=[entry for entry in hiScores] One bug and one wart here. The wart is the way you initialise self.hiScores - you use a list comprehension when you can just call the list builtin: self.hiScores = list(hiScores) The bug is that you don't sort the list. If you're certain that the initial set of high scores will always come sorted, that's okay, but i'd say it was good practice to sort them, just in case. In fact, i'd punt the addition to addScore: def __init__(self, hiScores): self.hiScores = [] for score, name in hiScores: self.addScore(score, name) This is the 'Once And Only Once' principle in action; the knowledge about how to keep the list sorted is expressed once and only once, in addScore; if any other parts of the code need to add items, they call that. This means there's only one piece of code you have to check to make sure it's going to get this right. > def showScores(self): > for score,name in self.hiScores: > score=str(score).zfill(5) > print "%s - %s" % name,score As has been pointed out, you need to wrap parens round "name, score" to make it into a tuple. Apart from that, i'd skip the string interpolation and just write: for score, name in self.hiScores: print name, "-", str(score).zfill(5) If you insist on the string interpolation, i'd still elide the intermediate variable and write: for score, name in self.hiScores: print "%s - %05i" % (name, score) The %05i in the format string means 'an integer, zero-filled to five digits'. Good, eh? > def addScore(self,score,name): > score.zfill(5) > bisect.insort(self.hiScores,(score,name)) > if len(self.hiScores)==6: > self.hiScores.pop() Two problems there. Well, two and a half. Firstly, the type confusion - are scores strings or integers? the zfill indicates that you're thinking in terms of strings here. You should be using integers, so you can just drop that line. And if you were working with strings, the zfill would still be wrong (this is the half problem!) - zfill doesn't affect the string it's called on (strings are immutable), it makes a new zero-filled string and returns it. You're not doing anything with the return value of that call, so the zero-filled string would just evaporate into thin air. Secondly, bisect.insort sorts the list so that the highest scores are at the tail end of the list; list.pop takes things off that same end, so you're popping the highest scores, not the lowest! You need to say pop(0) to specify that the item should be popped off the head (ie the low end) of the list. Also, i'd be tempted to program defensively and change the test guarding the pop to "while (len(self.hiScores > 6):". All in all, that makes my version: def addScore(self, score, name): bisect.insort(self.hiScores, (int(score), name)) while(len(self.hiScores) > 6): self.hiScores.pop(0) > def lastScore(self): > return self.hiScores[-1][0] This will return the top score; you want self.hiScores[0][0]. > def main(): > > hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] Here you've got scores as strings, and this is the root of the problem. Change this to: hiScores=[(10000,'Alpha'),(7500,'Beta'),(5000,'Gamma'),(2500,'Delta'),(0,'Epsilon')] Note that i've taken the leading zeroes off - leading zeroes on integers in python are a magic signal that the number is octal (yes, base eight!), which is not what you want at all. > a=HiScores(hiScores) > print "Original Scores\n---------------" > a.showScores() > > while 1: "while True:" is preferred here. > newScore=str(random.randint(0,10000)) Take out the str(). > if newScore > a.lastScore(): > print "Congratulations, you scored %s " % newScore Make that a %i (or a %05i). > name=raw_input("Please enter your name :") > a.addScore(newScore,name) > a.showScores() > > if __name__=="__main__": > main() Works like a charm! > The final part that's simply not working correctly is that the entire program > isn't sorting the data. > > If I run the program and get a score of, say, 6789, then when I add my name, > nothing is entered. I have changed the clause that deletes (pops) the last > array if the array count is 6 and seen what figures are being entered into > the array. > > Sure enough they are going in the array, and they are being sorted, but they > are only being sorted AFTER the 00000 of the initial array creation. > > I'm pretty sure it's to do with comparing a string against an integer > but can't for the life of me see where to force the comparrison to check > against two integers. Simple - you just make sure the scores are all integers in the first place! tom -- double mashed, future mashed, millennium mashed; man it was mashed From richard at fake.com Sun Sep 18 10:07:27 2005 From: richard at fake.com (richard) Date: Sun, 18 Sep 2005 09:07:27 -0500 Subject: complex data types? References: <1127017357.053187.45370@g43g2000cwa.googlegroups.com> Message-ID: "rixil at hotmail.com" wrote in news:1127017357.053187.45370 at g43g2000cwa.googlegroups.com: > At the same time, if array[0].songs equals array[1] songs, you are > probably initializing both array[0] and array[1] with the same object. > Since array[0] and array[1] both refer to the same object, a change to > one will be reflected in the other. > > I hope this is what you're looking for. > > Michael Loritsch I believe that was one of the things I was doing. thanks From mwm at mired.org Fri Sep 30 20:05:44 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 30 Sep 2005 20:05:44 -0400 Subject: Will python never intend to support private, protected and public? References: <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7xbr2btv84.fsf@ruckus.brouhaha.com> <7xy85fvxny.fsf@ruckus.brouhaha.com> Message-ID: <86vf0inlt3.fsf@bhuda.mired.org> Paul Rubin writes: > OTOH, "private" lets you say 100% for certain that another class > didn't clobber __xyz, and that any bug that clobbered it MUST reside > in the class that declared it. That makes auditing for __xyz-related > errors a lot simpler since you only have to look in one class for them. Horse pucky. >>> class Fools(object): ... _bar = "my private list of values".split() ... def broken(self, breaker): ... breaker(self._bar) ... >>> class Kings(object): [Elided, because you said you don't need it.] >>> fool = Fools() >>> king = Kings() >>> fool.broken(king.get_victim) >>> king.breakit() >>> fool._bar [] >>> So, fool._bar is now clobbered. Nuts, the _bar attribute is broken for *every* instance of Fools. According to you, the error must be in Fools. Care to point it out? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From varunhiremath at iitm.ac.in Fri Sep 2 06:02:09 2005 From: varunhiremath at iitm.ac.in (Varun Hiremath) Date: Fri, 2 Sep 2005 15:32:09 +0530 Subject: plotting with gnuplot.py In-Reply-To: <1125653745.659417.134620@z14g2000cwz.googlegroups.com> References: <1125653745.659417.134620@z14g2000cwz.googlegroups.com> Message-ID: <20050902100209.GA7427@god.godsdomain> On Fri, Sep 02, 2005 at 02:35:45AM -0700, skorpio11 at gmail.com wrote: > Hi, > > I've been having some problems trying some basic plotting commands with > gnuplot.py. My setup is the Python 2.3 Enthought edition and my script > looks as: > > from scipy import * > from scipy import gplt > import scipy.io.array_import > #import Gnuplot > > filename = ('Default.PL1') > data = scipy.io.array_import.read_array(filename) > > > y = data[:,1] > x = data[:,0] > z = data[:,2] > gplt.plot(x,y,'with points') > gplt('set logscale x') > gplt('set logscale y') > > > With the following error message: > > --->gplt('set logscale x') > TypeError: 'module' object is not callable > warning: Failure executing file: > > Any help would appreciated... Hi, Try doing this: import Gnuplot,Numeric filename = ('Default.PL1') data = scipy.io.array_import.read_array(filename) y = data[:,1] x = data[:,0] z = data[:,2] //I think u need to take the transpose of this column before plotting.. x=Numeric.transpose(x) y=Numeric.transpose(y) g=Gnuplot.Gnuplot() d=Gnuplot.Data(x,y) g('set logscale xy') g.plot(d) It should work... Bye -- ----------------------------------------------- Varun Hiremath 461, Jamuna Hostel IIT Madras, Chennai - 600 036 mob : +919840299732 ----------------------------------------------- My Webpage : http://www.ae.iitm.ac.in/~ae03b032 ----------------------------------------------- From mekstran at iastate.edu Thu Sep 29 10:46:36 2005 From: mekstran at iastate.edu (Michael Ekstrand) Date: Thu, 29 Sep 2005 09:46:36 -0500 Subject: converting Word to MediaWiki In-Reply-To: References: Message-ID: <200509290946.36562.mekstran@iastate.edu> On Thursday 29 September 2005 07:43, Peter Hansen wrote: > Are the two necessarily in conflict? Perl can save your butt and > _still_ suck! Hear, hear! Although I think it's the vi user in me that makes me like Perl... - Michael From http Wed Sep 7 19:15:45 2005 From: http (Paul Rubin) Date: 07 Sep 2005 16:15:45 -0700 Subject: encryption with python References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <1126128663.573686.148670@g44g2000cwa.googlegroups.com> Message-ID: <7xoe74eafy.fsf@ruckus.brouhaha.com> James Stroud writes: > Then your best bet is to take a reasonable number of bits from an sha hash. > But you do not need pycrypto for this. The previous answer by "ncf" is good, > but use the standard library and take 9 digits to lessen probability for > clashes > > import sha > def encrypt(x,y): > def _dosha(v): return sha.new(str(v)).hexdigest() > return int(_dosha(_dosha(x)+_dosha(y))[5:13],16) > ... > Each student ID should be unique until you get a really big class. If your > class might grow to several million, consider taking more bits of the hash. Please don't give advice like this unless you know what you're doing. You're taking 8 hex digits and turning them into an integer. That means you'll probably have a collision after around 65,000 id's, not several million. "Probably" means > 50%. You'll have a significant chance (say more than 1%) of collision after maybe 10,000. Also, if you know the student's graduation year, in most cases there are just a few hundred likely birthdates for that student, so by brute force search you can crunch the output of your function to a fairly small number of DOB/SSN combinations. The only approach that makes sense is for the secure database to assign arbitrary numbers that aren't algorithmically related to any sensitive data. Answers involving encryption will need to use either large ID numbers or secret keys, both of which will cause hassles. From jjl at pobox.com Sat Sep 24 06:39:13 2005 From: jjl at pobox.com (John J. Lee) Date: 24 Sep 2005 10:39:13 +0000 Subject: Using distutils 2.4 for python 2.3 References: Message-ID: <87hdcaycku.fsf@pobox.com> Noam Raphael writes: > Fredrik Lundh wrote: > > > > you can enable new metadata fields in older versions by assigning to > > the DistributionMetadata structure: > > > > try: > > from distutils.dist import DistributionMetadata > > DistributionMetadata.package_data = None > > except: > > pass > > > > setup( > > ... > > package_data=... > > ) > > > > > > I tried this, but it made python2.4 behave like python2.3, and not > install the package_data files. > > Did I do something wrong? I'm *guessing* should have been something like (untested): from distutils.dist import DistributionMetadata try: DistributionMetadata.classifiers except AttributeError: DistributionMetadata.classifiers = None setup( ... classifiers=... ) John From stefano at pragma2000.com Fri Sep 9 11:17:38 2005 From: stefano at pragma2000.com (Stefano Masini) Date: Fri, 9 Sep 2005 17:17:38 +0200 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: <432742240509090817230df311@mail.gmail.com> On 8 Sep 2005 08:24:50 -0700, Fuzzyman wrote: > What is pythonutils ? > ===================== > ConfigObj - simple config file handling > validate - validation and type conversion system > listquote - string to list conversion > StandOut - simple logging and output control object > pathutils - for working with paths and files > cgiutils - cgi helpers > urlpath - functions for handling URLs > odict - Ordered Dictionary Class Fuzzyman, your post reminded me of something I can't stop thinking about. Please don't take this as a critique on your work. I place myself on the same side of yours. I just wanted to share this thought with everybody had an opinion about it. I wonder how many people (including myself) have implemented their own versions of such modules, at least once in their pythonic life. I indeed have my own odict (even same name! :). My own pathutils (different name, but same stuff). My own validate... and so forth. This is just too bad. There are a few ares where everybody seems to be implementing their own stuff over and over: logging, file handling, ordered dictionaries, data serialization, and maybe a few more. I don't know what's the ultimate problem, but I think there are 3 main reasons: 1) poor communication inside the community (mhm... arguable) 2) lack of a rich standard library (I heard this more than once) 3) python is such an easy language that the "I'll do it myself" evil side lying hidden inside each one of us comes up a little too often, and prevents from spending more time on research of what's available. It seems to me that this tendency is hurting python, and I wonder if there is something that could be done about it. I once followed a discussion about placing one of the available third party modules for file handling inside the standard library. I can't remember its name right now, but the discussion quickly became hot with considerations about the module not being "right" enough to fit the standard library. The points were right, but in some sense it's a pity because by being in the stdlib it could have had a lot more visibility and maybe people would have stopped writing their own, and would have begun using it. Then maybe, if it was not perfect, people would have begun improving it, and by now we would have a solid feature available to everybody. mhm... could it be a good idea to have two versions of the stdlib? One stable, and one testing, where stuff could be thrown in without being too picky, in order to let the community decide and improve? Again, Fuzzyman, your post was just the excuse to get me started. I understand and respect your work, also because you put the remarkable effort to make it publicly available. That's my two cents, stefano From pwatson at redlinepy.com Fri Sep 2 16:40:02 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 02 Sep 2005 15:40:02 -0500 Subject: Proposal: add sys to __builtins__ In-Reply-To: References: Message-ID: <3nrrljF32nu3U1@individual.net> Steve Holden wrote: > Rick Wotnaz wrote: > >> Michael Hoffman wrote in >> news:df7jlu$1te$1 at gemini.csx.cam.ac.uk: >> >>> What would people think about adding sys to __builtins__ so that >>> "import sys" is no longer necessary? This is something I must >>> add to every script I write that's not a one-liner since they >>> have this idiom at the bottom: >>> >>> if __name__ == "__main__": >>> sys.exit(main(sys.argv[1:])) >>> >>> Additionally, the necessity of "import sys" makes some >>> one-liners a little more unwieldy than they should be--it is >>> surely the module I am missing the most in one-liners. For >>> example, with this proposal, this inelegant one-liner: >>> >>> $ python -c "import sys; print >>> ''.join(sorted(sys.stdin.readlines()))" >>> could be replaced by: >>> >>> $ python -c "print ''.join(sorted(sys.stdin.readlines()))" >>> >>> Since sys is surely the most commonly used module (it is >>> imported in 108 of 188 Python 2.4 stdlib modules on my system, >>> and certainly more than any other module), I would hope few >>> people would be affected by a namespace collision. >>> >>> Other languages (e.g. C#) always make their system namespace >>> available without needing a special import. >>> >>> In short, given the wide use of sys, its unambiguous nature, and >>> the fact that it really is built-in already, although not >>> exposed as such, I think we would be better off if sys were >>> always allowed even without an import statement. >> >> >> >> +1 here. As far as I'm concerned, both os and sys could be special- >> cased that way. That said, I would guess the likelihood of that >> happening is 0. > > I wonder if it would be worth special-casing the AttributeError > exception handling at the outermost lexical scope to try and import a > module with the troublesome name and then retrying the attribute access > if the import succeeded (possibly even from a path limited to the > standard locations). > > That way none of the standard library modules would need to be imported > before use. > > I can see that this would create problems as well as solving some, but > it would be nice not to have to import the standard library modules. I > don't personally find it a hardship, but some people do. > > though-i-could-just-be-raving-ly y'rs - steve This sounds pretty interesting. How about a switch to invoke this handling for the one-liner crowd and those who wish to use it? Somehow, I never heard any C programmers suggest that the default processing not include the need for: #include From hancock at anansispaceworks.com Fri Sep 16 11:58:48 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 16 Sep 2005 10:58:48 -0500 Subject: Self reordering list in Python In-Reply-To: <432AA685.5040709@designaproduct.biz> References: <1126852721.347855.278870@g14g2000cwa.googlegroups.com> <432AA685.5040709@designaproduct.biz> Message-ID: <200509161058.48155.hancock@anansispaceworks.com> On Friday 16 September 2005 06:03 am, Laszlo Zsolt Nagy wrote: > You are right in that holding a reference will have a better time > complexity. But holding a reference makes it impossible to free the > object. :-) As I said, my list has a maximum length. I just can't store > any number of images in memory. I need to keep only the most frequently > used ones. I do not know which ones will be used the most frequently, > this is why I need a self reordering list. Accessing an element makes it > "more imporant" than the others. I already implemented this in Python > and it was ten times faster compared to the original version. (200 > frames per sec instead of 20 fps) This is actually the use-case for an "LRU cache"="least recently used cache", which is probably already implemented in Python somewhere (or even as a fast extension). I'd do a google search for it. It almost certainly would use a dictionary interface within Python, ISTM. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ml.sven at subscience.de Mon Sep 19 06:01:32 2005 From: ml.sven at subscience.de (sven) Date: Mon, 19 Sep 2005 12:01:32 +0200 Subject: Synchronous/Asynchrnous Audio play with pymedia In-Reply-To: <5BmXe.12387$nq.6569@lakeread05> References: <5BmXe.12387$nq.6569@lakeread05> Message-ID: <6.2.3.4.2.20050919120052.02a4d738@post.strato.de> At 01:22 19.09.2005, Ron Provost wrote: >Hello, > >I'm developing a piece of software to assist illiteraate adults to learn to >read. I'm trying to figure out how, if possible, to make audio playback >asynchrnous but still controllable. I'm using python 2.4 with pymedia on >XP. there's a pymedia mailing list at: https://lists.sourceforge.net/lists/listinfo/pymedia-users better ask there, the author of pymedia is generally very helpful in answering question. sven. From fabioz at esss.com.br Tue Sep 6 13:14:43 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Tue, 06 Sep 2005 14:14:43 -0300 Subject: ANN: PyDev 0.9.8.1 released In-Reply-To: <431341E3.6020103@esss.com.br> References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br><42E6412A.4020905@esss.com.br> <430632E3.9050403@esss.com.br><431341E3.6020103@esss.com.br> Message-ID: Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.8.1 has been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Details for Release: 0.9.8.1 Major highlights: ------------------- * Java 1.4 support reintroduced. * Styles added for syntax highlighting (bold and italic), contributed by Gerhard Kalab. Others that are new and noteworthy: ------------------------------------- * zombie process after exiting eclipse should not happen anymore * paths with '.' are accepted for the pythonpath (unless they start with a '.', because it may not accept relative paths). * relative imports are added to code-completion * local imports are taken into consideration when doing code completion * debugger has 'change support', so, changed variables in a scope appear red Cheers, Fabio -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From edreamleo at charter.net Wed Sep 21 09:40:36 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 21 Sep 2005 08:40:36 -0500 Subject: ANN: Leo 4.3.3 released Message-ID: Leo 4.3.3 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.3.3 fixes several bugs reported in Leo 4.3.2 final. To learn about Leo, see: http://webpages.charter.net/edreamleo/intro.html The highlights of 4.3.3 (and 4.3.2) ----------------------------------- - Improved Leo's documentation: - A tutorial introduction to Leo: http://webpages.charter.net/edreamleo/intro.html - A 5-minute guide to programming with Leo: http://webpages.charter.net/edreamleo/intro.html#quick-start-for-programmers - The new rst3 plugin creates .html and .tex files from reStructuredText embedded in Leo files. Any node of the source outline may contain options for the rst3 plugin, which makes this plugin much more useful and flexible than the previous rst plugins. All of Leo's documentation was created using this plugin from sources in LeoDocs.leo. For full documentation for rst3 see: http://webpages.charter.net/edreamleo/rstplugin3.html. - The spellpyx (spell checking) plugin is now much easier to use. - The vim and openWith plugins now use Python's subprocess module if it is present. - Improved the Pretty Printing command. - The usual assortment of bug fixes. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From grante at visi.com Mon Sep 19 12:11:29 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 19 Sep 2005 16:11:29 -0000 Subject: Searching for a working example of a curses application that resizes in xterm References: <1127126438.588171.73720@g44g2000cwa.googlegroups.com> Message-ID: <11itopholn7vbb5@corp.supernews.com> On 2005-09-19, schwerdy at web.de wrote: > can someone provide an example of a curses application that works in a > xterm that can be resized? I'm afraid I can't post the entire program, but what you need to do is to catch the WINCH signal and set a flag which is checked by your main "event" loop and handled. Here's the basic C code: static void sigwinchHandler(int sig) { (void) sig; sigwinchReceived = 1; } static void clipWindows(void) { tCh *ch; int x,y,rows,cols; for (ch = chlist; ch != NULL; ch = ch->next) { getbegyx(ch->win,y,x); getmaxyx(ch->win,rows,cols); clipwin(&rows,&cols,&y,&x); moveWindow(ch,rows,cols,y,x); } } main() { [...] sigact.sa_handler = sigwinchHandler; s = sigaction(SIGWINCH, &sigact, NULL); assert(s==0); // start up curses while (1) { // do stuff if (sigwinchReceived) { struct winsize size; if (ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0) { resizeterm(size.ws_row, size.ws_col); clipWindows(); } sigwinchReceived = 0; } } } -- Grant Edwards grante Yow! If I am elected no at one will ever have to do visi.com their laundry again! From tjreedy at udel.edu Thu Sep 1 22:42:02 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Sep 2005 22:42:02 -0400 Subject: descriptors for container items References: Message-ID: "Brock Filer" wrote in message news:ffdbcc8dcfa9ff84b34b3285e4d213a5 at softhome.net... > countries['us']['Colorado']['Denver']['@population'] > > This is going to be used in user-input formulae, so I'm willing to do a > lot of work for minor beautifications. I'd like to be able to say (I > know, the quotes are still ugly, but at least you save a bracket): > > countries/'us'/'Colorado'/'Denver'/'@population' > > That's easy to do with a __div__ method, but it only works for getting, > not setting or deleting. > > I'd appreciate any thoughts on this problem. I personally would first try to dump the quotes and use standard attributes -- countries.us.Colorado... -- and the __get/set/delattr__ methods. > I keep thinking descriptors might be involved somehow in the solution, > but I may be on a completely wrong track. As far as I know, 'descriptor' is a behind-the-scenes concept, not something you directly program with. Perhaps you meant 'property'. However, properties are fixed in number when you create the class. Terry J. Reedy From fredrik at pythonware.com Mon Sep 26 13:29:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Sep 2005 19:29:00 +0200 Subject: Need to pass Object by value into a list References: <1127755064.816839.75810@g49g2000cwa.googlegroups.com> Message-ID: Aaron wrote: > I have a data sructure setup and I populate it in a loop like so: > > y=0 > while X: > DS.name = "ASDF" > DS.ID = 1234 > > list[y] = DS; > y = y + 1 > > print list > > This does not work because DS is passed in by reference causing all > entries into the list to change to the most current value. I cannot > find a "new" function in Python like there is in C++. How do you do > this in Python? I assume DS is a class? to create an instance of a class, call the class object: L = [] while X: ds = DS() ds.name = "ASDF" ds.id = 1234 L.append(ds) spending some time with the tutorial might help: http://docs.python.org/tut/tut.html (lists are described in chapter 3, classes in chapter 9) From gnukid at gmail.com Fri Sep 30 06:19:28 2005 From: gnukid at gmail.com (gnukid) Date: 30 Sep 2005 03:19:28 -0700 Subject: Hello gnome-terminal In-Reply-To: References: Message-ID: <1128075568.759036.73330@f14g2000cwb.googlegroups.com> Hi Launcher may spawn a new shell to execute your program. The new shell wont have your PYTHONPATH environment variable. Cheers, Noorul egbert wrote: > When I start the following script in a gnome-terminal: > > #!/usr/bin/env python > import os > print "hello gnome-terminal" > print os.environ["PYTHONPATH"] > > I see the expected results in the same gnome-terminal window. > > However starting this same script via a launcher in a panel, > a new gnome-terminal window is opened for output only, > and PYTHONPATH is an unknown entity. > How can I open a terminal over whose environment and > configuration I have more control ? > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 > ======================================================================== From ndbecker2 at gmail.com Thu Sep 22 09:14:04 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 22 Sep 2005 09:14:04 -0400 Subject: unusual exponential formatting puzzle References: <7xhdcd6av1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Neal Becker writes: >> Like a puzzle? I need to interface python output to some strange old >> program. It wants to see numbers formatted as: >> >> e.g.: 0.23456789E01 > > Yeah, that was normal with FORTRAN. > >> My solution is to print to a string with the '% 16.9E' format, then >> parse it with re to pick off the pieces and fix it up. Pretty ugly. >> Any better ideas? > > That's probably the simplest. Acutally, I found a good solution using the new decimal module: def Format(x): """Produce strange exponential format with leading 0""" s = '%.9E' % x d = decimal.Decimal (s) (sign, digits, exp) = d.as_tuple() s = '' if (sign == 0): s += ' ' else: s += '-' s += '0.' e = len (digits) + exp for x in digits: s += str (x) s += 'E' s += '%+03d' % e return s From davegu1 at hotmail.com Wed Sep 14 13:47:53 2005 From: davegu1 at hotmail.com (David Gutierrez) Date: Wed, 14 Sep 2005 12:47:53 -0500 Subject: Python on AIX 4.3. In-Reply-To: Message-ID: Alessandro, No, Im not trying to install a posix thread. I was just doing a straight forward installation in AIX 4..3.3. David From: Alessandro Bottoni Reply-To: alessandro.bottoni at infinito.it To: python-list at python.org Subject: Re: Python on AIX 4.3. Date: Wed, 14 Sep 2005 16:32:46 GMT MIME-Version: 1.0 Received: from smtp-vbr9.xs4all.nl ([194.109.24.29]) by mc7-f4.hotmail.com with Microsoft SMTPSVC(6.0.3790.211); Wed, 14 Sep 2005 09:36:44 -0700 Received: from bag.python.org (bag.python.org [194.109.207.14])by smtp-vbr9.xs4all.nl (8.13.3/8.13.3) with ESMTP id j8EGahbh078191for ; Wed, 14 Sep 2005 18:36:43 +0200 (CEST)(envelope-from python-list-bounces+davegu1=hotmail.com at python.org) Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) with ESMTP id EA1011E42DCfor ; Wed, 14 Sep 2005 18:35:41 +0200 (CEST) X-Message-Info: JGTYoYF78jEitB2IpXZKOzKsRwmxNvyoBOSEeaB+NVk= Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news.tele.dk!news.tele.dk!small.news.tele.dk!news.mailgate.org!nntp.infostrada.it!twister2.libero.it.POSTED!not-for-mail Newsgroups: comp.lang.python Mail-Copies-To: alessandro.bottoni at infinito.it References: Lines: 32 User-Agent: KNode/0.8.2 NNTP-Posting-Host: 151.37.234.42 X-Complaints-To: abuse at net24.it X-Trace: twister2.libero.it 1126715566 151.37.234.42 (Wed,14 Sep 2005 18:32:46 MET DST) NNTP-Posting-Date: Wed, 14 Sep 2005 18:32:46 MET DST Organization: [Infostrada] Xref: news.xs4all.nl comp.lang.python:395365 X-BeenThere: python-list at python.org X-Mailman-Version: 2.1.6 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: python-list-bounces+davegu1=hotmail.com at python.org X-Virus-Scanned: by XS4ALL Virus Scanner Return-Path: python-list-bounces+davegu1=hotmail.com at python.org X-OriginalArrivalTime: 14 Sep 2005 16:36:45.0152 (UTC) FILETIME=[7E887E00:01C5B94A] David Gutierrez wrote: > Hello Everyone, > I'm trying to install Python on an aix 4.3.3. but keep on getting a failed > attempt with the following errors. > > ld: 0711-317 ERROR: Undefined symbol: .pthread_mutex_lock > ld: 0711-317 ERROR: Undefined symbol: .pthread_mutex_unlock > ld: 0711-317 ERROR: Undefined symbol: .pthread_cond_signal > ld: 0711-317 ERROR: Undefined symbol: .pthread_cond_wait > ld: 0711-317 ERROR: Undefined symbol: .pthread_mutex_destroy > ld: 0711-317 ERROR: Undefined symbol: .pthread_cond_destroy > ld: 0711-317 ERROR: Undefined symbol: .pthread_mutex_init > ld: 0711-317 ERROR: Undefined symbol: .pthread_cond_init > ld: 0711-317 ERROR: Undefined symbol: .pthread_self > ld: 0711-317 ERROR: Undefined symbol: .pthread_attr_init > ld: 0711-317 ERROR: Undefined symbol: .pthread_attr_setscope > ld: 0711-317 ERROR: Undefined symbol: .pthread_create > ld: 0711-317 ERROR: Undefined symbol: .pthread_attr_destroy > ld: 0711-317 ERROR: Undefined symbol: .pthread_detach > ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more > information. > collect2: ld returned 8 exit status > make: 1254-004 The error code from the last command is 1. Are you trying to install a posix-thread- (pthread) -enabled Python interpreter on a not-pthread machine? It looks like the pthread module is missing. HTH ----------------------------------- Alessandro Bottoni -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Tue Sep 27 23:04:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Sep 2005 23:04:09 -0400 Subject: Python 2.4 under WinXP, free VC71 toolkit and VC6 libraries In-Reply-To: References: <43398685$0$7334$626a14ce@news.free.fr> Message-ID: Berthold H?llmann wrote: > As I understand it, ctypes is not really a solution. The code is about > data handling and FE analysis. It has not GUI component. I'm not sure > how well ctypes works with Numeric arrays, but I'm sure ctypes does > not work on Linux and Solaris, but my code has to. Neither of those comments makes sense, so you probably _don't_ understand what ctypes is. Not only does it definitely work on Linux, but it has nothing to do per se with GUI components, and should work fine for "data handling" of just about any kind that is done by a DLL. I'm not sure what you were thinking of, but it probably wasn't ctypes. -Peter From liquidbinary at gmail.com Tue Sep 6 23:08:35 2005 From: liquidbinary at gmail.com (liquidbinary at gmail.com) Date: 6 Sep 2005 20:08:35 -0700 Subject: Ode to python Message-ID: <1126062515.460542.95260@f14g2000cwb.googlegroups.com> *Organized Chaos* I crafted your purpose one line at a time. No other creation shall be like your kind. Boolean values fire connections. High level logic from your inception. I partitioned your system into functions of selfdom. Artificial neurons thread together to bond them. Not one routine shall be introspectively seen by another. For I tell you, only a value shall be returned from its brother. I encapsulate your fate into objects of state. Confused? Wait. I've flow charts to show how they relate. Abolish all globals, and all mutinous variables. Embed precious methods in organized crucibles. Polymorphism provides an element of evolution. Shifting and shaping to evolve a solution. Drink java? Good, maintain your work flow. Use java? Get burned like lava, for it moves just as slow. Python or C? C is simply a pawn. Venomous problem? Pythons squeeze and constrict, until the problem is gone. From fakeaddress at nowhere.org Sat Sep 3 18:35:51 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 03 Sep 2005 22:35:51 GMT Subject: Sockets: code works locally but fails over LAN In-Reply-To: References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> <1125681663.710557.320340@f14g2000cwb.googlegroups.com> <3m6ih1taaeo7kndnbuvfl5geed053ivunl@4ax.com> <1125774529.074965.269720@g44g2000cwa.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > Bryan Olson declaimed the following in comp.lang.python: > >>No, my guess is that you're running an old version of Python. >>The constant was added in the source on 27 Nov 2003; I'm not > > > Are you sure of that 2003? Yes, but that's when it went into the source, in the sense of first being edited into a file. It was Revision 1.279 of socketmodule.c. http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/socketmodule.c?rev=1.312&view=log -- --Bryan From malvert at telenet.be Wed Sep 7 09:20:36 2005 From: malvert at telenet.be (malv) Date: 7 Sep 2005 06:20:36 -0700 Subject: Installation question In-Reply-To: <431d93ce@127.0.0.1> References: <431d93ce@127.0.0.1> Message-ID: <1126099236.656545.319500@g43g2000cwa.googlegroups.com> I can't give you an exact answer, but maybe this helps a bit: I tried running both Python 2.3 and 2.4 (both 32) with Qt3 on two other distros. It never really worked and gave me lots of problems. It certainly "messed up" a few things here and there. I never managed to get things straightened out. I later installed Suse 9.3 Pro with both Gnome & KDE. When installing the eric3 IDE, I found that everything I needed, Python 2.4, Qt3.3, PyQt, Sip, QScintilla was there already. (If I recall, I had only to add in one or two development libraries for Qt). From dont at spam.me Tue Sep 13 12:47:11 2005 From: dont at spam.me (Bugs) Date: Tue, 13 Sep 2005 09:47:11 -0700 Subject: How to protect Python source from modification In-Reply-To: <1126598468.001875.16230@g49g2000cwa.googlegroups.com> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> <1126598468.001875.16230@g49g2000cwa.googlegroups.com> Message-ID: Thanks Frank, I appreciate the feedback. From mwm at mired.org Thu Sep 22 10:40:00 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 22 Sep 2005 10:40:00 -0400 Subject: Looking for system/network monitoring tool written in Python References: <86k6ham0aw.fsf@bhuda.mired.org> <1127394327.610348.302390@f14g2000cwb.googlegroups.com> Message-ID: <86aci5i2tb.fsf@bhuda.mired.org> "David Wilson" writes: > See http://pynms.sourceforge.net/ Thanks for the pointer. And to Simon Brunning for the pointer to Eddie. > Also see Google. :) While everything may be in Google, it's not always obvious how to get it out. I've managed to extract a score of systems from Google - but none based on Python... http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From smadim2 at grads.ece.mcmaster.ca Sat Sep 17 22:21:29 2005 From: smadim2 at grads.ece.mcmaster.ca (Mohammed Smadi) Date: Sat, 17 Sep 2005 22:21:29 -0400 (EDT) Subject: socket.gethostbyaddr problem Message-ID: hi; I am trying to do some very basic socket programming and i get the following error. Any help will be appreciated: Code: import socket x = socket.gethostbyaddr("www.google.ca") return an error: socket.herror: (1, 'Unknown host') I tried replacing the web URL with an IP address on the net, on my LAN and it does not work. It only works with "localhost" which is not very useful. Am using Python 2.3.4 if that matters. any direction will be great moe smadi From Luap777 at hotmail.com Wed Sep 21 18:25:00 2005 From: Luap777 at hotmail.com (Paul) Date: 21 Sep 2005 15:25:00 -0700 Subject: Chronological Processing of Files References: <1127338572.824186.243790@g49g2000cwa.googlegroups.com> Message-ID: <1127341500.755293.311510@o13g2000cwo.googlegroups.com> untested, ugly, but something like this would sort all the files in the directory on os.path.getctime (not using os.walk() though). I'm sure there is probably better ways to do it :) filelist = [] def walkdir(currdir): for files in os.listdir(currdir): path = os.path.join(currdir, files) if not os.path.isdir(path): filelist.append([os.path.getctime(path), path]) else: walkdir(path) walkdir(r'c:\somedirectory') filelist.sort() for item in filelist: dosomething(item[1]) dosomething is whatever function to process the files From andrea.valle at unito.it Sat Sep 17 06:17:16 2005 From: andrea.valle at unito.it (andrea valle) Date: Sat, 17 Sep 2005 12:17:16 +0200 Subject: problem with setup.py In-Reply-To: <20050607150658.GB5985@ActiveState.com> References: <20050607150658.GB5985@ActiveState.com> Message-ID: Hi to all, and sorry for cross-posting. I'm having troubles with installing packages. I'm on macosx 10.3.8 and I have activestate python 2.4 For example, pyrtf an pyx. it is the first time I install packages so pardon me if it's obvious. I call python from terminal, I pass the absolute path of the setup.py with command install, and results are always: error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during configure For example with pyrtf: apples-Computer:~ apple$ python /Users/apple/Desktop/PyRTF-0.45/setup.py installrunning install error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during configure What should I do? I guess I have to hack some configuration, but don't know which. Thanks a lot -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From fredrik at pythonware.com Fri Sep 9 08:37:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 9 Sep 2005 14:37:25 +0200 Subject: how to get the return value of a thread? References: <4e307e0f05090904583b3bfaa@mail.gmail.com> Message-ID: Leo Jay wrote: > i would like to get the return value of all threads > > e.g. > def foo(num): > if num>10: > return 1 > elif num>50: > return 2 > else > return 0 > > > after i invoked > t = thread.start_new_thread(foo,(12,)) > how to get the return value of `foo'? threads are subprograms, not functions. to allow a thread to generate values, create a shared Queue object and let your threads add stuff to that queue. an example: import threading import Queue import time, random class Worker(threading.Thread): def __init__(self, index, queue): self.__index = index self.__queue = queue threading.Thread.__init__(self) def run(self): # pretend we're doing something that takes 10-100 ms time.sleep(random.randint(10, 100) / 1000.0) # pretend we came up with some kind of value self.__queue.put((self.__index, random.randint(0, 1000))) queue = Queue.Queue() for i in range(10): Worker(i, queue).start() # start a worker for i in range(10): print "worker %d returned %d" % queue.get() From steve at holdenweb.com Thu Sep 1 23:17:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Sep 2005 22:17:05 -0500 Subject: OpenSource documentation problems In-Reply-To: <7x7je1tl9w.fsf@ruckus.brouhaha.com> References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <7x7je1tl9w.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: [snip snippety snip snip, snip snip] > > Calling the Python docs "worthless" is false and unconstructive; > saying that the docs have shortcomings in part because the Python > project itself places too little priority on doc quality is perfectly > legitimate. Python's core developers are in a leadership position for > Python whether they like it or not; and users and volunteers absorb > the attitudes of the leaders. So, what you are saying is because the developers (I explain in another post on this thread that I'm not a developer, but I *am* a director for the PSF), having taken the time and trouble to produce something that you (for want of a better example) find incredibly useful, are now beholden to improve it still further and make it still more useful, because otherwise nobody else will feel it necessary to create and maintain documentation of high quality? > The PSF and the FSF both sometimes fund > people to do coding projects. Why does the PSF (apparently) not fund > anyone to do doc projects, like the FSF does? I would say this shows > the PSF's priorities are screwed up. Documentation is every bit as > important as code. > Bear in mind that the PSF made its very first grants last year. The reason none of those grants was awarded to a documentation project was that the (volunteer) Grants Committee and helpers didn't see any documentation projects worthy of support. I'm not actually sure they saw any documentation proposals at all. So they chose to support the development of new teaching materials (hey, that might be documentation), an update to Jython and an improved SNMP implementation. I guess your proposal must have been lost in the mail ;-) What Python really needs is for Python enthusiasts to understand that the future of the language is largely in their hands. It's easy to say "but I can't do this" or "I can't do that". Forget such negativity. Find something you *can* do to improve Python - document a module, chair a conference, or (as *you* already do) contribute your knowledge and experience to c.l.py to improve the level of Python awareness. I have done all of these things, and I firmly believe that each could have been done better. Unfortunately those with superior skills chose not to engage the Python community. Which left it stuck with me. Poor Python. Most of all, realise that there is no "us" and "them". *We* are "them", and it's up to *us* to accept that and try to improve things. Please understand that I don't mean to belittle anyone who has made any kind of contribution to Python (even Xah Lee has his place, though I tremble to think so). I just want more Python users to understand that there are many contributions they could make that are well within their capabilities, and to get off their butts and start doing something! existential-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Holden Web Ltd From mekstran at scl.ameslab.gov Mon Sep 26 17:58:16 2005 From: mekstran at scl.ameslab.gov (Michael Ekstrand) Date: Mon, 26 Sep 2005 16:58:16 -0500 Subject: Metaclasses, decorators, and synchronization In-Reply-To: <43385215$1@nntp0.pdx.net> References: <43385215$1@nntp0.pdx.net> Message-ID: <3e9a0b20942381d9ee08f3eefc70abd5@scl.ameslab.gov> On Sep 26, 2005, at 4:21 PM, Scott David Daniels wrote: > Unnecessarily holding a lock while acquiring another can be a nasty > source of deadlock or at least delay. Another source of problems is > holding a lock because an exception skipped past the release code. I had thought of part of that after I sent my email. Didn't think of the exception issue or the specific deadlock scenario though. Thank you much for your help/advice. One issue remains in this function: my method's signature is lost when synchronized is applied (at least as somemeth=synchronized(somemeth); I'm currently in a 2.3 environment that doesn't have the decorator syntax, but my understanding is that makes no difference). I've been able to preserve the doc string by setting the __doc__ attribute of the inner function before returning it, but is there a way to make this inner function appear to bear the same argument list as the original method? I've been poking around in new and inspect, but it is not appearing like an easy task. Thanks, - Michael From steve at REMOVETHIScyber.com.au Fri Sep 9 07:36:47 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 09 Sep 2005 21:36:47 +1000 Subject: encryption with python References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> <1126128663.573686.148670@g44g2000cwa.googlegroups.com> Message-ID: On Wed, 07 Sep 2005 14:31:03 -0700, jlocc wrote: > Basically I will like to combine a social security number (9 digits) > and a birth date (8 digits, could be padded to be 9) and obtain a new > 'student number'. It would be better if the original numbers can't be > traced back, they will be kept in a database anyways. Hope this is a > bit more specific, thanks!!! There are "one-way" encryption functions where the result can't easily be traced back to the input, but why do you need the input anyway? Here is my quick-and-dirty student ID algorithm: last_number_used = 123 # or some other appropriate value def make_studentID(): global last_number_used last_number_used = last_number_used + 1 return last_number_used For a real application, I'd check the database to see if the number has already been used before returning the number. Also, if you need more than four digits in your IDs, I'd add a checksum to the end so you can detect many typos and avoid much embarrassment. Since the ID is entirely random (a factor of what order the students are entered into the database) no attacker can regenerate their SSN from their student ID. At worst, an attacker might be able to work out roughly what day they were added to the database. Big deal. And if that is a problem, you might do something like this: last_number_used = 12345 usable_IDs = [] def make_studentID(): global last_number_used global usable_IDs if not usable_IDs: # generate another batch of IDs in random order usable_IDs = range(last_number_used, last_number_used + 1000) usable_IDs.sort(random.random()) last_number_used += 1000 return usable_IDs.pop() In a real application you would need to store the global variables in a database, otherwise each time you reload the Python script you start generating the same IDs over and over again. -- Steven. From steve at holdenweb.com Sun Sep 11 02:51:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Sep 2005 02:51:12 -0400 Subject: getting words from readline In-Reply-To: References: Message-ID: Adam wrote: > How is best to extract word strings from a > line = infile.readline() > > I wish to quickly check the first word of > each line of a text file. > > Indeed, How do I break a lineinput() line > into component words (separate by spaces etc) ? > > Should I be looking at; > Re Parser Slice StringIO ? > > > Any help appreciated. > Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> s = "This is a line of text" >>> s.split() ['This', 'is', 'a', 'line', 'of', 'text'] >>> l = s.split() >>> l[0] 'This' >>> As you can see above, you probably don't need any complicated modules for this fairly simple requirement. If you are wanting to match the words against each other, or against some pre-exisitng list, you might want to reduce the input to lower-case first. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fabioz at esss.com.br Tue Sep 6 13:14:43 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Tue, 06 Sep 2005 14:14:43 -0300 Subject: ANN: PyDev 0.9.8.1 released In-Reply-To: <431341E3.6020103@esss.com.br> References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br> <42E6412A.4020905@esss.com.br> <430632E3.9050403@esss.com.br> <431341E3.6020103@esss.com.br> Message-ID: <431DCE83.1010702@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.8.1 has been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Details for Release: 0.9.8.1 Major highlights: ------------------- * Java 1.4 support reintroduced. * Styles added for syntax highlighting (bold and italic), contributed by Gerhard Kalab. Others that are new and noteworthy: ------------------------------------- * zombie process after exiting eclipse should not happen anymore * paths with '.' are accepted for the pythonpath (unless they start with a '.', because it may not accept relative paths). * relative imports are added to code-completion * local imports are taken into consideration when doing code completion * debugger has 'change support', so, changed variables in a scope appear red Cheers, Fabio -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From fredrik at pythonware.com Fri Sep 30 09:50:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 15:50:05 +0200 Subject: 'ascii' codec can't encode character u'\u2013' References: Message-ID: Thomas Armstrong wrote: > I'm trying to parse a UTF-8 document with special characters like > acute-accent vowels: > -------- > > ... > ------- > > But I get this error message: > ------- > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in > position 122: ordinal not in range(128) > ------- > It works, but I don't want to substitute each special character, because there > are always forgotten ones which can crack the program. if you really want to use latin-1 in the database, and you don't mind dropping unsupported characters, you can use text_extrated = text_extrated.encode('iso-8859-1', 'replace') or text_extrated = text_extrated.encode('iso-8859-1', 'ignore') a better approach is of course to convert your database to use UTF-8 and use text_extrated = text_extrated.encode('utf-8') it's also a good idea to switch to parameter substitution in your SQL queries: cursor.execute ("update ... set text = %s where id = %s", text_extrated, id) it's possible that your database layer can automatically encode unicode strings if you pass them in as parameters; see the database API documentation for details. From tjreedy at udel.edu Wed Sep 28 16:47:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2005 16:47:47 -0400 Subject: Pixel Manipulations References: <1127939605.328848.171860@o13g2000cwo.googlegroups.com> Message-ID: "PyPK" wrote in message news:1127939605.328848.171860 at o13g2000cwo.googlegroups.com... [an exact duplicate of the off-topic message posted under the more informative subject line of 'Straight line detection'] Please do no post the same message twice, especially not with two different subject lines. I believe these were also posted about a week ago. From desparn at wtf.com Fri Sep 23 08:11:14 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Fri, 23 Sep 2005 08:11:14 -0400 Subject: What is "self"? References: <43335c5f$1_4@alt.athenanews.com> Message-ID: Roy Smith wrote in news:roy-DE5389.07461923092005 at reader1.panix.com: > Ron Adam wrote: >> You can actually call it anything you want but "self" is sort >> of a tradition. > > That's true, but I think needs to be said a bit more > emphatically. There's no reason to call it anything other than > "self" and a newcomer to the language would be well advised to > not try and be creative here. Using "self" is virtually > universal, and calling it anything else will just lead to > confusion by other people who have to read your code. I've long thought that Guido missed an opportunity by not choosing to use 'i' as the instance identifier, and making it a reserved word. For one thing, it would resonate with the personal pronoun 'I', and so carry essentially the same meaning as 'self'. It could also be understood as an initialism for 'instance'. And, because it is shorter, the number of objections to its existence *might* have been smaller than seems to be the case with 'self' as the convention. And as a side benefit, it would make it impossible to use as a loop index a language feature that would be a huge selling point among a lot of experienced programmers. -- rzed From kst-u at mib.org Wed Sep 21 13:39:38 2005 From: kst-u at mib.org (Keith Thompson) Date: Wed, 21 Sep 2005 17:39:38 GMT Subject: Perl's documentation come of age References: <1123809822.696399.317570@g44g2000cwa.googlegroups.com> <1124736189.749363.32160@g47g2000cwa.googlegroups.com> <1125179974.483320.116780@g49g2000cwa.googlegroups.com> <1127299284.748225.68560@g14g2000cwa.googlegroups.com> Message-ID: "Xah Lee" writes: [ the usual ] +-------------------+ .:\:\:/:/:. | PLEASE DO NOT | :.:\:\:/:/:.: | FEED THE TROLLS | :=.' - - '.=: | | '=(\ 9 9 /)=' | Thank you, | ( (_) ) | Management | /`-vvv-'\ +-------------------+ / \ | | @@@ / /|,,,,,|\ \ | | @@@ /_// /^\ \\_\ @x@@x@ | | |/ WW( ( ) )WW \||||/ | | \| __\,,\ /,,/__ \||/ | | | jgs (______Y______) /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ============================================================== -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From steve at holdenweb.com Thu Sep 22 05:44:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Sep 2005 10:44:11 +0100 Subject: wxPython Notebook crash when pressing alt key In-Reply-To: <1127324089.976065.41510@g14g2000cwa.googlegroups.com> References: <1127311253.582981.277380@z14g2000cwz.googlegroups.com> <1127317059.085252.161500@g47g2000cwa.googlegroups.com> <1127324089.976065.41510@g14g2000cwa.googlegroups.com> Message-ID: Kreedz wrote: > Did it freeze for you too with the alt+f while focus on the tab? > No, the program appears to work perfectly normally. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org From pydecker at gmail.com Tue Sep 13 13:48:43 2005 From: pydecker at gmail.com (Peter Decker) Date: Tue, 13 Sep 2005 13:48:43 -0400 Subject: PyGTK or wXPython? In-Reply-To: <11idt45lsggj06@corp.supernews.com> References: <11idt45lsggj06@corp.supernews.com> Message-ID: On 9/13/05, Grant Edwards wrote: > Anyway, there are some lighter-weight wrappers that make the > API more Pythonic and hide the nasty stuff like the id and flag > parameters. I tried "wax" a while back and it looked > promising. I looked at Wax, too, but as of last spring it was barely being developed. I read that they got some money from the Summer of Code thing that Google sponsored, so I don't know if that injected any sustainable life into Wax. Dabo is very active; I've seen requests for features added to the product the same day! -- # p.d. From mmarch at gmail.com Wed Sep 21 13:53:49 2005 From: mmarch at gmail.com (Michael March) Date: 21 Sep 2005 10:53:49 -0700 Subject: Access CSV data by column name.. Message-ID: <1127325229.651431.262160@g47g2000cwa.googlegroups.com> I have seen a few recipes out there that allow for access to DB-API columns by their name instead of column number.. I was wondering if anyone knew of any code snippets that allow for the same thing with the CSV module? thanks! From googlenews at tooper.org Fri Sep 9 11:57:00 2005 From: googlenews at tooper.org (tooper) Date: 9 Sep 2005 08:57:00 -0700 Subject: Where do .pyc files come from? In-Reply-To: <1126279989.004437.270950@g49g2000cwa.googlegroups.com> References: <1126279989.004437.270950@g49g2000cwa.googlegroups.com> Message-ID: <1126281420.418998.306500@z14g2000cwz.googlegroups.com> Yes, these are bytecode files. If you run "python -o", you should also get .pyo files for optimized bytecode. As long as you do not modify the source code, python directly reuse the bytecode (that's also a way to distribute script without source code to avoid your users fiddling in thecode and make it not work properly - even if any advanced user will know how to revert back to source code) From reinhold-birkenfeld-nospam at wolke7.net Sun Sep 25 14:06:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 25 Sep 2005 20:06:09 +0200 Subject: cElementTree clear semantics In-Reply-To: References: Message-ID: <3po78hFbdl84U1@individual.net> D H wrote: > Igor V. Rafienko wrote: >> This gave me the desired behaviour, but: >> >> * It looks *very* ugly >> * It's twice as slow as version which sees 'end'-events only. >> >> Now, there *has* to be a better way. What am I missing? >> > > Try emailing the author for support. I don't think that's needed. He is one of the most active members of c.l.py, and you should know that yourself. Reinhold From twic at urchin.earth.li Fri Sep 23 14:11:39 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 23 Sep 2005 19:11:39 +0100 Subject: Productivity and economics at software development In-Reply-To: <43340180$1@nntp0.pdx.net> References: <43340180$1@nntp0.pdx.net> Message-ID: On Fri, 23 Sep 2005, Scott David Daniels wrote: > Adriano Monteiro wrote: > >> I'm making a little research project about programming languages e >> their respective IDEs. The goal is to trace each language silhouettes, >> where it fits better, their goods/bads and the costs of developing in >> this language. > > What do you consider the IDE for Assembly code or Microcode? emacs, of course - just as it is for every other language. tom -- If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair From renting at astron.nl Mon Sep 19 05:20:35 2005 From: renting at astron.nl (Adriaan Renting) Date: Mon, 19 Sep 2005 11:20:35 +0200 Subject: Python and Unix Commands Message-ID: Depending on what you axactly want there are a lot of ways to do this. There is the subProcess module, there is the pty module, there is os.system, there is the popen module, and my personal favorite is Pexpect (pexpect.sourceforge.org). Read the documentation of these modules is my first suggestion. Adriaan Renting. P.S. you don't need to post your question to this list every 5 minutes. |>>>"timdoyle05" 09/19/05 10:46 am >>> |Hi, | | I have a question relating to how Unix commands can be issued from |Python programs. Im am currently writing a large test script in python |and I need this script to call three other separate Python scripts, |where each one executes in it own thread of control. I would like to |use a Unix command to get each script to run in its own shell. I have |tried using the "Commands" module but after I issue the |first "command", execution blocks until I kill the called script. Is |there a way around this?? | |Thanks for your time, |I would really appreciate any assistance, | |Tim. | | | |-- |http://mail.python.org/mailman/listinfo/python-list From collinw at gmail.com Fri Sep 23 15:02:00 2005 From: collinw at gmail.com (Collin Winter) Date: Fri, 23 Sep 2005 15:02:00 -0400 Subject: Single type for __builtins__ in Py3.0 In-Reply-To: References: <43aa6ff7050923075512175c41@mail.gmail.com> Message-ID: <43aa6ff7050923120236d98711@mail.gmail.com> On 9/23/05, Fredrik Lundh wrote: > Collin Winter wrote: > > > As it currently stands, the type of the global __builtins__ differs > > depending on whether you're in the __main__ namespace (__builtins__ is > > a module) or not (its a dict). I was recently tripped up by this > > discrepancy, and googling the issue brings up half-a-dozen or so c.l.p > > threads where others have been bitten by this, too. > > __builtins__ is a CPython implementation detail. why not just let it > be an implementation detail, and refrain from using it? it's not that > hard, really. Given, but I fail to see why it can't be a consistent implementation detail. After my own encounter with __builtins__, I now know that I should use __builtin__ instead. However, the docs never mention this. The only way you'd know that __builtin__ is preferred is by searching the list archives, something you're not likely to do unless you're already having a problem. If it's decided to leave things they way they are, at the very least the docs should be amended to indicate that users shouldn't be touching __builtins__. If anyone has a suggestion as to where this kind of thing might best fit (tutorial, library reference, language reference?), I'd be happy to write a patch for the docs. Collin Winter From fredrik at pythonware.com Wed Sep 21 15:31:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Sep 2005 21:31:42 +0200 Subject: I am not able to setup pydb2 ! Any help ! References: <1127321226.420209.253360@g43g2000cwa.googlegroups.com><1127322750.143775.92010@g44g2000cwa.googlegroups.com> <43319d50$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > MS is fairly determined to get you develop money; you may not > redistribute the C runtime with your app from the "free" stuff. that's a myth, based on a flawed reading of the MS license. to repeat myself from various other fora: "As long as you're using a standard Python build, you don't need to buy VC7 to [legally redistribute the C runtime]. The python.org team uses a properly licensed VC7 to build Python, which turns Python into "licensee software" and you into a "distributor" doing "further distribution" of Python to end users (with your own stuff added on top, of course). And further distribution is perfectly okay, as long as you only ship the MS components together with proper "licensee software" (=Python), and that all parties respect the relevant portions of the original EULA (this basically means that you cannot use tricks to circumvent the MS EULA, e.g. by attempting to relicense the MS DLL's under less restrictive licenses or "viral" licenses. The same applies to all other licensed components, of course. You cannot relicense the Python core either.)." "(If in doubt, consult a real lawyer. If you do, make sure that he/she under- stands the various levels here -- i.e. that "you" in the MS EULA applies to the Python developers, not yourself)." From pedro.werneck at terra.com.br Sun Sep 18 20:17:17 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 18 Sep 2005 21:17:17 -0300 Subject: Possible bug in "metaclass resolution order" ? In-Reply-To: <1127073502.567105.241980@o13g2000cwo.googlegroups.com> References: <1126947879.528826.150440@f14g2000cwb.googlegroups.com> <1127064791.388848.284360@g47g2000cwa.googlegroups.com> <1127073502.567105.241980@o13g2000cwo.googlegroups.com> Message-ID: <20050918211717.56b90fd7.pedro.werneck@terra.com.br> On 18 Sep 2005 12:58:22 -0700 "Simon Percivall" wrote: > I definitely think that it's the intended behaviour: the example shows > how and why it works; and I definitely agree that it should be > documented better. Yes. I finally understood the decision and now I agree it's not a bug, it's the intended behaviour. If the explicit class is part of the hierarchy but not a subclass of base classes metaclass, it will search for the more specialized metaclass and use it, since it will have anything the class need and conforms to the metaclass I set explicitly. I will change the bug report and add some of the suggested documentation. Thanks -- Pedro Werneck From alanmk at hotmail.com Tue Sep 6 13:08:04 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 06 Sep 2005 18:08:04 +0100 Subject: Django Vs Rails In-Reply-To: <431dca31$0$29335$636a15ce@news.free.fr> References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <1125975775.892662.231980@f14g2000cwb.googlegroups.com> <431dca31$0$29335$636a15ce@news.free.fr> Message-ID: [D H] >>Go with Rails. Django is only like a month old. [bruno modulix] > Please take time to read the project's page. Django has in fact three > years of existence and is already used on production websites, so it's > far from pre-alpha/planning stage. But the APIs still aren't 100% stable. http://www.djangoproject.com/screencasts/model_syntax_change/ -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From peter at engcorp.com Wed Sep 7 23:17:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 07 Sep 2005 23:17:18 -0400 Subject: Job Offer in Paris, France : R&D Engineer (Plone) In-Reply-To: References: Message-ID: Fred Pacquier wrote: > This is a general case, and it goes both ways : we French usually > communicate much more easily with italians (or whatever) speaking english > than with native anglo-american speakers. Anyway, source code (esp. python) > is the modern esperanto/volap?k :-) I can't let that pass. :-) I believe it was well established in posts a few years ago that while the programming-language equivalent of Esperanto is clearly Python, "Volapuke" was most definitely reincarnated as *Perl*. -Peter From g.horvath at gmx.at Fri Sep 30 05:31:59 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Fri, 30 Sep 2005 11:31:59 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xy85fx81b.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> <7xbr2btv84.fsf@ruckus.brouhaha.com> <7x64sjduqk.fsf@ruckus.brouhaha.com> <7xek77p2i8.fsf@ruckus.brouhaha.com> <7xy85fx81b.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Gregor Horvath writes: >>Someone has a problem and tweaks a private variable as a workaround. > > They should have patched the source instead. > I think they are going to do that. In the meantime our friend has a working solution otherwise he would have nothing but broken code today. > > Believe it or not, not all development environments are that > disorganized. Martians? Examples? This has nothing to do with organisation but a lot with natural influances and constraints of software development (except really simple programs) -- Greg From gene.tani at gmail.com Fri Sep 9 19:54:01 2005 From: gene.tani at gmail.com (gene tani) Date: 9 Sep 2005 16:54:01 -0700 Subject: python object model diagram In-Reply-To: References: Message-ID: <1126310041.310250.95120@o13g2000cwo.googlegroups.com> I think he's looking for tidy pictures of how metaclasses and descriptors interact with your classes and instances at compile- & runtime, something like that (which I haven't seen) There's pictures of the class hierarchy for C and j-python: http://www.brpreiss.com/books/opus7/html/page114.html http://www.jython.org/docs/javadoc/overview-tree.html , there's pictures of method resolution order in Python Nutshell, (but I don't think that's what he's looking for.) Ara.T.Howard wrote: > anyone out there know where i might find a python object model diagram? > From nochiel at gmail.com Wed Sep 28 12:19:20 2005 From: nochiel at gmail.com (yoda) Date: 28 Sep 2005 09:19:20 -0700 Subject: 1 Million users.. I can't Scale!! Message-ID: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> Hi guys, My situation is as follows: 1)I've developed a service that generates content for a mobile service. 2)The content is sent through an SMS gateway (currently we only send text messages). 3)I've got a million users (and climbing). 4)The users need to get the data a minimum of 5 seconds after it's generated. (not considering any bottlenecks external to my code). 5)Generating the content takes 1 second. I'm considering moving to stackless python so that I can make use of continuations so that I can open a massive number of connections to the gateway and pump the messages out to each user simultaneously.(I'm thinking of 1 connection per user). My questions therefore are: 1)Should I switch to stackless python or should I carry out experiments with mutlithreading the application? 2)What architectural suggestions can you give me? 3)Has anyone encountered such a situation before? How did you deal with it? 4)Lastly, and probably most controversial: Is python the right language for this? I really don't want to switch to Lisp, Icon or Erlang as yet. I really need help because my application currently can't scale. Some user's end up getting their data 30 seconds after generation(best case) and up to 5 minutes after content generation. This is simply unacceptable. The subscribers deserve much better service if my startup is to survive in the market. From n00m at narod.ru Sun Sep 11 05:29:38 2005 From: n00m at narod.ru (n00m) Date: 11 Sep 2005 02:29:38 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> Message-ID: <1126430978.479008.307050@g43g2000cwa.googlegroups.com> Tim Peters; INCREDIBLE~ > 241433 2005-09-11 04:23:40 Tim Peters accepted 3.44 7096 PYTH BRAVO! I just wonder have I grey cells enough for to understand how your algo works... and hopefully it's not your last solved problem on the contester. > I'm pretty sure they're using > slower HW than mine (3.4 GHz P5). As I mentioned before their 4 identical machines are PIII Xeon 700MHz. PS: each accepted solution automatically gets into "Best Solutions" list. From skip at pobox.com Thu Sep 29 12:17:15 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 29 Sep 2005 11:17:15 -0500 Subject: Will python never intend to support private, protected and public? In-Reply-To: <311b5ce105092908332c12164c@mail.gmail.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> Message-ID: <17212.5003.567705.394945@montanaro.dyndns.org> >> **Encapsulation** is one of the 3 basic characteristics of OOP. This isn't an encapsulation issue. From the first hit on Google for the word: In programming, the process of combining elements to create a new entity. For example, a procedure is a type of encapsulation because it combines a series of computer instructions. Likewise, a complex data type, such as a record or class, relies on encapsulation. Object- oriented programming languages rely heavily on encapsulation to create high-level objects. Encapsulation is closely related to abstraction and information hiding. Python does encapsulation just fine. Your beef is with its information hiding. Skip From mtebeka at qualcomm.com Thu Sep 29 09:09:21 2005 From: mtebeka at qualcomm.com (Miki Tebeka) Date: Thu, 29 Sep 2005 16:09:21 +0300 Subject: Documenting members In-Reply-To: References: Message-ID: <20050929130921.GA8196@qualcomm.com> Hello Lasse, > I have a Connection class that exposes members for the hostname, etc. > > ie. > > class Connection: > def __init__(...): > self.server = server > > is there any way to document this "server" member? The only way I know > of right now is to expose it as a property and add the doc string to > that definition. > > I've tried finding an example in the lib code installed with Python but > can't seem to track down anything that is documented like that. IIRC Epydoc can do it. However you can't place the documentation directly next to the member but in the class document string. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From nyamatongwe+thunder at gmail.com Sun Sep 25 19:17:06 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 25 Sep 2005 23:17:06 GMT Subject: cElementTree clear semantics In-Reply-To: <1127679685.586120.312690@g47g2000cwa.googlegroups.com> References: <3po78hFbdl84U1@individual.net> <3po7i3Fbdl84U2@individual.net> <1127679685.586120.312690@g47g2000cwa.googlegroups.com> Message-ID: Paul Boddie: > Regardless of anyone's alleged connection with Boo or newsgroup > participation level, the advice to contact the package > author/maintainer is sound. It happens every now and again that people > post questions to comp.lang.python about fairly specific issues or > packages that would be best sent to mailing lists or other resources > devoted to such topics. It's far better to get a high quality opinion > from a small group of people than a lower quality opinion from a larger > group or a delayed response from the maintainer because he/she doesn't > happen to be spending time sifting through flame wars amidst large > volumes of relatively uninteresting/irrelevant messages. As the author of a widely used component (Scintilla) I feel public fora should be preferred over private mail since * The effort in answering is spread over more people. * The author will only have experience in a narrow range of usage and the query is likely to match some other user's experience. * The author may be out of touch or busy. * The author will make mistakes which can be picked up by other participants. I'd estimate that 10% of the answers I give are wrong or useless, sometimes due to misunderstanding the query and sometimes due to confusion over how the component works. * Public fora are archived and searchable. Neil From jjl at pobox.com Sun Sep 25 11:06:44 2005 From: jjl at pobox.com (John J. Lee) Date: 25 Sep 2005 15:06:44 +0000 Subject: How to decompile an exe file compiled by py2exe? References: <4e307e0f050923234732e2a7e9@mail.gmail.com> <4e307e0f050924062979bef071@mail.gmail.com> Message-ID: <87ll1lw5iz.fsf@pobox.com> Leo Jay writes: [...] > I opened the `hjparser.exe' file in UltraEdit(a hex editor), and found > some partial statements and comments but not complete. > > so, my problem is i'm sure that the source code is in `hjparser.exe' > but i don't know how to decompile the executable file `hjparser.exe' > into `hjparser.py', [...] Unfortunately, things we're sure of are not always true. But you could try asking on the relevant mailing list for py2exe, making sure to say some nice things about Thomas Heller at the same time ;-) Personally, if the source were valuable to me, I would stop using my hard drive immediately and pay a company to try to recover it, perhaps making a direct copy of my HDD first using a low level copy command like dd, so I had my other data to continue working with (though of course, I'd hope I would have a restorable backup if it were valuable). John From bokr at oz.net Sat Sep 17 12:36:03 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 17 Sep 2005 16:36:03 GMT Subject: Dictionary sorting problem References: <1126899106.189220.209940@o13g2000cwo.googlegroups.com> <432b2032$0$11071$e4fe514c@news.xs4all.nl> <432b6439.1661489986@news.oz.net> Message-ID: <432c407a.1717875864@news.oz.net> On 17 Sep 2005 11:01:41 GMT, Duncan Booth wrote: >Bengt Richter wrote: > >> or tell sorted what to do ;-) >> >> >>> original= { >> ... 'hello':135, >> ... 'goodbye':30, >> ... 'lucy':4, >> ... 'sky':55, >> ... 'diamonds':239843, >> ... 'yesterday':4 } >> >>> list(sorted(original.iteritems(), None, lambda t:t[1], True)) >> [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30), >> ('yesterday', 4), ('lucy',4)] > >or a slight variation on this theme which just gives you the keys in value >order rather than the tuples: > >>>> for k in sorted(original, key=original.get, reverse=True): > print k, original[k] > Nice. I like the keyword usage too. Much clearer than my hastypaste ;-) > >diamonds 239843 >hello 135 >sky 55 >goodbye 30 >yesterday 4 >lucy 4 Regards, Bengt Richter From no at spam Sat Sep 17 13:41:33 2005 From: no at spam (D H) Date: Sat, 17 Sep 2005 12:41:33 -0500 Subject: Why doesn't IDLE editor windows have horizontal scrollbars? In-Reply-To: <1126897568.799419.67360@g49g2000cwa.googlegroups.com> References: <1126881900.117737.10990@g43g2000cwa.googlegroups.com> <432b01bc$0$988$626a14ce@news.free.fr> <1126897568.799419.67360@g49g2000cwa.googlegroups.com> Message-ID: chuck wrote: > Well I don't want to start yet another thread on IDE's. I've googled > and all of that an am aware of most of the IDE's that are out there. I > am curious if there is someplace where statistics have been captured on > what IDE's most people are using. Since IDLE ships with Python I > assume a lot of people use it. I've been a PythonWin user for years > but it has shortcomings, isnt' being developed further and doesn't run > on FreeBSD, my other platform. > I like the JEdit editor, which is free and cross-platform ( http://www.jedit.org/ ), and for the interpreter if you ever use that, there is the normal console (cmd.exe in windows) or see also IPython. There is also a console plugin for JEdit. But if you want a more full-featured IDE with project management, etc., there is a Python addin for the Eclipse IDE called pydev I believe. I haven't tried it myself though. From rtw at freenet.co.uk Sat Sep 3 17:06:03 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 03 Sep 2005 16:06:03 -0500 Subject: Managing events References: <4319d765$0$1738$8fcfb975@news.wanadoo.fr> Message-ID: cantabile wrote in news:4319d765$0$1738$8fcfb975 at news.wanadoo.fr in comp.lang.python: > Hi, > > I have a class (a gui) with buttons and other controls. A button, for > example, has a callback method, so that writing > > b = Button(label, OnClick) > > will call the global OnClick method. > > Now, if I want the OnClick method to call some of my main class > methods, > I need to write: > > UI = None > ... > class MainClass: > ... > global UI = self > > > Then, > def OnClik(button): > UI.do_something(button.get_label()) > > Is this the correct way to do it in Python ? Try: class MainClass: def do_something( self, label ): pass def OnClick( self, button ): self.do_something( button.get_label() ) def some_method( self ): b = Button( label, self.OnClick ) With the above you could also do: main = MainClass() b = Button( "A Label", main.OnClick ) Rob. -- http://www.victim-prime.dsl.pipex.com/ From exarkun at divmod.com Wed Sep 21 19:32:29 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 21 Sep 2005 19:32:29 -0400 Subject: Threading, real or simulated? In-Reply-To: Message-ID: <20050921233229.3914.1764592280.divmod.quotient.19543@ohm> On Wed, 21 Sep 2005 18:23:33 -0500, Sam wrote: >I'm using Python 2.3.5 with pygtk 2.4.1, and I'm using the second threading >approach from pygtk's FAQ 20.6 - invoking "gtk.gdk.threads_init()", and >wrapping all gtk/gdk function calls with >gtk.threads_enter()/gtk.threads_leave() > >I start a thread, via thread.Threading.start(). The thread then calls a >particularly time consuming C function, from an extension module. I find >that when the thread is running the C code, the GUI hangs even though I'm >not inside the threads_enter/threads_leave territory. > Does the extension module release the GIL? It sounds like it does not. Of course, there are a dozen other mistakes that could be made which would have roughly this symptom. It's difficult to say which is the problem without actually seeing any code. >It looks like thread.Threading() only simulates threading, by having the >python interpreter multiplex between running threads. Is real threading >possible, so that I do something time-consuming in the thread, without >hanging the GUI? > Assuming you mean threading.Thread, this is a native thread. It is not a simulation. Something else is going wrong. Jp From ym66 at cornell.edu Sat Sep 10 20:09:54 2005 From: ym66 at cornell.edu (Yevgeniy (Eugene) Medynskiy) Date: Sat, 10 Sep 2005 17:09:54 -0700 Subject: calling command line programs? Message-ID: Hi all, This is probably a very newbie question, but after searching google and docs @ python.org I can't find an answer, so maybe someone would be able to help? I'd like to call command-line functions from my python script (like you would in perl using backticks)... Is there a way of doing this? And if so, how does the environment get treated (I have some variables in my env that the programs I'd be calling need to see). Thanks much! Eugene From jonhewer at gmail.com Thu Sep 1 04:32:06 2005 From: jonhewer at gmail.com (Jon Hewer) Date: Thu, 1 Sep 2005 09:32:06 +0100 Subject: command line arguments In-Reply-To: References: <1125512004.352928.103620@g47g2000cwa.googlegroups.com> Message-ID: >What's the purpose of this utility? Is it to do something with the URL? >And the URL must always be specified? What about the name? Also >mandatory, or optional? The relationship between the two? its just a simple rss reader. i'm writing it almost purely just to get me using language (i'm learning python) it lets you save rss feeds, and to do this one would specify a name and url (ie you have to specify both), but there are other things it can do (remove a rss feed, view a feed) hence i thought it was best to using command line options >You also could opt for the OptionParser in optparse.. Thanks, i'll take a look On 8/31/05, Michael Hoffman wrote: > wittempj at hotmail.com wrote: > > > py> parser.add_option("-n", "--name", dest="name", action="store", > > py> help="enter a name") > > py> parser.add_option("-u", "--url", action="store", dest="url", > > help = "enter an url") > > It's worth noting that this will have the same effect and involves less > repetitive typing: > > parser.add_option("-n", "--name", help="enter a name") > parser.add_option("-u", "--url", help="enter a url") > > Discovering this has made optparse usage much more painless for me, and > also reduces the incidence of those nasty multiple line option additions. > > Although I should note for the record that I agree with Peter Hansen > that if the arguments are not *optional* then they should not be made > options in this manner. > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list > From reinhold-birkenfeld-nospam at wolke7.net Fri Sep 23 12:44:50 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 23 Sep 2005 18:44:50 +0200 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com><1127426064.277907.251710@g47g2000cwa.googlegroups.com> <3pgqp0Fagh77U1@individual.net> Message-ID: <3pipo3Faf4s8U1@individual.net> Fredrik Lundh wrote: > Reinhold Birkenfeld wrote: > >>> And I think the discussion that followed proved your point perfectly >>> Fredrik. Big discussion over fairly minor things, but no "big picture". >>> Where are the initiatives on the "big stuff" (common documentation >>> format, improved build system, improved web modules, reworking the >>> standard library to mention a few) Hey, even Ruby is passing us here. >> >> This is Open Source. If you want an initiative, start one. > > you know, this "you have opinions? fuck off!" attitude isn't really helping. If I had wanted to say "you have opinions? fuck off!", I would have said "you have opinions? fuck off!". All I wanted to say is that if you want a common documentation format, and you want it badly, you should show up on python-dev and offer help. Unfortunately, there are not as many Python core developers as Perl core developers, and things move at a slower pace. That's mostly not their fault, and not anyone's fault. It's a consequence of the amount of time that is spent on Python-the-core itself. And why? Well, because it's more fun to program in Python than to program Python. Reinhold From qvx3000 at gmail.com Sat Sep 24 16:47:00 2005 From: qvx3000 at gmail.com (qvx) Date: 24 Sep 2005 13:47:00 -0700 Subject: Poor man's OCR: need performance improvement tips References: <1127585677.391112.70130@g49g2000cwa.googlegroups.com> Message-ID: <1127594820.721640.302800@g14g2000cwa.googlegroups.com> I also have 0 OCR experience, but the case is simple enough. I know about scipy but I have 0 experience with it. I was actually hoping somebody who knows about it might have some recipe. I also tried psyco, but unfortunetly, the speedup is only few percent. I will check out ADaM's site. I was hoping to replace matrix comparison with something more efficient (minimal code change). I like the idea of dictionary lookup but it requires more code to be changed. If nothing else comes up I will probably try this method. Of course I will have to check the wider characters first so there will be presumably several lookups for each position. The only problem here is how to efficiently transform portions of input picture into suitable format (some kind of list/buffer). Thanks. From caleb1 at telkomsa.net Mon Sep 19 14:41:38 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Mon, 19 Sep 2005 20:41:38 +0200 Subject: mathschallenge.net WAS Brute force sudoku cracker References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> <1126909078.589245.253390@g47g2000cwa.googlegroups.com> Message-ID: Very interesting that sudoku solving appears on the python group - there is a programming competition at mathschallenge.net (euler) where one of the puzzles is developing a sudoku solving algorithm... Actually the python entrants are giving the C guys a good run! On Mon, 19 Sep 2005 09:12:54 +0200, Antoon Pardon wrote: > Op 2005-09-16, my.correo.basura at gmail.com schreef > : >> >> Bas ha escrito: >> >>> Hi group, >>> >>> I came across some of these online sudoku games and thought after >>> playing a game or two that I'd better waste my time writing a solver >>> than play the game itself any longer. I managed to write a pretty dumb >>> brute force solver that can at least solve the easy cases pretty fast. >>> >>> It basically works by listing all 9 possible numbers for all 81 fields >>> and keeps on striking out possibilities until it is done. >>> [snip] >> >> This problem is desperately begging for backtracking. > > I don't think so. I regularly solve one and I never needed > to try something out, to see if it worked or not except > when there were muliple solutions. > > I think it is a beautifull problem, to make people think of > how they could code some of their thought processes, which > would be a more fruitfull experience as programming this > with backtracking. > From frank at chagford.com Tue Sep 13 04:01:08 2005 From: frank at chagford.com (Frank Millman) Date: 13 Sep 2005 01:01:08 -0700 Subject: How to protect Python source from modification In-Reply-To: References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Message-ID: <1126598468.001875.16230@g49g2000cwa.googlegroups.com> Bugs wrote: > As a side question Frank, how was your experiences using wxPython for > your GUI? > Any regrets choosing wxPyton over another toolkit? > Was it very buggy? > How was it to work with in general? > Any other real-world wxPython feedback you have is appreciated. > > Frank Millman wrote: > > I am writing a multi-user accounting/business system. Data is stored in > > a database (PostgreSQL on Linux, SQL Server on Windows). I have written > > a Python program to run on the client, which uses wxPython as a gui, > > and connects to the database via TCP/IP. > > > Difficult to give a balanced answer, but I will try. wxPython more or less chose itelf. I need the gui to work on Windows and Linux. Alternatives were Tkinter and PyQt. I got the impression from reading other comments that Tkinter is a bit old-fashioned and does not have a native look and feel, and PyQt is not free on Windows. That left wxPython. I did not evaluate the others, so I cannot compare directly, but do I have any regrets - no. Some things that I thought would be difficult I found amazingly easy. Other things that should have been simple gave me endless trouble. Understanding the concept of 'sizers' (for laying out the widgets on the screen) took me a while to grasp, and it is still not 100% clear, but I can get it to do most of what I want. The cross-platform capability is very good, but there were times when I got something to work on one platform and not the other. After much experimenting I usually managed to get it to work on both, often with a surprising side-effect - the code I eventually used was often cleaner and felt more correct than my original attempt, and therefore if I had been more experienced and done it the 'right' way in the first place, I may not have had a problem. Documentation is not perfect, though it is being worked on. The primary source is the documentation for wxWidgets, which is written in C++. Some people have commented that they do not understand the format, as the C++ function calls are not quite the same as Python's, but personally I did not find this a problem. A bigger problem is that the documentation does not keep up to date with the product, so there are often new features available that are not apparent. I have got into the habit of doing a dir() on most of the objects, to see if they have any methods that are not listed in the docs - quite often they do. Work has started on proper wxPython documentation, and apparently it looks quite good, but I have not used it. There is also a book in the pipeline. Support from the wxPython community is exceptional. There is a very willing and helpful mailing list, and a wiki with a lot of useful stuff. The main developer of wxPython, Robin Dunn, is a regular contributor to the mailing list, and is the authoritative source of up to date information. Unfortunately he has been tied up with personal business for a few months, and his absence from the list is quite noticeable. I am sure I speak for the entire list when I say I am really hoping that he returns soon - it makes us realise how dependent we are on him. Overall, I have found the experience frustrating from time to time, but I am happy with what I have achieved. I have shown samples of my app to a few people, and the appearance has never even raised a question - it just looks and feels like a modern gui application, and I can get on with demonstrating the functionality, which is as it should be. My 2.5c Frank From fredrik at pythonware.com Thu Sep 15 02:41:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Sep 2005 08:41:14 +0200 Subject: What XML lib to use? References: <0001HW.BF4CD7C600321189F0407550@news.individual.de><1126708245.864026.305870@g49g2000cwa.googlegroups.com> <1126734266.355342.97360@f14g2000cwb.googlegroups.com> Message-ID: Robert Kern wrote: > His interpretation of your words is a perfectly valid one even in the > context of this thread. "in Python" explicitly provides a context for > the rest of the sentence. Exactly. "in Python", not "in an application with an existing API". (also, if the OP had been forced to use an existing API by external constraints, don't you think he would have mentioned it?) > In English, at least, it is perfectly reasonable to presume that explicit > contexts override implicit ones. Letting a part of a sentence override the context of the discussion is perhaps popular in certain tabloid journalist circles, and among slash- dot editors and US political bloggers, but most people do in fact have a context buffer memory that can hold more than a few words. (how come you're so sure I wasn't talking about, say, the Python Lisp com- piler? or the Monty Python sketch with the sadistic Belgian instrument- making monk? or a Harry Potter book?) I know what I meant. You know what I meant. Paul knows what I meant. If you still want to play the "but there is a way to interpret this in another way" game, file a bug report against the python.org "what is python?" summary page. From claudio.grondi at freenet.de Tue Sep 6 11:55:18 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 6 Sep 2005 15:55:18 -0000 Subject: left/right mouse button events not trapped References: <1126011805.903624.194460@z14g2000cwz.googlegroups.com> Message-ID: <3o5leuF46dvvU1@individual.net> I don't know much about wxPython, but the left/right mouse button events _ARE_ trapped, but not when clicking on the image, probably because they are registered to the panel not to the image. Just resize the window and click next to the image. Hope this helps for now, before you get a response from someone who knows some more about wxPython (e.g. why the events from the bitmap are not forwarded to the panel containing it?). Claudio P.S. Here the corrected code I was able to run on my machine: import string import wx # import images import os import cStringIO import xml.sax from wxPython.wx import * # from Main import opj class DisplayPicture(wx.Frame): cD = 0 def __init__(self, parent, id, title, bmp, w, h): wxFrame.__init__(self, parent, wxID_ANY, title, size = ( w, h), style=wxDEFAULT_FRAME_STYLE ) mD = 0 self.Panel=wx.Panel(self) wx.StaticBitmap(self.Panel, -1, bmp, (5, 5) ) """ FOR SOME REASON THE MOUSE CLICKS DON-T WORK!""" """ SHIT SHIT SHIT SHIT ... x 1000 """ wx.EVT_LEFT_DOWN(self.Panel, self.OnLeftClick) wx.EVT_LEFT_UP(self.Panel, self.OnLeftClick) wx.EVT_LEFT_DCLICK(self.Panel, self.OnLeftClick) self.CreateStatusBar() self.Show() self.SetStatusText('Submap Coordinates:') def OnLeftClick(self, event): print "ok the mouse click works!" class MyApp(wx.App): cD = 0 def OnInit(self): wx.InitAllImageHandlers() return 1 # # Main # if __name__ == "__main__": app = MyApp(0) data = open('e:\winnt\Granit.bmp', "rb").read() stream = cStringIO.StringIO(data) bmp = wx.BitmapFromImage( wx.ImageFromStream( stream )) bmpW = bmp.GetWidth() bmpH = bmp.GetHeight() DisplayPicturePanel=DisplayPicture(None, -1, "Test MB", bmp, bmpW, bmpH) #MainFrame = DisplayPicture(None,-1,"Test Mouse Clicks") app.MainLoop() schrieb im Newsbeitrag news:1126011805.903624.194460 at z14g2000cwz.googlegroups.com... > Hi, > > I have included a small listing. The test program opens a panel and > show a bitmap. > What I want is to when the mouse is over the bitmap panel, I want to > trap the left mouse click. > The purpose is to get the position of the mouse pointer on the bitmap. > However, for some reason, the left (I also tried right) mouse clicks > are not intercepted. > I new to Python and wxWindows so any help would be greatly appreciated. > > With kind regards, > > Kris > " > import string > import wx > import images > import os > import cStringIO > import xml.sax > > from wxPython.wx import * > from Main import opj > > class DisplayPicture(wx.Frame): > cD = 0 > > def __init__(self, parent, id, title, bmp, w, h): > wxFrame.__init__(self,parent,wxID_ANY, title, size = ( w, h), > style=wxDEFAULT_FRAME_STYLE) > > mD = 0 > > self.Panel=wx.Panel(self) > wx.StaticBitmap(self.Panel, -1, bmp, (5, 5) ) > > """ FOR SOME REASON THE MOUSE CLICKS DON'T WORK!""" > """ SHIT SHIT SHIT SHIT ... x 1000 """ > wx.EVT_LEFT_DOWN(self.Panel, self.OnLeftClick) > wx.EVT_LEFT_UP(self.Panel, self.OnLeftClick) > wx.EVT_LEFT_DCLICK(self.Panel, self.OnLeftClick) > > > self.CreateStatusBar() > self.Show() > > self.SetStatusText('Submap Coordinates:') > > def OnLeftClick(self, event): > print "ok the mouse click works!" > > class MyApp(wx.App): > cD = 0 > def OnInit(self): > wx.InitAllImageHandlers() > return 1 > > # > # Main > # > > if __name__ == "__main__": > app = MyApp(0) > > > data = open(opj('c:\winnt\Greenstone.bmp'), "rb").read() > stream = cStringIO.StringIO(data) > bmp = wx.BitmapFromImage( wx.ImageFromStream( stream )) > bmpW = bmp.GetWidth() > bmpH = bmp.GetHeight() > DisplayPicturePanel=DisplayPicture(None, -1, "Test MB", bmp, bmpW, > bmpH) > #MainFrame = DisplayPicture(None,-1,"Test Mouse Clicks") > > > app.MainLoop() > " > From catalin.marinas at gmail.com Sun Sep 25 04:30:30 2005 From: catalin.marinas at gmail.com (Catalin Marinas) Date: Sun, 25 Sep 2005 09:30:30 +0100 Subject: [RFC] Parametric Polymorphism Message-ID: Hi, Sorry if this was previously discussed but it's something I miss in Python. I get around this using isinstance() but it would be cleaner to have separate functions with the same name but different argument types. I think the idea gets quite close to the Lisp/CLOS implementation of methods. Below is just simple implementation example (and class functions are not supported) but it can be further extended/optimised/modified for better type detection like issubclass() etc. The idea is similar to the @accepts decorator: methods = dict() def method(*types): def build_method(f): assert len(types) == f.func_code.co_argcount if not f.func_name in methods: methods[f.func_name] = dict() methods[f.func_name][str(types)] = f def new_f(*args, **kwds): type_str = str(tuple([type(arg) for arg in args])) assert type_str in methods[f.func_name] return methods[f.func_name][type_str](*args, **kwds) new_f.func_name = f.func_name return new_f return build_method And its utilisation: @method(int) def test(arg): print 'int', arg @method(float) def test(arg): print 'float', arg test(1) # succeeds test(1.5) # succeeds test(1, 2) # assert fails test('aaa') # assert fails Let me know what you think. Thanks. -- Catalin From mde at tracos.org Wed Sep 28 12:10:39 2005 From: mde at tracos.org (Micah Elliott) Date: Wed, 28 Sep 2005 09:10:39 -0700 Subject: PEP 350: Codetags In-Reply-To: <20050926223521.GE10940@kitchen.client.attbi.com> References: <20050926223521.GE10940@kitchen.client.attbi.com> Message-ID: <20050928161039.GF10940@kitchen.client.attbi.com> Thanks to all who have read and/or provided feedback. There have been some great ideas and admonitions that hadn't crossed my mind. I'll paraphrase some of the responses for the sake of brevity; I don't mean to misquote anyone. Tom> ISO 8601 includes a week notation. That's great. Thanks for pointing it out; seems like it should be the preferred week format. I might also want to allow a simple W42 (say) since it's so much shorter, and I'll consider myself generally in trouble if I wrap around on the year for due items. Terry> Shorter forms such as DO, FIX, DEF, DOC, etc. are better. I like the short proposals, so I'll add, and possibly even canonize them. My proposed canons were based on popular use and also my taste. I had originally wanted to state that only the canonical forms would be supported and use of the synonyms should be deprecated. That would have simplified things a bit (human and tool parsing). But based on people's ideas about what is canonical, that would never have flown. Instead, it seems useful to just list everything that's ever been used as long as it *fits one of the categories*. And the canon is mostly arbitrary/unnecessary; we'd never settle that peacefully anyway. The main point is that official categorization enables construction of productivity tools. Terry> IDEXXX isn't vim/emacs. Offer an x:"comment" field for a Terry> completed item. Bengt> Later a tool can strip this out to the devlog.txt or DONE Bengt> file, when the tool sees an added progress line like Bengt> # ---: woohoo, completed ;-) I wish we could rely on everyone to have/use cron. These are both great ideas. I'd like to allow/have both. Bengt> 7) A way of appending an incremental progress line to an existing code Bengt> tag line, e.g., Bengt> # FIXME: This will take a while: rework foo and bar Bengt> # ...: test_foo for new foo works! Bengt> # ...: vacation Status updates? Nice!! Great syntax too. Bengt> time, embedded in strings, scope, no DONE, same line as code... Your pennies are gold! Thanks! Another thing that came to mind recently: As with docstrings, the first sentence of a multiline codetags should be a meaningful summary. So for multiline codetags I'll suggest that the fist line be something that could show up in say a manpage or a BUGFIX file. Terry> Terminator <> is evil. Whitespace is good. Bruno> Or if the codetag is immediately followed by code it's Bruno> terminated. Yes, I'd actually forgotten that it is also not-equal! And I agree that \n\n (or code) is a good terminator. I had been in the practice of putting some TODOs together near the tops of my modules, but a white line between would probably look cleaner anyway. Phillip> there should be something besides just a comment to Phillip> distinguish these things; like starting with a symbol (e.g. Phillip> # !FIXME), so that that documentation extraction tools can Phillip> distinguish code tags from other documentation that just Phillip> happens to start with a CAPITALIZED word. That might be necessary. But if the extraction tools are aware of all official codetags, then it becomes less important. It might even be useful for lint tools to comment when seeing a line that begins with say "# FOO:" but isn't a codetag. Most such uses probably fall under one of the proposed categories anyway. pythondev> It has always been my choice to *only* use XXX. I hope there pythondev> aren't any developers contributing to the Python core who pythondev> use any others? $ csrcs=$(find ~/archive/Python-2.4.1 -name *.c) $ for tag in '!!!' '\?\?\?' XXX WARN CAUTION \ TBD FIXME TODO BUG HACK Note NOTE RFE IMPORTANT; do echo -n "$tag: "; egrep"\b$tag" $csrcs |wc -l done !!!: ~1 \?\?\?: ~12 [most of these part of XXXs] XXX: 365 WARN: ~4 CAUTION: 16 TBD: ~2 FIXME: 12 TODO: 12 BUG: 0 HACK: 0 Note: ~306 NOTE: ~9 RFE: 0 IMPORTANT: ~6 [some overlap with NOTEs] I subtracted most of the false positives but I think the model is being implicitly used to a small degree already. It's just hard to know that they're in the code. I'm impressed there are so few in 365 KLOC. I also notice some WHO: initials, as well as Hmmm:, bad:, Reference:, Obscure:, NB:, Bah:, and others. pythondev> I honestly don't see much of a point for pythondev> distinguishing different types; these are for humans to read pythondev> and review, and different tags just makes it harder to grep. Yes, they are hard to grep! And so are XXXs if multi-line. You'd have to do something like "$EDITOR `grep -l XXX $csrcs`" to really grok them. That's why a different tool is needed for inspection. Even if the codetag paradigm is despised for a given project, something (pychecker/pylint) needs to do a proper scan to address/remove/alert them. I won't argue that the interpreter should adopt codetags, but it would at least benefit from lint recognition. Phillip> You still need a tracking system. Agreed, for most projects, and I think Trac is great. But some might want to use codetags as a way to track anything that is not a full-blown bug. And how many times have you seen small projects that say, "We don't have a bug tracker yet. Please just send bugs to "? Josiah> Some even count exclamation points as an indicator of severity. Michael> I prefer TODO SMELL STINK STENCH VOMIT to indicate TODO priority. These seem useful. But I personally prefer a single TODO with a numeric priority, and I feel that the p: field is the simplest way to get that (easier to remember numbers 0..3 than contaminations or !-counts). I think the example you gave could be done with a "# FIXME: ..." and still be obvious, or even "# FIXME: ...", assuming you have mapped your bletcherosity level to numbers. This also assumes Terry's whitespace idea is used so the fields could show up at the front. Note that the PEP has separated TODO from FIXME semantics. Josiah> an unofficial spec is sufficient. See koders.com and search Josiah> for 'fixme' to see some common variants. But that's the problem -- there are already a bunch of "unofficial" specs, which don't serve much purpose as such. It's a cool site. I spent some time browsing and I do see a lot of codetags in use (many thousands in Python code alone; I'm not sure if the number represented strings or files). But I'll argue that this just reinforces the need for an *official* spec/guideline, so that the tools can do something with them. Paul> Such a PEP should not be approved unless there's Paul> already an implementation (e.g. PyChecker patch) Phillip> implement some tools, use them for a while, and come back Phillip> with more focused use cases Phillip> It seems like a spec in search of an application. The Phillip> Motivation is sorely lacking My two main motivations are avoiding duplication (for documentation) and organizing tasks. I'm presently using it on a smallish project (5 KLOC) to generate manpage sections (fed to help2man) for BUGS, GLOSSARY, and RFE. These should arguably be dumped to a BUGS/BUGFIX/ChangeLog file. I haven't yet figured out how to make Trac or SourceForge do a nice creation of such a file, though it's essential IMO to provide one with a source package. BUGS files are also non-standardized, though I've seen some pretty nice (yet wildly different) ones, and a tool could help here. The other current use (for me) is as a grep replacement. The tools (just ctdoc right now) are limited (pre-alpha) but really help me address the right tasks in the right order. See for a little comparison to grepping. I do think that the health-o-meter is also valuable (I see that pylint already does a nice job of this). I agree that proof of value is necessary. Without a spec though it will be hard to get people to know about a convention/toolset, so it's a bit of a chicken-egg problem -- I can't have a pep until the tools are in use, but the tools won't be used until programmers have means/motivation to use them, a pep. But now that I have your feedback/ideas I (and maybe the lint folks) can do better job of expanding flexible tools that can prove this paradigm useful (or useless). I will continue development on the tools and encourage anyone interested in using a standard set of codetags for documentation and tracking purposes to give them a try (and provide more feedback!) as they mature. -- Micah Elliott From max at alcyone.com Fri Sep 9 00:25:33 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 08 Sep 2005 21:25:33 -0700 Subject: What's the difference between VAR and _VAR_? In-Reply-To: <1126239543.098530.98570@f14g2000cwb.googlegroups.com> References: <1126239543.098530.98570@f14g2000cwb.googlegroups.com> Message-ID: Johnny Lee wrote: > I'm new in python and I was wondering what's the difference between > the two code section below: > > (I) > class TestResult: > _pass_ = "pass" > _fail_ = "fail" > _exception_ = "exception" > > (II) > class TestResult: > pass = "pass" > fail = "fail" > exception = "exception" > > Thanks for your help. There's nothing per se different between a variable named 'x' and one named '_x_'. The difference here is that pass is a keyword, so pass = 'pass' is illegal. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Experience is the name everyone gives to their mistakes. -- Oscar Wilde From am_public at email.it Thu Sep 29 03:54:17 2005 From: am_public at email.it (Mattia Adami) Date: 29 Sep 2005 00:54:17 -0700 Subject: c/c++ and python In-Reply-To: References: <1127978190.737988.89990@g47g2000cwa.googlegroups.com> Message-ID: <1127980457.858605.288150@g47g2000cwa.googlegroups.com> Thanks a lot, very clear and usefull anser! Yes, I know PyGTK and wxPython, but I want to develop a plugin for another application that requires c++. I guess that embedding is the appropriate way. Thanks. From stefnin at alussinan.org Wed Sep 28 12:43:37 2005 From: stefnin at alussinan.org (Stéphane Ninin) Date: 28 Sep 2005 16:43:37 GMT Subject: import problems in packages Message-ID: Hello all, I have an ImportError problem, which is probably correct, but I do not understand it. And how to fix it... Here is the basic structure of the code (I have reduced it first). ROOT: /main.py /Handlers/__init__.py (empty) /Handlers/Handlers.py /Handlers/HandlerFactory.py /Handlers/Default/__init__.py (empty) /Handlers/Default/Handlers.py /Handlers/Default/HandlerFactory.py Now, for the content of the files: ROOT/main.py contains: def main(): command = 'A' from Handlers.HandlerFactory import HandlerFactory handler = HandlerFactory().makeHandler(command) main() ROOT/Handlers/Handlers.py contains: class HandlerBase(object): pass ROOT/Handlers/HandlerFactory.py contains: def HandlerFactory(): import Handlers.Default.HandlerFactory return Handlers.Default.HandlerFactory.HandlerFactory() ROOT/Handlers/Default/Handlers.py contains: from Handlers.Handlers import HandlerBase class Handler(HandlerBase): pass and finally: ROOT/Handlers/Default/HandlerFactory.py contains: from Handlers.Default.Handlers import Handler class HandlerFactory(object): def makeHandler(self,command): print 'HERE' return Handler() ... when I start main.py, I get: Traceback (most recent call last): File "main.py", line 8, in ? main() File "main.py", line 5, in main handler = HandlerFactory().makeHandler(command) File "c:\ROOT\Handlers\HandlerFactory.py", line 6, in HandlerFactory import Handlers.Default.HandlerFactory ImportError: No module named Default.HandlerFactory Using a bit different structure (with relative imports), I also had an ImportError in ROOT/Handlers/Default/Handlers.py I guess there is something I do not understand in the way Python looks for the correct file in a package... Can someone give me some explanations about what is happening here ? And a way to solve that ? Thanks for any help, -- St?phane Ninin stefnin at alussinan.org From finite.automaton at gmail.com Tue Sep 13 16:26:51 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 13 Sep 2005 13:26:51 -0700 Subject: Windows Python 2.4: Unbuffered flag causes SyntaxError on interactive sessions? Message-ID: <1126643211.523525.22220@o13g2000cwo.googlegroups.com> >From the cmd shell on both Windows 2k and XP, I'm getting this weird syntax error in conjunction with the unbuffered flag. It works fine without -u. Has anyone else encountered it? This didn't happen with Python 2.2... C:\>python -u Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print 'hello' File "", line 1 print 'hello' ^ SyntaxError: invalid syntax (sorry if this is a known/fixed bug... I couldn't find anything about it) From larry.bates at websafe.com Fri Sep 23 12:23:50 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 23 Sep 2005 11:23:50 -0500 Subject: Config parser module In-Reply-To: <1127489369.091513.206040@g49g2000cwa.googlegroups.com> References: <1127489369.091513.206040@g49g2000cwa.googlegroups.com> Message-ID: <43342C16.9070507@websafe.com> ConfigParser is for parsing configuration files of the format: [section1] option1= option2= . . . optionN= [section2] option1= option2= . . . optionN= Your data doesn't fit that format. Looks to me like you should write a small class object for each different type of record that can be found in the file that knows how to parse that record and put the information from that record in to class attributes for easy access. Something like: class gridclass: def __init__(self, recordToParse): elements=recordToParse.split(' ') self.type=elements[0] self.pointId=int(elements[1]) self.coordinateSysNo=float(elements[2]) self.x=float(elements[3]) self.y=float(elements[4]) self.z=int(elements[5]) Then read the lines, determine the line type and create a class instance for each one. -larry qqcq6s59 at gmail.com wrote: > Hi all > I am a newbie and I just saw a ongoing thread on Fileprocessing which > talks abt config parser. > I have writen many pyhton program to parse many kind of text files by > using string module and regex. But after reading that config parser > thread I feel stunned. > > Can somebody tell me some intro info how to parse huge data (most of > them are input data to application softwares like nastran, abaqus etc) > > Recently I saw a great work by John on Nastran file parser (i am still > trying to understand the program, > http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ > > An example of dat may be like this, (part of) > (say point id coordinateSysNo x,y,z ...) > GRID 1 12478.0 0.0 256.75 1 > GRID 2 12357.25 0.0 256.75 1 > GRID 3 12357.25 0.0 199.0 1 > (say Elementtype id property point1 point 2 point3 point4 etc) > CQUAD4 7231 21 5691 5700 5701 56920.0 > > CQUAD4 7232 21 5692 5701 5702 56930.0 > > CQUAD4 7233 21 5693 5702 5703 56940.0 > > the data file is very complex if i consider all complexities) > > Is is possible to use config parser module insome way for this. I also > have few perl parser (for some part for some particular tasks) and now > changing them to python. (I feel perl regex combination is very easy to > learn and very powerfull) > > Any information will be appreciated. > > -jiro > From t-meyer at ihug.co.nz Mon Sep 26 22:26:39 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 27 Sep 2005 14:26:39 +1200 Subject: PEP 350: Codetags In-Reply-To: <7xvf0nuzr7.fsf@ruckus.brouhaha.com> References: <7x64sniedz.fsf@ruckus.brouhaha.com> <7xvf0nuzr7.fsf@ruckus.brouhaha.com> Message-ID: <76965280-810C-4DEA-B989-F7008D0B9BEA@ihug.co.nz> On 27/09/2005, at 12:21 PM, Paul Rubin wrote: > Neil Hodgson writes: > >> The PEP system allows for the documentation of a convention as an >> "Informational PEP". Documenting conventions is useful. > > If the preferred method of doing something is > consistent enough that it can be codified as a convention in a PEP, it > should be implemented in the compiler, so it becomes a language > feature, not a convention. Does this mean that you think that PEP 8 (Python Code Style Guide) should be enforced by the compiler? So that (e.g) lines that are too long just don't compile? I really doubt you'll find much agreement for this (the compiler should enforce it) position. The 'fewer conventions are better' position might enjoy more support, but doesn't strike me as particularly Pythonic (e.g. compare whitespace in Python and C). =Tony.Meyer From pythonic at seehart.com Thu Sep 15 15:51:08 2005 From: pythonic at seehart.com (Ken Seehart) Date: Thu, 15 Sep 2005 12:51:08 -0700 Subject: Creating Pie Chart from Python In-Reply-To: <1126797010.201367.220880@g43g2000cwa.googlegroups.com> References: <1126797010.201367.220880@g43g2000cwa.googlegroups.com> Message-ID: <4329D0AC.4030708@seehart.com> Thierry Lam wrote: > Let's say I have the following data: > > 500 objects: > -100 are red > -300 are blue > -the rest are green > > Is there some python package which can represen the above information > in a pie chart? > > Thanks > Thierry > What is the user interface context? Is it a web page? Do you want to create image files with pie chart? If yes to either of these, try gdchart. http://www.icewalkers.com/Linux/Software/52020/GDChart.html http://athani.pair.com/msteed/software/gdchart/download.html From bruce_taylor at unisoncoaching.com Mon Sep 26 20:31:04 2005 From: bruce_taylor at unisoncoaching.com (bruce_taylor at unisoncoaching.com) Date: 26 Sep 2005 17:31:04 -0700 Subject: How does company culture affect you? Message-ID: <1127781064.380892.271690@g47g2000cwa.googlegroups.com> Please forgive me if this is a little off topic, but I'm trying to reach a population of active programmers and this seems to be a popular gathering place. I am conducting research on how company cultures affect programmer productivity. If you would be willing to take 5 minutes to answer a few questions, you would help me very much and win my undying gratitude. At the end of the survey, you'll have an opportunity to see the results so far, and that might prove interesting. This is NOT a stealth marketing campaign or a recruiting troll. Your data is collected completely anonymously and will be reported only as aggregate statistics. If you're willing to take the survey, please go to this URL: http://www.surveymonkey.com/s.asp?u=596961324075&c=12 In any case, I thank you for your time and attention Bruce From invalid at invalid.com Mon Sep 5 16:15:01 2005 From: invalid at invalid.com (copx) Date: Mon, 5 Sep 2005 22:15:01 +0200 Subject: How to use the OS's native file selector in Tkinter References: Message-ID: schrieb im Newsbeitrag news:mailman.149.1125933157.4249.python-list at python.org... Thank you! copx From pkilambi at gmail.com Fri Sep 30 10:52:53 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 30 Sep 2005 07:52:53 -0700 Subject: grouping array In-Reply-To: References: <1128013300.041801.248180@g14g2000cwa.googlegroups.com> Message-ID: <1128091973.386729.121110@z14g2000cwz.googlegroups.com> fredrick's solutions seems to be more closer to what I was looking for.But I am still not sure if that could be done without the use of Image module. Also in your solution I cannot follow this [[1, 1, 2, 1, 2, 0], [2, 0, 0, 2, 0, 1], [1, 2, 2, 0, 2, 0], [0, 1, 0, 0, 0, 0], [2, 0, 0, 1, 1, 0], [2, 2, 2, 0, 1, 0]] >>> print "\n".join(str(reg) for reg in getregions(x)) [(0, 1), (0, 0), (0, 2), (1, 0), (0, 3), (2, 0), (1, 3), (0, 4), (2, 1), (3, 1), (2, 2)] [(5, 4), (4, 4), (4, 3)] [(5, 0), (5, 1), (4, 0), (5, 2)] [(1, 5)] [(2, 4)] This is kind of confusing...could you please correlate the grid to the result and explain From carlosjosepita at gmail.com Fri Sep 23 17:01:21 2005 From: carlosjosepita at gmail.com (Carlos) Date: 23 Sep 2005 14:01:21 -0700 Subject: Accessing class variable at class creation time Message-ID: <1127509281.767539.271230@g43g2000cwa.googlegroups.com> Hi! class A: X = 2 def F(): print A.X F() The above fails because the name A is not yet at global scope when the reference A.X is reached. Is there any way to refer to A.X without making explicit use of the name 'A'? Admittedly the code looks pretty unusual, but I'm defining configuration "minilanguages" to configure different parts of an application, each inside a configuration class (like A), and I find this very convenient except for the above problem. Thank you in advance Regards, Carlos From crankycoder at gmail.com Mon Sep 26 01:27:56 2005 From: crankycoder at gmail.com (Victor Ng) Date: Mon, 26 Sep 2005 01:27:56 -0400 Subject: Metaclasses, decorators, and synchronization In-Reply-To: <20050926042128.3914.816512439.divmod.quotient.20980@ohm> References: <20050926042128.3914.816512439.divmod.quotient.20980@ohm> Message-ID: Hmmm.... well that's obvious enough. This is why I shouldn't write code off the cuff on c.l.p.... :) OTOH - if I just assign the RLock in the base classes initializer, is there any problem? vic On 9/26/05, Jp Calderone wrote: > > On Sun, 25 Sep 2005 23:30:21 -0400, Victor Ng > wrote: > >You could do it with a metaclass, but I think that's probably overkill. > > > >It's not really efficient as it's doing test/set of an RLock all the > >time, but hey - you didn't ask for efficient. :) > > There's a race condition in this version of synchronized which can allow > two or more threads to execute the synchronized function simultaneously. > > > > > 1 import threading > > 2 > > 3 def synchronized(func): > > 4 def innerMethod(self, *args, **kwargs): > > 5 if not hasattr(self, '_sync_lock'): > > Imagine two threads reach the above test at the same time - they both > discover there is no RLock protecting this function. They both entire this > suite to create one. > > > 6 self._sync_lock = threading.RLock() > > Now one of them zooms ahead, creating the RLock and acquiring it on the > next line. The other one finally manages to get some runtime again > afterwards and creates another RLock, clobbering the first. > > > 7 self._sync_lock.acquire() > > Now it proceeds to this point and acquires the newly created RLock. Woops. > Two threads now think they are allowed to run this function. > > > 8 print 'acquired %r' % self._sync_lock > > 9 try: > > 10 return func(self, *args, **kwargs) > > And so they do. > > > 11 finally: > > 12 self._sync_lock.release() > > 13 print 'released %r' % self._sync_lock > > Of course, when the second gets to the finally suite, it will explode, > since it will be releasing the same lock the first thread to get here has > already released. > > > 14 return innerMethod > > 15 > > 16 class Foo(object): > > 17 @synchronized > > 18 def mySyncMethod(self): > > 19 print "blah" > > 20 > > 21 > > 22 f = Foo() > > 23 f.mySyncMethod() > > To avoid this race condition, you need to serialize lock creation. This is > exactly what Twisted's implementation does. You can read that version at < > http://svn.twistedmatrix.com/cvs/trunk/twisted/python/threadable.py?view=markup&rev=13745 > >. > The code is factored somewhat differently: the functionality is presented > as pre- and post-execution hooks, and there is function decorator. The > concept is the same, however. > > Jp > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Never attribute to malice that which can be adequately explained by stupidity." - Hanlon's Razor -------------- next part -------------- An HTML attachment was scrubbed... URL: From chriss at streiff.org Sat Sep 10 17:49:49 2005 From: chriss at streiff.org (chriss) Date: Sat, 10 Sep 2005 23:49:49 +0200 Subject: calling command line programs? References: <11i6k5m54i7422c@corp.supernews.com> Message-ID: <432354d4$0$1164$5402220f@news.sunrise.ch> Grant Edwards wrote: > On 2005-09-11, Yevgeniy (Eugene) Medynskiy wrote: > >> This is probably a very newbie question, but after searching >> google and docs @ python.org I can't find an answer, so maybe >> someone would be able to help? >> >> I'd like to call command-line functions from my python script >> (like you would in perl using backticks)... Is there a way of >> doing this? And if so, how does the environment get treated (I >> have some variables in my env that the programs I'd be calling >> need to see). > > Take a look at os.popen, os.spawn, or the popen2, and > subprocess modules. > > That last one seems to be gaining popularity. > The suggested modules and functions have been deprecated according to the python 2.4 docs. The doc suggests to use the functions in the 'subprocess' module. chriss From renting at astron.nl Fri Sep 23 04:20:32 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 23 Sep 2005 10:20:32 +0200 Subject: Ide RAD for linux? Message-ID: I use Eric3 as IDE on Linux. From brp13 at yahoo.com Fri Sep 30 14:43:43 2005 From: brp13 at yahoo.com (Tuvas) Date: 30 Sep 2005 11:43:43 -0700 Subject: ASCII In-Reply-To: <433d8376$0$930$da0feed9@news.zen.co.uk> References: <1128104641.277339.31800@g47g2000cwa.googlegroups.com> <433d8376$0$930$da0feed9@news.zen.co.uk> Message-ID: <1128105823.452745.184480@f14g2000cwb.googlegroups.com> Thanks alot! From larry.bates at websafe.com Tue Sep 13 17:57:17 2005 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Sep 2005 16:57:17 -0500 Subject: Unexpected Behavior Iterating over a Mutating Object In-Reply-To: <432740ae.1301867062@news.ispnetbilling.com> References: <432740ae.1301867062@news.ispnetbilling.com> Message-ID: <43274B3D.7040402@websafe.com> You are correct if you remove items from a list that you are iterating over you get the results you see. You either need to iterate over the list in reverse order or better yet create a new list from the old one with the items removed. In Python 2.4 you can do: data = [ 'First', 'Second DEL', 'Third', 'Fourth', 'Fifth DEL', 'DEL Sixth', 'Seventh DEL', 'Eighth DEL', 'Ninth DEL', 'Tenth', 'Eleventh', 'Twelfth'] bfr=[x for x in data if 'DEL' not in x] Note: I'm not sure why 'DEL' is at the end of all the strings EXCEPT the Sixth one where it is at the beginning, but if the "DEL" was consistently at the end of the strings I would do this instead (which would also work in Python 2.2+): bfr=[x for x in data if not x.endswith('DEL')] This also is much easier to read (IMHO) than the loops, etc. of the original code. In Python 2.4 list comprehensions are also quite efficient. Larry Bates Dave Hansen wrote: > OK, first, I don't often have the time to read this group, so > apologies if this is a FAQ, though I couldn't find anything at > python.org. > > Second, this isn't my code. I wouldn't do this. But a colleague did, > got an unexpected result, and asked me why. I think I can infer what > is occurring, and I was able to find a simple work-around. But I > thought I'd ask about it anyway. > > I've been pushing Python at work for use as a scripting language to > get simple tasks done. My colleague is modifying a parts library for > a schematic capture program with a Python script. The library is > entirely in ASCII text. > > He's trying to delete a group of parts from the library. The simple > code below shows what is occurring (taken from an IDLE session, Python > 2.4.1#65 for Windoze). The "parts" to be deleted in the example > contain the string 'DEL': > > ---begin included file--- > >>>>data = [ 'First', 'Second DEL', 'Third', 'Fourth', > > 'Fifth DEL', 'DEL Sixth', 'Seventh DEL', 'Eighth DEL', > 'Ninth DEL', 'Tenth', 'Eleventh', 'Twelfth'] > > >>>>bfr = [] >>>>for item in data: > > if item.find('DEL') >= 0: > bfr.append(item) > data.remove(item) > > > >>>>data > > ['First', 'Third', 'Fourth', 'DEL Sixth', 'Eighth DEL', 'Tenth', > 'Eleventh', 'Twelfth'] > >>>>bfr > > ['Second DEL', 'Fifth DEL', 'Seventh DEL', 'Ninth DEL'] > ---end included file--- > > It seems when an item is 'remove'd from data, the rest of the list > 'shifts' over one, so what was 'next' now occupies the slot of the > 'remove'd item. When the next 'item' is selected from 'data', the > _desired_ 'next' item is skipped. So when 'data' has several > consecutive items to be deleted, only every other one is 'remove'd. > > The workaround is very simple: > > ---begin included file--- > >>>>for item in data: > > if item.find('DEL') >= 0: > bfr.append(item) > > > >>>>for item in bfr: > > data.remove(item) > > > >>>>data > > ['First', 'Third', 'Fourth', 'Tenth', 'Eleventh', 'Twelfth'] > >>>>bfr > > ['Second DEL', 'Fifth DEL', 'DEL Sixth', 'Seventh DEL', 'Eighth DEL', > 'Ninth DEL'] > ---end included file--- > > Again, iterating over an item that is mutating seems like a Bad > Idea(tm) to me. But I was curious: is this the intended behavior, or > does this fall under what C programmers would call 'undefined > behavior.' > > Thanks, > > -=Dave From westside_indie at yahoo.com Thu Sep 22 21:41:21 2005 From: westside_indie at yahoo.com (John Walton) Date: Thu, 22 Sep 2005 18:41:21 -0700 (PDT) Subject: words relating to networks that I should probably know Message-ID: <20050923014121.70012.qmail@web31013.mail.mud.yahoo.com> Hello, again. I'm back with my instant messenger project. My teacher has assigned us to write our papers, excluding the procedure, results, and conclusion. One of my topics is going to be networks. Does anyone know a list of words relating to networking/networks that I should know for this project? Not the definitions, but just the words; I can look up the definitions on webopedia. It would be appreciated. Thanks! -John __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From frank at chagford.com Mon Sep 12 09:34:45 2005 From: frank at chagford.com (Frank Millman) Date: 12 Sep 2005 06:34:45 -0700 Subject: How to protect Python source from modification Message-ID: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> Hi all I am writing a multi-user accounting/business system. Data is stored in a database (PostgreSQL on Linux, SQL Server on Windows). I have written a Python program to run on the client, which uses wxPython as a gui, and connects to the database via TCP/IP. The client program contains all the authentication and business logic. It has dawned on me that anyone can bypass this by modifying the program. As it is written in Python, with source available, this would be quite easy. My target market extends well up into the mid-range, but I do not think that any CFO would contemplate using a program that is so open to manipulation. The only truly secure solution I can think of would involve a radical reorganisation of my program, so I am writing to see if anyone has a simpler suggestion. Here is the idea. 1. Write a socket server program that runs on the server. The socket server is the only program that connects to the database. The client program connects to the server, which authenticates the client against the database and then listens for requests from the client. 2. Devise my own protocol for communication between client and server. For selects, the client sends a request, the server checks permissions, then retrieves the data from the database and passes it to the client. For updates, the client passes up the data to be updated, the server checks it against its business logic, and then updates the database. There is the question of where state should be maintained. If on the server, I would have to keep all the client/server connections open, and maintain the state of all the sessions, which would put quite a load on the server. If on the client, I would have to reorganise my thinking even more, but this would have an advantage - I will eventually want to write a browser interface, and this would be much closer in concept, so the two approaches would be quite similar. This raises the question of whether I should even bother with a gui client, or bite the bullet and only have a browser based front end. Judging from recent comments about new technologies such as Ajax, a lot of the disadvantages have been overcome, so maybe this is the way to go. It would be a shame to scrap all the effort I have put into my wxPython-based front end. On the other hand, it would be pointless to continue with an approach that is never going to give me what I want. Any advice which helps to clarify my thinking will be much appreciated. Thanks Frank Millman From edhotchkiss at gmail.com Sat Sep 17 15:50:29 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Sat, 17 Sep 2005 15:50:29 -0400 Subject: MySQLdb error - PLEASE SAVE ME! In-Reply-To: References: Message-ID: Ok. I am trying to read a csv file with three strings separated by commas. I am trying to insert them into a MySQL DB online. MySQLdb is installed, no problems. I think that I am having some kind of error with my csv going into the fields and being broken apart correctly. Can someone please help? I attached the code below, it does work with that SQL server also if you want to try and run it. Thanks in advance .. ----- # Script to add links from a comma deliminated file to a MySQL database # 9/16/05 import MySQLdb conn=MySQLdb.connect( host="www.freesql.org", user="edhotchkiss", port=3306, passwd="test1", db="links") cursor = conn.cursor() stmt = "DROP TABLE IF EXISTS links" cursor.execute(stmt) stmt = """CREATE TABLE links ( ID INT NOT NULL, Name TEXT, URL LONGTEXT, Category LONGTEXT, primary key (ID) )""" cursor.execute(stmt) arr=[] inp = open ("sites1.txt","r") #read line into array for line in inp.readlines(): links = map(str, line.split(",")) arr.append(links) cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s)""" % tuple(links[0:3]) ) cursor.close() conn.close() -- edward hotchkiss -- edward hotchkiss -------------- next part -------------- # Script to add links from a comma deliminated file to a MySQL database # 9/16/05 import MySQLdb conn=MySQLdb.connect( host="www.freesql.org", user="edhotchkiss", port=3306, passwd="test1", db="links") cursor = conn.cursor() stmt = "DROP TABLE IF EXISTS links" cursor.execute(stmt) stmt = """CREATE TABLE links ( ID INT NOT NULL, Name TEXT, URL LONGTEXT, Category LONGTEXT, primary key (ID) )""" cursor.execute(stmt) arr=[] inp = open ("sites1.txt","r") #read line into array for line in inp.readlines(): links = map(str, line.split(",")) arr.append(links) cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s)""" % tuple(links[0:3]) ) cursor.close() conn.close() -------------- next part -------------- O'reilly Python Archive,http://python.oreilly.com/archive.html,python Python Tutorials,http://www.awaretek.com/tutorials.html,python MySQL Python,http://sourceforge.net/projects/mysql-python,python Python Vaults of Parnassus,http://www.vex.net/parnassus/,python PyCrypto,http://www.amk.ca/python/code/crypto,Python From felix.schwarz at web.de Thu Sep 1 08:38:34 2005 From: felix.schwarz at web.de (Felix Schwarz) Date: Thu, 01 Sep 2005 14:38:34 +0200 Subject: Inline::Python, pyperl, etc. In-Reply-To: References: Message-ID: <3nob74F2evktU1@individual.net> Eli Stevens (WG.c) wrote: > PyPerl 1.0.1 > http://wiki.python.org/moin/PyPerl > > The interest in these projects seems to have died off about 2001, > however. That, or they simply haven't needed to be updated for the last > few Python versions. > > I've bumped into some snags with pyperl (can't import perl2.so? But > it's right there in site-packages/ !), and I'm wondering if it's bitrot > or a config error on my end. > > Similarly, with Inline::Python I end up getting strings passed into my > python code when I expect integers (I posted about this on > inline at perl.org, but things seem pretty dead over there). > > Is anyone actually using any of this stuff? I made some patches to pyperl and the unit testing suite some months ago. At least basic functionality is working again. Have a look at the zope-perl mailing list. I don't know if I announced a single source tar.gz on this mailing list but if you have still some interest in this I can mail you the package. fs From pinard at iro.umontreal.ca Fri Sep 30 13:27:57 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 30 Sep 2005 13:27:57 -0400 Subject: PEP 350: Codetags In-Reply-To: References: <4338bc2f.2535976150@news.oz.net> Message-ID: <20050930172757.GA13021@phenix.progiciels-bpi.ca> [Tom Anderson] > ISO 8601 suggests writing date-and-times like 2005-09-26T12:34:56 - > using a T as the separator between date and time. I don't really like > the look of it, but it is a standard, so i'd suggest using it. ISO 8601 suggests a few alternate writings, and the ``T`` you mention is for only one of them, meant for those cases where embedded spaces are not acceptable. Other ISO 8601 writings accept embedded spaces, and this is how ISO 8601 is generally used by people, so far that I can see. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From peter at commonlawgov.org Sun Sep 25 16:53:12 2005 From: peter at commonlawgov.org (Peter) Date: Sun, 25 Sep 2005 13:53:12 -0700 Subject: Struggling with basics In-Reply-To: <43370854.5090505@commonlawgov.org> References: <43370854.5090505@commonlawgov.org> Message-ID: <43370E38.1000203@commonlawgov.org> Peter wrote: >Jason wrote: > > > >>A week ago I posted a simple little hi-score routine that I was using to >>learn Python. >> >>I've only just managed to examine the code, and the responses that >>people gave, and I'm now seriously struggling to understand why things >>aren't working correctly. >> >>At present my code is as follows... >> >>import random >>import bisect >> >>class HiScores: >> def __init__(self,hiScores): >> self.hiScores=[entry for entry in hiScores] >> >> def showScores(self): >> for score,name in self.hiScores: >> score=str(score).zfill(5) >> print "%s - %s" % name,score >> >> >> def addScore(self,score,name): >> score.zfill(5) >> bisect.insort(self.hiScores,(score,name)) >> if len(self.hiScores)==6: >> self.hiScores.pop() >> >> def lastScore(self): >> return self.hiScores[-1][0] >> >>def main(): >> >>hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] >> >> a=HiScores(hiScores) >> print "Original Scores\n---------------" >> a.showScores() >> >> while 1: >> newScore=str(random.randint(0,10000)) >> if newScore > a.lastScore(): >> print "Congratulations, you scored %s " % newScore >> name=raw_input("Please enter your name :") >> a.addScore(newScore,name) >> a.showScores() >> >>if __name__=="__main__": >> main() >> >> >>My first problem (lack of understanding of course) is that if I run the >>above, I get an error saying: >> >> print "%s - %s" % name,score >>TypeError: not enough arguments for format string >> >> >>Now I understand what it's saying, but I don't understand why. >> >>If I change the code to read: >> >>print "%s - %n" % name, score (thinking of course that ah-ha, score is >>numeric) then I get the same error. >> >>The only way for the program to run is to simply have >> >>print name,score (or print score,name) >> >> >> >> >This is because 'print' is accepting 'score' as a seperate argument, not >the formatting, as you want it to. >Try 'print "%s - %s" % (name, score)' > > > > >>The final part that's simply not working correctly is that the entire >>program isn't sorting the data. >> >>If I run the program and get a score of, say, 6789, then when I add my >>name, nothing is entered. I have changed the clause that deletes (pops) >>the last array if the array count is 6 and seen what figures are being >>entered into the array. >> >>Sure enough they are going in the array, and they are being sorted, but >>they are only being sorted AFTER the 00000 of the initial array creation. >> >>I'm pretty sure it's to do with comparing a string against an integer >>but can't for the life of me see where to force the comparrison to check >>against two integers. >> >> >> >> >> >Humm. This is a harder problem. I will copy this text into JEdit to >highlight the text and see if i cannot find the problem. > > > Correction: I will fix my apearently semi-broaken Python installation wich gives me undefined reference errors from math.h and then see if i cannot fix the problem. -.- >>Apologies for going over old ground and if I'm not understanding, I'm >>getting there honest ;) >> >> >> >> >> > >HTH, >Peter > > > Peter From http Thu Sep 1 06:15:58 2005 From: http (Paul Rubin) Date: 01 Sep 2005 03:15:58 -0700 Subject: Decrypting GPG/PGP email messages References: Message-ID: <7x7je1gkkh.fsf@ruckus.brouhaha.com> Alessandro Bottoni writes: > 1) What would you use to decrypt the messages? The GPG module created by > Andrew Kuchling is declared "incomplete" and "no more maintained" on his > web pages (http://www.amk.ca/python/code/gpg) so I think it is out of the > game. I think I'd just run gpg as an external command. I've done that from perl scripts and it's pretty simple. > Would you use OpenPGP (http://www.aonalu.net/openpgp/python)? Any > other module? Oh hey, I didn't know about that, I'll have to look at it. I started writing something similar a long time ago and got as far as being able to decrypt straightforward messages, and have been meaning to get back to it. But it's great if someone else is doing it more seriously.q > 2) I did not find any mention of _encrypted attachments_ on the Net. Does > anybody know of a tutorial or a guide that explains how to encrypt (with > Thunderbird/Enigmail) and decrypt (with Python) the (ANSI text) files > attached to a email message? PGP/GPG have their own base64 encoding called "ascii armor" in PGP lingo. This stuff predates widespread use of MIME and traditionally, PGP messages are sent as ascii armored plain text, not attachments. You'd just send messages like: From: alice To: bob Subject: encrypted message -----BEGIN PGP MESSAGE----- Version: GnuPG v1.2.1 (GNU/Linux) jA0EAwMC+QyBtnf2kVxgyUgkWXDwnHHu6GR8xYJ4GuorEo8t9BHfExmcwCyUok/z wZsmoCCdulYjLnAjgU0WZRhe7woCrgy14pzc7PSOhqRPEG1IFJqeZuM= =5l/P -----END PGP MESSAGE----- Note the complete absence of mime headers and separators. As far as the mail agents are concerned, the message is just text. I'm not sure how the Thunderbird/Enigmail plugins work. From gkj at gregorykjohnson.com Fri Sep 16 00:00:39 2005 From: gkj at gregorykjohnson.com (Gregory K. Johnson) Date: Fri, 16 Sep 2005 00:00:39 -0400 Subject: Sorting Unix mailboxes In-Reply-To: <1126628615.046122.325960@g43g2000cwa.googlegroups.com> References: <1126628615.046122.325960@g43g2000cwa.googlegroups.com> Message-ID: <20050916040039.GA12820@andy.gregorykjohnson.com> On Tue, Sep 13, 2005 at 09:23:35AM -0700, sfeil at io.com wrote: > I'm writing a program in python to sort the mail in standard Unix > email boxes. In my "prof of concept" example I am coping a letter to a > second mailbox if the letter was send from a particular email > address. [...] > Also, I was wondering is there were a way to use Python to delete items > from a mailbox. As part of Google's Summer of Code program, I wrote a replacement for the mailbox module that would be well suited for this. It might be included in the Python 2.5 distribution. Until then, you could get the module from Python CVS, under nondist/sandbox/mailbox. More info is on the project Web site: http://gkj.freeshell.org/soc/ -- Gregory K. Johnson From erniedude at gmail.com Fri Sep 16 10:49:15 2005 From: erniedude at gmail.com (Ernesto) Date: 16 Sep 2005 07:49:15 -0700 Subject: Wrapper module for Linux shared lib Message-ID: <1126882155.941208.240150@g49g2000cwa.googlegroups.com> What's the best resource for finding out how to write a wrapper module for a shared library file *.so* in Linux? From tmm at fastmail.fm Sat Sep 10 11:18:27 2005 From: tmm at fastmail.fm (Tom) Date: Sat, 10 Sep 2005 11:18:27 -0400 Subject: simple problem with os.rename() parameters - path with spaces In-Reply-To: <6oCdnVNf_rbxU7zeRVn-qA@comcast.com> References: <6oCdnVNf_rbxU7zeRVn-qA@comcast.com> Message-ID: Yes, I am sure about those things. I've tried shutil.move and got the same result. Forward slash? I'll give that a try and report back here if it works. Thanks, Tom. Larry Bates wrote: > Are you sure the source directory exists and you > have rights to rename it? Because the rename works > for me. > > But you may want to look at shutil.move and/or > use forward slashes (they work under Windows) > > -Larry Bates > > > Tom wrote: > >>I'm having a problem using a path with spaces as a parameter to >>os.rename() in a program on WinXP. >> >>This works fine at the command line (where the folder "c:\aa bb" exists) >> >> >>>os.rename( "c\aa bb", "c:\cc dd" ); >>> >> >>But, I can't get it to work in my program, eg. >> >>print SrcDir >>print NewDir >>os.rename( SrcDir, NewDir ); >> >>when I run this I get something like this: >> >>"e:\\music\\Joni Mitchell\\ogg-8" >>"e:\\music.ogg\\Joni Mitchell\\ogg-8" >> >>Traceback (most recent call last): >> File "E:\Music\MoveMusic.py", line 64, in ? >> main(); >>... >> File "E:\Music\MoveMusic.py", line 49, in Visit >> os.mkdir( NewDir ); >>OSError: [Errno 22] Invalid argument: '"e:\\music.ogg\\Joni >>Mitchell\\ogg-8"' >> >>I've tried different combinations of single backslash vs. double >>backslash, and quoted vs. non-quoted, but it always fails. >> >>The problem is not specific to os.rename. If I instead use mkdir( >>SrcDir ) I get the same problem. >> >>Thanks, >>Tom. >> From monuindia at gmail.com Mon Sep 12 06:43:04 2005 From: monuindia at gmail.com (monuindia at gmail.com) Date: 12 Sep 2005 03:43:04 -0700 Subject: read from label Message-ID: <1126521784.766654.10890@g14g2000cwa.googlegroups.com> HI, It may be a very elementry question, but I need to know that how can I get text of a label. From martin at v.loewis.de Wed Sep 14 01:52:15 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Sep 2005 07:52:15 +0200 Subject: python/SSL/Certificate. In-Reply-To: References: Message-ID: <4327ba8e$0$22192$9b622d9e@news.freenet.de> Vanessa PARISSE wrote: > In my website, the user connect in HTTPS whith a client certificate. > I would like to get the email in the certificate. > I'm trying to get the client certificate presented to the server. What does that have to do with Python? Are you trying to use Python on the client side, or on the server side? In either case, what precisely are you trying to do *with Python*? Regards, Martin From billiejoex at fastwebnet.it Mon Sep 5 16:48:19 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Mon, 5 Sep 2005 22:48:19 +0200 Subject: Python compiled? References: <1125951529.838575.107200@z14g2000cwz.googlegroups.com> Message-ID: > there are "noob" questions and there are uneducated questions, yours > are of the latter ( actually yours are STATEMENTS not questions ), and > just trolling for what it is worth, if you would take the time to read > what Python is and why it is you would not be asking these "questions". I'm really sorry man. I didn't wanted to be uneducated, believe me. I wrote fastly, I'm new in Python and probably for my language problems I didn't expressed concepts properly. From jjl at pobox.com Fri Sep 30 17:37:30 2005 From: jjl at pobox.com (John J. Lee) Date: 30 Sep 2005 21:37:30 +0000 Subject: Where to find python c-sources References: Message-ID: <878xxegrtx.fsf@pobox.com> "Tor Erik S??nvisen" writes: > "Erik Max Francis" wrote in message > news:Ab6dnZLcB8e2zqHeRVn-hw at speakeasy.net... > > Tor Erik S?nvisen wrote: > > > >> I need to browse the socket-module source-code. I believe it's contained > >> in the file socketmodule.c, but I can't locate this file... Where should > >> I look? > > > > The source tarball, available on python.org. Are people really too lazy > > to do elementary research on Google? > > > > -- > > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > > The people are to be taken in very small doses. > > -- Ralph Waldo Emerson > > Thanks for the answers... And yes, I have searched google! How odd -- the most useful link (the viewcvs page for this source file) is the very first link for me when I search for socketmodule.c Does google vary in its results across the globe? John From gsakkis at rutgers.edu Sun Sep 18 17:31:14 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 18 Sep 2005 14:31:14 -0700 Subject: Python Doc Problem Example: os.path.split References: <1127040363.949490.248560@z14g2000cwz.googlegroups.com> Message-ID: <1127079074.497652.272120@g43g2000cwa.googlegroups.com> Another epileptic seizure on the keyboard. Apart from clue deficit disorder, this guy seems to suffer from some serious anger management problems...*plonk* "Xah Lee" wrote: > Python Doc Problem Example > > Quote from: > http://docs.python.org/lib/module-os.path.html > ---------- > split( path) > Split the pathname path into a pair, (head, tail) where tail is the > last pathname component and head is everything leading up to that. The > tail part will never contain a slash; if path ends in a slash, tail > will be empty. If there is no slash in path, head will be empty. If > path is empty, both head and tail are empty. Trailing slashes are > stripped from head unless it is the root (one or more slashes only). In > nearly all cases, join(head, tail) equals path (the only exception > being when there were multiple slashes separating head from tail). > ---------- > > Can anyone tell me what this verbiage is trying to fucking say? > > what the fuck is with the head and tail thing? > > is the doc writer, trying to write the doc with some austereness, but > is confused about the behavior of split, or confused about expressing > it? Did his pretension fucked him up? > > i was working on a program where i needed to split a path into dirname, > corename, and suffix. But this fucking python doc diverted my work and > wasted my time. It normally isn't a problem to find imperfections in > the world except the fucking OpenSourcers fuck with their fucking > moronicity and moronitude and propagate haughtily their fucking lies > and stupidity. Die. > > Suggested rewrite: > > split(path) > returns a pair (dirname,filename), where dirname is the part of path > up to the last slash, and filename is the rest of the string after the > last slash. > > Exceptional cases are: > ? if path is a single slash (or repeated), then path == dirname and > filename is empty. > ? If the "last" slash is repeated, they are treated as one single > slash. > > ------------ > Fuck the motherfucking liers of OpenSourcing fuckheads. > (Note: my use of OpenSource here does not include people of GNU > community.) > > For more about Python Doc problems, see > http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > From jcarlson at uci.edu Thu Sep 29 18:44:34 2005 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 29 Sep 2005 15:44:34 -0700 Subject: [Python-Dev] PEP 350: Codetags In-Reply-To: <20050928161039.GF10940@kitchen.client.attbi.com> References: <20050926223521.GE10940@kitchen.client.attbi.com> <20050928161039.GF10940@kitchen.client.attbi.com> Message-ID: <20050929153237.97E1.JCARLSON@uci.edu> Micah Elliott wrote: > Josiah> an unofficial spec is sufficient. See koders.com and search > Josiah> for 'fixme' to see some common variants. > > But that's the problem -- there are already a bunch of "unofficial" > specs, which don't serve much purpose as such. It's a cool site. I > spent some time browsing and I do see a lot of codetags in use (many > thousands in Python code alone; I'm not sure if the number represented > strings or files). But I'll argue that this just reinforces the need > for an *official* spec/guideline, so that the tools can do something > with them. Defining a spec for code tags doesn't mean that people will start using them. Why? Because it is a documentation spec. From my experience, documentation specs are only adhered to by the organizations (companies, groups, etc.) which the code is produced by and for, and they generally define the code specs for their organization. Further, even if it becomes a spec, it doesn't guarantee implementation in Python editors (for which you are shooting for). Take a wander through current implementations of code tags in various editors to get a feel for what they support. I've read various posts about what code tags could support, but not what editors which implement code tags and/or its variants actually currently support; which is a better indication of what people want than an informal survey via email of python-dev, python-list, and/or the PEP submission process. - Josiah From ICG04984 at nifty.com Thu Sep 22 09:40:41 2005 From: ICG04984 at nifty.com (Masayuki Takemura) Date: Thu, 22 Sep 2005 22:40:41 +0900 Subject: re.split() problem Message-ID: Hi all. re.split() doesn't work as I intend. My Python Version is 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32. For example, >>> r = re.compile('^$', re.MULTILINE) >>> r.split('foo\nbar\n\nbaz') ['foo\nbar\n\nbaz'] but I expected ['foo\nbar\n', 'baz']. This problem has been discussed following threads. [ 852532 ] ^$ won't split on empty line re.split on empty patterns Will it be fixed in Python 2.4.2? Regards, -- Masayuki Takemura From rkern at ucsd.edu Fri Sep 2 02:19:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 01 Sep 2005 23:19:54 -0700 Subject: Are there free molecular libraries written in python ? In-Reply-To: <4317EB2A.8030407@gmail.com> References: <4317EB2A.8030407@gmail.com> Message-ID: Xiao Jianfeng wrote: > Hi, > > Are there any free libraries for the analysis and manipulation of > molecular structural models, implemented in the Python programming > language ? Google is your friend. http://starship.python.net/crew/hinsen/mmtk.html http://pymol.sourceforge.net/ http://www.scripps.edu/~sanner/python/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gsakkis at rutgers.edu Tue Sep 13 19:39:32 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 13 Sep 2005 16:39:32 -0700 Subject: Simplifying imports? References: <1126580971.076107.314490@o13g2000cwo.googlegroups.com> <1126633591.941693.229420@z14g2000cwz.googlegroups.com> Message-ID: <1126654772.731672.169060@o13g2000cwo.googlegroups.com> "Terry Hancock" wrote: > On Tuesday 13 September 2005 12:46 pm, George Sakkis wrote: > > Or even better, forget about the braindead java restriction of one > > class per file and organize your code as it makes more sense to you. > > While this is good sound Python advice, there are good Human-readability > reasons for keeping a small number of classes per module. Python classes > certainly may not tend to blossum into the verbosity of their Java > counterparts, but I've still seen some pretty chunky classes (e.g. in > the Zope sources). So, the __init__.py approach and packaging is > still a good idea. I agree, and that's what I had in mind with "as it makes more sense to you". Big fat classes _are_ a good reason to keep them in separate files, if nothing else, for readability reasons. What's braindead is that java imposes a rule for what should be at best a good style guideline. George From alessandro.bottoni at infinito.it Fri Sep 2 02:21:21 2005 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Fri, 02 Sep 2005 06:21:21 GMT Subject: Are there free molecular libraries written in python ? References: Message-ID: Xiao Jianfeng wrote: > Hi, > > Are there any free libraries for the analysis and manipulation of > molecular structural models, implemented in the Python programming > language ? > > Thanks. What about the followings? MMTK = http://starship.python.net/crew/hinsen/MMTK/ PyMol = http://pymol.sourceforge.net/ (Just model visualization, I'm afraid) Chimera = http://www.cgl.ucsf.edu/chimera/ Other projects you should be aware of: SciPy = http://www.scipy.org/ BioPython = http://biopython.org/scriptcentral/ Other Python/Science resources and articles: http://starship.python.net/crew/hinsen/ http://www.dalkescientific.com/writings/PyCon2004.html http://www.foretec.com/python/workshops/1998-11/demosession/dalke.html http://www.swig.org/papers/Py97/beazley.html And, of course, have a look at these Python software repositories: http://www.python.org/pypi http://www.vex.net/parnassus/ And at these generic software repositories: http://freshmeat.net/ http://sourceforge.net/ (search or browse for scientific/chemistry) HTH ----------------------------------- Alessandro Bottoni From mwm at mired.org Sun Sep 11 17:03:48 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 11 Sep 2005 17:03:48 -0400 Subject: How to upgrade to 2.4.1 on Mac OS X tiger References: <1126102477.882046.95490@z14g2000cwz.googlegroups.com> <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> <1126196055.843689.208130@g43g2000cwa.googlegroups.com> <1126275430.044429.72830@g49g2000cwa.googlegroups.com> <86hdcu2chu.fsf@bhuda.mired.org> <1tdnavaxrqyra$.163zjezg5v8he.dlg@40tude.net> Message-ID: <86psrfz58r.fsf@bhuda.mired.org> "Mike P." writes: > I just got a Mac and was wondering the same thing as the original poster - > how to move to 2.4, but I found out there was more than one version. > So in addition to the Apple installation of 2.3, there are 4 versions of > Python 2.4 (ActivePython, MacPython, fink, darwinports). emerge probably has one as well. And Robert Kern mentioned the official one. The package systems may use one of the others, especially if they are available in source form. If they all do, there are only three distributions (ActivePython, MacPython, and the official one), with the packages installing them in different places. > Which one should I go for? What are other people using (i.e. which is the > most popular version)? Any particular advantages/disadvantages for each > version? Depends on what you want to do with it. If you favor one of the package systems (fink, darwinports, emerge), you probably want to use that one. That way, you won't have to worry about whether or not another package from that system will find the one Python you installed (and hence all the things installed by it), or will install things again. Otherwise, I agree with Robert - use the official one. Of course, if one of the other two includes all the extra functionality you want, use it. Come to think of it, what's installed by Apple may count as a different distribution as well. It certainly includes more than just the official distribution. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From twic at urchin.earth.li Wed Sep 28 12:21:55 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 28 Sep 2005 17:21:55 +0100 Subject: Silly function call lookup stuff? In-Reply-To: References: Message-ID: On Tue, 27 Sep 2005, Dan Sommers wrote: > On Wed, 28 Sep 2005 00:38:23 +0200, > Lucas Lemmens wrote: > >> On Tue, 27 Sep 2005 13:56:53 -0700, Michael Spencer wrote: > >>> Lucas Lemmens wrote: > >>>> Why isn't the result of the first function-lookup cached so that >>>> following function calls don't need to do the function-lookup at all? >>> >>> I guess because the function name may be re-bound between loop >>> iterations. Are there good applications of this? I don't know. >> >> Yuk I'd hate that. I think it would be extremely rare. > > With duck typing, I think it would be fairly common: > > def process_list_of_things_to_process( list_of_things_to_process ): > for x in list_of_things_to_process: > x.process( ) That's not what's being talked about here. In this code, x.process would be a different method each time through, and wouldn't be cached (this isn't C++, you know!). We're talking about this case: class Foo: def process(self): return "foo's version of process" def bar(foo): foo.process = lambda: "bar's version of process" x = Foo() print x.process() bar(x) print x.process() Naive local method cacheing would get this wrong. Worldly-wise method cacheing that would get this right would be a nightmare to implement. A better bet might be to speed up method lookup. I should say that i know bugger all about how python's method lookup is implemented now, but i believe that it's basically a dict lookup in a per-object feature dictionary (ie self.__dict__). It might be possible to instead use a sort of vtable, with a translucent layer of indirection wrapped round it to allow for python's dynamism. Okay, thinking out loud follows. The following is pseudocode showing how the interpreter is implemented; any resemblance to an actual programming language, living or dead, is purely coincidental. The current implementation looks something like this: def classmembers(cl): def new(cl): "Make a new instance of a class cl. An object is a pair (cl, members), where cl is its class and members is a dict of its members." members = {} for name, member in classmembers(cl): members[name] = member obj = (cl, members) return obj def lookup(obj, name): members = obj[1] member = members[name] return member def bind(obj, name, member): members = obj[1] members[name] = member Since the members dict is mutable, there's nothing that can be cached here. This is what i'd suggest ... type mtuple: def new(cl): index = {} members = [cl, index] for name, member in classmembers(cl): index[name] = len(members) members.append(member) obj = (cl, index, mtuple(members)) return obj # the index dict is *never* modified by any code anywhere def lookup(obj, name): index = obj[1] offset = index[name] value = obj[offset] return value def bind(obj, name, value): index = obj[1] offset = index[name] obj[offset] = value So far, this wouldn't be any faster; in fact, it would be slightly slower, due to the extra layer of indirection. However, now we can expose a little of the lookup mechanism to the execution machinery: def offset(obj, name): index = obj[1] offset = index[name] return offset def load(obj, offset): value = obj[offset] return value And refactor: def lookup(obj, name): offset = offset(obj, name) value = load(obj, offset) return value We now have something cachable. Given code like: while (foo()): x.bar() The compiler can produce code like: _bar = offset(x, "bar") while (foo()): load(x, _bar)() It has to do the lookup in the dict once, and after that, just has to do a simple load. The crucial thing is, if the method gets rebound, it'll be rebound into exactly the same slot, and everything keeps working fine. Note that the code above doesn't handle binding of members to names that weren't defined in the class; it thus doesn't support dynamic extension of an object's interface, or, er, member variables. However, these are fairly simple to add, via an extra members dict (which i create lazily): def new(cl): index = {} extras = None members = [cl, index, extras] for name, member in classmembers(cl): index[name] = len(members) members.append(member) obj = (cl, index, mtuple(members)) return obj def lookup(obj, name): index = obj[1] try: offset = index[name] value = obj[offset] except KeyError: extras = obj[2] if (extras == None): raise KeyError, name value = extras[name] return value def bind(obj, name, value): index = obj[1] try: offset = index[name] obj[offset] = value except KeyError: extras = obj[2] if (extras == None): extras = {} obj[2] = extras extras[name] = value It also doesn't call __init__ on new objects, or do metaclasses properly, or support __slots__, or any of that jazz, but that would all be fairly easy to add. __slots__ would be a big performance win here. It would be really nice if the object could somehow be put together after __init__ has run; that way, the member variables set there could be included in the members which are stored in the mtuple and indexed, which is a big performance and compactness win over having them as extras. This is probably possible, using objects which can invisibly change their implementation, but i'm not going to think about it now! Also, as a memory optimisation, you'd want to arrange for all instances of a class to share the same index dictionary instance. That would be pretty trivial. You could also split the members which are likely to be constant across all instances - the class reference, index, and the methods, but not the extras - into a separate table, and share that too; you would have to handle rebinding of members on individual objects with a copy-on-write policy applied to this table. This is fairly straightforward to do, but i'm not going to do it here; the result would be something very close to C++-style vtables, but supporting python's object model. Did that make any sense? Speaking of __slots__, can you use slots for methods? Does it speed up lookup at all? tom -- Children are born true scientists. -- R. Buckminster Fuller From http Fri Sep 30 17:55:09 2005 From: http (Paul Rubin) Date: 30 Sep 2005 14:55:09 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> Message-ID: <7xslvmnruq.fsf@ruckus.brouhaha.com> Steve Holden writes: > That would make a good Onion (www.TheOnion.com) headline: "Users > Discover Computer Security Conflicts with Desire for Convenience" +1 QOTW From lamthierry at gmail.com Fri Sep 16 10:34:01 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 16 Sep 2005 07:34:01 -0700 Subject: Creating Pie Chart from Python In-Reply-To: <87k6hh40dr.fsf@peds-pc311.bsd.uchicago.edu> References: <1126797010.201367.220880@g43g2000cwa.googlegroups.com> <87k6hh40dr.fsf@peds-pc311.bsd.uchicago.edu> Message-ID: <1126881241.265670.140040@o13g2000cwo.googlegroups.com> Those python pie chart add ons are not very useful. For my specific pie chart, I have some 6-8 items to show up and some of them occupy only 2-5% of the pie. This cause the names and percentages to overlap each other. From nowayjose at noway.com Fri Sep 9 18:49:16 2005 From: nowayjose at noway.com (el chupacabra) Date: Fri, 09 Sep 2005 22:49:16 GMT Subject: error processing variables Message-ID: >Your problem is that the def statement reassignes the name "toHPU" to a >function instead of a string. So when the code runs, you're passing a >function object to s.copy2. So...how do fix it? >> import shutil >> >> #variables >> s = shutil >> >> toHPU = "/etc/sysconfig/network/toHPU.wifi" >> wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d" >> toAnyWifi = "/etc/sysconfig/network/toAny.wifi" >> wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88" >> >> >> def toHPU(): >> >> >> s.copy2(toHPU,wlan) >> s.copy2(toAnyWifi,wired) >> >> #end >> >> #execute function >> toHPU() --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading made easy =--------- -= Get GrabIt for free from http://www.shemes.com/ =- From vinay_sajip at yahoo.co.uk Tue Sep 13 20:03:40 2005 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 13 Sep 2005 17:03:40 -0700 Subject: logging into one file problem In-Reply-To: References: Message-ID: <1126656220.794776.169020@f14g2000cwb.googlegroups.com> Maksim Kasimov wrote: [Example snipped] Will the following do what you want? Don't add handlers in each module. Just add a handler to the root logger in the main script. Thus: module1.py: import logging logger = logging.getLogger('module1') #now use the logger in your code module2.py: import logging logger = logging.getLogger('module2') #now use the logger in your code script.py: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='/tmp/script.log', filemode='w') # this only works with 2.4+ - for earlier versions, need to do as in your original post Then, the output from loggers 'module1' and 'module2' will end up in '/tmp/script.log' automatically. Regards, Vinay From fredrik at pythonware.com Mon Sep 5 15:38:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Sep 2005 21:38:06 +0200 Subject: Possible improvement to slice opperations. References: <431c3b4f$1@nntp0.pdx.net> <4F_Se.6251$4i6.6069@tornado.tampabay.rr.com> Message-ID: Ron Adam wrote: > However, I would like the inverse selection of negative strides to be > fixed if possible. If you could explain the current reason why it does > not return the reverse order of the selected range. why? you're not listening anyway. From tjreedy at udel.edu Thu Sep 8 02:54:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Sep 2005 02:54:10 -0400 Subject: Construct raw strings? References: <1126130881.555483.296200@g47g2000cwa.googlegroups.com> Message-ID: "Thomas W" wrote in message news:1126130881.555483.296200 at g47g2000cwa.googlegroups.com... >I got a stupid problem; on my WinXP-box I want to scan the filesystem > and enter a path to scan like this : > > path_to_scan = 'd:\test_images' I believe you can always use / instead of \ for Win filenames from Python. Avoids the \ problem. I think only the shell that uses / for options has a problem with / in filenames, but Python calls directly to C. Terry J. Reedy From apardon at forel.vub.ac.be Thu Sep 15 07:16:14 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Sep 2005 11:16:14 GMT Subject: round() wrong in Python 2.4? References: <1126617470.648201.223630@g44g2000cwa.googlegroups.com> Message-ID: Op 2005-09-14, Robert Kern schreef : > Antoon Pardon wrote: >> Op 2005-09-13, Robert Kern schreef : >> >>>Jeremy Sanders wrote: >>> >>>>Nils Grimsmo wrote: >>>> >>>>>Why did round() change in Python 2.4? >>>> >>>>It the usual floating point representation problem. 0.0225 cannot be >>>>represented exactly: >>> >>>That's not what he's asking about. He's asking why his Python 2.3 rounds >>>0.0225 *up* to 0.023 while his Python 2.4 rounds *down* to 0.022. It's >>>the change in behavior that he's concerned with and isn't just the usual >>>floating point problem. >> >> I would say the usual floating point problem is involved. >> >> Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down. >> >> 0.0225 isn't representable and it happens that the actual number >> you get differ. Now which number python should choose when it is >> fed 0.0225, I don't know. But expressing the different behaviour >> as a change in round, suggest that the O.P. would be wise to >> learn about floating point problems > > Uhh, Python didn't change anything between 2.3 and 2.4 wrt round(). That is what I said, or at least meant to say. > The > reason he is seeing a difference is because the two executables were > built with different compilers. The fact that the version of Python was > different in the two cases obscures the real cause. IMO the real cause is unimportant. The real cause can be a different CPU or a different compilor or a different library. What it boils down to is that you can't expect 0,0225 to be represented in a value that will be rounded up. > Saying that 0.0225 can't be represented exactly as a binary floating > point number is entirely true but is an incomplete answer. Yes, > obviously binary floating point representations are involved. But one > could always define a standard representation scheme that always gives > the same answer for the same input. Can we? I don't think we can, unless you are working with decimal numbers. If you work with floats you are basically saying that the program should choose the best approximation it can. That approximation can differ according to circumstances. So one must be prepared that round(0.225,3) can give different results in different circumstances. > The fact is that for some reason > there are two schemes being used. Another fact is that this has nothing > to do with difference in the versions of Python he is using. Most of > Python's floating point behavior is a platform-dependent accident (as > Tim Peters always says), and Nils is using two slightly different platforms. Yes and he wouldn't have blamed it on round, had he known or thought about FP representations. -- Antoon Pardon From trapeze.jsg at gmail.com Sat Sep 3 19:03:20 2005 From: trapeze.jsg at gmail.com (trapeze.jsg at gmail.com) Date: 3 Sep 2005 16:03:20 -0700 Subject: Digest MD5 authentication over using ZSI Message-ID: <1125788600.022554.154010@g43g2000cwa.googlegroups.com> Hi. I am trying to get through to Microsoft MapPoint Services using ZSI for soap handling. I can generate the service classes and also the soap-requests generated by the service classes seem to be OK. The problem I am facing is that I can't seem to authenticate myself. I have made a small change to ZSI.client so that when I get a "401 Unauthorized" response from the remote server I build up a nice authorization request: POST /Find-30/FindService.asmx HTTP/1.1 Host: findv3.staging.mappoint.net Accept-Encoding: identity User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 1.1.4322.573) SOAPAction: "http://s.mappoint.net/mappoint-30/FindAddress" Authorization: Digest username="106288", realm="MapPoint", nonce="91168da8e3a097f41264875211009a194b99a94ffe5bc619415820880a5b", uri="/Find-30/FindService.asmx", response="26aa9e36f9ff2a8308030810ab83dad1", qop=auth, nc=00000001, cnonce="623c12f33f0eb883" Content-length: 0 Expect: 100-continue The problem is that the server won't authorize me. I have a C# .net program that does exactly the same I'm trying in python, and it is authorized nicely: POST /Find-30/FindService.asmx HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 1.1.4322.573) Content-Type: text/xml; charset=utf-8 SOAPAction: "http://s.mappoint.net/mappoint-30/FindAddress" Authorization: Digest username="106288",realm="MapPoint",nonce="487911f02ed2ef706326675211008a8ec39cfa4fb09304757c8dde417354",uri="/Find-30/FindService.asmx",cnonce="e1ed9880c5e3777a4ba280cec1c9e362",nc=00000001,qop="auth",response="b4119a4db73814fd09ae5fec11fc9730" Content-Length: 523 Expect: 100-continue Host: findv3.staging.mappoint.net So I guess the problem is in the Digest calculation. Unfortunately I don't know much about the issue but I have managed to "steel" this from urllib2 and changed it a bit to fit my usage (see below). 1. Can I do this another way? 2. Has anybody made a digest MD5 authenticator for ZSI? 3. Whats wrong with my calculation or is it the header?? 4. Can I use urllib2 to test the authentication part of a Soap Service. ----------------- My authentication calculator ----> import md5 import sha import re import time import random import os.path def randombytes(n): """Return n random bytes.""" # Use /dev/urandom if it is available. Fall back to random module # if not. It might be worthwhile to extend this function to use # other platform-specific mechanisms for getting random bytes. if os.path.exists("/dev/urandom"): f = open("/dev/urandom") s = f.read(n) f.close() return s else: L = [chr(random.randrange(0, 256)) for i in range(n)] return "".join(L) class Challenge: def __init__(self,challenge): self.params = {} self.no_chal=0 if challenge.upper().find('WWW-Authenticate:'.upper())==-1: self.no_chal=1 rx = re.compile('WWW-Authenticate:.*qop="(\w+)"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['qop'] = m.group(1) rx = re.compile('WWW-Authenticate:.*realm="(\w+)"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['realm'] = m.group(1) rx = re.compile('WWW-Authenticate:.*algorithm="(\w+)"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['algorithm'] = m.group(1) rx = re.compile('WWW-Authenticate:.*nonce="(\w+)"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['nonce'] = m.group(1) rx = re.compile('WWW-Authenticate:.*opaque="(\w+)"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['opaque'] = m.group(1) rx = re.compile('WWW-Authenticate:.*Digest.*"',re.IGNORECASE|re.MULTILINE) m = rx.search(challenge) if m: self.params['Digest'] = 1 def get(self,keyword,default=None): if self.params.has_key(keyword): return self.params[keyword] else: return default def no_challenge(self): return self.no_chal class AbstractDigestAuthHandler: # Digest authentication is specified in RFC 2617. # XXX The client does not inspect the Authentication-Info header # in a successful response. # XXX It should be possible to test this implementation against # a mock server that just generates a static set of challenges. # XXX qop="auth-int" supports is shaky def __init__(self, user, passwd): self.user = user self.passwd = passwd self.retried = 0 self.nonce_count = 0 def reset_retry_count(self): self.retried = 0 def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: auth_val = 'Digest %s' % auth if req.headers.get(self.auth_header, None) == auth_val: return None req.add_header(self.auth_header, auth_val) resp = self.parent.open(req) return resp def get_cnonce(self, nonce): # The cnonce-value is an opaque # quoted string value provided by the client and used by both client # and server to avoid chosen plaintext attacks, to provide mutual # authentication, and to provide some message integrity protection. # This isn't a fabulous effort, but it's probably Good Enough. dig = sha.new("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(), randombytes(8))).hexdigest() return dig[:16] def get_authorization(self, chal, method, selector): try: realm = chal.get('realm') nonce = chal.get('nonce') qop = chal.get('qop') algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None H, KD = self.get_algorithm_impls(algorithm) if H is None: return None user, pw = self.user, self.passwd if user is None: return None # XXX not implemented yet entdig = None #if req.has_data(): # entdig = self.get_entity_digest(req.get_data(), chal) A1 = "%s:%s:%s" % (user, realm, pw) A2 = "%s:%s" % (method, # XXX selector: what about proxies and full urls selector) if qop == 'auth': self.nonce_count += 1 ncvalue = '%08x' % self.nonce_count cnonce = self.get_cnonce(nonce) noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2)) respdig = KD(H(A1), noncebit) else: pass # XXX should the partial digests be encoded too? base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 'response="%s"' % (user, realm, nonce, selector, respdig) if opaque: base = base + ', opaque="%s"' % opaque if entdig: base = base + ', digest="%s"' % entdig if algorithm != 'MD5': base = base + ', algorithm="%s"' % algorithm if qop: base = base + ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce) return base def get_algorithm_impls(self, algorithm): # lambdas assume digest modules are imported at the top level if algorithm == 'MD5': H = lambda x: md5.new(x).hexdigest() elif algorithm == 'SHA': H = lambda x: sha.new(x).hexdigest() # XXX MD5-sess KD = lambda s, d: H("%s:%s" % (s, d)) return H, KD def get_entity_digest(self, data, chal): # XXX not implemented yet return None <--------------- Ethereal request sniffer: (the authorization request and server response) No. Time Source Destination Protocol Info 15 0.757244 192.168.0.106 64.4.58.250 HTTP POST /Find-30/FindService.asmx HTTP/1.1 Frame 15 (612 bytes on wire, 612 bytes captured) Arrival Time: Sep 3, 2005 23:57:20.487466000 Time delta from previous packet: 0.000111000 seconds Time since reference or first frame: 0.757244000 seconds Frame Number: 15 Packet Length: 612 bytes Capture Length: 612 bytes Protocols in frame: eth:ip:tcp:http Ethernet II, Src: FirstInt_6c:a0:01 (00:40:ca:6c:a0:01), Dst: D-Link_36:0e:3d (00:0d:88:36:0e:3d) Destination: D-Link_36:0e:3d (00:0d:88:36:0e:3d) Source: FirstInt_6c:a0:01 (00:40:ca:6c:a0:01) Type: IP (0x0800) Internet Protocol, Src: 192.168.0.106 (192.168.0.106), Dst: 64.4.58.250 (64.4.58.250) Version: 4 Header length: 20 bytes Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00) 0000 00.. = Differentiated Services Codepoint: Default (0x00) .... ..0. = ECN-Capable Transport (ECT): 0 .... ...0 = ECN-CE: 0 Total Length: 598 Identification: 0x7797 (30615) Flags: 0x04 (Don't Fragment) 0... = Reserved bit: Not set .1.. = Don't fragment: Set ..0. = More fragments: Not set Fragment offset: 0 Time to live: 128 Protocol: TCP (0x06) Header checksum: 0x44fa [correct] Source: 192.168.0.106 (192.168.0.106) Destination: 64.4.58.250 (64.4.58.250) Transmission Control Protocol, Src Port: 3183 (3183), Dst Port: http (80), Seq: 1, Ack: 1, Len: 558 Source port: 3183 (3183) Destination port: http (80) Sequence number: 1 (relative sequence number) Next sequence number: 559 (relative sequence number) Acknowledgement number: 1 (relative ack number) Header length: 20 bytes Flags: 0x0018 (PSH, ACK) 0... .... = Congestion Window Reduced (CWR): Not set .0.. .... = ECN-Echo: Not set ..0. .... = Urgent: Not set ...1 .... = Acknowledgment: Set .... 1... = Push: Set .... .0.. = Reset: Not set .... ..0. = Syn: Not set .... ...0 = Fin: Not set Window size: 64512 Checksum: 0x9143 [correct] Hypertext Transfer Protocol POST /Find-30/FindService.asmx HTTP/1.1\r\n Request Method: POST Request URI: /Find-30/FindService.asmx Request Version: HTTP/1.1 Host: findv3.staging.mappoint.net\r\n Accept-Encoding: identity\r\n User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 1.1.4322.573)\r\n SOAPAction: "http://s.mappoint.net/mappoint-30/FindAddress"\r\n Authorization: Digest username="106288", realm="MapPoint", nonce="8033d257de12190a048487521100021388b534e89ffd4bad4292666e620c", uri="/Find-30/FindService.asmx", response="0ff36d6cbaf353f4aba183cef52d1de9", qop=auth, nc=00000001, cnonce="8 Content-length: 0\r\n Expect: 100-continue\r\n \r\n 0000 00 0d 88 36 0e 3d 00 40 ca 6c a0 01 08 00 45 00 ...6.=. at .l....E. 0010 02 56 77 97 40 00 80 06 44 fa c0 a8 00 6a 40 04 .Vw. at ...D....j@. 0020 3a fa 0c 6f 00 50 88 c9 eb f1 f0 ea 88 6f 50 18 :..o.P.......oP. 0030 fc 00 91 43 00 00 50 4f 53 54 20 2f 46 69 6e 64 ...C..POST /Find 0040 2d 33 30 2f 46 69 6e 64 53 65 72 76 69 63 65 2e -30/FindService. 0050 61 73 6d 78 20 48 54 54 50 2f 31 2e 31 0d 0a 48 asmx HTTP/1.1..H 0060 6f 73 74 3a 20 66 69 6e 64 76 33 2e 73 74 61 67 ost: findv3.stag 0070 69 6e 67 2e 6d 61 70 70 6f 69 6e 74 2e 6e 65 74 ing.mappoint.net 0080 0d 0a 41 63 63 65 70 74 2d 45 6e 63 6f 64 69 6e ..Accept-Encodin 0090 67 3a 20 69 64 65 6e 74 69 74 79 0d 0a 55 73 65 g: identity..Use 00a0 72 2d 41 67 65 6e 74 3a 20 4d 6f 7a 69 6c 6c 61 r-Agent: Mozilla 00b0 2f 34 2e 30 20 28 63 6f 6d 70 61 74 69 62 6c 65 /4.0 (compatible 00c0 3b 20 4d 53 49 45 20 36 2e 30 3b 20 4d 53 20 57 ; MSIE 6.0; MS W 00d0 65 62 20 53 65 72 76 69 63 65 73 20 43 6c 69 65 eb Services Clie 00e0 6e 74 20 50 72 6f 74 6f 63 6f 6c 20 31 2e 31 2e nt Protocol 1.1. 00f0 34 33 32 32 2e 35 37 33 29 0d 0a 53 4f 41 50 41 4322.573)..SOAPA 0100 63 74 69 6f 6e 3a 20 22 68 74 74 70 3a 2f 2f 73 ction: "http://s 0110 2e 6d 61 70 70 6f 69 6e 74 2e 6e 65 74 2f 6d 61 .mappoint.net/ma 0120 70 70 6f 69 6e 74 2d 33 30 2f 46 69 6e 64 41 64 ppoint-30/FindAd 0130 64 72 65 73 73 22 0d 0a 41 75 74 68 6f 72 69 7a dress"..Authoriz 0140 61 74 69 6f 6e 3a 20 44 69 67 65 73 74 20 75 73 ation: Digest us 0150 65 72 6e 61 6d 65 3d 22 31 30 36 32 38 38 22 2c ername="106288", 0160 20 72 65 61 6c 6d 3d 22 4d 61 70 50 6f 69 6e 74 realm="MapPoint 0170 22 2c 20 6e 6f 6e 63 65 3d 22 38 30 33 33 64 32 ", nonce="8033d2 0180 35 37 64 65 31 32 31 39 30 61 30 34 38 34 38 37 57de12190a048487 0190 35 32 31 31 30 30 30 32 31 33 38 38 62 35 33 34 521100021388b534 01a0 65 38 39 66 66 64 34 62 61 64 34 32 39 32 36 36 e89ffd4bad429266 01b0 36 65 36 32 30 63 22 2c 20 75 72 69 3d 22 2f 46 6e620c", uri="/F 01c0 69 6e 64 2d 33 30 2f 46 69 6e 64 53 65 72 76 69 ind-30/FindServi 01d0 63 65 2e 61 73 6d 78 22 2c 20 72 65 73 70 6f 6e ce.asmx", respon 01e0 73 65 3d 22 30 66 66 33 36 64 36 63 62 61 66 33 se="0ff36d6cbaf3 01f0 35 33 66 34 61 62 61 31 38 33 63 65 66 35 32 64 53f4aba183cef52d 0200 31 64 65 39 22 2c 20 71 6f 70 3d 61 75 74 68 2c 1de9", qop=auth, 0210 20 6e 63 3d 30 30 30 30 30 30 30 31 2c 20 63 6e nc=00000001, cn 0220 6f 6e 63 65 3d 22 38 61 63 33 34 34 37 33 63 33 once="8ac34473c3 0230 33 32 66 61 38 66 22 0d 0a 43 6f 6e 74 65 6e 74 32fa8f"..Content 0240 2d 6c 65 6e 67 74 68 3a 20 30 0d 0a 45 78 70 65 -length: 0..Expe 0250 63 74 3a 20 31 30 30 2d 63 6f 6e 74 69 6e 75 65 ct: 100-continue 0260 0d 0a 0d 0a .... No. Time Source Destination Protocol Info 16 0.950469 64.4.58.250 192.168.0.106 HTTP HTTP/1.1 401 Unauthorized Frame 16 (387 bytes on wire, 387 bytes captured) Arrival Time: Sep 3, 2005 23:57:20.680691000 Time delta from previous packet: 0.193225000 seconds Time since reference or first frame: 0.950469000 seconds Frame Number: 16 Packet Length: 387 bytes Capture Length: 387 bytes Protocols in frame: eth:ip:tcp:http Ethernet II, Src: D-Link_36:0e:3d (00:0d:88:36:0e:3d), Dst: FirstInt_6c:a0:01 (00:40:ca:6c:a0:01) Destination: FirstInt_6c:a0:01 (00:40:ca:6c:a0:01) Source: D-Link_36:0e:3d (00:0d:88:36:0e:3d) Type: IP (0x0800) Internet Protocol, Src: 64.4.58.250 (64.4.58.250), Dst: 192.168.0.106 (192.168.0.106) Version: 4 Header length: 20 bytes Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00) 0000 00.. = Differentiated Services Codepoint: Default (0x00) .... ..0. = ECN-Capable Transport (ECT): 0 .... ...0 = ECN-CE: 0 Total Length: 373 Identification: 0x395f (14687) Flags: 0x04 (Don't Fragment) 0... = Reserved bit: Not set .1.. = Don't fragment: Set ..0. = More fragments: Not set Fragment offset: 0 Time to live: 108 Protocol: TCP (0x06) Header checksum: 0x9813 [correct] Source: 64.4.58.250 (64.4.58.250) Destination: 192.168.0.106 (192.168.0.106) Transmission Control Protocol, Src Port: http (80), Dst Port: 3183 (3183), Seq: 1, Ack: 559, Len: 333 Source port: http (80) Destination port: 3183 (3183) Sequence number: 1 (relative sequence number) Next sequence number: 334 (relative sequence number) Acknowledgement number: 559 (relative ack number) Header length: 20 bytes Flags: 0x0018 (PSH, ACK) 0... .... = Congestion Window Reduced (CWR): Not set .0.. .... = ECN-Echo: Not set ..0. .... = Urgent: Not set ...1 .... = Acknowledgment: Set .... 1... = Push: Set .... .0.. = Reset: Not set .... ..0. = Syn: Not set .... ...0 = Fin: Not set Window size: 17122 Checksum: 0x0f4b [correct] SEQ/ACK analysis This is an ACK to the segment in frame: 15 The RTT to ACK the segment was: 0.193225000 seconds Hypertext Transfer Protocol HTTP/1.1 401 Unauthorized\r\n Request Version: HTTP/1.1 Response Code: 401 Connection: close\r\n Date: Sat, 03 Sep 2005 22:00:41 GMT\r\n Server: Microsoft-IIS/6.0\r\n P3P:CP="BUS CUR CONo FIN IVDo ONL OUR PHY SAMo TELo"\r\n X-Powered-By: ASP.NET\r\n WWW-Authenticate: Digest qop="auth", realm="MapPoint", nonce="13c38f357408a1fc148487521100702d0fadd05e6b7cf54806565713c790"\r\n Content-Length: 0\r\n \r\n 0000 00 40 ca 6c a0 01 00 0d 88 36 0e 3d 08 00 45 00 . at .l.....6.=..E. 0010 01 75 39 5f 40 00 6c 06 98 13 40 04 3a fa c0 a8 .u9_ at .l...@.:... 0020 00 6a 00 50 0c 6f f0 ea 88 6f 88 c9 ee 1f 50 18 .j.P.o...o....P. 0030 42 e2 0f 4b 00 00 48 54 54 50 2f 31 2e 31 20 34 B..K..HTTP/1.1 4 0040 30 31 20 55 6e 61 75 74 68 6f 72 69 7a 65 64 0d 01 Unauthorized. 0050 0a 43 6f 6e 6e 65 63 74 69 6f 6e 3a 20 63 6c 6f .Connection: clo 0060 73 65 0d 0a 44 61 74 65 3a 20 53 61 74 2c 20 30 se..Date: Sat, 0 0070 33 20 53 65 70 20 32 30 30 35 20 32 32 3a 30 30 3 Sep 2005 22:00 0080 3a 34 31 20 47 4d 54 0d 0a 53 65 72 76 65 72 3a :41 GMT..Server: 0090 20 4d 69 63 72 6f 73 6f 66 74 2d 49 49 53 2f 36 Microsoft-IIS/6 00a0 2e 30 0d 0a 50 33 50 3a 43 50 3d 22 42 55 53 20 .0..P3P:CP="BUS 00b0 43 55 52 20 43 4f 4e 6f 20 46 49 4e 20 49 56 44 CUR CONo FIN IVD 00c0 6f 20 4f 4e 4c 20 4f 55 52 20 50 48 59 20 53 41 o ONL OUR PHY SA 00d0 4d 6f 20 54 45 4c 6f 22 0d 0a 58 2d 50 6f 77 65 Mo TELo"..X-Powe 00e0 72 65 64 2d 42 79 3a 20 41 53 50 2e 4e 45 54 0d red-By: ASP.NET. 00f0 0a 57 57 57 2d 41 75 74 68 65 6e 74 69 63 61 74 .WWW-Authenticat 0100 65 3a 20 44 69 67 65 73 74 20 71 6f 70 3d 22 61 e: Digest qop="a 0110 75 74 68 22 2c 20 72 65 61 6c 6d 3d 22 4d 61 70 uth", realm="Map 0120 50 6f 69 6e 74 22 2c 20 6e 6f 6e 63 65 3d 22 31 Point", nonce="1 0130 33 63 33 38 66 33 35 37 34 30 38 61 31 66 63 31 3c38f357408a1fc1 0140 34 38 34 38 37 35 32 31 31 30 30 37 30 32 64 30 48487521100702d0 0150 66 61 64 64 30 35 65 36 62 37 63 66 35 34 38 30 fadd05e6b7cf5480 0160 36 35 36 35 37 31 33 63 37 39 30 22 0d 0a 43 6f 6565713c790"..Co 0170 6e 74 65 6e 74 2d 4c 65 6e 67 74 68 3a 20 30 0d ntent-Length: 0. 0180 0a 0d 0a ... From cfbolz at gmx.de Sun Sep 11 10:46:44 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 11 Sep 2005 16:46:44 +0200 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: <8fd4a2fe05091021035847675c@mail.gmail.com> References: <7x3bocy0vn.fsf@ruckus.brouhaha.com> <8fd4a2fe05091021035847675c@mail.gmail.com> Message-ID: <43244354.4050807@gmx.de> Hi! adDoc's networker Phil wrote: >> >> experimental Python-to-C++ compiler. >> >> why that instead of Pypy? >> > > . pypy compiles to llvm (low-level virtual machine) bytecode > which is obviously not as fast as the native code coming from c++ compilers; PyPy can currently compile Python code to C code and to LLVM bytecode. Note that even for LLVM bytecode the argument is void since LLVM (despite its name, which might lead one to think that it is Java-like) compiles its bytecode to native assembler. > but the primary mission of pypy > is just having a python system that is > written in something like python rather than c or c++ it's really just plain python (it completely runs on top of CPython after all) together with some restrictions -- which seem similar to the restictions that shedskin imposes btw. > . there is no reason why the pypy project can't have a .NET architecture > instead of the java-like arrangement I assume it has now Sorry, I can't really follow you here. In what way does PyPy have a Java-like arrangement? > . without such a pypy.NET system, > shedskin is offering a service that pypy can't yet provide: > a ( python -> c++ )-conversion allows me to > smoothly integrate python contributions > with my already-staggering c++ library > . I'm not suggesting that pypy should be another > Mono rewritten in python, > because the essential mission of the .NET architecture > is being able to compile > any language of the user`s choice, > to some intermediate language designed to be > far more efficiently compiled to > any machine language of the user`s choice > than any human-readable language such as c++ > . perhaps llvm bytecode can serve as such an intermediate language? > then llvm could be the new c++ (our defacto IL (intermediate language)) > and shedskin (python -> IL=c++) could then be replaced by > the combination of pypy (python -> IL=llvm) > and some incentive for all target platforms > to develope a highly optimized > ( llvm -> native code)-compiler > -- assuming also, that there is available > a highly optimized ( c++ -> llvm bytecode )-compiler . there is. look at the LLVM page for details: www.llvm.org Cheers, Carl Friedrich Bolz From ivoras at __yahoo.org__ Sat Sep 24 12:44:34 2005 From: ivoras at __yahoo.org__ (Ivan Voras) Date: Sat, 24 Sep 2005 18:44:34 +0200 Subject: Using '__mul__' within a class In-Reply-To: <1127576164.489710.291280@g49g2000cwa.googlegroups.com> References: <1127576164.489710.291280@g49g2000cwa.googlegroups.com> Message-ID: Gerard Flanagan wrote: > def Square( self ): > self *= self You probably mean return self * self > A = FibonacciMatrix() > A.Square() Make this A = A.Square() From karczma at info.unicaen.fr Wed Sep 14 08:32:17 2005 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Wed, 14 Sep 2005 14:32:17 +0200 Subject: Software bugs aren't inevitable In-Reply-To: References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> <7xwtlkrs4c.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano recommends iteration over recursion: > For instance, try these two simple functions for the nth number > in the Fibonacci sequence: > > def fibr(n): > "Recursive version of Fibonacci sequence." > if n == 0: return 0 > elif n == 1: return 1 > else: return fibr(n-1) + fibr(n-2) > > def fibi(n): > "Simple iterative version of Fibonacci sequence." > if n == 0: return 0 etc. > Try timing how long it takes to generate the 30th Fibonacci number > (832040) using both of those algorithms. Now try the 50th. (Warning: the > amount of work done by the recursive version increases at the same rate as > the Fibonacci sequence itself increases. That's not quite exponentially, > but it is fast enough to be very painful.) First of all, the recursive version of Fibonacci IS EXPONENTIAL in complexity, don't say such not-quite-truth as "not quite". But, what is more important: If you don't know too much about the way the functional programming is used nowadays, please refrain from giving nonsensical examples, since NOBODY serious programs something in the style of your recursive version. Such anti-advertizing of recursion says less about the recursion than about yourself. Here you are a recursive version linear in n; it returns the two last Fibonacci numbers of the sequence def fibo(n): if n<2: return (n-1,n) else: (a,b)=fibo(n-1) return (b,a+b) The exponential complexity, cascading version is a nice test case how to use memoization, though, so it is not entirely senseless to learn it. Jerzy Karczmarczuk From ed_zeng at yahoo.com Fri Sep 2 16:36:18 2005 From: ed_zeng at yahoo.com (Laguna) Date: 2 Sep 2005 13:36:18 -0700 Subject: Find day of week from month and year In-Reply-To: References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> Message-ID: <1125693378.950355.210830@g49g2000cwa.googlegroups.com> > What do you mean by, "the 9 element tuple need to be populated > correctly"? Do you need someone to tell you what values it > needs? What happens if you use (2005, 9, 1, 0, 0, 0, 0, 0, 0), > for example? If you make this tuple with localtime or gmtime, > do you know what the 7th (tm[6]) element of the tuple is? > What tricks did you try, exactly? > > Donn Cave, donn at u.washington.edu Thanks for pointing out. tm[6] = weekday, and tm[7] = Julian data, but I wouldn't know these values when my input values are month and year. I will try out the more constructive suggestions from Paul and Robert. Following is what I have tried. As you can tell, the results are wrong! >>> import time >>> time.asctime((2003, 9, 1, 0, 0, 0, 0, 0, 0)) 'Mon Sep 01 00:00:00 2003' >>> time.asctime((2003, 8, 1, 0, 0, 0, 0, 0, 0)) 'Mon Aug 01 00:00:00 2003' >>> time.asctime((2003, 7, 1, 0, 0, 0, 0, 0, 0)) 'Mon Jul 01 00:00:00 2003' From andreas.zwinkau at googlemail.com Sat Sep 24 14:47:56 2005 From: andreas.zwinkau at googlemail.com (beza1e1) Date: 24 Sep 2005 11:47:56 -0700 Subject: Parsing an HTML a tag In-Reply-To: <868xxmgvrn.fsf@bhuda.mired.org> References: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> <1127585033.260765.258760@g44g2000cwa.googlegroups.com> <868xxmgvrn.fsf@bhuda.mired.org> Message-ID: <1127587676.458962.35950@g43g2000cwa.googlegroups.com> I think for a quick hack, this is as good as a parser. A simple parser would miss some cases as well. RE are nearly not extendable though, so your critic is valid. The point is, what George wants to do. A mixture would be possible as well: Getting all by a RE and then extracting the url with something like a parser. From brp13 at yahoo.com Fri Sep 30 14:24:01 2005 From: brp13 at yahoo.com (Tuvas) Date: 30 Sep 2005 11:24:01 -0700 Subject: ASCII Message-ID: <1128104641.277339.31800@g47g2000cwa.googlegroups.com> Is there a function that will take a char. and return the ascii value? Thanks! From sjmachin at lexicon.net Sun Sep 4 18:26:30 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Sep 2005 08:26:30 +1000 Subject: String from File -> List without parsing In-Reply-To: References: Message-ID: <431b7493$1@news.eftel.com> Gregor Horvath wrote: > Hi, > > given the dynamic nature of python I assume that there is an elegant > solution for my problem, but I did not manage to find it. > > I have a file that contains for example on line: > ['147', '148', '146'] > when I read the file > f = file("I050901.ids").readlines() Y3K bug alert :-) > I have a string > f[0] == "['147', '148', '146']" The last (or sole) line is highly likely to be "['147', '148', '146']\n". If there are multiple lines in the file, all but the last will definitely have "\n" at the end. > How can I turn this string into a list > li == ['147', '148', '146'] > without parsing? Something like this: >>> def munch(astrg): ... return [x[1:-1] for x in astrg.rstrip("\n")[1:-1].split(", ")] ... >>> munch("['147', '148', '146']") ['147', '148', '146'] >>> munch("['147', '148', '146']\n") ['147', '148', '146'] >>> munch("['147']\n") ['147'] >>> # Warning: various flavours of "nothing" give the same result: >>> munch("['']\n") [''] >>> munch("[]\n") [''] >>> munch("\n") [''] >>> This assumes that the contents are no more complicated than in your example. Some notes: (1) You neither want nor need to use eval. (2) What is creating files like that? If it is a Python script, consider writing them using the csv module; that way, other software can read them easily. HTH, John From mark.dufour at gmail.com Tue Sep 20 08:39:16 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 20 Sep 2005 14:39:16 +0200 Subject: Release of Shed Skin 0.0.2: Easy Windows/OSX Installation Message-ID: <8180ef69050920053977538970@mail.gmail.com> Hi! Shed Skin 0.0.2 is up on SourceForge. It should install easily under Windows 2000/XP and OSX. Please give it a try and let me know if there are still some problems. If you would like to help me improve Shed Skin, please send me small code snippets, preferrably extracted from real-life use cases, that the compiler has problems with. Thanks to everyone who has helped me out, especially Khalid, Leonardo and Luis here on python-list, and Denis de Leeuw Duarte right here in the street :-) http://shedskin.sourceforge.net http://shed-skin.blogspot.com thanks! mark. From theller at python.net Tue Sep 6 07:30:30 2005 From: theller at python.net (Thomas Heller) Date: Tue, 06 Sep 2005 13:30:30 +0200 Subject: py2exe 0.6.1 released References: <1KbTe.51152$F23.643754@twister2.libero.it> <1126005093.200664.64140@g47g2000cwa.googlegroups.com> Message-ID: svbrk at start.no writes: > First: Thank you Thomas for the good work with py2exe. The single-file > option is something I have been waiting for :-) > Will it also be possible to build independent files (such as > my_app_data.zip) into the executable? Depends on how you want to access them at runtime. What you can do is to include them as win32 resources, see the advanced example - it puts the winXP manifest file as resource into the exe. test_wx = Target( ... other_resources = [(resource_type, resource_id, resource_data)], ) resource_type and resource_id must be integers, resource_data must be the data itself as a string. At runtime you can access them with a win32api.LoadResource() call. >> > I tried it using the wx singlefile example, but unfortunately the >> > resulting executable segfaults at startup (using Python 2.3.3 on >> > Windows 2000, with latest wxWindows). >> >> Yes, I can reproduce that. I'm still using wxPython 2.4.2.4 for Python >> 2.3.5, and that combo works. I have done a few tests, and wxPython >> 2.5.1.5 also works, while 2.5.5.1 crashes. >> > > I have tried two more combinations for this example > (samples/singlefile/gui/test_wx.py), both giving segfault on WindowsXP > / SP2: > 1. Python 2.3.3 with wxPython 2.6.1.0 unicode > 2. Python 2.4.1 with wxPython 2.6.1.0 unicode > > However, the combinations > Python 2.4.1 with wxPython 2.4.5.1 ansi You probably mean 2.5.5.1 ? > Python 2.4.1 with wxPython 2.6.1.0 ansi > do not cause segfault, but shows a dialog box pointing to a log file, > the contents of which is: > > Traceback (most recent call last): > File "test_wx.py", line 1, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wxPython\__init__.pyo", line 10, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wxPython\_wx.pyo", line 3, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wxPython\_core.pyo", line 15, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wx\__init__.pyo", line 42, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wx\_core.pyo", line 4, in ? > File "zipextimporter.pyo", line 89, in load_module > ImportError: MemoryLoadLibrary failed loading _core_.pyd > > Maybe this could help localizing the problem? I hope. Thanks for these, Thomas From theller at python.net Wed Sep 14 13:38:58 2005 From: theller at python.net (Thomas Heller) Date: Wed, 14 Sep 2005 19:38:58 +0200 Subject: stdin and py2exe References: <1126718877.513683.112600@z14g2000cwz.googlegroups.com> Message-ID: "Mike Tammerman" writes: > Hi, > > I want create a subprocess using Popen and pipe some input to it. > Although everything works perfectly while executing python in, it > doesn't work if I try with executables made by py2exe. > > I think, stdin is invalidated if the program becomes an executable. > Because I get a "Bad file descriptor" exception in subprogram.py. I > will be more than apreciated, if any suggestions occur. > > Thanks, > Mike > > == main.py == > from subprocess import * > > pInput = Popen('python subprogram.py', stdin=PIPE, shell=True).stdin > # pInput = Popen('subprogram.exe', stdin=PIPE, shell=True).stdin # > doesn't work > > pInput.write('Data') > pInput.close() > > > == subprogram.py == > import sys > > input = sys.stdin.read() # Throws a bad descriptor exception. > print input Can it be that you're building a windows exe of subprogram.py? I get the error you describe when I do that, for console programs it works - both in the Python script and in the py2exe'd version. This is, afaik, standard windows behaviour: GUI programs start with stdin, stdout and stderr closed. Thomas From jstroud at mbi.ucla.edu Thu Sep 29 23:42:36 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 29 Sep 2005 20:42:36 -0700 Subject: A Moronicity of Guido van Rossum In-Reply-To: <77498FFE-AEC3-4148-A113-E434EE4A4E52@ihug.co.nz> References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> <77498FFE-AEC3-4148-A113-E434EE4A4E52@ihug.co.nz> Message-ID: <200509292042.36051.jstroud@mbi.ucla.edu> I know nobody wants to do add "white/black-listing", so we can do it probabilistically. In case it is not obvious, mailings with the words "jargon" or "moron" and their derrivatives should be flagged as 99.9% probability for Moronicity Xha Lee, Jargonizer, spam. If spam bayes can't figure this out, then either it is not properly implemented or Bayes himself was out to lunch. James On Thursday 29 September 2005 16:39, Tony Meyer wrote: > > To fight this sort of message, I think spambayes would have to be > able to understand the context more. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From pedro.werneck at terra.com.br Fri Sep 23 17:17:34 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Fri, 23 Sep 2005 18:17:34 -0300 Subject: Wrapping classes In-Reply-To: <4333BCBA.1060308@tiscali.it> References: <4333BCBA.1060308@tiscali.it> Message-ID: <20050923181734.0d57b554.pedro.werneck@terra.com.br> I agree this is a case for using metaclasses. What about an implementation like this ? Seems like checking if init was already called will slow down all attribute access significantly, but, I don't like this approach of changing the __init__ method. class LazyInit(type): def __new__(self, name, bases, dict): def __getattribute__(self, attr): attrs = object.__getattribute__(self, "__dict__") init = attrs["_init"] if not init: args = attrs["_args"] kwds = attrs["_kwds"] __init__ = object.__getattribute__(self, "__init__") __init__(*args, **kwds) attrs["_init"] = True return object.__getattribute__(self, attr) dict['__getattribute__'] = __getattribute__ return type.__new__(self, name, bases, dict) def __call__(cls, *args, **kwds): o = object.__new__(cls, *args, **kwds) o._args = args o._kwds = kwds o._init = False return o And some simple testing: >>> class Foo: ... __metaclass__ = LazyInit ... def __init__(self, x, y): ... print "init was called", x, y ... self.x = x ... self.y = y ... >>> o = Foo(1, None) >>> o <__main__.Foo object at 0x402cc96c> >>> o.x init was called 1 None 1 >>> o.y >>> Regards, Pedro On Fri, 23 Sep 2005 10:28:42 +0200 Paolino wrote: > Jeremy Sanders wrote: > > Is it possible to implement some sort of "lazy" creation of objects > > only when the object is used, but behaving in the same way as the > > object? > > > A generic approach would override __getattribute__ to let it perform > the > __init__ method on not initialized objects.This is a case for using > metaclasses as even __init__ method must be overridden ad hoc to > register the arguments for the lazy initialization. > Probably you want to fine-tune the triggering (specifing which > attribute should make it happen ),as every look up would trigger..... > > class NotInitializedObjects(type): > def __init__(cls,*_): > realInit=cls.__init__ > def __newInit__(self,*pos,**key): > def _init(): > realInit(self,*pos,**key) > self._init=_init > cls.__init__=__newInit__ > def __getattribute__(self,attr): > def getter(attr): > return object.__getattribute__(self,attr) > if '_init' in getter('__dict__'): > getter('_init')() > del self._init > return getter(attr) > cls.__getattribute__=__getattribute__ > > > if __name__=='__main__': > class Class: > __metaclass__=NotInitializedObjects > def __init__(self,*pos,**key): > self.initialized=True > print 'initializing with',pos,key > a=Class('arg',key='key') # a fake initialization > > try: > object.__getattribute__(a,'initialized') > except AttributeError: # should raise > print 'not initialized' > else: > raise > try: > a.initialized #every look up would do ,even a print > except AttributeError: > raise > else: > print 'initialized' > > > Have fun Paolino > > > > > > ___________________________________ > Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB > http://mail.yahoo.it > -- > http://mail.python.org/mailman/listinfo/python-list -- Pedro Werneck From forestiero at qwest.net Mon Sep 26 23:44:12 2005 From: forestiero at qwest.net (DogWalker) Date: Mon, 26 Sep 2005 20:44:12 -0700 Subject: webbrowser failing In-Reply-To: <042101c5be78$a026d6a0$346ea8c0@tintz.co.nz> References: <042101c5be78$a026d6a0$346ea8c0@tintz.co.nz> Message-ID: <20050927034148.26962.68534@linux.local> "Thomas Thomas" said: >Hi All, > >import webbrowser >url='http://www.cnn.com' >webbrowser.open(url) > >giving the error > >Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> ## working on region in file c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py... >Traceback (most recent call last): > File "", line 1, in ? > File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py", line 3, in ? > webbrowser.open(url) > File "C:\Python23\lib\webbrowser.py", line 43, in open > get().open(url, new, autoraise) > File "C:\Python23\lib\webbrowser.py", line 250, in open > os.startfile(url) >WindowsError: [Errno 2] The system cannot find the file specified: 'http://www.cnn.com' >>>> > >any help >Thoma Were you connected when you tried? From jepler at unpythonic.net Tue Sep 27 20:09:28 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 27 Sep 2005 19:09:28 -0500 Subject: Human readable number formatting In-Reply-To: <1127862406.11827.2.camel@localhost.localdomain> References: <1127862406.11827.2.camel@localhost.localdomain> Message-ID: <20050928000928.GA25595@unpythonic.net> Compared to your program, I think the key to mine is to divide by "limit" before taking the log. In this way, things below the "limit" go to the next lower integer. I think that instead of having 'step' and 'base', there should be a single value which would be 1000 or 1024. import math def MakeFormat(prefixes, step, limit, base): def Format(n, suffix='B', places=2): if abs(n) < limit: if n == int(n): return "%s %s" % (n, suffix) else: return "%.1f %s" % (n, suffix) magnitude = math.log(abs(n) / limit, base) / step magnitude = min(int(magnitude)+1, len(prefixes)-1) return '%.1f %s%s' % ( float(n) / base ** (magnitude * step), prefixes[magnitude], suffix) return Format DecimalFormat = MakeFormat( prefixes = ['', 'k', 'M', 'G', 'T'], step = 3, limit = 100, base = 10) BinaryFormat = MakeFormat( prefixes = ['', 'ki', 'Mi', 'Gi', 'Ti'], step = 10, limit = 100, base = 2) values = [0, 1, 23.5, 100, 1000/3, 500, 1000000, 12.345e9] print [DecimalFormat(v) for v in values] print [BinaryFormat(v) for v in values] -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From john at jmsd.co.uk Thu Sep 15 15:36:02 2005 From: john at jmsd.co.uk (John Moore) Date: Thu, 15 Sep 2005 20:36:02 +0100 Subject: IDE, widget library In-Reply-To: References: Message-ID: <4329CD22.2050308@jmsd.co.uk> Thomas Jollans wrote: >With that I come to the second question: >What cross-platform GUI libraries are there ? cross-platform meaning >functional and free on (at least) X11 and Win32 >PyQT obviously doesn't count because qt3 is not free on windows. >Tk is ugly. (how well) is Tile supported with python ? >does PyGTK/Glade work on win32 ? > > wxPython? http://www.wxpython.org/ -- ============================================== John Moore - Norwich, UK - john at jmsd.co.uk ============================================== From http Sat Sep 17 16:59:41 2005 From: http (Paul Rubin) Date: 17 Sep 2005 13:59:41 -0700 Subject: Wanted: mutable bitmap References: Message-ID: <7xacib9zr6.fsf@ruckus.brouhaha.com> Tom Anderson writes: > One thing that would be rather useful in various bits of programming > i've done would be a mutable bitmap type. > Am i right in thinking there's no such thing in the standard library? > Is there an implementation out there somewhere else? Is there a hack > for doing it with the stuff that is in the standard library? The obvious way is with the array module. From mekstran at iastate.edu Wed Sep 21 09:21:03 2005 From: mekstran at iastate.edu (Michael Ekstrand) Date: Wed, 21 Sep 2005 08:21:03 -0500 Subject: Perl's documentation come of age In-Reply-To: <1127299284.748225.68560@g14g2000cwa.googlegroups.com> References: <1123809822.696399.317570@g44g2000cwa.googlegroups.com> <1125179974.483320.116780@g49g2000cwa.googlegroups.com> <1127299284.748225.68560@g14g2000cwa.googlegroups.com> Message-ID: <200509210821.03783.mekstran@iastate.edu> On Wednesday 21 September 2005 05:41, Xah Lee wrote: > One easy way to test this, is for Pythoners to read Perl docs and > vice versa. > > Pythoners will find that, you really don't know what the fuck the > Perlers are talking about. Same with Perler with Python docs. At the risk of feeding the troll here... point defeated. I learned Python before I learned Perl, but consider myself to now be fluent in both. And I find the docs for both to be immensely useful and fairly well-organized (OK, so sometimes I have to hunt a bit longer than I'd like in the Perl docs, but perldoc.perl.org looks promising). And in my early stages of Python from C++, and Perl from Python, shell, and C, I really didn't have any trouble figuring out what was going on. So, Guido, Fred Drake, and everyone else involved in writing Python docs: done well you have. Keep up the good work. Python IMHO has some of the best docs in the open-source world (on a par with Vim). - Michael From sp1d3rx at gmail.com Wed Sep 14 16:24:34 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 14 Sep 2005 13:24:34 -0700 Subject: ezPyCrypto In-Reply-To: <1126728287.603932.256190@o13g2000cwo.googlegroups.com> References: <1126728287.603932.256190@o13g2000cwo.googlegroups.com> Message-ID: <1126729473.993336.103980@z14g2000cwz.googlegroups.com> Why do you want to encrypt just the numbers? From steven.bethard at gmail.com Mon Sep 12 11:27:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 12 Sep 2005 09:27:01 -0600 Subject: which is more 'pythonic' / 'better' ? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > try...except... blocks are quick to set up, but slow to catch the > exception. If you expect that most of your attempts will succeed, then the > try block will usually be faster than testing the length of the list > each time. > > But if you expect that the attempts to write the line will fail more > frequently, then testing will be quicker. > > You will need to do your own testing before hand to find the exact > cut-off, and expect that cut-off to vary according to the Python > implementation and version. But a rough rule of thumb is, if you expect > your code to fail more often than succeed, then test first, otherwise > catch an exception. FWIW, these are almost exactly my criteria too. Exceptions are for "exceptional" conditions, that is, things that you expect to happen infrequently[1]. So if I think the code is going to fail frequently, I test the condition, but if I think it won't, I use exceptions. STeVe [1] Note though that what is "infrequent" in Python might be still considered "frequent" in other languages. For example, Java's iterators check the result of a .hasNext() method before each .next() call, while Python's iterators assume the .next() call will succeed, and simply test for the "exceptional" condition of a StopIteration exception. From frithiof.jensen at die_spammer_die.ericsson.com Tue Sep 20 08:21:29 2005 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 20 Sep 2005 14:21:29 +0200 Subject: Help! Python either hangs or core dumps when calling C malloc References: <1126198290.288644.247510@o13g2000cwo.googlegroups.com> <1126199525.752904.254930@z14g2000cwz.googlegroups.com> <1126203439.152057.78210@o13g2000cwo.googlegroups.com> Message-ID: "Christian Stapfer" wrote in message news:dfr3sr$7rj$1 at news.hispeed.ch... > Check your program for _uninitialized_variables_. good point. > (Just a guess: but what other side-effect than > changing the values of uninitialized variables > - and the program's timing, of course - might > the stepping through with a debugger have?) that, f.ex. with some debuggers, all application memory is conveniently zeroed so you might survive popping NOP's off the stack until you eventually hit a valid return ... I once traced through an embedded assembly program - that had been working for years - with a logic analyser to re-create the source from the old flow charts and the hundreds of patches that had been applied to the thing during "comissioning", i.e. On Site Development. I found that the "correct" program would somtimes get hit by an unitialised interupt, the CPU would land between two instructions and start executing garbage until it chrashed over something else and magically re-synchronised. Fine stuff. The reassembled program executed 40% faster without all the jump-to-patch stuff so I had to re-adjust all the timers too. From jstroud at mbi.ucla.edu Thu Sep 22 20:38:34 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Sep 2005 17:38:34 -0700 Subject: Anyone else getting posts back as email undeliverable bounces? In-Reply-To: <433346fa.2178291167@news.oz.net> References: <433346fa.2178291167@news.oz.net> Message-ID: <200509221738.34870.jstroud@mbi.ucla.edu> This is an autoreply to your message. Oh wait, no its not, its really me. Yes, I am getting the same trash. I hope whoever it is at liage.net, gets tired of mail related threads like this and disables their damn autobounce. Perhaps they will check to see if they are responsible before the chime in with some righteous admonishment about off-topic threads. On Thursday 22 September 2005 17:16, Bengt Richter wrote: > It seems lately all my posts have been coming back to me as bounced emails, > and I haven't emailed them ;-( > > I've been getting bounce messages like (excerpt): > ... > _______________________________________________ > > This is the Postfix program at host deimos.liage.net. > > I'm sorry to have to inform you that your message could not be > be delivered to one or more recipients. It's attached below. > > For further assistance, please send mail to > > If you do so, please include this problem report. You can > delete your own text from the attached returned message. > > The Postfix program > > : Host or domain name not found. Name service error > for name=lindensys.net type=A: Host not found > Reporting-MTA: dns; deimos.liage.net > X-Postfix-Queue-ID: DC5264161 > X-Postfix-Sender: rfc822; bokr at oz.net > Arrival-Date: Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > > Final-Recipient: rfc822; lists at lindensys.net > Action: failed > Status: 5.0.0 > Diagnostic-Code: X-Postfix; Host or domain name not found. Name service > error for name=lindensys.net type=A: Host not found > Received: by deimos.liage.net (Postfix, from userid 126) > id DC5264161; Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > Received: from smtp-vbr5.xs4all.nl (smtp-vbr5.xs4all.nl [194.109.24.25]) > by deimos.liage.net (Postfix) with ESMTP id 79D8340AA > for ; Thu, 22 Sep 2005 19:50:13 -0400 (EDT) > Received: from bag.python.org (bag.python.org [194.109.207.14]) > by smtp-vbr5.xs4all.nl (8.13.3/8.13.3) with ESMTP id j8MNoClb072177 > for ; Fri, 23 Sep 2005 01:50:12 +0200 (CEST) > (envelope-from python-list-bounces+lists=listpreserve.org at python.org) > Received: from bag.python.org (bag [127.0.0.1]) > by bag.python.org (Postfix) with ESMTP id 8C4871E4013 > for ; Fri, 23 Sep 2005 01:50:10 +0200 (CEST) > _________________________________________________ > ... > > > Regards, > Bengt Richter -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From russandheather at gmail.com Thu Sep 29 17:40:31 2005 From: russandheather at gmail.com (Russell Warren) Date: 29 Sep 2005 14:40:31 -0700 Subject: scope of socket.setdefaulttimeout? Message-ID: <1128030031.130958.185620@z14g2000cwz.googlegroups.com> Does anyone know the scope of the socket.setdefaulttimeout call? Is it a cross-process/system setting or does it stay local in the application in which it is called? I've been testing this and it seems to stay in the application scope, but the paranoid side of me thinks I may be missing something... any confirmation would be helpful. From python-url at phaseit.net Mon Sep 5 10:06:00 2005 From: python-url at phaseit.net (Diez B. Roggisch) Date: Mon, 05 Sep 2005 14:06:00 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 5) Message-ID: QOTW: "You can lead an idiot to idioms, but you can't make him think ;-)" -- Steve Holden "A foolish consistency is the hobgoblin of little minds." -- Ralph Waldo Emerson (used by Tim Churches, and also found in http://www.python.org/peps/pep-0008.html) PyPy has come a long way - and made great progress with release 0.7: http://groups.google.com/group/comp.lang.python/msg/5f12849e4c28fc6c Processing large XML files can be tedious, especially when using DOM. Jog shows ways to do so, and ElementTree is as usual amongst the best, both api- and performance-wise: http://groups.google.com/group/comp.lang.python/msg/b1b259c448a867e9 Date processing is often way more difficult than one thinks - in languages that don't have a rich date api like python, that is: http://groups.google.com/group/comp.lang.python/msg/9d125ca55b83b17a Not exactly new, these new-style classes. But you can always find nifty details you didn't know about: http://groups.google.com/group/comp.lang.python/browse_frm/thread/3fa6468b47d5334c/8118bfd6cf266c13#8118bfd6cf266c13 Congratulations to SpamBayes contributors on the announcement that *Personal Computer World* awarded that project its "Editors' Choice" award, besting competitors including products from Symantec, McAfee, and so on: http://pcw.co.uk There is always room for new syntax proposals, like a "isa" keyword to sugar isinstance - and while it's unlikely to become part of the language, discussing it produces nice insights: http://groups.google.com/group/comp.lang.python/msg/36b504905a36155d Often requested, but never realized: a yield to yield them all. Apparently this won't change soon, but yield itself is going to become an expression: http://groups.google.com/group/comp.lang.python/msg/d66f346c98b8eac6 Using struct to marshal C-structures is easy - dealing with pointers in them, too: http://groups.google.com/group/comp.lang.python/msg/13eb61975154a25d ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From fredrik at pythonware.com Tue Sep 27 12:45:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Sep 2005 18:45:53 +0200 Subject: number of python users References: Message-ID: Bryan wrote: > just for fun, i looked at the top linux distros at distrowatch and looked at > what version of python the latest released version is shipping with out of the box: > > 1. ubuntu hoary - python 2.4.1 > 2. mandriva 2005 - python 2.4 > 3. suse 9.3 - python 2.4 > 4. fedora core 4 - python 2.4.1 > 5. mepis 3.3.1 - python 2.3.5 > 6. knoppix 4.0.2 - python 2.3.5 > 7. debian sarge - python 2.3.5 > 8. gentoo 2005.1 - python 2.3.5 > 9. slackware 10.2 - python 2.4.1 > 10.kubuntu hoary - python 2.4.1 > 11. freebsd 5.4 - python 2.4 > 12. xandros 3.0 - python 2.3.4 > 13. pclinuxos 0.91 - python 2.3.4 no RHEL? (are they still stuck on 2.2, btw?) From ptmcg at austin.rr._bogus_.com Tue Sep 20 16:38:25 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 20 Sep 2005 20:38:25 GMT Subject: Object default value References: <1127244679.263516.106970@g49g2000cwa.googlegroups.com><43306858.20003@websafe.com><1127246758.691165.23920@g49g2000cwa.googlegroups.com> Message-ID: <5r_Xe.25006$S26.11723@tornado.texas.rr.com> > I think you want to overload the assignment operator here. I'm not sure that > is allowed in python (I've never seen it done). You can't because assignment is not an operator in Python. Is it safe to assume that the OP's next question will be how to invoke functions without the ()'s? To save you the trouble, then answer is 'no'. Python is simple, VB is simple, but Python is not VB. -- Paul From pmaupin at gmail.com Tue Sep 6 21:37:53 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 6 Sep 2005 18:37:53 -0700 Subject: Proposal: add sys to __builtins__ In-Reply-To: References: Message-ID: <1126057073.105399.191540@g47g2000cwa.googlegroups.com> Sybren Stuvel wrote: > A programming language should not be ambiguous. The choice > between importing a module and calling a function should not > depend on the availability of a (local) variable. Yeah, this behavior would be as ambiguous as if we had a system-defined search-path for modules, where you might get one module or another depending on the path order. Oh, wait -- we have one of those. > The question is not if it's possible or not - in principle, everything > is possible. The question is if it is desirable. Exactly. So it pays to try to understand what the payoff might be, and I always try to be open-minded about that (although I sometimes fail miserably in this goal). In the case of sys.path, the payoff is that a Python application has a small chance of running on a completely different system. In the case of automagic importation, the only payoff I have seen discussed is that some people would be happier with a little less typing. The thing I always find baffling is that people who find it hard to type "import sys" seem to find it quite easy to write eight paragraphs explaining why it's bad to have to type "import sys." Regards, Pat From hancock at anansispaceworks.com Wed Sep 7 11:09:41 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 7 Sep 2005 10:09:41 -0500 Subject: Job Offer in Paris, France : R&D Engineer (Plone) In-Reply-To: References: <7xpsrn3100.fsf@ruckus.brouhaha.com> Message-ID: <200509071009.41590.hancock@anansispaceworks.com> On Tuesday 06 September 2005 03:34 am, Huron wrote: > > 1) whether there would be legal or procedural obstacles for a > > non-European wanting to work in Paris for a while; and > If you are a member of the EU (the netherlands ?), there no such problem on > our side. Only _you_ would have some paperwork to do. Europeans have been tearing Americans to shreds over our "parochialism", it's amusing to see them succomb to the same faults now that they are convinced they are the economic center of the universe, isn't it? I guess the foot's on the other hand now. ;-D -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jforcier at strozllc.com Tue Sep 13 18:09:41 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: 13 Sep 2005 15:09:41 -0700 Subject: Printing w/o newlines inside loops - odd behavior In-Reply-To: <43274C7B.1090500@websafe.com> References: <1126648452.814304.139740@g44g2000cwa.googlegroups.com> <43274C7B.1090500@websafe.com> Message-ID: <1126649381.275592.75470@g49g2000cwa.googlegroups.com> Erik: Thanks, that was it! Figured it was something along those lines, but like I said, I didn't know specifically what was going on or what to look for. Larry: That recipe could be useful, thanks a lot :) And thanks for the quick replies, too, you guys are awesome. Regards, Jeff From monuindia at gmail.com Wed Sep 7 05:54:21 2005 From: monuindia at gmail.com (monuindia at gmail.com) Date: 7 Sep 2005 02:54:21 -0700 Subject: multi pointer slider(scale) Message-ID: <1126086861.768629.301910@g44g2000cwa.googlegroups.com> HI, I am new to python graphics. I want to have a scale(tkinter) or slider(wxpython), on which I can have more than one pointers. Using it I want to have single slider for different parameters of an entity. Can anyone help me to look for it OR make it. Thanks in adwance. From learningProgramming at gmail.com Fri Sep 9 13:59:34 2005 From: learningProgramming at gmail.com (Learning Python) Date: 9 Sep 2005 10:59:34 -0700 Subject: circular import problem Message-ID: <1126288774.239916.310020@z14g2000cwz.googlegroups.com> An example in the book I didn't understood well two modules files recursively import/from each other in recur1.py,we have: x=1 import recur2 y=1 in recur2.py, we have from recur1 import x from recur1 import y If we run interactively at python command line, >>> import recur1 it has errors like this: Traceback (most recent call last): File "", line 1, in ? File "recur1.py", line 2, in ? import recur2 File "recur2.py", line 2, in ? from recur1 import y ImportError: cannot import name y I understood this because recur1 is not finished when recur2 is trying to import y. However, if you run interactive for recur2.py interactively, it is fine. when you run as script from command line, recur1.py is fine. but when you python recur2.py at commmand line, it has errors like this: Traceback (most recent call last): File "recur2.py", line 1, in ? from recur1 import x File "recur1.py", line 2, in ? import recur2 File "recur2.py", line 2, in ? from recur1 import y ImportError: cannot import name y What's really the problem here? Thanks From lily.poon at gmail.com Thu Sep 8 13:12:05 2005 From: lily.poon at gmail.com (Lil) Date: 8 Sep 2005 10:12:05 -0700 Subject: Help! Python either hangs or core dumps when calling C malloc In-Reply-To: <43206F10.3070704@websafe.com> References: <1126198290.288644.247510@o13g2000cwo.googlegroups.com> <43206F10.3070704@websafe.com> Message-ID: <1126199525.752904.254930@z14g2000cwz.googlegroups.com> Hi Larry, It's in the C code mainly because the buffer is an input to the driver. The driver takes a char* as input and I didn't want to pass a char* from python -> swig -> C since swig has memory leaks passing pointers. Do you think this is a Python issue or a Red Hat issue? I'm going to try it on my windows machine now and see what happens. thanks! Lil From ramen at lackingtalent.com Fri Sep 30 16:22:51 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 30 Sep 2005 13:22:51 -0700 Subject: Duplicating Modules In-Reply-To: References: Message-ID: Misto . wrote: > Hi folks! > > Short: > > There is a way to dumplicate a module ? Here's one way... it doesn't quite work with modules inside of packages, unfortunately, but it does avoid defeating module caching and tries to keep sys.modules in a predictable state. I don't know what the thread-safety implications are for this sort of trickery with sys.modules. def import_as(newname, oldname): """Import a module under a different name. This procedure always returns a brand new module, even if the original module has always been imported. Example:: try: # Reuse this module if it's already been imported # as "mymath". import mymath except ImportError: # "mymath" has not yet been imported. # Import and customize it. mymath = import_as('mymath', 'math') mymath.phi = (mymath.sqrt(5.0) - 1.0) / 2.0 The above code will not reinitialize "mymath" if it executes a second time (ie. if the module containing this code is reloaded). Whether or not "math" has already been imported, it will always be a different object than "mymath". """ import sys if sys.modules.has_key(oldname): tmp = sys.modules[oldname] del sys.modules[oldname] result = __import__(oldname) sys.modules[newname] = sys.modules[oldname] sys.modules[oldname] = tmp else: result = __import__(oldname) sys.modules[newname] = sys.modules[oldname] del sys.modules[oldname] return result Dave From godoy at ieee.org Wed Sep 28 08:17:54 2005 From: godoy at ieee.org (Jorge Godoy) Date: 28 Sep 2005 09:17:54 -0300 Subject: number of python users References: Message-ID: <87k6h1gzd9.fsf@ieee.org> Bryan writes: > just for fun, i looked at the top linux distros at distrowatch and looked at > what version of python the latest released version is shipping with out of the > box: > > 1. ubuntu hoary - python 2.4.1 > 2. mandriva 2005 - python 2.4 > 3. suse 9.3 - python 2.4 3.1. OpenSuSE 10 will be coming out with Python 2.4.1 as well. Be seeing you, -- Jorge Godoy From ara at nestle.csail.mit.edu Fri Sep 2 06:41:34 2005 From: ara at nestle.csail.mit.edu (Allan Adler) Date: 02 Sep 2005 06:41:34 -0400 Subject: anaconda.real in RH7.1 Message-ID: I'm trying to reinstall RedHat 7.1 Linux on a PC that was disabled when I tried to upgrade from RH7.1 to RH9. This is presenting lots of unexpected difficulties. Apart from wanting to keep the old model T in shape, I'm treating this as a learning experience. Right now, I'm trying to gain more control over the installation CD. By that I mean, I intend to modify the installation script and other aspects of the CD and burn a new installation CD. The installation script starts off as a shell script named anaconda which then calls a python script named anaconda.real. The former is pretty easy to understand, but I don't know anything about python. At the moment, I'm using the book, "Programming Python", by Mark Lutz, as a reference. The file anaconda.real is about 526 lines long. I've copied out about an eighth of it into a notebook and am trying to use the book to make sense of what I have copied. I'm not finding it very helpful. I don't know whether that is because the script relies on aspects of python that aren't well explained in the book or because it relies on aspects of RedHat Linux. I thought I should ask here first about what seem like purely python issues. The file anaconda.real is invoked with the line exec /usr/bin/anaconda.real -T "$@" I don't know what effect the -T "$@" has. The file anaconda.real begins: #!/usr/bin/python signal.signal(signal.SIGINT,signal.SIG_DFL) There is nothing about signal or signal.signal or the other signal.* in the book. The file continues: # For anaconda in test mode if (os.path.exists('isys')) sys.path.append('edd') sys.path.append('libfdisk') [lots of lines like that] else: sys.path.append('/usr/lib/anaconda') sys.path.append('/usr/lib/anaconda/textw') sys.path.append('/usr/lib/anaconda/iw') sys.path.append('/usr/lib/anaconda/installclasses') Here I'm guessing that the if never happens and the various /usr/lib/anaconda directories are appended to the PATH environment variable. Later on, after importing traceback (which is briefly mentioned in the book), string, isys, iutil, _ from translate, handleException from exception, it apparently worries about the environment variable ANACONDAARGS and then executes try: (args, extra) = isys.getopt(theargs, 'GTRxtdr:fm:', ['gui','text','reconfig','xmode','test','debug','nofallback', 'method=','rootpath=',... Anyway, in a nutshell, whenever I see anything specific in the file anaconda.real, it isn't mentioned in the book and I don't know how to get more information about it and I don't know how python gets its information about it. What do I need to read? -- Ignorantly, Allan Adler * Disclaimer: I am a guest and *not* a member of the MIT CSAIL. My actions and * comments do not reflect in any way on MIT. Also, I am nowhere near Boston. From hancock at anansispaceworks.com Wed Sep 14 18:47:29 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 14 Sep 2005 17:47:29 -0500 Subject: Interface with C In-Reply-To: References: Message-ID: <200509141747.29742.hancock@anansispaceworks.com> On Wednesday 14 September 2005 12:34 pm, Ben Pearson wrote: > I have a program that is developed in C, that has a simple text > interface. I would like to use the same program, but with a GUI. I > would like to use Python to interface with it, so that Python will > simply read and write the code that would be used from a normal user, > but using a TK GUI. For example, in the C program, if you type 0, it > will send a ping. I would like to build a program that will run the C > program, simply inputing the values that the Text interface would > use, but with the graphical interface. EI, the following should work. If you are asking what I think you're asking, you need to read up on the "subprocess" module (Python 2.4). There are ways to do it with earlier versions, but everything I've heard about this (and personal experience with the old way) suggests you should just use 2.4's subprocess. What I thought you said is that your C program runs its own control loop, taking data from stdin and acting on it, presumeably outputting to stdout if necessary. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From efrat_regev at yahoo.com Fri Sep 30 06:50:14 2005 From: efrat_regev at yahoo.com (Efrat Regev) Date: Fri, 30 Sep 2005 13:50:14 +0300 Subject: Python CGI Script Message-ID: <433f9875@news.bezeqint.net> Hello, I'm a data-structures course TA trying to write a python CGI script for automatically compiling and testing students' projects. Unfortunately, I've run into some questions while writing this, which I couldn't solve with the various (and helpful) python-CGI documentation. (It's possible that I'm posting to the wrong group; if so, I'd appreciate suggestions for the appropriate group.) 1. In my HTML page, I have the following:
...
In the above, submission_processor.py is the python CGI script. I didn't write a URL in the action field, since I'm first testing everyting on a local machine (running FC4). The first line of submission_processor.py is #!/usr/bin/python and I've done chmod +x submission_processor.py When I hit the "submit" button, my browser (Firefox on FC4) doesn't run the script; it asks me whether it should open submission_processor.py or save it to disk. I couldn't figure out why. 2. My HTML page has the option for an instructor to list the various submissions and scores. Obviously, this should be inaccessible to students. The instructor has a password for doing this, therefore. Suppose I place the password inside a python script, and give this script only +x permission for others. Is this adequate as far as security? Thanks in advance for answering these questions. Efrat From rattan at cps.cmich.edu Fri Sep 9 10:57:49 2005 From: rattan at cps.cmich.edu (rattan at cps.cmich.edu) Date: 9 Sep 2005 07:57:49 -0700 Subject: re module help Message-ID: <1126277869.480420.3740@g47g2000cwa.googlegroups.com> I am trying to make prescript-2.2 (old python based psotscript to plain text converter). It gives the following dprecation message /local/users/ishwar/prescript-2.2/misc.py:23: DeprecationWarning: the regex module is deprecated; please use the re module import os, regex, sys, string if I start replacing regex by re I get stuck at replacement of regex.symcomp() and regex.pattern() methods. The are not in re module. Is there a solution? -ishwar From fredrik at pythonware.com Mon Sep 26 15:59:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Sep 2005 21:59:11 +0200 Subject: Plotting points to screen References: <1127763119.071302.300810@g44g2000cwa.googlegroups.com> Message-ID: Jay wrote: > One question, that's twice in as many days that someone has said "YMMV". > > What's it mean!? http://www.google.com/search?q=acronym+ymmv From theller at python.net Tue Sep 13 03:40:32 2005 From: theller at python.net (Thomas Heller) Date: Tue, 13 Sep 2005 09:40:32 +0200 Subject: improvements for the logging package References: <1125935246.425351.260880@z14g2000cwz.googlegroups.com> <20050906172418.GL4377@ActiveState.com> <17182.22978.718108.100126@montanaro.dyndns.org> <20050907171420.GB31649@ActiveState.com> <1126563514.072523.26980@g47g2000cwa.googlegroups.com> Message-ID: "Vinay Sajip" writes: > OK, it's not right at the top of the docs, but the example at > > http://docs.python.org/lib/minimal-example.html > > has been there for a while, and if you think it can be made clearer, > please suggest how. Maybe I'm missing something, but the code from the example doesn't work for me: >>> import logging >>> >>> logging.basicConfig(level=logging.DEBUG, ... format='%(asctime)s %(levelname)s %(message)s', ... filename='/tmp/myapp.log', ... filemode='w') Traceback (most recent call last): File "", line 4, in ? TypeError: basicConfig() takes no arguments (4 given) >>> From ramdaz at gmail.com Tue Sep 13 14:58:31 2005 From: ramdaz at gmail.com (Ramdas) Date: 13 Sep 2005 11:58:31 -0700 Subject: What XML lib to use? In-Reply-To: <0001HW.BF4CD7C600321189F0407550@news.individual.de> References: <0001HW.BF4CD7C600321189F0407550@news.individual.de> Message-ID: <1126637911.799889.210870@g47g2000cwa.googlegroups.com> You can try xml.dom and xml.sax. Both are inbuilt libraries with Python standard package. You can read and write xml files with these very easily. There are number of third party modules for Python that manipulate XML. But the above are the basic ones. From __peter__ at web.de Wed Sep 28 14:55:07 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Sep 2005 20:55:07 +0200 Subject: import problems in packages References: Message-ID: St?phane Ninin wrote: > Also sprach St?phane Ninin : Sollte es denn m?glich sein! Dieser alte Heilige hat in seinem Walde noch Nichts davon geh?rt... that intra-package import takes precedence over absolute import! > Here is the basic structure of the code (I have reduced it first). And nicely so. Not letting similar names for modules, packages and classes abound might have been a good idea, too. > I have an ImportError problem, which is probably correct, > but I do not understand it. And how to fix it... > ROOT: > /main.py > /Handlers/__init__.py?(empty) > /Handlers/Handlers.py > /Handlers/HandlerFactory.py > /Handlers/Default/__init__.py?(empty) > /Handlers/Default/Handlers.py > /Handlers/Default/HandlerFactory.py > ROOT/main.py contains: > from?Handlers.HandlerFactory?import?HandlerFactory works and triggers > ROOT/Handlers/HandlerFactory.py contains: > import?Handlers.Default.HandlerFactory which tries to import ROOT/Handlers/Handlers/Default/HandlerFactory.py, but unfortunately ROOT/Handlers/Handlers[.py] is not a package and therefore doesn't contain a Default package. Currently, when you have amodule.py apackage/amodule.py apackage/anothermodule.py and try to import amodule into anothermodule, there is no way to tell Python that you mean amodule.py and not apackage/anmodule.py. Peter From michaelschneider at fuse.net Thu Sep 29 20:24:13 2005 From: michaelschneider at fuse.net (Michael Schneider) Date: Thu, 29 Sep 2005 20:24:13 -0400 Subject: What python idioms for private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com><7xbr2dxqqq.fsf@ruckus.brouhaha.com><7xk6h0zxnm.fsf@ruckus.brouhaha.com><7x64skzvas.fsf@ruckus.brouhaha.com><7xd5mstqab.fsf@ruckus.brouhaha.com> <3f11a$433bf55e$d8c4f6e6$10834@FUSE.NET> Message-ID: <433C85AD.6000803@fuse.net> Frederik, Thank you very much for the info on properties, that is very useful. Sorry about the public typo, that should have been protected. I should not post before coffee hits :-) Happy coding, Mike Fredrik Lundh wrote: > Michael Schneider wrote: > > >>1) mark an object as dirty in a setter (anytime the object is changed, >>the dirty flag is set without requiring a user to set the dirty flag > > > properties. > > >>2) enforce value constraints (even if just during debugging) > > > properties. (when you no longer need to enforce things, switch back > to a plain attribute). > > >>3) lazy init, don't bring the data in until needed > > > properties. > > >>4) adding debug info > > > properties. > > >>5) .... more here???? > > > properties. > > >>It would be easy for me to say "Add public and private to python so I >>can code the way that I am used to". > > > huh? what do "private" and "public" have to do with what you're describing? > > >>What are some python alternatives to achieve the design intents specified >>above above? > > > properties. > > http://users.rcn.com/python/download/Descriptor.htm#properties > > > > > From http Fri Sep 30 10:32:43 2005 From: http (Paul Rubin) Date: 30 Sep 2005 07:32:43 -0700 Subject: [Info] PEP 308 accepted - new conditional expressions References: <3q4ro9Fd770nU3@individual.net> Message-ID: <7xbr2a4odw.fsf@ruckus.brouhaha.com> Richie Hindle writes: > Yes. From Guido's announcement at > http://mail.python.org/pipermail/python-dev/2005-September/056846.html: > > The syntax will be > > A if C else B Wow, I thought this was a prank at first. Congratulations to Guido. I think the introduction of list and sequence comprehensions made the absence of a conditional construct felt even more strongly than before, for those of us who program in this style. From http Mon Sep 26 14:52:42 2005 From: http (Paul Rubin) Date: 26 Sep 2005 11:52:42 -0700 Subject: Telephony project References: <1127758835.527555.217870@g47g2000cwa.googlegroups.com> Message-ID: <7x64snbr0l.fsf@ruckus.brouhaha.com> "Roger" writes: > 1. Fetch phone number from my ASCII data. > 2. Dial (always a local number) phone (through USRobotics 56K? ). > 3. Ask @3 questions to called phone number. Y/N Y/N Y/N > 4. Save answers to ASCII file. > 5. Say 'Thanks', hang up. > Repeat till eof() There is an excellent graphic on the web showing how to do this phone spamming with Python. It used to be at http://goatse.cx but I don't know where it is now. From chris.cavalaria at free.fr Wed Sep 28 08:43:41 2005 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 28 Sep 2005 14:43:41 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: <433a8e49$0$20855$626a14ce@news.free.fr> Steven D'Aprano a ?crit : > For some reason, the original post never made it to my newsreader, so > apologies for breaking threading by replying to a reply when I mean to > answer the original post. > > On Wed, 28 Sep 2005 12:05:21 +0100, Simon Brunning wrote: > > >>On 9/28/05, could ildg wrote: > > >>>Python is wonderful except that it has no real private and protected >>>properties and methods. > > > Do you know any language that has real private and protected attributes? > > There may be some. I don't know. But anyone who says "C++" is fooling > themselves: > > #define private public #undef private :) From jason.mobarak at gmail.com Fri Sep 16 17:52:46 2005 From: jason.mobarak at gmail.com (Jason Mobarak) Date: 16 Sep 2005 14:52:46 -0700 Subject: Dictionary sorting problem References: <1126899106.189220.209940@o13g2000cwo.googlegroups.com> Message-ID: <1126907566.572463.131080@g43g2000cwa.googlegroups.com> You can't sort dictionaries (as implemented by hash tables), they are unordered data types, so by definition there's no way to force an order on them. http://en.wikipedia.org/wiki/Hash_tables From n00m at narod.ru Wed Sep 14 13:32:51 2005 From: n00m at narod.ru (n00m) Date: 14 Sep 2005 10:32:51 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: <3or48lF7480dU1@individual.net> References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> <1126715343.490964.5640@f14g2000cwb.googlegroups.com> <3or48lF7480dU1@individual.net> Message-ID: <1126719171.467217.149220@g14g2000cwa.googlegroups.com> Got it! He is a kind of pythonic monsters. Btw, why it's impossible to reply to old threads? Namely, there're no more "Reply" link in them. Only "Reply to author" etc. From tundra at tundraware.com Sat Sep 10 18:57:07 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 10 Sep 2005 18:57:07 EDT Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <1126340055.955682.88870@g49g2000cwa.googlegroups.com> <97mav2-lc3.ln1@eskimo.tundraware.com> Message-ID: Dennis Lee Bieber wrote: > On 10 Sep 2005 05:36:08 EDT, Tim Daneliuk > declaimed the following in comp.lang.python: > > > >>On a more general note, for all the promises made over 3 decades about >>how OO was the answer to our problems, we have yet to see quantum > > > OO goes back /that/ far? (2 decades, yes, I might even go 2.5 > decades for academia ). My college hadn't even started "structured > programming" (beyond COBOL's PERFORM statement) by the time I graduated > in 1980. Well, okay... SmallTalk... But for most of the "real world", OO > became a known concept with C++ mid to late 80s. > OO ideas predate C++ considerably. The idea of encapsulation and abstract data types goes back to the 1960s IIRC. I should point out that OO isn't particularly worse than other paradigms for claiming to be "The One True Thing". It's been going on for almost a half century. I've commented on this previously: http://www.tundraware.com/Technology/Bullet/ -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From rrr at ronadam.com Mon Sep 5 18:33:33 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 05 Sep 2005 22:33:33 GMT Subject: Possible improvement to slice opperations. In-Reply-To: <431c9da1.693206578@news.oz.net> References: <431c3b4f$1@nntp0.pdx.net> <431c9da1.693206578@news.oz.net> Message-ID: <1J3Te.14058$xl6.2182@tornado.tampabay.rr.com> Bengt Richter wrote: > On Mon, 5 Sep 2005 18:09:51 +0200, "Fredrik Lundh" wrote: > OTOH, ISTM we must be careful not to label an alternate alpha-version > "way to model the real world" as a "misunderstanding" just because it is alpha, > and bugs are apparent ;-) Thanks! I couldn't have said this myself. :-) > BTW, it just occurred to me that alternate slice member semantics could be RELATIVE, > EACH depending on sign. I.e., > > x[start:stop:step] > > could mean start with x[start] as now as a starting point reference point element, > then let stop be a relative range length in either direction from the > starting point, and step absolute value indicating step size, and its sign > indicating insertion side for zero length slices. In effect, stop would > be a count for the slice range in either direction starting with the starting > element > > s = 'abcde' > s[2:2] => 'cd' > s[2:-2] => 'cb' > s[-2:-3] => 'dcb' > s[-2:0] => '' > s[2:0] => '' > s[-2:-3:2] => 'db' > r = range(10) > r[5:0] = 'a' > r => [0, 1, 2, 3, 4, 5, 'a', 6, 7, 8, 9] > r[-2:0:-1] = 'b' > r => [0, 1, 2, 3, 4, 5, 'a', 6, 7, 'b', 8, 9] > r[-2:0] = ['c', 'd'] > r => [0, 1, 2, 3, 4, 5, 'a', 6, 7, 'b', 8, c, d, 9] Interesting, so it would be... slice( position, count, step ) Items are addressed directly so there's no 'gap's to account for. > note that slice assignment would work by iterating through the right hand > sequence, which could do interesting things: > > r = range(6) > r[3:-2] = 'ab' > r => [0, 1, 'b', 'a', 4, 5] > but two reverse relative slices match order, so > r = range(10) > r[5:-3] = range(10)[-1:-3] # rh seq is 9, 8 > r => [0, 1, 8, 9, 4, 5] > > I think this is kind of interesting, and I probably wouldn't have thought of > it if I had not been for Ron's enthusiasm for his "misunderstanding" ;-) > > In a way, "misunderstandings" are the mutations of open source evolution of ideas, > most of which die, but some of which mutate again and may occasionally survive. > So we need them ;-) Here's another possible "misunderstanding". (or alternative alpha-version) ;-) Have you thought of using a slice object as a buffer pointer for indirect operations? r = range(100) d = [10:20] r.range_add(d,5) # Adds 5 to items in range d d = d[5:] -> [15:20] # relative range modification. # slice of a slice object r.range_sub(d,3) # subtract 3 from items in range d Or more flexible ... r.range_modify(d, add(), 5) Using your suggestion that would be... r = range(100) d = [10:10] r.range_add(d,5) d = d[5:] -> [15:5] # interesting symmetry. r.range_sub(d,3) Of course adding and subtracting slice objects could also be possible. d = [10:20] e = [15:25] f = d + e -> [10:25] or ... d = [10:10] e = [15:10] f = d + e -> [10:15] Cheers, Ron > Regards, > Bengt Richter From vimakefile at yahoo.com Tue Sep 27 21:35:52 2005 From: vimakefile at yahoo.com (Mike) Date: Tue, 27 Sep 2005 18:35:52 -0700 Subject: Perl's documentation come of age References: <1123809822.696399.317570@g44g2000cwa.googlegroups.com> <1125179974.483320.116780@g49g2000cwa.googlegroups.com> <1127299284.748225.68560@g14g2000cwa.googlegroups.com> <200509210821.03783.mekstran@iastate.edu> <43318730.1050305@bellsouth.net> Message-ID: "Mike" wrote in message news:HfydnbcfL6Pnd6TeRVn-uQ at comcast.com... > Looks like I'm having a bad week w/these URLs, because now I'm not able to > access http://lists.ironpython.com/listinfo.cgi/users-ironpython.com . > I was hoping to get at the archives to see if I can glean more info before > I asked too many questions... It's back up... From n00m at narod.ru Sat Sep 3 17:35:30 2005 From: n00m at narod.ru (n00m) Date: 3 Sep 2005 14:35:30 -0700 Subject: Sockets: code works locally but fails over LAN In-Reply-To: References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> <1125681663.710557.320340@f14g2000cwb.googlegroups.com> <3m6ih1taaeo7kndnbuvfl5geed053ivunl@4ax.com> <1125774529.074965.269720@g44g2000cwa.googlegroups.com> Message-ID: <1125783330.784819.63380@z14g2000cwz.googlegroups.com> 1. Python 2.3.4 2. Win98 and Win2k Professional From rschroev_nospam_ml at fastmail.fm Fri Sep 30 03:50:09 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 30 Sep 2005 07:50:09 GMT Subject: Writing EXIF data In-Reply-To: References: Message-ID: Larry Bates schreef: > I've used jhead and wrapped it with os.system call. > > http://www.sentex.net/~mwandel/jhead/ Looks like it can do what I was looking for. Thanks a lot! -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From neil.fraser at gmail.com Fri Sep 23 18:39:21 2005 From: neil.fraser at gmail.com (neil.fraser at gmail.com) Date: 23 Sep 2005 15:39:21 -0700 Subject: Simple Dialogs In-Reply-To: References: <1127500418.970813.321910@g44g2000cwa.googlegroups.com> Message-ID: <1127515161.138744.159240@g14g2000cwa.googlegroups.com> James Stroud wrote: > from tkMessageBox import showerror > showerror('Problem','Program Crashed before Starting') Thanks. That works great when interpreted (though a blank window seems to open as well). Unfortunately it still takes 40 seconds to execute after it has been 'compiled' with py2exe (I've only got a P3). This probably has something to do with the fact that the resulting files for this two-liner weigh in at just under 8MB. Sounds like I'll need to write a one-line msgbox.exe in Visual Whatever or Euphoria and execute that from Python. From fakeaddress at nowhere.org Fri Sep 2 12:09:05 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 02 Sep 2005 16:09:05 GMT Subject: Code run from IDLE but not via double-clicking on its *.py In-Reply-To: <67pfh1ljjcus4i0fp2iuasfb9f4233b6gf@4ax.com> References: <1125478316.530781.315540@g44g2000cwa.googlegroups.com> <1125490472.670850.247240@g49g2000cwa.googlegroups.com> <1125509322.964828.27510@o13g2000cwo.googlegroups.com> <1125579678.705228.172970@f14g2000cwb.googlegroups.com> <1125592608.894215.186670@g43g2000cwa.googlegroups.com> <67pfh1ljjcus4i0fp2iuasfb9f4233b6gf@4ax.com> Message-ID: Dennis Lee Bieber wrote: > I'm going to go back a few messages... Looking for a > simplification... [...] > TWO threads, both just infinite loops of the same nature (you could > actually have done ONE def and passed different arguments in to > differentiate the two thread invocations. > > However, threads aren't really needed for this simple connection > relay... True, though I prefer the tread solution. You can see my exmaple in message . http://groups.google.com/group/comp.lang.python/msg/ffd0159eb52c1b49 > The following has /not/ been run (since I don't have your > server nor VBS) but should do about the same thing (see comments for one > lack). There's an easy trick to pseudo-test such a thing: for the server host and port, edit in 'www.yahoo.com' and 80. Then direct a browser to http://localhost:1434. > =======> Suggested code I have a few further suggestions. [...] > DBMSSocket.connect((host, DBMSPort)) > > MySocket.bind((host, MyPort)) I'd definitely wait for the client connection to come in, before making the server connection. > MySocket.listen(1) > > Client, Addr = MySocket.accept() > > while True: > # wait for either connection to have readable data > (inbound, outbound, excption) = select.select([DBMSSocket, Client], [], []) One trick I used was to pass a timeout parameter; I used one second. Python (at least my version on WinXP) won't honor the keyboard interrupt while waiting at the select. The select is in an infinite loop anyway, so it just means polling for a keyboard interrupt every second. > # handle each readable socket > # NOTE: there is no way (in this quick and dirty code) to > # detect end of connections. > # probably need to do things with the excption list -- > # passing in the sockets, and closing them when they > # show up in excption -- actually, if one side closes > # there is no reason to continue processing the other > # side, so on any excption, could close both and exit Not really. If the remote side shuts down writing, the socket will select as readable, and read will return the empty string. That's the documented method to detect when the remote side is done writing. When it happens, you should send the shutdown across, much like you copy data across: shutdown writing on the other socket. To terminate clean, copy all data and both shutdowns (though the latter shutdown should happen automatically if you just let the socket be destructed). > data = s.recv(4096) > if s is Client: > print "From VBS: ", > MyDBMS.send(data) Use sendall() in place of send(); same for the other call to socket.send(). It's an evil trap: under most circumstances, send() will send all the data, but it's not guaranteed to do so. With a size of 4096, you're probably O.K., but technically it's a bug. (The slicker-than-needed thing to do would be to test whether the outgoing socket is writable within the select, then send() as much as you can, and keep selecting and sending until all the data is out.) -- --Bryan From nochiel at gmail.com Thu Sep 29 02:22:59 2005 From: nochiel at gmail.com (yoda) Date: 28 Sep 2005 23:22:59 -0700 Subject: 1 Million users.. I can't Scale!! In-Reply-To: References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> Message-ID: <1127974979.901104.186960@o13g2000cwo.googlegroups.com> >1. How are you transmitting your SMSs? Currently, a number of different gateways are being used: 2 provide a SOAP web service interface, 1 other provides a REST based web service. A transaction using the SOAP web services takes 3-5 seconds to complete (from the point of calling the method to receive an error\success confirmation) The REST web service transaction takes 1 second or less to complete. > 2. If you disable the actual transmission, how many SMSs can your >application generate per second? Currently, the content is generated and a number of SMS per user are generated. I'll have to measure this more accurately but a cursory glance indicated that we're generting approximately 1000 sms per second. (I'm sure this can't be right.. the parser\generator should be faster than that:) Additionally, I've just confirmed that the gateway's we use can pump out 20-100 sms's per second. This is currently too slow and we'll probably get direct access to the mobile operator's SMSC which provides larger throughput From fairwinds at eastlink.ca Fri Sep 23 10:51:17 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 23 Sep 2005 11:51:17 -0300 Subject: Sniffing Text Files In-Reply-To: Message-ID: <7F0A1E3E-2C41-11DA-98AE-000A27B3B070@eastlink.ca> Hi Steven. Thank you for your detailed response. The code will be executed on a web server with limited memory so the desire to keep file loading in check. I like the approach you have suggested to score to give the best guess. It leaves it fairly modular in respect to how detailed you want to be about adding statements specific to a particular format (that would increase the certainty of choosing it correctly). I wish I had more control over the files I may receive but I have to assume the worse. File extensions are not always telling the true situation and sometimes they can be left off. Mime types are not always interpreted properly either and I am restricting these before getting to a sniffing stage to eliminate certain types of files from getting that far. I think what I might do is read the first x lines with readlines(). I think a sample of up to the first 100 lines should probably be good enough to generate a decent scores for the type. Regards, David > def sniff(filename): > """Return one of "xml", "csv", "txt" or "tkn", or "???" > if it can't decide the file type. > """ > fp = open(filename, "r") > scores = {"xml": 0, "csv": 0, "txt": 0, "tkn": 0} > for line in fp.readlines(): > if not line: > continue > if line[0] == "<": > scores["xml"] += 1 > if '\t' in line: > scores["txt"] += 1 > if ',' in line: > scores["csv"] += 1 > if SOMETOKEN in line: > scores["csv"] += 1 > # Pick the best guess: > L = [(score, name) for (name, score) in scores.items()] > L.sort() > L.reverse() > # L is now sorted from highest down to lowest by score. > best_guess = L[0] > second_best_guess = L[0] > if best_guess[0] > 10*second_best_guess[0]: > fp.close() > return best_guess[1] > fp.close() > return "???" From steve at REMOVETHIScyber.com.au Tue Sep 20 19:03:00 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 21 Sep 2005 09:03:00 +1000 Subject: Question About Logic In Python References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> Message-ID: On Tue, 20 Sep 2005 03:03:15 +0000, Ron Adam wrote: > Steven D'Aprano wrote: >> Are there actually any usage cases for *needing* a Boolean value? Any >> object can be used for truth testing, eg: [snip] > Of course if any of the default False or True conditions are > inconsistent with the logic you use, you need to do explicit truth testing. [snip] > So.. > > bool(a and b) * value > > Would return value or zero, which is usually what I want when I do this > type of expression. That's all very interesting, and valuable advice for somebody who doesn't understand how Python's logical operators work, but the question is, when would you actually want that type of expression? In practice, how often do you really care that your truth values have the specific values 0 and 1 rather than anything false and anything true? In what circumstances? -- Steven. From brucedickey at micron.com Mon Sep 26 15:34:26 2005 From: brucedickey at micron.com (brucedickey at micron.com) Date: Mon, 26 Sep 2005 13:34:26 -0600 Subject: Debugging callbacks? Message-ID: <029E352135E99D49B4B14E42F95D8C5001FFA1C0@ntxboimbx12.micron.com> Hi All, I have a Python app that receives CORBA callbacks in Linux. I post a msg to the GUI and am having refresh issues with some GTK controls in wxPython. The Python-specific question is -- I have tried to set a breakpoint inside the event handler in the GUI, but the debugger does not break. (Works fine anywhere else). Is this activity not supported? Or is there a way to debug the event handler in the debugger (w/o resorting to prints)? How? More specifics: This is a two-way CORBA callback. In the Python module handling the callback I post a message (ProcessEvent) to the GUI and immediately returns. It is in the event handler in the GUI that I want to break with the debugger. (Using Wing 2.0). Thanks, Bruce -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Sep 9 19:10:44 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 10 Sep 2005 01:10:44 +0200 Subject: error processing variables References: Message-ID: In , el chupacabra wrote: >>Your problem is that the def statement reassignes the name "toHPU" to a >>function instead of a string. So when the code runs, you're passing a >>function object to s.copy2. > > So...how do fix it? Don't give two different objects the same name!? >>> import shutil >>> >>> #variables >>> s = shutil This can be written as ``import shutil as s`` or maybe you could use ``from shutil import copy2`` to import the `copy2` function into the moduls namespace. Ciao, Marc 'BlackJack' Rintsch From hancock at anansispaceworks.com Fri Sep 23 09:13:44 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 23 Sep 2005 08:13:44 -0500 Subject: Question About Logic In Python In-Reply-To: References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> Message-ID: <200509230813.44357.hancock@anansispaceworks.com> On Thursday 22 September 2005 07:09 pm, Ron Adam wrote: > Terry Hancock wrote: > > On Thursday 22 September 2005 12:26 pm, Ron Adam wrote: > >>>>True and True > > > > True > > > > Also makes sense (and this is indeed what happens). > > Only because True is the last value here. ;-) Nope, works for False, too: >>> True and False False I see what you mean, but if you were mixing types, then you probably wanted the "value preserved" behavior. If both objects are bool, the result is too (even if this is only a coincidence, it still happens to be true). So this still makes sense: >>> True and 1 1 Effectively, what you'd be asking for is to have bool coerce more strongly than ints or other types, so that results would become boolean if any boolean argument existed. But that would be a pretty major change in Python, and break lots of code. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From apardon at forel.vub.ac.be Mon Sep 12 03:55:05 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Sep 2005 07:55:05 GMT Subject: PEP-able? Expressional conditions References: <1126088966.277030.267410@g14g2000cwa.googlegroups.com> <7x3bofc3fo.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-09-09, Terry Hancock schreef : > On Thursday 08 September 2005 04:30 am, Paul Rubin wrote: >> Terry Hancock writes: >> > > Not the same at all. It evaluates both the true and false results, >> > > which may have side effects. >> > >> > If you are depending on that kind of nit-picking behavior, >> > you have a serious design flaw, a bug waiting to bite you, >> > and code which shouldn't have been embedded in an expression >> > in the first place. >> >> Are you kidding? Example (imagine a C-like ?: operator in Python): >> >> x = (i < len(a)) ? a[i] : None # make sure i is in range >> >> Where's the design flaw? > > It's a syntax error. See? > >>>> x = (i < len(a)) ? a[i] : None # make sure i is in range > File "", line 1 > x = (i < len(a)) ? a[i] : None # make sure i is in range > ^ > SyntaxError: invalid syntax > > That's a pretty serious design flaw. > > You see, I'm not discussing an imaginary Python interpreter here. Nobody is, but the general consensus about a ternary operator has always been that it should have lazy evaluataion. That is even mentioned in the PEP. http://www.python.org/peps/pep-0308.html The BDFL's position is that short-circuit behavior is essential for an if-then-else construct to be added to the language. And you did claim that depending on side effects was a serious design flaw. And as far as I understand what you wrote that was independant of the language used. >> Where's the bug waiting to bite? That's a >> completely normal use of a conditional expression. If the conditional >> expression works correctly, this does the right thing, as intended. >> If both results get evaluated, it throws a subscript out of range >> error, not good. > > No. It throws a syntax error, as I demonstrated. Which is a dishonest remark. The way you made the remark, made it a claim about algorithmic design, independant of the language chosen or the specific construct chosen to interpret it. That Paul chose a construct that is not syntactic python to dispute your claim, is beside the point. >> Every time this topic comes up, the suggestions that get put forth are >> far more confusing than just adding conditional expressions and being >> done with it. > > If it's so easy, then do it, and quit whining. You could easily > have published an alternative "better" ternary function instead > of just complaining that mine "isn't right", by which you mean > only that it doesn't work exactly as it would in C, or in your > imaginary Python interpreter. There have been alternatives enough that have been published. It is not a matter of publishing yet an other alternative. It is just that the BDFL has declare this a no no. > Myself, I just can't see how writing: > > if (i < len(a)): x = a[i] > else: x = None > > is gonna kill you. It's also not by any means a solution so obvious > that I would not want to see the special case on it's own line. And how do I do this in a list comprehension? Myself I couldn't see how writing: def fun(...): ... fun = deco(fun) Would kill anyone, but decorator syntax appeared anyway. > After all, in most cases where I would use a limiter like this, I'd > want the special case to be handled by something other than None. Or > I'd want to raise an exception, even. Which, come to think of it, > I wouldn't even have to code, would I? The thing is, if you return > None like this, you won't be able to treat it the same as the normal > output, so you're still going to have to check the result. Which just > means you've moved the complexity upwards (almost always a bad move > which replicates effort -- another design flaw). Examples given here, are done so to make a point. The example itself may never been used in actual code, but code that is similar enough in behaviour, may. Try to look at the argument one is trying to make instead of looking at insignificant details. > If you want to go and argue with Guido over this, go ahead. I'm all > for a ternary operator. > > But IIRC, that parrot is dead. It's an ex-parrot. Yes probably, but the fact that it is a dead parrot, doesn't make the idea bad. I sometimes get the impression that just because Guido declared a subject dead, some people feel obligated to argue how bad it would have been anyway. -- Antoon Pardon From paul at subsignal.org Sun Sep 25 08:13:28 2005 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Sun, 25 Sep 2005 14:13:28 +0200 Subject: unittest setup Message-ID: hi all, I noticed that setUp() and tearDown() is run before and after *earch* test* method in my TestCase subclasses. I'd like to run them *once* for each TestCase subclass. How do I do that. thanks paul From fredrik at pythonware.com Fri Sep 30 09:53:43 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 15:53:43 +0200 Subject: Overloading __init__ & Function overloading References: Message-ID: "Iyer, Prasad C" wrote: > a. Is there something like function overloading in python? not in the usual sense, no. function arguments are not typed, so there's nothing to dispatch on. there are several cute tricks you can use to add dispatching on top of "raw" python, but that's nothing you should do unless you have very good reasons. > b. Can I overload __init__ method not in the usual sense, no. same reason as above. also see: http://www.python.org/doc/faq/programming.html#how-can-i-overload-constructors-or-methods-in-python From grante at visi.com Thu Sep 29 16:11:35 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Sep 2005 20:11:35 -0000 Subject: xml.sax removing newlines from attribute value? References: <11joa6r22k79340@corp.supernews.com> <11jof4kpir8je24@corp.supernews.com> Message-ID: <11joijn3blhks6d@corp.supernews.com> On 2005-09-29, Fredrik Lundh wrote: >>> http://www.w3.org/TR/REC-xml/#AVNormalize >> >> I can't quite find it in the BNF, but I take it that chr(10) >> isn't really allowed in XML attribute strings. IOW, the file >> generate by Trolltech's app is broken. > > it's allowed, but the parser must not pass it on to the application. > > (in other words, whitespace in attributes doesn't, in general, survive > roundtripping) Ah, I see. That's good to know. [This is my first attempt at anything XMLish.] -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com From haircut at gmail.com Mon Sep 19 11:58:33 2005 From: haircut at gmail.com (Adam Monsen) Date: 19 Sep 2005 08:58:33 -0700 Subject: time.strptime() for different languages In-Reply-To: <1126652550.802196.270120@g47g2000cwa.googlegroups.com> References: <1125519061.261802.285840@o13g2000cwo.googlegroups.com> <1125522144.209140.266590@f14g2000cwb.googlegroups.com> <1125536884.953514.226790@o13g2000cwo.googlegroups.com> <1125545984.087611.16570@g49g2000cwa.googlegroups.com> <1126652550.802196.270120@g47g2000cwa.googlegroups.com> Message-ID: <1127145513.645835.290940@g47g2000cwa.googlegroups.com> Brett Cannon fixed this bug last week. Thanks, Brett! -- Adam Monsen http://adammonsen.com/ From rkern at ucsd.edu Mon Sep 19 17:20:37 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 19 Sep 2005 14:20:37 -0700 Subject: Windows paths, Java, and command-line arguments, oh my! In-Reply-To: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> References: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> Message-ID: Steve M wrote: > I'm trying to invoke a Java command-line program from my Python program > on Windows XP. I cannot get the paths in one of the arguments to work > right. > > The instructions for the program describe the following for the > command-line arguments: > > java -jar sforcedataloader.jar -Dsalesforce.config.dir=CONFIG_DIRECTORY > > They also give an example: > > java -Dsalesforce.config.dir=c:\config -jar sforcedataloader.jar > > If I type the example above at the cmd.exe command line the thing works > (assuming I have the config file in c:\config). What doesn't work is > these two lines: > > cmd = r'java -jar sforcedataloader.jar -Dc:\config' That's not the same thing as the examples you give above. Namely, you're missing the "salesforce.config.dir=" which is probably pretty fundamental to telling the program where the salesforce config dir is. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gsakkis at rutgers.edu Fri Sep 23 08:34:13 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 23 Sep 2005 08:34:13 -0400 Subject: Using distutils 2.4 for python 2.3 References: Message-ID: <1127478856.607901050bd8fd20ba8a9505385ea026@teranews> "Noam Raphael" wrote: > Hello, > > I want to distribute a package. It's compatible with Python 2.3. > Is there a way to use distutils 2.4 feature package_data, while > maintaining the distribution compatible with python 2.3 ? > > Thanks, > Noam Raphael You could distribute the whole 2.4 distutils package in yours so that setup.py finds it before the default one. If distutils 2.4 is compatible with 2.3, that should work. George From pydecker at gmail.com Thu Sep 15 10:37:06 2005 From: pydecker at gmail.com (Peter Decker) Date: Thu, 15 Sep 2005 10:37:06 -0400 Subject: MySQL & Python In-Reply-To: References: Message-ID: On 9/15/05, Ed Hotchkiss wrote: > I am trying to create a simple script to access a MySQL DB. > The Module for MySQL looks very easy, however I do not understand one thing > ... > > In ASP, you can just create a new DB with Access. In MySQL, how do I create > a database to start playing with? I see all of the commands to edits tables > and values and move a cursor, but I do not see how I actually create THE > INITIAL DB, any help would be appreciated. thanks. If you connect as a user who has database creation privileges on the server, running: cursor.execute("CREATE DATABASE FooBar") will create a new database named 'FooBar' on the server. You will then need to call: cnnct.select_db("FooBar") to change your connection to the new database. -- # p.d. From bill.mill at gmail.com Wed Sep 21 13:02:22 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 21 Sep 2005 13:02:22 -0400 Subject: C#3.0 and lambdas In-Reply-To: <43316ffd$1@nntp0.pdx.net> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> <43315dd9$0$3051$626a14ce@news.free.fr> <43316ffd$1@nntp0.pdx.net> Message-ID: <797fe3d405092110023f71442a@mail.gmail.com> On 9/21/05, Scott David Daniels wrote: > Roel Schroeven wrote: > > ... > > Christophe schreef: > >> ... > >>And what about a function which computes the line length ? > > > > That would have been a better example indeed, since the *p1 trick > > doesn't work there. > > > > def euclidian_distance((x1, y1), (x2, y2)): > > return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) > > > > That's a lot nicer, I think, than this: > > > > def euclidian_distance(p1, p2): > > return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) > > But not massively nicer than: > > def euclidian_distance(p1, p2): > (x1, y1), (x2, y2) = p1, p2 > return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) > But the question is - why go to the effort to remove the (by your admission) slightly nicer version? Peace Bill Mill bill.mill at gmail.com From Nainto at gmail.com Wed Sep 7 07:14:22 2005 From: Nainto at gmail.com (Nainto) Date: 7 Sep 2005 04:14:22 -0700 Subject: determine if os.system() is done In-Reply-To: References: <1126087115.516061.50290@o13g2000cwo.googlegroups.com> Message-ID: <1126091662.799627.136770@o13g2000cwo.googlegroups.com> Yeah, I agree. The Python documentation just merey describes what arguements a function can take not as much how to use the actual function. From presentt at gmail.com Tue Sep 6 23:52:28 2005 From: presentt at gmail.com (presentt) Date: 6 Sep 2005 20:52:28 -0700 Subject: Python executable In-Reply-To: <1574481.7mYkaXAehe@knode.kde> References: <1125978845.080791.14520@g43g2000cwa.googlegroups.com> <1574481.7mYkaXAehe@knode.kde> Message-ID: <1126065148.553360.77150@z14g2000cwz.googlegroups.com> Thanks everyone! I think I'm going to stick with Python; at least I know there are some people here willing to help. From peter at engcorp.com Thu Sep 29 08:43:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Sep 2005 08:43:45 -0400 Subject: converting Word to MediaWiki In-Reply-To: References: Message-ID: Jeff Schwab wrote: > ChiTownBob wrote: > >> Perl just sucks, as all good Python hackers know! > > > I disagree. Perl has saved my butt more times than I care to count. > Python certainly has its advantages, but I won't be giving up Perl any > time soon. Are the two necessarily in conflict? Perl can save your butt and _still_ suck! ;-) ;-) -Peter From edhotchkiss at gmail.com Tue Sep 20 17:29:24 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 20 Sep 2005 17:29:24 -0400 Subject: Best Encryption for Python Client/Server In-Reply-To: <7x1x3j77sx.fsf@ruckus.brouhaha.com> References: <200509191446.15240.jstroud@mbi.ucla.edu> <7x1x3j77sx.fsf@ruckus.brouhaha.com> Message-ID: hah :P awesome, I will be busy this week! -edward On 20 Sep 2005 14:23:10 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > > Steve Holden writes: > > > Here's my mission: simple P2P class with encryption of whatever type > > > of file is being sent, and authentication via encrypted user > > > name/password. So any type of file or login being sent over the net, > > > any communication between the scripts should be encrypted, > > > regardless of whether it is client/server communication, or file > > > transfer. > > Robert's suggestion was a good one, as ssh (rather than SSH) is very > > good at building encrypted tunnels between arbitrary processes. > > If you want to use SSL in a similar fashion, try stunnel > (http://www.stunnel.org). Frankly I've never understood why ssh even > exists, but it's very widespread by now, and works pretty well within > its limitations. > -- > http://mail.python.org/mailman/listinfo/python-list > -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Thu Sep 1 05:48:39 2005 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 1 Sep 2005 12:48:39 +0300 Subject: Extended Language c++ in pyhton In-Reply-To: <4316B733.7080203@delair.de> References: <4316B733.7080203@delair.de> Message-ID: <7465b61705090102483b0c67d3@mail.gmail.com> Decide your self: http://seal.web.cern.ch/seal/snapshot/work-packages/scripting/evaluation-report.html My recomendation is boost.python. If you choose boost.python then there are a few code generator tools for it. One of them is pyplusplus ( see http://pygccxml.sourceforge.net/pyplusplus/pyplusplus.html ) Roman On 9/1/05, elho wrote: > I found serveral tool for using C++ as extended languate in python - but > what's the best / easiest to use? > > With C I used wrappy - not sure if it's the wright name, it's included > since Python 1.6 and it ist pretty ease to use. You know an example with > this util for C++ or isn't it possible for C++. > > Would be nice to get your opinion. thx > -- > http://mail.python.org/mailman/listinfo/python-list > From mtammerman at gmail.com Wed Sep 14 13:51:11 2005 From: mtammerman at gmail.com (Mike Tammerman) Date: 14 Sep 2005 10:51:11 -0700 Subject: stdin and py2exe In-Reply-To: References: <1126718877.513683.112600@z14g2000cwz.googlegroups.com> Message-ID: <1126720271.702610.193370@g43g2000cwa.googlegroups.com> Yes, it throws exceptions if I build the exe of the subprogram.py. So, is it possible to pipe some data to another py2exe'd application without a console. Mike From lasse at vkarlsen.no Wed Sep 28 06:54:38 2005 From: lasse at vkarlsen.no (=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?=) Date: Wed, 28 Sep 2005 12:54:38 +0200 Subject: Module organization Message-ID: I am slowly learning Python and I'm already starting to write some minor modules for myself. Undoubtedly there are better modules available either built-in or 3rd party that do the same as mine and much more but I need to learn it one way or another anyway. What I'm wondering about is module organization. I created my own directory for storing my modules and added the full path to this to PYTHONPATH (Windows XP platform). This means that "import modulename" works for my modules now. However, the name of my module is "db" or "database", a module name that will likely conflict with other modules I might encounter later. As such, I was thinking of doing the same that the "distutils" set of modules have done, by creating a subdirectory and storing them there, so I created a "lvk" directory in that directory of mine and moved the module in there, but now "import lvk.modulename" doesn't find the module. Is there a trick to this? Do I have to store my own modules beneath C:\Python24\Lib? or can I use the organization I've tried just with some minor fixes to make python locate my modules? -- Lasse V?gs?ther Karlsen http://usinglvkblog.blogspot.com/ mailto:lasse at vkarlsen.no PGP KeyID: 0x2A42A1C2 From godoy at ieee.org Thu Sep 15 14:14:38 2005 From: godoy at ieee.org (Jorge Godoy) Date: 15 Sep 2005 15:14:38 -0300 Subject: Django Vs Rails References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <3o54knF46solU1@uni-berlin.de> <1126171655.554721.304130@g43g2000cwa.googlegroups.com> <1126802157.139711.226740@f14g2000cwb.googlegroups.com> Message-ID: <871x3q19m9.fsf@ieee.org> Jacob Smullyan writes: > I have mixed feelings about automagical schema introspection. PyDO > supports it, and will probably do so increasingly robustly if people > use it. But part of me feels that "explicit is better than implicit" > may win out over DRY here, because the ORM layer and the db layer > exist in different realms, and if the ORM layer adapts silently to > changes in the db layer, other code is likely to fail in unpredictable > ways, including silently, whereas an explicit declaration of what > fields are in a table, for instance, will fail with a hard error. But > maybe this is anal retentiveness, akin to a need for strong typing. I just wonder when it becomes bad having to declare everything. For example, we have databases with 600 tables. Declaring them all again will make a huge PITA and would not be very helpful, specially because there's already some declarations at the ER diagrams, at the SQL script, inside the database, and then again at each and every python class? Having the introspection is great in this case (even though it is boring having to declare all those classes and tell them to fetch their structure from the database it is better than having to "recreate" all of them). With regards to failures, this is one of the reasons for unit tests :-) They can help finding out where is the problem and they should never fail silently. -- Jorge Godoy From paul.pigott at acs-inc.com Wed Sep 14 13:35:18 2005 From: paul.pigott at acs-inc.com (paulp) Date: 14 Sep 2005 10:35:18 -0700 Subject: HELP!! Accessing other machines with an IIS CGI script Message-ID: <1126719318.537588.107060@g47g2000cwa.googlegroups.com> Greetings, I'm working on a CGI program that will run under MS IIS 5.0 and will browse folders on three other machines, building HTML pages that will provide links to these folders. Essentially, the CGI will connect to each machine in turn, doing the FindFirst/FindNext process based on the current criteria. It will select certain files/folders, and build an HTML page as it goes. The premise is fine. If I run the program from the command line, it seems to work fine and I get my HTML code out. I can copy the code into a separate file, open it in the browser, and all appears right with the world. However, when I try to run the CGI from the browser itself, I get all kinds of problems. The first one I got was a 1312, "A specified logon session does not exist. It may have already been terminated." After doing some searching, I began to investigate impersonation of a logged on user. This produces a different error: 1314, "A required privilege is not held by the client." I've been arguing with this now for several days and the frustration level is beginning to get quite high. Has anyone else ever tried this? I find it hard to believe that I'm the first to do this. Of course, one of my problems is that I'm neither an IIS guru nor an Admin guru. And we have neither here in the office. I'm coding this in Python 2.4 and the Windows extensions. I have a number of other CGI programs in Python running under IIS that work correctly, but those only do database accesses. This one I'm trying to put together is the first one to actually do file searches. I have set the privileges for the logged on account on my IIS box for SE_TCB_NAME, SE_CHANGE_NOTIFY_NAME and SE_ASSIGNPRIMARYTOKEN_NAME and rebooted. To no avail. I'm not sure if there are additional alterations that need to be done to the security policies or not. Again, I'm not a guru. If anyone can give me more information/guidance I would greatly appreciate it. If you need more information from me, I will do my best to provide it. TIA, Paul From duncan.booth at invalid.invalid Thu Sep 8 08:42:36 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Sep 2005 12:42:36 GMT Subject: PEP-able? Expressional conditions References: <1126088966.277030.267410@g14g2000cwa.googlegroups.com> <1126113430.910646.69290@g44g2000cwa.googlegroups.com> Message-ID: Antoon Pardon wrote: > Which is why I don't understand the resistance against introducing > such a beast. The idea has already been discussed to death. Read PEP 308 to see what was proposed, discussed, and why the PEP was eventually rejected: http://www.python.org/peps/pep-0308.html: > Status: Rejected > ... > Requests for an if-then-else ("ternary") expression keep coming up > on comp.lang.python. This PEP contains a concrete proposal of a > fairly Pythonic syntax. This is the community's one chance: if > this PEP is approved with a clear majority, it will be implemented > in Python 2.4. If not, the PEP will be augmented with a summary > of the reasons for rejection and the subject better not come up > again. While the BDFL is co-author of this PEP, he is neither in > favor nor against this proposal; it is up to the community to > decide. If the community can't decide, the BDFL will reject the > PEP. > ... > Following the discussion, a vote was held. While there was an > overall > interest in having some form of if-then-else expressions, no one > format was able to draw majority support. Accordingly, the PEP was > rejected due to the lack of an overwhelming majority for change. > Also, a Python design principle has been to prefer the status quo > whenever there are doubts about which path to take. From tores at stud.cs.uit.no Mon Sep 12 11:23:37 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Mon, 12 Sep 2005 17:23:37 +0200 Subject: Socket options Message-ID: Hi For an online game I'm developing I need some advice concerning tcp-sockets, and especially which socket options to set and not. What I want is a connection where nothing is buffered (but are sent immediatly), and I also want to keep the connections persistent until explicitly closed. The server-side socket will receive multiple incomming requests from clients... regards tores From bokr at oz.net Mon Sep 5 21:45:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 06 Sep 2005 01:45:52 GMT Subject: py2exe 0.6.1 released References: Message-ID: <431cf3eb.715296532@news.oz.net> On Mon, 05 Sep 2005 21:55:19 +0200, Thomas Heller wrote: > >py2exe 0.6.1 released >===================== > >py2exe is a Python distutils extension which converts python scripts >into executable windows programs, able to run without requiring a >python installation. Console and Windows (GUI) applications, windows >NT services, exe and dll COM servers are supported. > >Changes in this release: > > * py2exe can now bundle binary extensions and dlls into the > library-archive or the executable itself. This allows to > finally build real single-file executables. > > The bundled dlls and pyds are loaded at runtime by some special > code that emulates the Windows LoadLibrary function - they are > never unpacked to the file system. So py2exe is windows-only (like exe ;-) or is there a py2elf or py2coff or such? > > This part of the code is distributed under the MPL 1.1, so this > license is now pulled in by py2exe. Mozilla? > > * By default py2exe now includes the codecs module and the > encodings package. > > * Several other fixes. > >Homepage: > > > >Download from the usual location: > > > >Enjoy, > >Thomas > I haven't tried this, but I am getting interested in cannibalizing some functionality ;-) Regards, Bengt Richter From cam.ac.uk at mh391.invalid Fri Sep 2 18:08:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 02 Sep 2005 23:08:44 +0100 Subject: Problems with os.system In-Reply-To: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> References: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> Message-ID: alexLIGO wrote: > I am trying to run a python script that executes several other programs > on the bash (under linux) and reads some of the output of those > programs. This works fine for a couple of os.system() calls, but then > it does not work anymore. os.system() returns always -1, but when > executing exactly the same program directly on the linux-bash it works! Try to break this down to a minimal testcase and then post that. Also, I usually use the subprocess module instead of os.system these days. > How can I check the memory usage in my python > script? Can I force python to execute the program on the bash? If bash is your shell, then os.system will call the program through a bash subshell. -- Michael Hoffman From steven.bethard at gmail.com Wed Sep 14 23:00:16 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 14 Sep 2005 21:00:16 -0600 Subject: python-dev Summary for 2005-08-01 through 2005-08-15 In-Reply-To: References: Message-ID: Steve Tregidgo wrote: > on 2005-08-30 01:45 Tony Meyer said the following: > >> [The HTML version of this Summary is available at >> http://www.python.org/dev/summary/2005-08-01_2005-08-15.html] > ... >> Many revision control systems were extensively discussed, including >> `Subversion`_ (SVN), `Perforce`_, `Mercurial`_, and `Monotone`_. >> Whichever >> system is moved to, it should be able to be hosted somewhere (if >> *.python.org, then it needs to be easily installable), > ... > > Take a look at the HTML version of this summary -- there's some oddness, > possibly caused by the asterisk above. After the paragraph ending > "appropriate", we get this, linked by the asterisk: > > System Message: WARNING/2 (./2005-08-01_2005-08-15.ht, line 65); backlink > Inline emphasis start-string without end-string. Thanks for the pair of eyes. Brett Cannon kindly fixed that for us. STeVe From mfranklin1 at gatwick.westerngeco.slb.com Tue Sep 20 06:41:19 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 20 Sep 2005 11:41:19 +0100 Subject: services on linux In-Reply-To: <20050920090705.GB29522@torf.workaround.org> References: <20050920075726.60843.qmail@web35803.mail.mud.yahoo.com> <20050920090705.GB29522@torf.workaround.org> Message-ID: Christoph Haas wrote: > On Tue, Sep 20, 2005 at 02:57:26AM -0500, pt python wrote: > >>im moving from the windows world to the linux world and i need to make >>a python script to see if a service is instaled (ex: apache), if it is >>running or stoped and to start/stop a service like apache or mysql. >>Theres an API on windows to manage services and i need to know how to >>do that on linux. Can anyone help me with the module and API to work >>with services on linux? > > > Unless you really want to do that in Python. It's just a matter of "ps" > and "grep". Simple shell stuff. > > Example: ps ax | grep apache > On RedHat based distro's (fedora in my case) /sbin/service sshd status gives me (as a normal user) the status of my ssh server not sure if other distro's have this... > >>by the way, im developing a app, maybe multi-plataform, to install and >>manage several open source packages like apache, mySQL, phpwebadmin, >>phpnuke, etc... if anyone have nice ideais i apreciate that.. > > > That's usually the Linux distribution's job to handle the installed > packages. Some distributions do that better than others > (Debian). ;) Or what did you mean when you said "install > and manage"? > yeah you really need to look at the tools you have been given with your distro, rpm, deb, etc for the best way. If it's pure python then the distutils package (in the python standard library) may help, also I noticed that PyInstaller 1.0 has just been released http://pyinstaller.hpcf.upr.edu/pyinstaller and has options to create single file installers for Linux / IRIX and Windows... From http Fri Sep 30 07:43:00 2005 From: http (Paul Rubin) Date: 30 Sep 2005 04:43:00 -0700 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xd5mstqab.fsf@ruckus.brouhaha.com> <7xzmpwuxd0.fsf@ruckus.brouhaha.com> Message-ID: <7xhdc24w8r.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > 2) Allow the client access to these private variables, through > > a special construct. Maybe instead of "from ... import ..." > > "from ... spy ...". > > What you are suggesting is that you have private variables that are only > private by convention, since anyone can simply call use spy to treat > them as public. This notion isn't so bad, if there's way for modules to notice when they're spied on, like an import hook, e.g.: def __spy__(othermodule, symbol_list): # this gets called when another module spies on symbols It's like a runtime version of C++'s "friend" declaration. Well, not quite as good, it's like having some stranger slide over to you in a bar and say "I wanna be your friend". But at least it's better than not finding out at all where the external references are. From tdwdotnet at gmail.com Fri Sep 23 19:17:20 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Sat, 24 Sep 2005 00:17:20 +0100 Subject: Help installing Python 2.3 on Win2K In-Reply-To: <43348836.5090206@webstudios.net> References: <43348836.5090206@webstudios.net> Message-ID: <9afea2ac05092316175c4f9f37@mail.gmail.com> On 23/09/05, D.S. Hein wrote: > I have tried various ways to set PYTHONPATH with the various directories > where I have python programs (i.e. xxxxxx.py) but no matter how I set > PYTHONPATH I keep getting a message that python can't open the python > file. If I try to specify the full pathname by typing: python > c:\Documents and Settings\-rest of path- I get an error message that > python can't open c:\Documents. > add these directories to a text file called python.pth in your python23 directory in the format d:\dir1\dir2 HTH :) -- Tim Williams From fredrik at pythonware.com Fri Sep 9 06:09:33 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 9 Sep 2005 12:09:33 +0200 Subject: sys.stdout References: <1126255685.873523.293080@o13g2000cwo.googlegroups.com><1126257573.719356.151770@z14g2000cwz.googlegroups.com> <1126259024.967722.205860@g44g2000cwa.googlegroups.com> Message-ID: S?bastien Boisg?rault wrote: > Thanks for your answer. The execution of your example leads to a > 'aaa' display during 2 secs, before it is erased by the prompt. > > This behavior is standard ? The standard output is not supposed > to *concatenate* the 'aaa' and the '>>>' ? what "python shell" are you using, and what platform are you running it on? here's what I get on a standard Unix console: >>> import sys >>> sys.stdout.write("AAAA") AAAA>>> sys.stdout.write("BBBB\n") BBBB >>> sys.stdout.write("CCCC\nDDDD") CCCC DDDD>>> From gandalf at designaproduct.biz Tue Sep 20 12:02:37 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Tue, 20 Sep 2005 18:02:37 +0200 Subject: Where is my exception Message-ID: <4330329D.606@designaproduct.biz> I have this code in a wxWidgets program: class HtmlHintWindow(wx.Frame): def __init__(self,pos,hint,config): global _current_hint_window # Determine the size of the screen self.screensize = wx.ClientDisplayRect()[2:] # Calculate the size of the hint ;-) self.renderer = MegaXMLRenderer() self.renderer.LoadStyle(config.style) self.cookie, self.parsed_xml = self.renderer.Parse(hint) print "point 1" try: self.image = self.renderer.Render( self.cookie, self.parsed_xml, (0,0,self.screensize[0],self.screensize[1]), draw=True ) finally: print "point 2" raise The program prints out "point 1" but it does not print "point 2". What am I missing? Les From achim.domma at syynx.de Wed Sep 14 02:58:16 2005 From: achim.domma at syynx.de (Achim Domma (SyynX Solutions GmbH)) Date: Wed, 14 Sep 2005 08:58:16 +0200 Subject: calling .Net Webservice using SOAPpy Message-ID: Hi, I'm using SOAPpy to call a .Net Webservice. Using WSDL.Proxy(service_url) works fine but has to get the WSDL each time from the server. If I try SOAPpy.SOAPProxy(service_url) the call fails with low level SOAP errors. Was somebody able to call a .Net service without using WSDL.Proxy and could provide me with an example? regards, Achim PS.: I could post error message, but I don't think that they are very helpfull. From peter at engcorp.com Tue Sep 20 20:22:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Sep 2005 20:22:17 -0400 Subject: Question about smtplib, and mail servers in general. In-Reply-To: References: <9_6dnY_ct8a0lK3eRVn-qQ@powergate.ca> Message-ID: Steve Holden wrote: > Peter Hansen wrote: >> In any case, unless the mail server will allow "relaying", which most >> don't these days (to prevent spamming), then it won't work the way you >> are hoping unless *all* the 100 addresses are local ones, to be >> delivered to users on the server you are sending the mail to. >> >> If the addresses are scattered all over the planet, and the server >> allows relaying, then it's intended for exactly this sort of use >> (other than if it's spam ;-) ), and no, you won't be putting a "drain" >> on the server. > > To add one final note, if the "fromaddress" belongs to a domain that's > properly handled by the SMTP server then you aren't relaying (since you > are a legitimate domain user) so the mails should go through. I think that statement might not be widely valid any more, Steve. In my experience, lately, many if not most servers pay no attention to the "MAIL FROM" address but instead allow relaying only from *IP addresses* on the "internal" network (e.g. those served by an ISP, for example), regardless of how the sender is identified. On a Linux box with Qmail, for example, one would have an /etc/tcp.smtp file which specifies for which subnets relaying is allowed, and all others are disallowed regardless of the claimed MAIL FROM address. It's kind of a shame, really, that you can no longer trust either the recipient *or* the sender addresses when using basic SMTP. Damn spammers. -Peter From fakeaddress at nowhere.org Tue Sep 13 16:45:20 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 13 Sep 2005 20:45:20 GMT Subject: How to protect Python source from modification In-Reply-To: <4325ab35$0$14825$626a54ce@news.free.fr> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> <4325ab35$0$14825$626a54ce@news.free.fr> Message-ID: bruno modulix wrote: > Frank Millman wrote: >>I am writing a multi-user accounting/business system. Data is stored in >>a database (PostgreSQL on Linux, SQL Server on Windows). I have written >>a Python program to run on the client, which uses wxPython as a gui, >>and connects to the database via TCP/IP. >> >>The client program contains all the authentication and business logic. >>It has dawned on me that anyone can bypass this by modifying the >>program. > > If your program relies on a RDBMS, then it's the RDBMS job to enforce > security rules. Don't know enough about Millman's app to comment on it specifically, but many reasonable server-side applications use a single log-in to the database, then enforce security in the application server. Web shopping-carts, for example, generally work that way. -- --Bryan From fumanchu at amor.org Thu Sep 8 11:58:41 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Sep 2005 08:58:41 -0700 Subject: CGI File Uploads and Progress Bars Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3772932@exchange.hqamor.amorhq.net> Doug Helm wrote: > I'm writing a CGI to handle very large file uploads. > I would like to include a progress bar. > ...I need to know not only the number of > bytes received, but also the total number of > incoming bytes. Here's the heart of the code: > > while afcommon.True: > lstrData = lobjIncomingFile.file.read(afcommon.OneMeg) > if not lstrData: > break > lobjFile.write(lstrData) > llngBytes += long(len(lstrData)) > lobjFile.close() > > Assume that lobjIncomingFile is actually a file-type > element coming from CGI.FieldStorage. It's already > been tested to ensure that it is a file-type element. > Also, assume that I've already opened a file on the > server, referred to by lobjFile (so lobjFile is the > target of the incoming data). I took a cursory look through the cgi module (and am trying to remember what we did for CherryPy*). It seems that, at the time you run the above code, the uploaded file has already been completely read from the client and placed into a temporary file. That is, lobjIncomingFile.file.read does not read from the HTTP request body; it reads from a temporary file instead. > If this were a client application opening a file, > I would just do the following: > > import os > print os.stat('myfile.dat')[6] > > But, of course, this isn't a local file. In fact, > it's not really a file at all. In fact, it is a file, just a temporary one. See cgi.FieldStorage.makefile(). > So, bottom line: Does anyone know how to get the > size of the incoming file data without reading the > whole thing into a string? Can I do something with > content_header? Sure. Subclass cgi.FieldStorage, and override make_file to provide your own file-like object that you can monitor as its "write" method is called (see read_binary for the actual upload r/w code). The existing FieldStorage class places the file size (gleaned from the Content-Length request header) into self.length. Robert Brewer System Architect Amor Ministries fumanchu at amor.org * See CherryPy's From ksenia.marasanova at gmail.com Thu Sep 8 14:49:15 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Thu, 8 Sep 2005 21:49:15 +0300 Subject: Django and SQLObject. Why not working together? In-Reply-To: <43206FBF.8010105@intercable.ru> References: <43206FBF.8010105@intercable.ru> Message-ID: <130df19305090811494da1743a@mail.gmail.com> 2005/9/8, Sokolov Yura : > Django Model is wonderfull. But SQLObject more flexible (and powerfull, > as i think, and has already more db interfaces). > But Django Model is tied with Django, and using Django with another OO > mapping is not comfortable. > Why do not working together? I can't understand. You probably want to post it on django-developers mailing list: http://groups.google.com/group/django-developers BTW, while SQLObject is very advanced, there are/were some other ORM mappers in python: http://www.thinkware.se/cgi-bin/thinki.cgi/ObjectRelationalMappersForPython While not all of them share the same philosophy with SQLObject, some do. But they are not merging together either. Just like web frameworks :) I guess it's just the joy of creating something that fits you mind and solves all you problems, instead of picking up something that does it partially and was created by another person with different views and philosophy. -- Ksenia From Michael.J.Fromberger at Clothing.Dartmouth.EDU Sun Sep 4 18:17:00 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Sun, 04 Sep 2005 18:17:00 -0400 Subject: Replacing large number of substrings References: <431af96c$0$29438$da0feed9@news.zen.co.uk> Message-ID: In article <431af96c$0$29438$da0feed9 at news.zen.co.uk>, Will McGugan wrote: > Hi, > > Is there a simple way of replacing a large number of substrings in a > string? I was hoping that str.replace could take a dictionary and use it > to replace the occurrences of the keys with the dict values, but that > doesnt seem to be the case. > > To clarify, something along these lines.. > > >>> dict_replace( "a b c", dict(a="x", b="y") ) > "x y c" Hi, Will, Perhaps the following solution might appeal to you: . import re . . def replace_many(s, r): . """Replace substrings of s. The parameter r is a dictionary in . which each key is a substring of s to be replaced and the . corresponding value is the string to replace it with. . """ . exp = re.compile('|'.join(re.escape(x) for x in r.keys())) . return exp.sub(lambda m: r.get(m.group()), s) Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From mabden at sbc_global.net Thu Sep 22 09:28:09 2005 From: mabden at sbc_global.net (Mabden) Date: Thu, 22 Sep 2005 13:28:09 GMT Subject: Perl's documentation come of age References: <1123809822.696399.317570@g44g2000cwa.googlegroups.com> <1124736189.749363.32160@g47g2000cwa.googlegroups.com> <1125179974.483320.116780@g49g2000cwa.googlegroups.com> <1127299284.748225.68560@g14g2000cwa.googlegroups.com> Message-ID: "M?ns Rullg?rd" wrote in message news:yw1xr7biqpm1.fsf at ford.inprovide.com... > This guy deserves two ascii trolls: > > ___________________ > /| /| | | > ||__|| | Please do | > / O O\__ NOT | > / \ feed the | > / \ \ trolls | > / _ \ \ ______________| > / |\____\ \ || > / | | | |\____/ || > / \|_|_|/ \ __|| > / / \ |____| || > / | | /| | --| > | | |// |____ --| > * _ | |_|_|_| | \-/ > *-- _--\ _ \ // | > / _ \\ _ // | / > * / \_ /- | - | | > * ___ c_c_c_C/ \C_c_c_c____________ > > > +-------------------+ .:\:\:/:/:. > | PLEASE DO NOT | :.:\:\:/:/:.: > | FEED THE TROLLS | :=.' - - '.=: > | | '=(\ 9 9 /)=' > | Thank you, | ( (_) ) > | Management | /`-vvv-'\ > +-------------------+ / \ > | | @@@ / /|,,,,,|\ \ > | | @@@ /_// /^\ \\_\ > @x@@x@ | | |/ WW( ( ) )WW > \||||/ | | \| __\,,\ /,,/__ > \||/ | | | jgs (______Y______) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > ============================================================== And the Original Troll: s sS. S, $Ss, SSs$$SSs, s SSs$$SSSSs,Ss. SSs$$SSSS$$ss sSSs$$SSS$$sSSS. s sSSSs$$SSSSS$$sSSs$s, sSSSSs$$SSSSSSS$$sSS$$SS, s sSSSSSSs$$SSSSSSS$$sSSSs$$SSs, sSs$$SSSSs$$SSSSSSS$$sSSSSSS$$SSSSs sSSs$$SSSSSS$$SSSSSS$$sSSSSSSs$$SSSSSS, sSSSS$$SSSSSSSS$SSSSSSS$$sSSSSSSS$$SSSSSSs, sSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSs$$SSSSSSSSs SSSSSSS$$SSSSSSSSSSSSSSSSSSSSSSSSSSS$$SSSSSSSSSS, .SSSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSSs$$SSSSSSSSSSS, SSSSSSSSS$$SSSSSSSSSSSSSSSSSSSSSSSSSS$$SSSSSSSSSSSSS, .SSSSSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSs$$SSSSSSSSSSSSSSS $SSSSSSSSSSS$$SSSSSSSSSSSSSSSSSSSSSSS$$SSSSSSSSSSSSSSS .s$$SSSSSSSSSs$$SSSSSSSSSSSSSSSSSSSSS$SSSSSSSSSSSSSSSS' SSs$$SSSSSSSSSS$$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$s SSSSs$$SSSSSSSSS$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$$sS SSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$$sSSS `SSSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$$sSSSSS SSSSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$$sSSSSSSS' `SSSSSSs$$SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS$$sSSSSSSSS SSSSSs$$SSSSSSS%%%%%%%%%%%%%%%%%%%%SSSSSS$$sSSSSSS' `SSSSSSSSSSS%,;mmmmmnv%%;;;%%vnmmmmm;,%SSSSSSSSSS' `SSSSSSS.vnnmmvvvvvmmn%%;%%nmmvvvvvmmnnv.SSSSSS' `S%%%%,vnnmmvv' `vmmn%;%nmmv' `vvmmnnv,%%%S' /vmnnnvnnmmmvv, .vnnnv;vnnnv, .vvmmmnnvnnnmv\ ;vm;%%nvnnnnnnnvvvv%;mmmmmmm;%vvvvnnnnnnnvn%%;mv; `vmm;%nvnnmmmmnnv%;mmmmmmmmmmm;%vnnmmmmnnvn%;mmv' `vmmnvnnmmmmnvv%;m%%mmmmm%%m;%vvnmmmmnnvnmmv' \vvvnnnvvv;vvvvvnnnnnnnvvvvv;vvvnnnvvv/ \vvnnn;vvv;vvvvvvvvvvvvv;vvv;nnnvv/ \vvnnnvv;%;%;%;%;%;vvnnnvv/ .,v% \nnnmmmmmmmmmnnn/%v,. .,vvnnnvv%;%;%;%;%;%;%;%vvnnvv,. .,vvnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnvv,. ,vvnnnnnnnnvvvvnnnnnnnnnnnnnnvvvvnnnnnnnnvv, ,vvnnnnnnnnnvvmmmmnnnnnnnnnnnnnnmmmmvvnnnnnnnnnvv, .vvnnnnnnnnnn `mmmmnnnnnnnnnnnnnnnnnnmmmm' nnnnnnnnnnvv. .vvnnnnnnnnnn' mmnnnnnnnnnnnnnnnnnnnnnnnnmm `nnnnnnnnnnvv. vmmvnmmvnmmv' .nnnnnnnnnnnnnnnnnnnnnnnnnnnn, `vmmnvmmnvmmv `nm%nm%nm%' nnnnnnnnnnnnnnnnnnnnnnnnnnnnnn `%mn%mn%mn' nnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnn(*)nnnnnnnnnnnnn .vmmnnnnnnnnnnnnnnnnnnnnnnnnmmv, .vnvmmmmnnnnnnnnnnnnnnnnnnnnmmmmvnv. .vvnvvvmmmmnnnnnnnnnnnnnnnnmmmmvvvnvv. vvnnnnvvvvmmmmnnnnnnnnnnnmmmvvvvvnnnvv .vvnnnnnnnvvvvvvvv' `vvvvvvvnnnnnnnvv. vvnnnnnnnnnnnnnnvv vvnnnnnnnnnnnnnvv .vvnnnnnnnnnnnnnnnv vnnnnnnnnnnnnnnvv. vnmnvnmnvnmnvnmnvnm. .mnvnmnvnmnvnmnvnmv vmmm%mmm%mmm%mmm%mmm mmm%mmm%mmm%mmm%mmm From abo at google.com Tue Sep 27 04:41:33 2005 From: abo at google.com (ABO) Date: 27 Sep 2005 01:41:33 -0700 Subject: Self reordering list in Python References: <200509161058.48155.hancock@anansispaceworks.com> Message-ID: <1127810493.378770.282050@z14g2000cwz.googlegroups.com> LRU caches are nice and simple, but if you want something fancier, with support for squid-like expiry models (ie, using mtime and atime to estimate a "stale time", and IMS fetches), you can have a look at my GCache; http://minkirri.apana.org.au/~abo/projects/GCache Even if you don't want something that fancy, it uses a PQueue priority queue to achieve exactly what you want. I provide a pure-python implementation using bisect, but recommend a C extension module with the same name by Andrew Snare which uses a fibonacci heap (python-pqueue is the Debian Package). Note that python 2.3 introduced a heapq module that does for queue lists what bisect does for heap lists. I am planning to modify my PQueue to use it instead of bisect. From bdesth.quelquechose at free.quelquepart.fr Mon Sep 19 15:58:00 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Sep 2005 21:58:00 +0200 Subject: functional or object-oriented? In-Reply-To: <1127149721.962815.46690@g43g2000cwa.googlegroups.com> References: <1127149721.962815.46690@g43g2000cwa.googlegroups.com> Message-ID: <432f0f98$0$1648$626a14ce@news.free.fr> beza1e1 a ?crit : > I see myself shifting more and more over to the functional kind of > coding. Could be related to the Haskell, we had to learn in CS. Now i > was wondering, how other people use Python? > > With functional i mean my files mostly consist of functions which is not enough to make it 'functional'. > and only > rarely i use "class". The library modules seem to be mostly written the > object-way on the other hand. > > If you use both paradigms. What are your criterias to choose the right > method for a project? > Well, I'm most from an OO background, but I think OO and FP have in common to try to be as declarative as possible, FP by avoiding side-effects and relying on function composition, OO by hiding implementation and relying on polymorphic message dispatch. When it comes to 'pure' OO languages like Python, there's no real differences between classes, objects, functions, methods, attributes etc - they're *all* objects. So functional programming in Python is still OO ! When you realize that the def statement is nothing more than syntactic sugar to instantiate a function object, you can ask yourself if using or not using the class statement is really the question. Now to answer your question, I don't have 'criterias to choose the right method for a project'. I happily mix procedural, OO and FP wherever it fits. From irmen.NOSPAM at xs4all.nl Wed Sep 28 13:49:30 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 28 Sep 2005 19:49:30 +0200 Subject: 1 Million users.. I can't Scale!! In-Reply-To: <1127928015.717841.177610@g43g2000cwa.googlegroups.com> References: <1127924360.190081.155420@g14g2000cwa.googlegroups.com> <1127928015.717841.177610@g43g2000cwa.googlegroups.com> Message-ID: <433ad7ac$0$11068$e4fe514c@news.xs4all.nl> Chris Curvey wrote: > Multi-threading may help if your python program is spending all it's > time waiting for the network (quite possible). If you're CPU-bound and > not waiting on network, then multi-threading probably isn't the answer. Unless you are on a multi cpu/ multi core machine. (but mind Python's GIL) --Irmen From onurb at xiludom.gro Fri Sep 16 13:32:42 2005 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 16 Sep 2005 19:32:42 +0200 Subject: Why doesn't IDLE editor windows have horizontal scrollbars? In-Reply-To: <1126881900.117737.10990@g43g2000cwa.googlegroups.com> References: <1126881900.117737.10990@g43g2000cwa.googlegroups.com> Message-ID: <432b01bc$0$988$626a14ce@news.free.fr> chuck wrote: > The browser windows do. Why not the editor windows? > > I hate to complain but is there any way to get IDLE to run in more of > an MDI mode? Having the floating windows everywhere is rather > confusing to me. > IDLE is open source, so you may want to consider contributing to it !-) More seriously, I dont think IDLE is intended to be a real professional IDE - anyway, I would not use it as such. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From n00m at narod.ru Sat Sep 10 04:52:24 2005 From: n00m at narod.ru (n00m) Date: 10 Sep 2005 01:52:24 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126129942.736374.260770@g44g2000cwa.googlegroups.com> <1126161203.409605.27880@f14g2000cwb.googlegroups.com> <1126196908.479379.22010@z14g2000cwz.googlegroups.com> <1126201801.250692.27750@f14g2000cwb.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> Message-ID: <1126342344.307873.210780@g44g2000cwa.googlegroups.com> Bryan Olson wrote: > Could be. Yet you did write: > > It's incredibly fast! I just was obliged to exclaim "It's incredibly fast!" because I THOUGHT your first version handled ALL TEN testcases from the input. But the code read from the *20-lines* input *ONLY 2* its first lines. Usually they place heavy data testcase(s) at the end of the (whole) input. Like this: 3 2 3 1 7 4 5 6 1 2 7 3 ... ... ... 100000 456 2 6789 ... ... ... ... ... 55444 1 ... 234 Surely producing an answer for list [2, 3, 1] will be "incredibly fast" for ANY language and for ANY algorithm. > My first version bombed for the zero-length sequence. That was a > mistake, sorry, but it may not be one of their test-cases. In my turn I can bet there's not an empty sequence testcase in the input. > I > wonder how many of the accepted entries would perform properly. Info of such kind they keep in secret (along with what the input data are). One more thing. They (the e-judge's admins) are not gods and they don't warrant that if they put 9 sec timelimit for a problem then this problem can be "solved" in all accepted languages (e.g. in Python). > I never intended to submit this program for competition. "Competition" is not quite relevant word here. It just LOOKS as if it is a "regular" competetion. There nobody blames anybody. Moreover, judging on my own experience, there nobody is even interested in anybody. It's just a fun (but very useful fun). From mauriceling at acm.org Thu Sep 22 04:52:45 2005 From: mauriceling at acm.org (Maurice LING) Date: Thu, 22 Sep 2005 18:52:45 +1000 Subject: Do thread die? In-Reply-To: References: Message-ID: <433270DD.3070903@acm.org> Frithiof Andreas Jensen wrote: > "Maurice LING" wrote in message > news:dgh54e$e8c$1 at domitilla.aioe.org... > > >>I do have another dumb question which is OT here. Say aFunc method >>instantiates a SOAP server that serves forever, will it prevent bFunc >>from running as a separate thread? > > > If the SOAP server thread never sleeps or block, it will effectively stop > everything else in your program by eating all the CPU time available. If it > does some IO and other OS functions, probably not because it is likely to > block on those - I do not know SOAPpy in detail, but it being a socket-based > server it should end up in a select loop somewhere. i.e. block when no work > is available. which is what you want. > > >>For example, >> >>class myClass4: >> def repeat(self, s): return s+s >> def aFunc(self, a): >> import SOAPpy >> serv = SOAPpy.SOAPServer((a[0], a[1])) >> serv.registerFunction(repeat) >> serv.serve_forever() >> def bFunc(self, b): pass >> def runAll(self, a, b): >> threading.Thread(target=self.aFunc, args = (a)).start() >> threading.Thread(target=self.bFunc, args = (b)).start() >> >>if __name__=='__main__': myClass4().runAll(['localhost', 8000], 'hi') >> >>Will the 2nd thread (bFunc) ever run since the 1st thread is running >>forever? Intuitively, I think that both threads will run but I just want >>to be doubly sure, because some of my program logic depends on the 2nd >>thread running while the 1st thread acts as a SOAP server or something. > > > Both should run independently, sharing the CPU-time available for your > application. Remember "main" is a thread too, so you will want "main" to > hang around while your threads are running and you will want "main" to block > on something also, thread.join(), time.sleep(), command line parser e.t.c. > whatever is natural. > > Somehow I cannot reconcile your replies because I am essentially asking the same thing and expanding on the original question with an example of what I am trying to do, but the replies seems contradictory. Do you mind to explain a bit more? thanks Maurice From ptmcg at austin.rr.com Mon Sep 19 10:47:25 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 19 Sep 2005 07:47:25 -0700 Subject: How to program efficient pattern searches in a list of float numbers? References: <1127113354.897477.235360@g44g2000cwa.googlegroups.com> Message-ID: <1127141245.713328.289320@g49g2000cwa.googlegroups.com> Have you tried coding even the brute-force naive search? It is far easier to improve an algorithm when you have someplace relatively concrete to start from. Plus, the naive approach is most likely to return a correct result, so that you can regression test your exotic interval-skipping, second-derivative conjugate interpolation algorithm. :) In sum, I started to think through your problem this morning, and yes, I can visualize the rectangles floating across the 2D curve, and yes, I can picture that there are likely to be shortcuts and optimizations over the brute-force "check every index" approach. But really, you *should* do some of the work yourself... -- Paul From http Mon Sep 5 15:58:00 2005 From: http (Paul Rubin) Date: 05 Sep 2005 12:58:00 -0700 Subject: Possible improvement to slice opperations. References: <0BZSe.13427$xl6.12703@tornado.tampabay.rr.com> Message-ID: <7xfysjb83b.fsf@ruckus.brouhaha.com> Steve Holden writes: > Given that Python has a 1's-complement operator already I don;t see > why you can't just leave Python alone and use it, What's the meaning of the 1's complement operator (for example, what is ~1), when ints and longs are the same? From erchamion.beren at gmail.com Fri Sep 16 03:03:14 2005 From: erchamion.beren at gmail.com (Sinan Nalkaya) Date: Fri, 16 Sep 2005 10:03:14 +0300 Subject: re and escape character In-Reply-To: References: Message-ID: <432A6E32.80000@gmail.com> Thomas Guettler wrote: >Am Thu, 15 Sep 2005 14:36:38 +0300 schrieb Sinan Nalkaya: > > > >>i re-format incoming messages like this, >>command = re.findall("^\002(.{2})\|.*\003$", response)[0] >>it works well but when response comes with escape characters , my >>command variable crashes, >>i cannot parse if response variable is like , >>response = '\002AB|TIasdasdasd >>asdasdasd >>xzczxc >>qwewer >>werwer|\003' >> >>ps:there must be \002 at the start and \003 at the end. >>thanks. >> >> > >Hi, > >I don't know what you mean with "escape characters". >The dot does not match a newline. You have to use the >re.DOTALL option if you want this. > > HTH, > Thomas > > > thats exactly what i want, how can i use DOTALL, by doing re.compile ? thanks From Scott.Daniels at Acm.Org Mon Sep 5 08:36:38 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 05 Sep 2005 05:36:38 -0700 Subject: dual processor In-Reply-To: References: <0NGSe.4128$3R1.94@fe06.lga> Message-ID: <431c2f84$1@nntp0.pdx.net> Nick Craig-Wood wrote: > Splitting the GIL introduces performance and memory penalties.... > However its crystal clear now the future is SMP. Modern chips seem to > have hit the GHz barrier, and now the easy meat for the processor > designers is to multiply silicon and make multiple thread / core > processors all in a single chip. > So, I believe Python has got to address the GIL, and soon. However, there is no reason to assume that those multiple cores must work in the same process. One of the biggest issues in running python in multiple simultaneously active threads is that the Python opcodes themselves are no longer indivisible. Making a higher level language that allows updates work with multiple threads involves lots of coordination between threads simply to know when data structures are correct and when they are in transition. Even processes sharing some memory (in a "raw binary memory" style) are easier to write and test. You'd lose too much processor to coordination effort which was likely unnecessary. The simplest example I can think of is decrementing a reference count. Only one thread can be allowed to DECREF at any given time for fear of leaking memory, even though it will most often turn out the objects being DECREF'ed by distinct threads are themselves distinct. In short, two Python threads running simultaneously cannot trust that any basic Python data structures they access are in a consistent state without some form of coordination. --Scott David Daniels Scott.Daniels at Acm.Org From lycka at carmen.se Fri Sep 2 09:42:25 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 02 Sep 2005 15:42:25 +0200 Subject: Well, Python is hard to learn... In-Reply-To: References: Message-ID: wen wrote: > due to the work reason, i have to learn python since last month. i have > spent 1 week on learning python tutorial and felt good. but i still don't > understand most part of sourcecode of PYMOL(http://pymol.sourceforge.net/) > as before. Maybe you (or someone else) is making a mistake if you are trying to understand PyMol in this stage of learning. I haven't used PyMol, but I really doubt that you need to understand its source code unless your aiming to maintain that code. If you approached it as a learning exercise, you aimed way too high. If you approached it because you need to use PyMol, trying to understand its source code is probably the wrong approach. You don't need to learn all the details of how a car works to drive it. You don't even have to understand how the engine is designed to change wheels or fix rust holes. I'm aware that you use Python to perform advanced operations in PyMol, but you don't need to understand PyMol's internals for that. From knipknap at gmail.com Fri Sep 9 08:29:03 2005 From: knipknap at gmail.com (Samuel) Date: 9 Sep 2005 05:29:03 -0700 Subject: Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse Message-ID: <1126268943.521825.307580@g49g2000cwa.googlegroups.com> Hello, I am trying to convert a local time into UTC ISO8601, then parse it back into local time. I tried the following: ---------------------- #!/usr/bin/python import time import datetime import xml.utils.iso8601 year = 2005 month = 7 day = 22 hour = 10 # This is localtime minute = 30 mydatetime = datetime.datetime(year, month, day, hour, minute) strtime = mydatetime.isoformat() print "Time: " + strtime # Localtime too mytimestamp = xml.utils.iso8601.parse(strtime) ---------------------- How can I convert this into UTC? Commonsense would have me guess that the date is converted into UTC on construction of the datetime object, hovever, this doesn't seem to be the case. I also found the astimezone(tz) method, but where can I obtain the concrete tz object? The second problem has to do with the ISO8601 parser, which raises the following error: ---------------------- Traceback (most recent call last): File "./timetest.py", line 16, in ? mytimestamp = xml.utils.iso8601.parse(strtime) File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py", line 22, in parse raise ValueError, "unknown or illegal ISO-8601 date format: " + `s` ValueError: unknown or illegal ISO-8601 date format: '2005-07-22T10:30:00' ---------------------- Why does it fail to parse the value returned by the datetime object, and how can I create a parseable time from the datetime object? Thanks, -Samuel From jlocc at fau.edu Wed Sep 7 17:31:03 2005 From: jlocc at fau.edu (jlocc at fau.edu) Date: 7 Sep 2005 14:31:03 -0700 Subject: encryption with python In-Reply-To: References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> Message-ID: <1126128663.573686.148670@g44g2000cwa.googlegroups.com> Basically I will like to combine a social security number (9 digits) and a birth date (8 digits, could be padded to be 9) and obtain a new 'student number'. It would be better if the original numbers can't be traced back, they will be kept in a database anyways. Hope this is a bit more specific, thanks!!! From cam.ac.uk at mh391.invalid Fri Sep 30 10:15:27 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 30 Sep 2005 15:15:27 +0100 Subject: Overloading __init__ & Function overloading In-Reply-To: <433D4714.9050808@websafe.com> References: <433D4714.9050808@websafe.com> Message-ID: Larry Bates wrote: > class myclass(baseclass): > def __init__(self, arg): > # > # This method gets called when I instantiate this class. > # If I want to call the baseclass.__init__ method I must > # do it myself. > # > baseclass.__init__(arg) This is an example of polymorphism generally, not overloading. -- Michael Hoffman From paul at boddie.org.uk Fri Sep 23 12:42:49 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Sep 2005 09:42:49 -0700 Subject: desktop module (was Re: Open PDF) References: <36141C39871E4D4DAE92F79D1838543601B176C8@itcnt14.itc.nl> Message-ID: <1127493769.123164.48270@g44g2000cwa.googlegroups.com> Dennis Lee Bieber skrev: > On Thu, 22 Sep 2005 15:16:09 +0100, Dan declaimed > the following in comp.lang.python: > > > > I would like to know how to open a PDF document from a python script > > > > You mean open it and display it to the user? Under Windows you may be > > able to get away with just "executing" the file (as though it were an > > executable): > > For Windows, os.startfile() may be better... I've just uploaded a patch/suggestion/module (#1301512) to SourceForge which seeks to provide the equivalent of os.startfile for KDE and GNOME (as well as Windows) as part of a generic desktop module: http://sourceforge.net/tracker/index.php?func=detail&aid=1301512&group_id=5470&atid=305470 Rather than submit yet another PEP and argue about insignificant details whilst the webbrowser module sits comfortably in the standard library, failing to address general file-opening issues directly and doing the wrong thing under various modern desktop environments, I advocate people submitting suggestions, criticism and amendments to the uploaded attachment until we have something like os.startfile for all major desktop environments. Paul From rjr at nowhere.net Thu Sep 1 14:11:10 2005 From: rjr at nowhere.net (Robert) Date: Thu, 01 Sep 2005 18:11:10 GMT Subject: Python / web Message-ID: <2vHRe.5244$_84.3338@newsread1.news.atl.earthlink.net> Hi, I know general Python pretty well and interested in using Python for a web project. It will have the standard display, user input, fields, look-ups, reports, database routines, etc..... Been looking though the Python web docs. and seeing stuff like mod_python, CGI, PSP, CherryPy, etc..., Also a fair amount of googling. I'll say there's a large amount of technology to pick from. Rather than spend time going down the wrong road, can I get some feedback as directions from you folks that's "been there, done that." thanks a bunch. Robert From dw-google.com at botanicus.net Thu Sep 15 07:57:31 2005 From: dw-google.com at botanicus.net (David Wilson) Date: 15 Sep 2005 04:57:31 -0700 Subject: Python in C integration and WxPython References: Message-ID: <1126785450.997525.285950@g44g2000cwa.googlegroups.com> It sounds like your C program and Python script are running under different interpreters. Your C program almost certainly is using a Python version that comes with Cygwin, while the script is probably using a native win32 Python that has wxPython installed. Assuming this is true, then compiling your C program natively on Windows should solve the problem. Alternatively, if wxPython is available for cygwin (possibly via cygwin's X server) then installing it would also help. David. Alain Paschoud wrote: > Hi all, > > I made a small dialog in WxPython. I can run the python script with a > double-click or through command line, and everything goes fine (dialog > appears, which means that wx module has been found). > Then, I decided to write a C program (under Windows, with Cygwin) that > will read my script (through PyRun_SimpleFile() function) and run it. > But the system doesn't find the wx module to import... > > Traceback (most recent call last): > File "Dialog.py", line 2, in ? > import wx > ImportError: No module named wx > > How can I say to my program where to search for this module ? I tried to > set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything. > > More generally : Does a C program that embedded python run an external > executable (interpreter), or does it only load libraries ? > > Thank you very much for any help on this topic. > > Best regards. From fredrik at pythonware.com Fri Sep 16 07:57:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Sep 2005 13:57:03 +0200 Subject: Rendering HTML References: <1126863962.886966.158460@o13g2000cwo.googlegroups.com> Message-ID: Harlin Seritt wrote: >I am looking for a module that will render html to console but > formatted much like one might see with Lynx. Is there such a module > already out there for this? use htmllib+formatter: http://effbot.org/librarybook/formatter.htm From mwm at mired.org Tue Sep 6 21:32:36 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 06 Sep 2005 21:32:36 -0400 Subject: dual processor References: <0NGSe.4128$3R1.94@fe06.lga> <431cadd6$0$97134$ed2619ec@ptn-nntp-reader03.plus.net> <431d4bd3$0$1314$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <86fyshoe6j.fsf@bhuda.mired.org> Jeremy Jones writes: > 1) find a good clean way to utilize muti-CPU machines and I like SCOOP. But I'm still looking for alternatives. > 2) come up with a simple, consistent, Pythonic concurrency paradigm. That's the hard part. SCOOP attaches attributes to *variables*. It also changes the semantics of function calls based on the values of those attributes. Part of the power of using SCOOP comes from the processor detecting when a variable has been declared as having an attribute is used to reference objects for which the attribute doesn't apply. I'm not sure how Pythonic that can be made. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bretthoerner at gmail.com Thu Sep 29 10:21:05 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 29 Sep 2005 07:21:05 -0700 Subject: Set up Windows environment with python In-Reply-To: <1128002458.793327.101090@g44g2000cwa.googlegroups.com> References: <1128002458.793327.101090@g44g2000cwa.googlegroups.com> Message-ID: <1128003665.387035.229380@o13g2000cwo.googlegroups.com> I don't have experience with scipting this... but I know that resolution for example is stored in registry, and _that_ is what is loaded when you boot. I think most, if not all, of your changes will be found in the registry (for permenance). Also, have you checked out PyWin32? It's just a big pre-made wrapper for the Win32 stuff, not sure if it will be more/less work than ctypes but it could make it easier on you. PyWin32 http://sourceforge.net/project/showfiles.php?group_id=78018 From catalin.marinas at gmail.com Mon Sep 26 05:52:48 2005 From: catalin.marinas at gmail.com (Catalin Marinas) Date: Mon, 26 Sep 2005 10:52:48 +0100 Subject: [RFC] Parametric Polymorphism References: Message-ID: Tom Anderson wrote: > Is there any reason you have to stringify the type signature? Types > are hashable, so a tuple of types is hashable, so you can just use > that as a key. Replace "methods[f.func_name][str(types)] = f" with > "methods[f.func_name][types] = f" and "type_str = str(tuple([type(arg) > for arg in args]))" with "type_str = tuple(type(arg) for arg in > args)". And then rename type_str to types thoughout. You're right. I initially had a list in there and it wasn't hashable (and I thought tuples aren't either). Anyway, the implementation is just an example, it should use isinstance() instead. The link posted by Kay shows a better implementation. -- Catalin From ccurvey at gmail.com Thu Sep 8 11:51:51 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 8 Sep 2005 08:51:51 -0700 Subject: job scheduling framework? Message-ID: <1126194711.728965.86630@g43g2000cwa.googlegroups.com> Has anyone seen a simple open source job-scheduling framework written in Python? I don't really want to reinvent the wheel. All I need is the ability to set up a series of atomic "jobs" as a "stream", then have the system execute the jobs in the stream one-at-a-time until all the jobs in the stream are complete or one of them reports an error. (If it tied into a really simple grid-style computing farm, that would be worth double points!) -Chris From daniel at dittmar.net Mon Sep 19 18:18:28 2005 From: daniel at dittmar.net (Daniel Dittmar) Date: Tue, 20 Sep 2005 00:18:28 +0200 Subject: Windows paths, Java, and command-line arguments, oh my! In-Reply-To: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> References: <1127163978.989268.37990@g14g2000cwa.googlegroups.com> Message-ID: <3p8rpkF9a8o3U1@uni-berlin.de> Steve M wrote: > I'm trying to invoke a Java command-line program from my Python program > on Windows XP. I cannot get the paths in one of the arguments to work > right. > > The instructions for the program describe the following for the > command-line arguments: > > java -jar sforcedataloader.jar -Dsalesforce.config.dir=CONFIG_DIRECTORY > > They also give an example: > > java -Dsalesforce.config.dir=c:\config -jar sforcedataloader.jar > > If I type the example above at the cmd.exe command line the thing works > (assuming I have the config file in c:\config). What doesn't work is > these two lines: > > cmd = r'java -jar sforcedataloader.jar -Dc:\config' > os.system(cmd) If you write java -jar x.jar -Dwhatever=x then -Dwhatever=x is passed as an argument to the main method of the main class in x.jar. If you write java -Dwhatever=x -jar x.jar then -Dwhatever=x is interpreted by java and put into the system properties. Daniel From sciurus1 at iwon.com Wed Sep 14 13:38:09 2005 From: sciurus1 at iwon.com (Todd Steury) Date: Wed, 14 Sep 2005 12:38:09 -0500 Subject: working with VERY large 'float' and 'complex' types Message-ID: Greetings Python'ers: I'm just an amature who occasionally uses Python for complex mathematical models. The current model I'm working with occasionally generates really large numbers that are either "float" or "complex" types. These numbers are so large that I either get an overflow error, or some funky code like #INF or 1.#INDj. However I really need these numbers to be calculated (although precision isn't key). Is there a way to get python to increase the size limit of float and complex numbers? I should mention that I'm using a lot of pre-made modules and functions like math.exp() and scipy.special.erf() that don't seem to be able to use available types like "Decimal" or "FixedPoint" (especially since these don't seem to handle complex numbers). Since I learn best by example, how could one solve the following problem: from math import exp >>>x=1000. >>>z=exp(x) so that z returns an actual value Thanks in advance for any advice! Todd From kreedz at gmail.com Mon Sep 12 14:56:07 2005 From: kreedz at gmail.com (Kreedz) Date: 12 Sep 2005 11:56:07 -0700 Subject: wxPython MainLoop exception handling problem In-Reply-To: <1126549912.010473.9670@o13g2000cwo.googlegroups.com> References: <1126547432.879309.55170@g49g2000cwa.googlegroups.com> <1126549912.010473.9670@o13g2000cwo.googlegroups.com> Message-ID: <1126551367.553824.223900@g44g2000cwa.googlegroups.com> Well, it worked :) Thanks a lot! - Kreedz From news at NOwillmcguganSPAM.com Thu Sep 15 12:11:28 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 15 Sep 2005 17:11:28 +0100 Subject: Britney Spears nude In-Reply-To: References: <20050915114937.89958.qmail@web35611.mail.mud.yahoo.com> Message-ID: <43299d31$0$525$da0feed9@news.zen.co.uk> Tim Peters wrote: > [john basha] > >>send me the britney nude photos > > > Because they're a new feature, you'll have to wait for Python 2.5 to > be released. She has just spawned a child process. Give her to Python 2.6 to get back in shape. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From cjw at sympatico.ca Fri Sep 9 11:54:23 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 09 Sep 2005 11:54:23 -0400 Subject: bug in numarray? In-Reply-To: References: Message-ID: Xiangyi wrote: > Hi, there, > > I got the following segmentation fault. > >> from numarray import * >> a = zeros((5,100), Float64) >> b = kroneckerproduct(a, identity(12)) >> segmentation fault > > > If I use a = zeros((5,100)), everything is fine. Kind of weird! > Can someone help me figure it out? BTW, the python version is 2.4.1 and > numarray 1.3.2 > > Many thanks! > Xiangyi > >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Looks OK to me, Winodows XP, Python 2.4.1, numarray 1.3.3 Colin W. From ramdaz at gmail.com Tue Sep 13 14:58:35 2005 From: ramdaz at gmail.com (Ramdas) Date: 13 Sep 2005 11:58:35 -0700 Subject: What XML lib to use? In-Reply-To: <0001HW.BF4CD7C600321189F0407550@news.individual.de> References: <0001HW.BF4CD7C600321189F0407550@news.individual.de> Message-ID: <1126637915.736074.211910@g43g2000cwa.googlegroups.com> You can try xml.dom and xml.sax. Both are inbuilt libraries with Python standard package. You can read and write xml files with these very easily. There are number of third party modules for Python that manipulate XML. But the above are the basic ones. From nnorwitz at gmail.com Fri Sep 9 23:24:05 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 9 Sep 2005 20:24:05 -0700 Subject: Python Design Principles In-Reply-To: <1126291289.420473.262990@g49g2000cwa.googlegroups.com> References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> <1126291289.420473.262990@g49g2000cwa.googlegroups.com> Message-ID: <1126322645.117057.98220@z14g2000cwz.googlegroups.com> lechequier at gmail.com wrote: > > But I am still puzzled by the argument that has been given for why > methods that operate on mutable types should return None, namely, that > the designers of python didn't want the users to shoot themselves in > the foot by thinking a method simply returned a result and left the > data structure unchanged. Let me try to answer your question with a question. Given this code: >>> d = {} >>> e = d.update([(1, 2)]) If .update() returned a dictionary, does d == e? I'm not sure what you would guess. I am pretty sure that everyone wouldn't agree whether d should equal e or not. If they are not equal, that would mean a new copy would be made on each update which could be incredibly expensive in speed and memory. It is also different from how Python works today, since the update() method mutates the dictionary. > In the context of fundamental design principles, if you asked a random > sample of Python gurus what is more Pythonesque: preventing users from > shooting themselves in the foot or making things easier to accomplish, > my impression is that people would overwhelmingly choose the latter. Probably true, but ... > After all, the fact that Python is not strongly typed and is > interpreted rather than compiled gives plenty of ways for people to > shoot themselves in the foot but what is gained is the abilitity to do > more with less code. I think most people programming Python are pretty pragmatic. There is no single language that is ideal in all circumstances. There are necessarily some trade-offs. Many believe that tools can help bridge this gap. There are at least 2 tools for finding bugs (or gotchas) of this sort: pychecker and pylint. > But in this instance, by not allowing operations on mutable types to > return the mutated objects, it seems that the other side is being > taken, sacrificing programmer producitivity for concerns about > producing possible side effects. It is somewhat ironic, I think, that > Java, a language whose design principles clearly side on preventing > users from shooting themselves in the foot, much more so thatn Python, > generally allows you to get back the mutated object. I think Python has attempted to create an internal consistency. I believe Java has tried to do the same. However, these aren't the same sets of consistency. People are always going to have assumptions. Python strives to be as intuitive as possible. However, it can't be right 100% of the time for all people. HTH, n From davidnicolson1 at hotmail.com Sun Sep 18 23:13:44 2005 From: davidnicolson1 at hotmail.com (David Nicolson) Date: Mon, 19 Sep 2005 13:13:44 +1000 Subject: win32com.client.GetActiveObject() Message-ID: Hi, I have been successfully using iTunes' COM interface with Python using either of the following lines successfully: iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") iTunes = win32com.client.Dispatch("iTunes.Application") The only problem is that it will launch iTunes if it is not running by instantiating the object here. There are some reasons why I have not attempted to use more COM to check if iTunes is an active process, I tried either of the following lines to only form a connection if iTunes is running. iTunes = win32com.client.GetActiveObject("iTunes.Application") iTunes = win32com.client.GetObject(Class = "iTunes.Application") Both lines result in a pythoncom.com_error with 'Operation unavailable' in the second element of the tuple. Has anyone been able to successfully do this with iTunes' COM server? I have seen other 'Operation unavailable' messages in a few other mailing lists but was unable to find any solutions to this problem. Regards, David From n00m at narod.ru Thu Sep 1 09:01:18 2005 From: n00m at narod.ru (n00m) Date: 1 Sep 2005 06:01:18 -0700 Subject: Code run from IDLE but not via double-clicking on its *.py In-Reply-To: References: <1125402893.124342.54690@g47g2000cwa.googlegroups.com> <1125425945.667967.181000@g49g2000cwa.googlegroups.com> <1125478316.530781.315540@g44g2000cwa.googlegroups.com> <1125490472.670850.247240@g49g2000cwa.googlegroups.com> <1125509322.964828.27510@o13g2000cwo.googlegroups.com> Message-ID: <1125579678.705228.172970@f14g2000cwb.googlegroups.com> It's soooooo pity I'm too buzy at my work today. I'll reply a bit later. Thank you, guys! PS Port 1433 SQL Server listens to. PPS SQL Server is a rdbms from M$. From fredrik at pythonware.com Fri Sep 30 00:52:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Sep 2005 06:52:40 +0200 Subject: File Upload Script References: <1128055281.104206.253450@g44g2000cwa.googlegroups.com> Message-ID: "Chuck" wrote: > Hi, can anyone provide or point me in the direction of a simple python > file upload script? I've got the HTML form part going but simply > putting the file in a directory on the server is what I'm looking for. > Any help would be greatly appreciated. upload how? WebDAV? scp? FTP? if the latter, the third script on this page is about as simple as things can get: http://effbot.org/librarybook/ftplib.htm From tjreedy at udel.edu Tue Sep 27 14:52:22 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 Sep 2005 14:52:22 -0400 Subject: WindowsError: stack overflow References: <1127834209.353672.316530@g44g2000cwa.googlegroups.com> Message-ID: wrote in message news:1127834209.353672.316530 at g44g2000cwa.googlegroups.com... > I can get through about 1750 pages of 5000 before I get a WindowsError: > stack overflow exception. Any ideas how I can keep the program chugging > along? A typical source of stack overflow is recursion. Without seeing the code or actual stacktrace, I would guess that you are somehow using recursion instead of iteration. Or perhaps you are analyzing big, deeply nested pages. Terry J. Reedy From michaels at rd.bbc.co.uk Wed Sep 21 03:23:58 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Wed, 21 Sep 2005 08:23:58 +0100 Subject: Crypto.Cipher.ARC4, bust or me doing something wrong? References: Message-ID: Michael J. Fromberger wrote: ... > Since ARC4 is a stream cipher, the keystream changes over time -- with > ARC4, after each character enciphered. To decrypt successfully, you > need to make sure the decrypting keystream exactly matches the > encrypting one. ... >>>> from Crypto.Cipher import ARC4 as cipher >>>> enc = cipher.new("abcdefgh") >>>> dec = cipher.new("abcdefgh") >>>> x = enc.encrypt("This is some random text") >>>> x > "\x05o\xd5XH|\xa4\xfc\xf7z\xecd\xe92\xfb\x05rR'\xbf\xc0F\xfc\xde" >>>> y = dec.decrypt(x) >>>> y > 'This is some random text' >>>> enc.decrypt(x) > 'M|[bI\x1ciG6A]\x13Hz\xb0\x19\xca\xf1-\x9a\x1a2\x9e%' > > I hope this helps clear up your confusion. Hi Michael, Thanks for this, much appreciated. Michael -- Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From snail at objmedia.demon.co.uk Tue Sep 27 13:18:54 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 27 Sep 2005 18:18:54 +0100 Subject: Memory stats References: Message-ID: In message , Tarek Ziad? writes >I am trying to find a general memory profiler that can measure the >memory usage in Python program >and gather some stats about object usages, and things like that. Not a Python module, but Python Memory Validator may fit the bill. No data on the website, just go straight to the beta page and select the product. Windows NT/W2K/XP/etc.. http://www.softwareverify.com http://www.softwareverify.com/beta.php?product=PMVB000 Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From schwerdy at web.de Tue Sep 20 02:35:03 2005 From: schwerdy at web.de (schwerdy at web.de) Date: 19 Sep 2005 23:35:03 -0700 Subject: Searching for a working example of a curses application that resizesin xterm References: <1127126438.588171.73720@g44g2000cwa.googlegroups.com> Message-ID: <1127198103.026114.279620@g44g2000cwa.googlegroups.com> Thanks, but I had already read these discussions (hope the grammar is correct...), and thought I understood them. But my exact problem: If I resize a xterm, in most cases curses prints crap (if it does not crash python). And I could not find any python-curses application that is displayed correctly after a terminal resize. I hope nobody will kill me, 'cause I'm a spammer; here is my example: ------ import curses def gettermres(): """ returns the current terminal size in columns and lines """ import struct, fcntl, sys, termios lines, cols = struct.unpack("HHHH", fcntl.ioctl(sys.stdout.fileno(),termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)))[:2] return cols, lines def splitwin(scr, extend1, axis=0, isPercent=True, useFullScreen=False): """ splits the scr in 2 windows and return both extend1 is the size of the first window axis=0 --> split horizontal axis=1 --> split vertical if isPercent is False, extend1 will be interpreted as absolut size """ if isPercent and not 0 < extend1 < 100: raise "extend1 must be between 0 and 100" if not axis in (0,1): raise "axis must be 0 or 1" if useFullScreen: res = [0,0] res[1], res[0] = gettermres() pos = (0,0) else: res = scr.getmaxyx() pos = scr.getbegyx() size1 = list(res) size2 = list(res) if isPercent: totallen = float(res[axis]) size1[axis] = int( totallen*extend1 / 100 ) else: size1[axis] = extend1 size2[axis] = res[axis] - size1[axis] start1 = list(pos) start2 = list(pos) start2[axis] = size1[axis] win1 = curses.newwin(size1[0], size1[1], start1[0], start1[1]) win2 = curses.newwin(size2[0], size2[1], start2[0], start2[1]) return win1, win2 def startcurses(stdscr): curses.use_default_colors() # transparency curses.init_pair(2, curses.COLOR_GREEN, -1) while 1: curses.setupterm() winTop, winBottom = splitwin(stdscr, 80, useFullScreen=True) winLeft, winRight = splitwin(winTop, 50, 1) winLeft.border() winLeft.noutrefresh() winRight.border() winRight.addstr(1,1,"hallo", curses.color_pair(2)) winRight.noutrefresh() winBottom.border() winBottom.noutrefresh() curses.doupdate() k = winLeft.getch() if k == ord('q'): break curses.wrapper(startcurses) ------ From malvert at telenet.be Mon Sep 19 03:02:34 2005 From: malvert at telenet.be (malv) Date: 19 Sep 2005 00:02:34 -0700 Subject: How to program efficient pattern searches in a list of float numbers? Message-ID: <1127113354.897477.235360@g44g2000cwa.googlegroups.com> Simple case: In this list, how to find all occurences of intervals of n adjacent indexes having at least one list-member with a value between given limits. Visualizing the list as a two-dimensional curve, this is like horizontally dragging a given rectangle over the curve and finding the x coordinates where the curve passes through the rectangle.(Define such a x-index coordinate as the left corner of the rectangle.) More complicated case: Given a pair of rectangles spaced relatively to each other in a fixed manner. Drag this rectangle pair horizontally over the above two-dimensional curve and list the indexes of the occurences where the curve passes simultaneously through both rectangles. (Define such a x-index coordinate as the leftmost corner of the rectangle pair). These problems can be solved by programming a naive search advancing index by index. It seems obvious that due to the localized properties searched for, much more efficient searches should be possible. After having found the occurence-indexes for one particular rectangle set, how to find the pattern occurences after changing one or more rectangle parameters? From rbt at athop1.ath.vt.edu Thu Sep 22 08:25:00 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 22 Sep 2005 08:25:00 -0400 Subject: Finding where to store application data portably In-Reply-To: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1127391900.24765.0.camel@athop1.ath.vt.edu> On Tue, 2005-09-20 at 23:03 +0100, Tony Houghton wrote: > I'm using pygame to write a game called Bombz which needs to save some > data in a directory associated with it. In Unix/Linux I'd probably use > "~/.bombz", in Windows something like > "C:\Documents And Settings\\Applicacation Data\Bombz". > > There are plenty of messages in the archives for this group about how to > find the correct location in Windows, but what about Mac OS? ~/.bombz works equally well on OSX. From deets at nospam.web.de Thu Sep 1 03:20:51 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Sep 2005 09:20:51 +0200 Subject: cgi, reusing html. common problem? In-Reply-To: References: Message-ID: <3nnoeeF2dvbiU1@uni-berlin.de> John M. Gabriele wrote: > I'm putting together a small site using Python and cgi. > > (I'm pretty new to this, but I've worked a little with > JSP/servlets/Java before.) > > Almost all pages on the site will share some common (and > static) html, however, they'll also have dynamic aspects. > I'm guessing that the common way to build sites like this > is to have every page (which contains active content) be > generated by a cgi script, but also have some text files > hanging around containing incomplete html fragments which > you read and paste-in as-needed (I'm thinking: > header.html.txt, footer.html.txt, and so on). > > Is that how it's usually done? If not, what *is* the > usual way of handling this? The basic idea is correct - but there are sooo many other people that had the same problem, and thus they creted web-framworks like e.g. CherryPy or Django or... and then there is ZOPE. Search this group for webframeworks, and you might get more answers than you wanted :) Diez From Nainto at gmail.com Fri Sep 16 22:27:54 2005 From: Nainto at gmail.com (Nainto) Date: 16 Sep 2005 19:27:54 -0700 Subject: FTP status problems. (Again) Message-ID: <1126924074.901404.214550@g49g2000cwa.googlegroups.com> Hello, I have posted before about trying to find the status of an FTP uplaod but couldn't get anything to work. After some more searching I found http://groups.google.com/group/comp.lang.python/browse_thread/thread/76be9a994547db4/91917c906cdc04d4?q=ftp+progress&rnum=1#91917c906cdc04d4 but it does not seem to work because it just uploads the file and does not print a . onto the screen. HEre is the code I have when I'm using the code from that link. import ftplib import os class dot_FTP(ftplib.FTP): def storbinary(self, cmd, fp, blocksize=8192): self.voidcmd('TYPE I') conn = self.transfercmd(cmd) while 1: buf = fp.read(blocksize) if not buf: break conn.send(buf) sys.stdout.write('.') sys.stdout.flush() conn.close() return self.voidresp() ftp = ftplib.FTP("FTPADDRESS") ftp.login("user","pass") file = "/file" ftp.storbinary("STOR " + file, open(file, "rb"), 1024) ftp.quit() Does anyone know why this is not working? IS there any other way to find out when a chunc has been sent or the bytes uploaded of a file? Thanks. From dimitri.pater at gmail.com Thu Sep 1 17:56:34 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 1 Sep 2005 23:56:34 +0200 Subject: Python / web In-Reply-To: <4317730E.4040004@websafe.com> References: <2vHRe.5244$_84.3338@newsread1.news.atl.earthlink.net> <4317730E.4040004@websafe.com> Message-ID: On 9/1/05, Larry Bates wrote: > > > flexibility comes complexity. For less complex needs there are other > more lightweight things like CherryPy. Yes, I agree CherryPy is very nice. I am currently updating my site using CherryPy (and CherryTemplate) and it all works very nice. You'll learn most of the basic stuff in a day or two. It is not as sophisticated as Zope I suppose but I do not have the time for the steep learning curve and my site doesn't just need it. So the choice does depends on your requirements and the time you are willing to spend learning it. CherryPy is very nice, try it. Run it on http://localhost:8080 and just test it. regards, dimtiri -- All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident. Arthur Schopenhauer ----- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stanc at al.com.au Thu Sep 15 00:31:59 2005 From: stanc at al.com.au (Astan Chee) Date: Thu, 15 Sep 2005 14:31:59 +1000 Subject: urllib.open problem In-Reply-To: References: Message-ID: <4328F93F.3070708@al.com.au> yeah, I actually typed that by hand, the url is a local intranet thus I dont specify any proxies of any kind (which I assume isnt required). Sorry about the typo. Cheers Dennis Lee Bieber wrote: >On Thu, 15 Sep 2005 09:19:53 +1000, Astan Chee >declaimed the following in comp.lang.python: > > > >> The code snipplet where this error >> happens is >> f = urllib.urlopen("http://www.hotmail.com/) >> notes= f.readlines() >> >> >> > Is that a cut&paste, or did you type it by hand? > > Note that you have no closing " on that URL. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at o2.usun.pl Sat Sep 17 16:41:23 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 17 Sep 2005 22:41:23 +0200 Subject: Looking for a database. Sugestions? In-Reply-To: References: Message-ID: ionel napisa?(a): > I'm looking for a thread-safe database. > Preferably an embedded, sql database. > > What are the best choices in terms of speed ? Interbase/Firebird is thread-safe, is SQL-compliant. And once it was embedded. In a tank. M1 Abrams, specifically. At least the tale tells that... ;) -- Jarek Zgoda http://jpa.berlios.de/ From jepler at unpythonic.net Fri Sep 2 18:09:16 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Fri, 2 Sep 2005 17:09:16 -0500 Subject: Problems with os.system In-Reply-To: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> References: <1125693942.824322.274060@g49g2000cwa.googlegroups.com> Message-ID: <20050902220912.GA26572@unpythonic.net> Repeated calls to system() seem to cause no problem here. I ran the following program: import os for i in xrange(10000): assert os.system("true") == 0 in around 25 seconds, the 'for' loop completed, and the 'true' command always returned 0 from system, as expected. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From exarkun at divmod.com Tue Sep 20 12:26:16 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 20 Sep 2005 12:26:16 -0400 Subject: Crypto.Cipher.ARC4, bust or me doing something wrong? In-Reply-To: Message-ID: <20050920162616.3914.611169982.divmod.quotient.18897@ohm> On Tue, 20 Sep 2005 16:08:19 +0100, Michael Sparks wrote: >Hi, > > >I suspect this is a bug with AMK's Crypto package from >http://www.amk.ca/python/code/crypto , but want to >check to see if I'm being dumb before posting a bug >report. > >I'm looking at using this library and to familiarise myself writing >small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've >found that I can't get it to decode what it encodes. This might be a >case of PEBKAC, but I'm trying the following: > >>>> from Crypto.Cipher import ARC4 as cipher >>>> key = "........" >>>> obj = cipher.new(key) >>>> obj.encrypt("This is some random text") >')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX' >>>> X=_ >>>> X >')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX' >>>> obj.decrypt(X) >'\x87\xe1\x83\xc1\x93\xdb\xed\x93U\xe4_\x92}\x9f\xdb\x84Y\xa3\xd4b\x9eHu~' > >Clearly this decode doesn't match the encode. Me being dumb or bug? > >Any comments welcome :) > You need two ARC4 instances. Performing any operation alters the internal state (as it is a stream cipher), which is why your bytes did not come out intact. >>> import Crypto.Cipher.ARC4 as ARC4 >>> o = ARC4.new('hello monkeys') >>> p = ARC4.new('hello monkeys') >>> p.decrypt(o.encrypt('super secret message of doom')) 'super secret message of doom' >>> Jp From keygrand at libero.it Thu Sep 8 12:14:15 2005 From: keygrand at libero.it (dario) Date: 8 Sep 2005 09:14:15 -0700 Subject: question from beginner In-Reply-To: <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> References: <1126102477.882046.95490@z14g2000cwz.googlegroups.com> <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> Message-ID: <1126196055.843689.208130@g43g2000cwa.googlegroups.com> Thanks Dennis. In effect stringZVEI doesn't remain empty after the .read method, then the loop is executed 1 time. How could be a 'while' loop to wait a no empty string from the serial port? Dario. Dennis Lee Bieber ha scritto: > On 7 Sep 2005 07:14:37 -0700, "dario" declaimed the > following in comp.lang.python: > > > Hi, Im new on phyton programming. > > On my GPRS modem with embedded Phyton 1.5.2+ version, I have to receive > > a string from serial port and after send this one enclosed in an > > e-mail. > > All OK if the string is directly generated in the code. But it doesn't > > works if I wait for this inside a 'while' loop. This is the simple > > code: > > > First -- post the real code file would help -- the indentation of > the first two statements below is wrong. > > > global stringZVEI > > > This does nothing at the top level -- if only makes sense INSIDE a > "def" block, where it has the effect of saying "this variable is not > local to the function" > > > while stringZVEI=='': > > MOD.sleep(10) > > There is something wrong with > > import time > time.sleep() > ???? > > > a=SER.send(' sono nel while stringZVEI==st vuota') > > stringZVEI = SER.readbyte() > > #for debug > print "%2X " % stringZVEI > > > a=SER.send(' stringZVEI=') > > a=SER.send(stringZVEI) > > > > MOD and SER are embedded class maked by third part. > > > > >From my very little debug possibility it seem that loop is executed 1 > > time only nevertheless stringZVEI is still empty. The line > > a=SER.send(' stringZVEI=') > > work correctly but > > > > a=SER.send(stringZVEI) > > > What does .readbyte() do if there is no data to be read? Since your > loop is based on a totally empty string, if .readbyte returns /anything/ > (even a "null" byte -- 0x00) your loop will exit; and a null byte may > not be visible on the send... > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From xah at xahlee.org Sat Sep 3 21:02:30 2005 From: xah at xahlee.org (Xah Lee) Date: 3 Sep 2005 18:02:30 -0700 Subject: os.system(r"ls") prints to screen?? Message-ID: <1125795750.304104.280660@g49g2000cwa.googlegroups.com> does anyone know why the folllowing prints to the screen? # python import os os.system(r"ls") Xah xah at xahlee.org ? http://xahlee.org/ From rkern at ucsd.edu Tue Sep 13 11:57:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 13 Sep 2005 08:57:00 -0700 Subject: py2app without a mac? In-Reply-To: <312cfe2b05091308405816eccf@mail.gmail.com> References: <312cfe2b05091220524ac2db5b@mail.gmail.com> <918E74C8-B196-4935-9DBE-6B9D1BE38356@ihug.co.nz> <312cfe2b05091308405816eccf@mail.gmail.com> Message-ID: Gregory Pi?ero wrote: > That's an interesting idea, Tony. My program uses things like wxPython, > PythonCard, etc, so would distutils know to package that stuff? Do you > know what distutils commands I would use? If not, I'll look it up later > today. Sure. bdist_mpkg, which is provided with py2app. And so the circle is complete.... Again, it's probably not going to work without some major surgery on py2app. And if you don't have a Mac to test on, you probably won't get far. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From k.robert at gmx.de Tue Sep 13 12:52:11 2005 From: k.robert at gmx.de (Robert) Date: Tue, 13 Sep 2005 18:52:11 +0200 Subject: time.strptime intolerant on weekday string length? Message-ID: A certain DAV server reports a time stamp as "Tues, 30 Aug 2005 20:48:31" ( but not "Tue, ..." as usual) This produces the error below. >>> time.strptime("Tue, 30 Aug 2005 20:48:31","%a, %d %b %Y %H:%M:%S") (2005, 8, 30, 20, 48, 31, 1, 242, -1) >>> time.strptime("Tues, 30 Aug 2005 20:48:31","%a, %d %b %Y %H:%M:%S") Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\_strptime.py", line 425, in strptime raise ValueError("time data did not match format: data=%s fmt=%s" % ValueError: time data did not match format: data=Tues, 30 Aug 2005 20:48:31 fmt=%a, %d %b %Y %H:%M:%S >>> I also don't see how to alter the pattern for strptime to be tolerante for more long weekday strings? Any ideas? Shouldn't it be possible to insert real regexp-like stuff in the pattern? Robert From calfdog at yahoo.com Wed Sep 7 08:32:06 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 7 Sep 2005 05:32:06 -0700 Subject: Open source Web testing tool - cPAMIE 1.6b released Message-ID: <1126096326.480849.73410@g47g2000cwa.googlegroups.com> I am pleased to announce version cPAMIE 1.6 the Web automation tool for Internet explorer. If your looking for a fast way, easy to learn way to drive your browser check out PAMIE. Is PAMIE right for you?, depends on your needs and complexity of the web application. Pamie can take care of the basic needs such as driving web forms without a problem. Been used to test and/or drive Dot Net and Java web applications. can be combined with other opensource tools such as JMeter for performance testing. New Features: * WriteScript method that writes out pamie scripts * Frame Support * Fixes for bugs related to XP sp2 * Get and Set methods for manipulating most controls. For example you can set and/or get the values of textboxes, listboxes, radiobuttons, tables, textarea's, checkboxes etc... * Click methods for buttons, tree objects and links * Fire Event methods * Ability to parameterize data and drive data with add-on DataDriver Class. * Manipulate existing or new Browser windows (not modal dialogs)using find window method. * Use with pythons's PyUnit (unittest) for a complete web testing framework. To Do: * Better Support for modal/non-modal type dialogs * Threading to be addded. Questions - email me: calfdog at yahoo.com Enjoy Rob M. From renting at astron.nl Tue Sep 20 05:02:39 2005 From: renting at astron.nl (Adriaan Renting) Date: Tue, 20 Sep 2005 11:02:39 +0200 Subject: Python and Unix Commands Message-ID: >>>"Adriaan Renting" 09/19/05 11:20 am >>> | |P.S. you don't need to post your question to this list every 5 minutes. | Hmmm, somehow my reply also got posted more than once... At least that's what it looks like in my mail viewer, I only see one post in Google. Maybe it's just Groupwise that's giving me phantom messages, I appologize for my remark if that's the case. I hope Groupwise 7 will be an improvement over my current 6.5. From edhotchkiss at gmail.com Mon Sep 19 20:45:06 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Mon, 19 Sep 2005 20:45:06 -0400 Subject: Best Encryption for Python Client/Server In-Reply-To: References: <200509191446.15240.jstroud@mbi.ucla.edu> Message-ID: I apologize for misreading your H my dear professor. Perhaps you can google:asshole and see if your image is present, I would highly doubt that it is not within the first page of results. I'm sorry that I did not see the message in the thread which recommended SSH rather than SSL. There is no need to be a dick. - Luckily you were never my professor -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon.brunning at gmail.com Thu Sep 29 11:47:28 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 29 Sep 2005 16:47:28 +0100 Subject: Will python never intend to support private, protected and public? In-Reply-To: <311b5ce105092908332c12164c@mail.gmail.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> <7xll1gvk7w.fsf@ruckus.brouhaha.com> <1128001308.905398.321670@g44g2000cwa.googlegroups.com> <311b5ce105092908332c12164c@mail.gmail.com> Message-ID: <8c7f10c6050929084726ff8c36@mail.gmail.com> On 9/29/05, could ildg wrote: > **Encapsulation** is one of the 3 basic characteristics of OOP. Pyhton has encapsulation. On objetcts members are encapsulated in a namespace all of its own. You can't change these by accident. > Every programmer is just a human being, but not God. Our life is limited, > our time is limited, so we need to use convenient tools to save time. > Private variables guarantee that we will never make stupid mistakes Private variables prevent the developer of the *client* of a class from making a small subset of all possible stupid mistakes. But if the developer of the classitself is mistaken in marking a variable as private, and if the language enforces this, then there is nothing at all that the client can do to fix it. Why should the developer of the class be more likely to be god-like than the user of the class? This has happened to me more than once. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From grante at visi.com Thu Sep 15 21:25:30 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 16 Sep 2005 01:25:30 -0000 Subject: 2.3 -> 2.4: long int too large to convert to int References: <11ijsh0h2dec0ed@corp.supernews.com> Message-ID: <11ik7oanakemad9@corp.supernews.com> On 2005-09-15, Terry Reedy wrote: >>I give up, how do I make this not fail under 2.4? >> >> fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00)) >> >> I get an OverflowError: long int too large to convert to int >> >> ioctl() is expecting a 32-bit integer value, and 0xc0047a80 has >> the high-order bit set. I'm assuming Python thinks it's a >> signed value. How do I tell Python that 0xc0047a80 is an >> unsigned 32-bit value? > > In 2.3 and before, you get this: >>>> 0xc0047a80 > -1073448320 I don't particular care how Python prints the value -- I just want that value passed to the function I'm calling. > In 2.4, positive hex literals are treated as positive numbers, and that is > your problem: your literal is greater than the largest int and hence gets > stored as long int. I knew that, I just couldn't come up with a good way to fix it. > I would try -1073448320 as the arg. That should work, but it's kind of lame (no offense). ioctl values are always, always written in hex. A block of ioctl values is generally assigned to a particular driver such that the high order N (is it 4 oe 5?) hex digits are unique to that driver. Writing the value in decimal is going to completely confuse anybody looking at the code. I rather like the other suggestion of writing a function that accepts 0x and returns the appropriate integer value. Another poster suggested a solution using struct. Here's my solution (which assume python integers are represented in 2's compliment binary): def ioctlValue(i): if i & 0x80000000: i = -((i^0xffffffff)+1) return i -- Grant Edwards grante Yow! Somewhere in Tenafly, at New Jersey, a chiropractor visi.com is viewing "Leave it to Beaver"! From jstroud at mbi.ucla.edu Thu Sep 1 22:02:44 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 1 Sep 2005 19:02:44 -0700 Subject: pain In-Reply-To: <1123166972.948428.219140@g47g2000cwa.googlegroups.com> References: <42f1f51b$0$11068$e4fe514c@news.xs4all.nl> <1123166972.948428.219140@g47g2000cwa.googlegroups.com> Message-ID: <200509011902.44745.jstroud@mbi.ucla.edu> On Thursday 04 August 2005 07:49 am, projecktzero wrote: > "a manager telling me what tools to use to do my job is a bad > manager by definition because he should realize that the people who > best > know what tools to use are the peope who use the tools*." > > I'm sorry, this doesn't make much sense to me. In an ideal world where > all developers are all knowing and know every language inside and out, > then allowing each developer to choose his tools(languages) would work. > You don't see a problem with programmer Joe using Perl, Brad using > Python, Carl uses Smalltalk, Nate uses Java, Steve using Ruby, and Ed > using Haskell? A library could be written in python and interfaced in java for others to use who are too lazy to know both. > "* Did you know that most good chef cooks have their own knive set? > And what do you think is the reason a restaurant manager don't tell > them > to use the company in-house Amefa blades instead of his global knives? > " > > This is a very poor analogy. The next chef doesn't have to re-cook what > the previous chef has done(well, that didn't work either)...er...This > has nothing to do with programming. > > The manager may have his reasons for choosing the tools. Reason: ignorance. > Perhaps nearly > all projects that have been developed and are in development are using > paticular tools. It's easy for team members to work on any project.(I'm > speaking more of languages and frameworks not down to the editors and > IDEs.) It would be nice if the team could decide on tools, and > sometimes that's appropriate. Maybe they want to migrate to a new > language or framework. Maybe there's a throw away project that could be > a test for the new language or framework. If you want to try a > new/different language, you need to show the benefit other than "it's > cool/new". A manager insisting on java is probably only thinking about name recognition anyway. Hey Mr. Client, were using java. Isn't that "cool"? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From edhotchkiss at gmail.com Fri Sep 16 14:43:18 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Fri, 16 Sep 2005 14:43:18 -0400 Subject: Looking for a database. Sugestions? In-Reply-To: References: <20050916123924.GA20643@torf.workaround.org> Message-ID: So I opted actually to stick with MySQL since I got hooked up with a DB free and It's more of a standard. I'm looking at documentation, and wondering why not just use _mysql which is built in, versus the MySQLdb module? I don't get this ... -edward -------------- next part -------------- An HTML attachment was scrubbed... URL: From n00m at narod.ru Fri Sep 2 08:47:31 2005 From: n00m at narod.ru (n00m) Date: 2 Sep 2005 05:47:31 -0700 Subject: problems with smtplib In-Reply-To: References: <1125660341.067470.55670@z14g2000cwz.googlegroups.com> <1125661924.699163.69180@g47g2000cwa.googlegroups.com> Message-ID: <1125665251.617078.25630@o13g2000cwo.googlegroups.com> Steve Holden wrote: > That's pretty strange: the second argument should be a list. Are you > *sure* it worked? Hmm... I sent a couple of letters to my two different addresses... and got them! From theller at python.net Wed Sep 7 12:03:24 2005 From: theller at python.net (Thomas Heller) Date: Wed, 07 Sep 2005 18:03:24 +0200 Subject: py2exe 0.6.1 released References: <1KbTe.51152$F23.643754@twister2.libero.it> <431e897e.819123967@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > If you have a place in the program where output should never happen > except when you would want a console window to see it in, you can > call AllocConsole [1] safely even in multiple such places, just before > the printing, and the first such call will create the console and hook > up stdout and stderr ready to print. Subsequent calls to AllocConsole > are effectively ignored, so all the output goes to the same console > no matter which code section executed first. IMO this should be > built into at least the windows wpython to trigger at the first > attempt at stdout or stderr output. There could be an option to > override that default and thus ignore stdout/stderr output, but I > think it would be a useful default. Plus it would tell people early > that they had usesless prints going in their wpython programs. > IMO that would be a nice addition to pythonw.exe, but I have no time to care about this myself. For py2exe, I'm still unsure how debugging output from a frozen gui program should be handled. Thomas From cakebread at gmail.com Fri Sep 9 16:01:17 2005 From: cakebread at gmail.com (cakebread) Date: 9 Sep 2005 13:01:17 -0700 Subject: disabling TCP connections, just for one script In-Reply-To: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> References: <1126284066.723527.274460@g14g2000cwa.googlegroups.com> Message-ID: <1126296077.445884.313850@z14g2000cwz.googlegroups.com> How about this: import timeoutsocket timeoutsocket.setDefaultSocketTimeout(0) This will make all sockets in your Python app fail. https://svn.plone.org/svn/collective/CMFSquidTool/trunk/timeoutsocket.py From gmane-esc at mmf.at Wed Sep 21 04:02:03 2005 From: gmane-esc at mmf.at (Erich Schreiber) Date: Wed, 21 Sep 2005 10:02:03 +0200 Subject: Premature wakeup of time.sleep() References: Message-ID: Thank you every body for your comments. Especially Jeff Epler for your hint about NTP. You're right. I see a (constant but somewhat huge)time drift of about 1 ms/min which I can correct for. Thank you Steve Horsley for the clarification of the interrupts that would end the delay. I didn't think of something as trivial as ^C. And thank you Nick Craig-Wood for the shell script to get hands on the HZ value. I had to modify it a little as I do not have /proc/interrupts, but I've got the idea. I measure about 100 and so I have a 10 ms granularity in my VPS as you predicted. Erich From michael at stroeder.com Fri Sep 30 04:30:23 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 30 Sep 2005 10:30:23 +0200 Subject: Fixes since 2.4.2c1? In-Reply-To: <433c35c6$0$20810$9b622d9e@news.freenet.de> References: <5hkr03-jo6.ln1@nb2.stroeder.com> <433c35c6$0$20810$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Michael Str?der wrote: > >>Does that differ from 2.4.2c1? On Monday I noticed a crash in the test >>suite on a box running Solaris 8. It seems I can build Python 2.4.1 and >>run make test there without problems. > > There is also a chance that you found a compiler bug. So reporting the > compiler you used would be essential. It's gcc 3.0 installed by a Solaris 8 (probably outdated) package from http://www.sunfreeware.com I can dig further into on Tuesday. It's not my box. Ciao, Michael. From jegenye2001 at gmail.com Mon Sep 12 11:27:04 2005 From: jegenye2001 at gmail.com (jegenye2001) Date: 12 Sep 2005 08:27:04 -0700 Subject: ANNOUNCEMENT: The ring of the friendly serpent in business suite: Python, Zope, Plone References: <1126536283.747998.139820@f14g2000cwb.googlegroups.com> Message-ID: <1126538824.902519.67180@g47g2000cwa.googlegroups.com> Oops, "suit" indeed. Though it might be considered as a pun if you really want to. :-) Anyway, thanks, I will correct it. Cheers, Miklos From swarnapsv at yahoo.co.in Tue Sep 13 19:47:08 2005 From: swarnapsv at yahoo.co.in (swarna pulavarty) Date: Wed, 14 Sep 2005 00:47:08 +0100 (BST) Subject: retrieve data using FTP in Python Message-ID: <20050913234708.82132.qmail@web8406.mail.in.yahoo.com> Hi all, I am new to this Python group and to Python . I need to retrieve data from an arbitrary URL and save it to a file. Can anyone tell me how to retrieve "any" data using FTP modules in Python ? And also, Can you suggest me some books and online references to get familiar with Python and especially FTP modules in Python ? Your help is appreciated ! Swarna. --------------------------------- Yahoo! India Matrimony: Find your partner now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From float_dublin at mail.ru Fri Sep 16 12:24:19 2005 From: float_dublin at mail.ru (float_dublin) Date: Fri, 16 Sep 2005 20:24:19 +0400 Subject: IDE, widget library In-Reply-To: References: Message-ID: Thomas Jollans wrote: > I guess questions like this come all the time here ... well: > > I a looking for a python IDE for gnu/linux that : > - has decent sytax highlighting (based on scintilla would be neat) > - has basic name completition, at least for system-wide modules > - has an integrated debugger > - is open source, or at least free of charge > > an integrated GUI designer would of course be cool, but cannot be > counted as a requirement. > > With that I come to the second question: > What cross-platform GUI libraries are there ? cross-platform meaning > functional and free on (at least) X11 and Win32 > PyQT obviously doesn't count because qt3 is not free on windows. > Tk is ugly. (how well) is Tile supported with python ? > does PyGTK/Glade work on win32 ? wxPython + boaconstructor as IDE + RAD (looks like delphi or VB) and easy to use (i'm c++'er but it took 15minutes to create some 15 buttons application and 5 to create win32exe with py2exe, so I'm happy, cause I don't even know python) http://boa-constructor.sourceforge.net/ -- float_dublin From peter at engcorp.com Thu Sep 15 22:10:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Sep 2005 22:10:52 -0400 Subject: read stdout/stderr without blocking In-Reply-To: References: <11ib4sfhuj94m0b@corp.supernews.com> Message-ID: Donn Cave wrote: > Peter Hansen wrote: >>Jacek Pop?awski wrote: >>>My tests showed, that it will block. >> >>Not if you use non-blocking sockets, as I believe you are expected to >>when using select(). > > On the contrary, you need non-blocking sockets only if > you don't use select. select waits until a read [write] > would not block - it's like "if dict.has_key(x):" instead of > "try: val = dict[x] ; except KeyError:". I suppose you > knew that, but have read some obscure line of reasoning > that makes non-blocking out to be necessary anyway. No, no, I suspect I was just plain wrong. I think I felt a twinge of suspicion even as I wrote it, but I went ahead and hit Send anyway perhaps because I'd had two nights with little sleep (if I need an excuse to be wrong, that is, which I don't :-) ). > Who knows, but it certainly isn't in this case. Thanks for straightening things out for the record. -Peter From peter at engcorp.com Tue Sep 20 20:33:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Sep 2005 20:33:38 -0400 Subject: Finding where to store application data portably In-Reply-To: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> References: <4330872a$0$1304$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Tony Houghton wrote: > > I'm using pygame to write a game called Bombz which needs to save some > data in a directory associated with it. In Unix/Linux I'd probably use > "~/.bombz", in Windows something like > "C:\Documents And Settings\\Applicacation Data\Bombz". > > There are plenty of messages in the archives for this group about how to > find the correct location in Windows, but what about Mac OS? There I > don't know the correct location for this sort of thing at all. And there > are other, more obscure systems like RISC OS (it may not have pygame but > it definitely has python). Surely this is something that's crying out > for an official function in os or sys. Perhaps using "import user; user.home" would be adequate. Note the documented side effects of doing that however. -Peter From eh1 at delair.de Fri Sep 30 05:50:42 2005 From: eh1 at delair.de (elho) Date: Fri, 30 Sep 2005 11:50:42 +0200 Subject: return (PyObject*)myPyType; ...segmentation fault! Message-ID: <433D0A72.5090805@delair.de> I called a own python type 'PyType' with a c function and returned it into my python programm - there it fault. It is said that the object has a NULL-Pointer when I try to debug it? Here are the importent snips from my code: // == test.py ========================================================= . : myNewPyType = PyMyExtention.GetValue ("xxx") # printings for testing print "...back to python... test.py" print "pp\t ...PyMyType.PyMyObject:", type(tySdlXml) //===================================================================/ // == PyMyExtention.c ================================================= . : static PyObject* wrap_GetValue (PyObject* self, PyObject* args) { char* pchXXX; if (!PyArg_ParseTuple(args, "s", &pchXXX)) { return 0; } long llong = CFunktion::CallMe(pchXXX); // returning Python-Objekt PyObject *pyType = PyMyObject_NewC (llong); cout << "cc ..." << ((PyMyType*)pyType)->lAttribute << endl; cout << "\t ...proof object-valid pointer?" << (void*)pyType << endl; return (PyObject*)pyType; } . : //===================================================================/ // == PyMyExtention.c ================================================= . : typedef struct { PyObject_HEAD long lAttribute; } PyMyObject; static PyObject* PyMyObject_NewC (long lAttribute) { PySDLXMLNode *self; PySDLXMLNode *type; self = new PySDLXMLNode; self->lAttribute = lAttribute; return (PyObject*)self; } static PyMethodDef PyMyObject_methods[] = { {"PyMyObject_NewC", (PyCFunction)PyMyObject_NewC, METH_NOARGS, "Create PyMyObject_NewC from C-Code"}, {NULL} /* Sentinel */ }; : static PyTypeObject PySDLXMLNodeType = { PyObject_HEAD_INIT(NULL) : }; //===================================================================/ // ::: output :::::::::::::::::::::::::::::::::::::::::::::::::::: cc ...135603272 t ...proof object-valid pointer?: 0x8165940 ...back to python... test.py Segmentation fault //===================================================================/ ...you see: It returns to python but over there the object is something bad. So what is wrong? From rrr at ronadam.com Thu Sep 22 13:26:20 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 22 Sep 2005 17:26:20 GMT Subject: Question About Logic In Python In-Reply-To: References: <1127089204.462591.250950@g14g2000cwa.googlegroups.com> Message-ID: <0PBYe.109568$p_1.45988@tornado.tampabay.rr.com> Steve Holden wrote: > Ron Adam wrote: >> >> 2. Expressions that will be used in a calculation or another >> expression. >> > By which you appear to mean "expressions in which Boolean values are > used as numbers". Or compared to other types, which is common. >> This matters because if you aren't careful your results may not be >> what you expect. >> > Well yes, but then I wouldn't necessarily expect good results if I tried > to use a nail file as a tyre-lever, either. If you abuse the intent of > anything sufficiently you should expect trouble. But then, you seem to > like trouble ;-) Steve... You seem to agree, but think if any one has a problem with this, it's a misuse or an abuse. Ok. fair enough. Its not so much I like trouble, It's more that I tend to get stuck on contradictions and inconsistencies. They bug me. (sometimes I bug myself as well) ;-) >> >>> True * True >> 1 # Why not return True here as well? >> > Why not return 42? Why not return a picture of a banana? My question still stands. Could it be helpful if bools were preserved in more cases than they are now? My feelings is that it isn't needed as long as you strictly use your own modules, functions, and classes, and can depend on the behavior you decide on. But if you are using routines and object written by others, you can't always be sure if a values should be treated as a bool or as an integer. Preserving bools when possible, may help in that regard. >> This is like adding two integer types and getting a float. >> > No it isn't. It's like trying to multiply April 2 1994 by June 5 2005. > The operation isn't defined. So you choose an arbitrary definition and > say "it would be nice if it worked like this instead of how it actually > does work". Sure, but if we didn't suggest changes, then nothing would change. We would just have extremely detailed documentation of everything and strict rules of use so that we don't misuse them. ;-) > When in fact it doesn't really "work" at all, except for the most > tenuous possible value of "work". It's an accident, because Guido > decided that least code breakage was good when Booleans were introduced. Good point, but it could be changed in Python 3000 since it will drop the backwards compatible requirement. This doesn't mean that it should though. The reasons for doing so still need to be sufficient. >> There's the possibility of adding two (normally) True values and >> getting a False result. >> >> >>> a = True >> >>> b = -1 >> >>> a + b # True_value + True = False_value >> 0 >> > Which is yet another reason why it makes absolutely no sense to apply > arithmetic operations to Boolean values. Again you agree, yet disagree. Ok, I see your point about breaking code, but should this be changed, either throw an exception or by changing to a boolean operation in Python 3000? You already consider it an abuse. > You are, of course, ignoring the huge amount of code breakage this > little change you'd find so convenient would cause. I'm not suggesting anything be changed before Python 3000 which has as a purpose of changing things that haven't been changed because of backwards compatibility. And I don't think I'm the only one who has suggested these. >> On one hand these seem like little things, but little things is >> sometimes what will bite you the hardest as they are more likely to >> get by your guard. >> > Kindly think again about the vast number of times that Python > programmers have relied on the documented property of "and", which says > that it returns the left operand (without evaluating the right one) > unless the left operand is equivalent to False, in which case it returns > the right operand. The shortcut behavior would still work, but the returned values would be either True or False. I agree the above is useful behavior, but I also see the boolean behavior as desirable. I would like both in clear and separate contexts if possible. Guido said the other day on python-dev, he would consider having 'and' and 'or' return True and False in order to reduce bugs, if a trinary was also added. It's not as short to type, but the same functionality would still be present in the language. Another possibility would be to just add bool operators '||' and '&&' which would always return True and False and leave 'and' and 'or' as they are. > You talk about "least surprises" and "in my opinion" as though your > opinions are the only ones that anyone would dream of holding. This is > in itself quite surprising to me. No, "in my opinion" means exactly that, It's my personal opinion. You are free and welcome to express "your opinion" as well. And "least surprises" is, I believe, a good thing to strive for. Weather or not this would fit that I'm not sure. It's quite possible that some of these changes would create more surprises not less. Also these ideas aren't mine, they are fairly standard concepts that other languages use as well, nothing really new here. Cheers, Ron From jstroud at mbi.ucla.edu Tue Sep 6 17:36:50 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 6 Sep 2005 14:36:50 -0700 Subject: Function returns a function In-Reply-To: <7x4q8xx5fn.fsf@ruckus.brouhaha.com> References: <7x4q8xx5fn.fsf@ruckus.brouhaha.com> Message-ID: <200509061436.50972.jstroud@mbi.ucla.edu> Thank you Paul, this makes much more sense. James On Tuesday 06 September 2005 02:16 pm, Paul Rubin wrote: > ? ? def FunctionMaker(avar, func, label): > ? ? ? ?def callback(): > ? ? ? ? ? avar.set(label) > ? ? ? ? ? func() > ? ? ? ?return callback -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bbands at gmail.com Fri Sep 2 12:57:49 2005 From: bbands at gmail.com (BBands) Date: 2 Sep 2005 09:57:49 -0700 Subject: Add lists to class? References: <1125605901.380239.210350@z14g2000cwz.googlegroups.com> <86oe7c3z1x.fsf@bhuda.mired.org> Message-ID: <1125680269.341295.97210@g43g2000cwa.googlegroups.com> That's interesting and I take your point. Maybe there is a better way. Here is what I am doing now. (working) I start with a text file of ticker symbols. I read each symbol and stick it in a list, retrieve the data for it from MySQL, do a trivial smoothing and pass the data to a modeling routine. I read the tickers into a list, self.symbols. Then for each ticker I create a list, self._0, self._1, ... and a list for the smoothed values, self._0_smooth, self._1_smooth, ... I end up with data I can access with self.__dict__["_" + str(var)] and a matching symbol which I can access self.symbols[var]. Ideas for a better approach gladly accepted. jab From steve at holdenweb.com Fri Sep 30 03:50:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 30 Sep 2005 08:50:39 +0100 Subject: scope of socket.setdefaulttimeout? In-Reply-To: <1128030031.130958.185620@z14g2000cwz.googlegroups.com> References: <1128030031.130958.185620@z14g2000cwz.googlegroups.com> Message-ID: Russell Warren wrote: > Does anyone know the scope of the socket.setdefaulttimeout call? Is it > a cross-process/system setting or does it stay local in the application > in which it is called? > > I've been testing this and it seems to stay in the application scope, > but the paranoid side of me thinks I may be missing something... any > confirmation would be helpful. > Yes, it's an application setting, you aren't changing things for anyone else. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From b_c_searle at yahoo.com Mon Sep 19 10:34:32 2005 From: b_c_searle at yahoo.com (b_c_searle) Date: Mon, 19 Sep 2005 14:34:32 -0000 Subject: are variables local to try/except blocks ? Message-ID: # Is this valid (or is excp local only to try/except)? try: try: doSomething1 excp = 0 except: excp = 1 #endTry if (_excp_): doSomething1 # is excp defined here? excp = 0 except: excp = 1 #endTry if (excp): doSomething2 # is excp defined here? # valid, but more verbose (and maybe redundant?) excp = 0 try: excp = 0 try: doSomething1 excp = 0 # reset incase future inner block except: excp = 1 #endTry if (_excp_): doSomething1 excp = 0 # reset incase inner block set excp=1 except: excp = 1 #endTry if (excp): doSomething2 I am not so interested in what a particular version of the Python/Jython interpreter does, but rather what is "right". Pls "CC" replies to searle at ca.ibm.com (as well as newsgroup) Barry Searle, searle at ca.ibm.com From keir.robinson at gmail.com Tue Sep 6 12:43:16 2005 From: keir.robinson at gmail.com (keirr) Date: 6 Sep 2005 09:43:16 -0700 Subject: which reg values modified my python installer under windows References: Message-ID: <1126024996.916146.200370@o13g2000cwo.googlegroups.com> Philippe, You wrote: I wish to associate *.pyc with pythonw.exe is there some reason why Tools->Folder Options->File Types (from a Windows Explorer menu) won't work? You could do it from a cmd prompt with assoc and ftype if you needed to script it. All the best, Keir. From reinhold-birkenfeld-nospam at wolke7.net Wed Sep 28 09:31:44 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 28 Sep 2005 15:31:44 +0200 Subject: What tools are used to write and generate Python Library documentation. In-Reply-To: References: Message-ID: <3pvka0FccfkiU1@individual.net> Kenneth McDonald wrote: > I have a module I'd like to document using the same style... The Python Library documentation is written in LaTeX and converted to HTML with latex2html. The relevant style and source files are in the Python CVS tree. Reinhold From twic at urchin.earth.li Mon Sep 26 19:28:03 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 27 Sep 2005 00:28:03 +0100 Subject: PEP 350: Codetags In-Reply-To: References: Message-ID: On Mon, 26 Sep 2005, Micah Elliott wrote: > Please read/comment/vote. This circulated as a pre-PEP proposal > submitted to c.l.py on August 10, but has changed quite a bit since > then. I'm reposting this since it is now "Open (under consideration)" > at . Seems generally fine to me; i'm not the best person to comment, though, since it's highly unlikely i'll use them. I did notice one thing that is sort of wrong, though: :Objection: *WorkWeek* is an obscure and uncommon time unit. :Defense: That's true but it is a highly suitable unit of granularity for estimation/targeting purposes, and it is very compact. The `ISO 8601`_ is widely understood but allows you to only specify either a specific day (restrictive) or month (broad). Actually, ISO 8601 includes a week notation. Have a read of this: http://www.cl.cam.ac.uk/~mgk25/iso-time.html Which explains that you can write things like 2005-W20 to mean the 20th week of 2005, and ISO won't send you to hell for it. tom -- Brace yourself for an engulfing, cowardly autotroph! I want your photosynthetic apparatii! From peter at engcorp.com Sat Sep 3 11:40:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 03 Sep 2005 11:40:29 -0400 Subject: Find day of week from month and year In-Reply-To: <7xek86oquq.fsf@ruckus.brouhaha.com> References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> <7xzmqvnu2e.fsf@ruckus.brouhaha.com> <1125693964.021011.111040@f14g2000cwb.googlegroups.com> <7xek86oquq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Hansen writes: > >>(And, if I were "optimizing", I would of course dispense with the >>dynamic creation of the static table upon every execution of >>expiration(), and move it outside the function.) > > Replacing it with a tuple might be enough for that. You're right, and in fact that would actually be even faster since then it's a LOAD_CONST instead of a LOAD_GLOBAL. -Peter From tjreedy at udel.edu Thu Sep 1 11:36:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Sep 2005 11:36:42 -0400 Subject: Bug in string.find References: <1124160882.554543.75730@g43g2000cwa.googlegroups.com><3ErPe.853$sV7.65@newssvr21.news.prodigy.com><7sJPe.573$MN5.131@newssvr25.news.prodigy.net><7xy86k3r7n.fsf@ruckus.brouhaha.com><4314b190.174021119@news.oz.net> Message-ID: "Fredrik Lundh" wrote in message news:df6slb$4n8$1 at sea.gmane.org... > [slice] indices point to the "gap" between items, not to the items > themselves. > > positive indices start from the left end, negative indices from the > righept end. > > straight indexing returns the item just to the right of the given gap > (this is > what gives you the perceived assymmetry), slices return all items between > the given gaps. Well said. In some languages, straight indexing returns the item to the left instead. The different between items and gaps in seen in old terminals and older screens versus modern gui screens. Then, a cursur sat on top of or under a character space. Now, a cursur sits between chars. Terry J. Reedy From roccomoretti at hotpop.com Fri Sep 2 10:24:08 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 02 Sep 2005 09:24:08 -0500 Subject: 'isa' keyword In-Reply-To: References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> <1125577823.da914aee91f630e1c5ca0bb07d0fa224@teranews> Message-ID: Terry Hancock wrote: > On Thursday 01 September 2005 07:28 am, Fuzzyman wrote: > >>What's the difference between this and ``isinstance`` ? > > I must confess that an "isa" operator sounds like it would > have been slightly nicer syntax than the isinstance() built-in > function. But not enough nicer to change, IMHO. Especially conidering that checking parameters with "isinstance" is considered bad form with Python's duck typing. From gsakkis at rutgers.edu Sat Sep 24 18:03:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 24 Sep 2005 18:03:52 -0400 Subject: Most direct way to strip unoprintable characters out of a string? References: Message-ID: <1127599437.e4ab33f8d8f65cbcfb07427b68e97909@teranews> "Steve Bergman" wrote: > When sanitizing data coming in from HTML forms, I'm doing this (lifted > from the Python Cookbook): > > from string import maketrans, translate, printable > allchars = maketrans('','') > delchars = translate(allchars, allchars, printable) > input_string = translate(input_string, allchars, delchars) > > Which is OK. But it seems like there should be more straightforward way > that I just haven't figured out. Is there? If by straightforward you mean one-liner, there is: ''.join(c for c in input_string if c not in string.printable) If you care about performance though, string.translate is faster; as always, the best way to decide on a performance issue is to profile the alternatives on your data and see if it's worth going for the fastest one at the expense of readability. George From enrique.palomo at xgs-spain.com Fri Sep 16 07:16:50 2005 From: enrique.palomo at xgs-spain.com (=?Windows-1252?Q?Enrique_Palomo_Jim=E9nez?=) Date: Fri, 16 Sep 2005 13:16:50 +0200 Subject: dictionary to file Message-ID: Hi all, I'm writing an application who needs to handle a lot of information of several files. So, i think the better way is design a batch process to catch that information in a dictionary and write it in a file. So, after that when a user wants to retrieve something, only with an execfile i'll have all the information avaiable. Creating the file with pythonic syntax will be a hard job so, is there some module to do that? is there a better way? The information will be used no more than 3-4 days a month and install databases is not allowed. Thanks From jstier at cs.uvic.ca Wed Sep 14 16:23:35 2005 From: jstier at cs.uvic.ca (J) Date: 14 Sep 2005 13:23:35 -0700 Subject: packaging python for install. In-Reply-To: <1126722446.580981.255450@g44g2000cwa.googlegroups.com> References: <1126722446.580981.255450@g44g2000cwa.googlegroups.com> Message-ID: <1126729415.006853.98680@z14g2000cwz.googlegroups.com> Hi I found the solution to problem and I just want to document it for the next guy. I did not copy the content of the 'dist' directory created by Py2exe to the folder containing my executable. Changing HKEY_LOCAL_MACHINE\SOFTWARE\PythonCore\. alone did not work for me... maybe I should have found and changed PYTHONPATH as well :) Anyways, now I have a solution. thx for all the help From fperez.net at gmail.com Thu Sep 8 13:24:00 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 08 Sep 2005 11:24:00 -0600 Subject: job scheduling framework? References: <1126194711.728965.86630@g43g2000cwa.googlegroups.com> <5cOdnfriiORj8L3eRVn-vA@comcast.com> Message-ID: Larry Bates wrote: > Google turned up these links that might be of interest: > > http://www.foretec.com/python/workshops/1998-11/demosession/hoegl/ > http://www.webwareforpython.org/Webware/TaskKit/Docs/QuickStart.html > http://www.slac.stanford.edu/BFROOT/www/Computing/Distributed/Bookkeeping/SJM/SJMMain.htm > > Larry Bates > > > Chris Curvey wrote: >> Has anyone seen a simple open source job-scheduling framework written >> in Python? I don't really want to reinvent the wheel. All I need is >> the ability to set up a series of atomic "jobs" as a "stream", then >> have the system execute the jobs in the stream one-at-a-time until all >> the jobs in the stream are complete or one of them reports an error. >> >> (If it tied into a really simple grid-style computing farm, that would >> be worth double points!) In addition to Larry's links, this might also be of interest: http://directory.fsf.org/science/visual/Pyslice.html Not exactly the same, but I suspect it may be useful. Cheers, f From larry.bates at websafe.com Thu Sep 29 17:32:35 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 29 Sep 2005 16:32:35 -0500 Subject: Writing EXIF data In-Reply-To: References: Message-ID: I've used jhead and wrapped it with os.system call. http://www.sentex.net/~mwandel/jhead/ -Larry Bates Roel Schroeven wrote: > Hi, > > I'm looking into processing images with EXIF data. I've been looking > around and I've found a number of Python modules that read EXIF data, > but I did not find a module for writing EXIF data. Does anybody know of > such a beast? > From pje at telecommunity.com Thu Sep 29 12:10:09 2005 From: pje at telecommunity.com (Phillip J. Eby) Date: Thu, 29 Sep 2005 12:10:09 -0400 Subject: [Python-Dev] PEP 350: Codetags In-Reply-To: <20050928161039.GF10940@kitchen.client.attbi.com> References: <20050926223521.GE10940@kitchen.client.attbi.com> <20050926223521.GE10940@kitchen.client.attbi.com> Message-ID: <5.1.1.6.0.20050929120234.01ae7390@mail.telecommunity.com> At 09:10 AM 9/28/2005 -0700, Micah Elliott wrote: >I agree that proof of value is necessary. Without a spec though it >will be hard to get people to know about a convention/toolset, so it's >a bit of a chicken-egg problem -- I can't have a pep until the tools are >in use, but the tools won't be used until programmers have >means/motivation to use them, a pep. My point about the lack of motivation was that there was little reason shown why this should be a PEP instead of either: 1. Documentation for a specific tool, or group of tools 2. A specific project's process documentation Are you proposing that this format be used by the Python developers for Python itself? A process spec like this seems orthogonal to Python-the-language. To put it another way, this seems like writing a PEP on how to do eXtreme Programming, or perhaps a PEP on how the blogging "trackback" protocol works. Certainly you might implement those things using Python, but the spec itself seems entirely orthogonal to Python. I don't really see why it's a PEP, as opposed to just a published spec on your own website, unless you intend for say, the Python stdlib to conform to it. From frithiof.jensen at die_spammer_die.ericsson.com Tue Sep 20 08:09:18 2005 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 20 Sep 2005 14:09:18 +0200 Subject: Help! Python either hangs or core dumps when calling C malloc References: <1126198290.288644.247510@o13g2000cwo.googlegroups.com> <1126199525.752904.254930@z14g2000cwz.googlegroups.com> <1126203439.152057.78210@o13g2000cwo.googlegroups.com> Message-ID: "Lil" wrote in message news:1126203439.152057.78210 at o13g2000cwo.googlegroups.com... > I already double checked my C code. It runs perfectly fine in C without > any errors. Errr - It runs perfectly fine without *announcing* any errors (while gleefully urinating all over its memory space). The programming model for "C" is "*you* asked for it, you got it mate!" - so you have to "tell" the program how to debug memory by rebuilding it with f.ex. Electric Fence, or whatever memory debug lib is preferred for your box, and running that again. The tools will spot mistakes faster and more reliable than the developer who wrote the code. Use them. > So in my python program, I added a pdb.set_trace() > and step through the program and it did not dump. But when i took out > the tracing, the core dump came back. "sigh" So?? You re-jiggled the bits, so something important got thrashed this time. Run the C program trough with gdb and see what it does. It thrashes something. From rdh at new.rr.com Fri Sep 23 15:14:45 2005 From: rdh at new.rr.com (DataSmash) Date: 23 Sep 2005 12:14:45 -0700 Subject: batch mkdir using a file list In-Reply-To: <1127501470.425241.212450@g43g2000cwa.googlegroups.com> References: <1127500054.273772.112470@g14g2000cwa.googlegroups.com> <1127501470.425241.212450@g43g2000cwa.googlegroups.com> Message-ID: <1127502885.612276.304560@g47g2000cwa.googlegroups.com> I am using bash shell on windows and I'm getting the error: TypeError: loop over non-sequence Is there any way around not messing with the text file. I want to batch generate the text lists as well. Thanks! From martin at v.loewis.de Sat Sep 17 10:48:45 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Sep 2005 16:48:45 +0200 Subject: Unicode-aware file shortcuts in Windows In-Reply-To: References: Message-ID: <432c2ccd$0$19472$9b622d9e@news.freenet.de> John Bauman wrote: > I see that another way is available here: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_int/shell_int_programming/shortcuts/shortcut.asp > I haven't tried, and I don't have the knowledge to convert the C++ to > Python, but it works at a lower level and may get around the bugs. It does > seem that the name of the file isn't Unicode in their method, either, so I'm > not sure if it'll work. There are two versions of the IShellLink interface: IShellLinkA and IShellLinkW. You need to use the *W version to pass characters outside the ANSI code page. Regards, Martin From txdiversity at hotmail.com Sun Sep 11 05:14:49 2005 From: txdiversity at hotmail.com (James) Date: 11 Sep 2005 02:14:49 -0700 Subject: Question about consistency in python language References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> Message-ID: <1126430089.717219.117770@g49g2000cwa.googlegroups.com> > Also, you shouldn't use "1", I mean "l", as a variable name. It gets confusing > because "l", I mean "1", looks a lot like "1", I mean "l". I have seen the same warnning above significantly several times. Is this problem originally came from the similarities between 'l' and '1' or from bad looking news-browser? Forgive me if it is out of your interests. -James GOLD From Tommy.Ryding at gmail.com Tue Sep 6 02:43:53 2005 From: Tommy.Ryding at gmail.com (Tommy.Ryding at gmail.com) Date: 5 Sep 2005 23:43:53 -0700 Subject: Controlling memory allocation In-Reply-To: <1125929796.323975.53230@g49g2000cwa.googlegroups.com> References: <1125871034.660265.208150@g43g2000cwa.googlegroups.com> <1125920561.351388.315390@o13g2000cwo.googlegroups.com> <1125929796.323975.53230@g49g2000cwa.googlegroups.com> Message-ID: <1125989033.104370.275630@g47g2000cwa.googlegroups.com> Yep! I redirect Free, Realloc and Malloc. (calloc is never used by Python). "The more I thoug..." That could be a possible problem. I will look in to it today and try and find out if that occurs and in that case how often. //T From leftwing17 at gmail.com Thu Sep 15 16:37:04 2005 From: leftwing17 at gmail.com (Adam Endicott) Date: 15 Sep 2005 13:37:04 -0700 Subject: Create and display an email References: <1126654259.131820.121010@o13g2000cwo.googlegroups.com> Message-ID: <1126816624.217904.29570@g14g2000cwa.googlegroups.com> Thanks for the MAPI suggestion. I did a bit more googling, and combined a few things, along with some trial and error to come up with something that works. Here it is for posterity: ================================ import win32com.client olMailItem = 0x0 obj = win32com.client.Dispatch("Outlook.Application.11") newMail = obj.CreateItem(olMailItem) newMail.Subject = 'A subject line' newMail.Body = 'Body, wonderful body' newMail.To = 'somebody at example.com' filename = r'c:\test.txt' newMail.Attachments.Add(filename) newMail.Display() ================================ Everything I saw just had "Outlook.Application" on line 3, but that was giving me an error: pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) Looking in the makepy generated file for Outlook, I saw: # This CoClass is known by the name 'Outlook.Application.11' referring to the Application class. So I tried that and it worked. I assume that the number will need to be changed for different versions of Outlook, or perhaps is only necessary for 11 (11+?). The other thing to note is that this still gave me an error: pywintypes.com_error: (-2147024770, 'The specified module could not be found.', None, None) if Outlook was not actually open and running. Also, I believe the filename for the attachment needs to be an absolute path. But with Outlook open, this code works and displays an email message with the specified Subject, Body, addressee, and attachment. Hopefully somebody else can find this useful. From mekstran at scl.ameslab.gov Sat Sep 10 11:48:08 2005 From: mekstran at scl.ameslab.gov (Michael Ekstrand) Date: Sat, 10 Sep 2005 10:48:08 -0500 Subject: What's the difference between VAR and _VAR_? In-Reply-To: <1126244885.487859.21660@z14g2000cwz.googlegroups.com> References: <1126239543.098530.98570@f14g2000cwb.googlegroups.com> <1126240211.306844.157130@f14g2000cwb.googlegroups.com> <1126241274.488280.122210@g49g2000cwa.googlegroups.com> <85KdneRT4a5AhLzeRVn-qg@speakeasy.net> <1126244885.487859.21660@z14g2000cwz.googlegroups.com> Message-ID: <20050910104808.701f3607.mekstran@scl.ameslab.gov> On 8 Sep 2005 22:48:05 -0700 "Johnny Lee" wrote: > I thought there must be something special when you named a VAR with > '_' the first character. Maybe it's just a programming style and I had > thought too much... It is just a programming style issue. In Python, variables and functions beginning with '_' are regarded by convention to be semi-private; essentially the Python equivalent of 'protected'. Since Python has no formal access specifications, conventions like this have been adopted. Likewise, '__' is private. Code using your code can bypass this, of course, but it's just a signal to the programmer 'avoid using this; it is an internal detail that may change.' Incidentally, epydoc regards all items beginning with '_' as private, and hides them from the public documentation it generates. And, in one project I'm working on, I use underscores to base/background/helper modules in a mechanism where modules are dynamically loaded (to prevent name collisions, since no dynamically loaded module will begin with an underscore). - Michael From no at spam Sun Sep 25 14:56:19 2005 From: no at spam (D H) Date: Sun, 25 Sep 2005 13:56:19 -0500 Subject: Reinhold Birkenfeld [Re: "Re: cElementTree clear semantics"] In-Reply-To: <3po99cFb5tpjU2@individual.net> References: <3po78hFbdl84U1@individual.net> <3po7i3Fbdl84U2@individual.net> <3po99cFb5tpjU2@individual.net> Message-ID: Reinhold Birkenfeld wrote: > D H wrote: > >>D H wrote: >> >>>Reinhold Birkenfeld wrote: >>> >>> >>>>Well, if I had e.g. a question about Boo, I would of course first ask >>>>here because I know the expert writes here. >>>> >>>>Reinhold >>> >>> >>>Reinhold Birkenfeld also wrote: >>> > If I had wanted to say "you have opinions? fuck off!", I would have said >>> >"you have opinions? fuck off!". >>> >>> >>>Take your own advice asshole. > > > And what's that about? I think it means you should fuck off, asshole. From timdoyle05 at yahoo.com Mon Sep 19 04:46:31 2005 From: timdoyle05 at yahoo.com (timdoyle05) Date: Mon, 19 Sep 2005 08:46:31 -0000 Subject: Python and Unix Commands Message-ID: Hi, I have a question relating to how Unix commands can be issued from Python programs. Im am currently writing a large test script in python and I need this script to call three other separate Python scripts, where each one executes in it own thread of control. I would like to use a Unix command to get each script to run in its own shell. I have tried using the "Commands" module but after I issue the first "command", execution blocks until I kill the called script. Is there a way around this?? Thanks for your time, I would really appreciate any assistance, Tim. From rkern at ucsd.edu Wed Sep 28 06:31:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 28 Sep 2005 03:31:28 -0700 Subject: number of python users In-Reply-To: References: Message-ID: Magnus Lycka wrote: > Bryan wrote: > >>is there a rough estimate somewhere that shows currently how many python >>1.5 vs 2.2 vs 2.3 vs 2.4 users there are? have a majority moved to 2.4? >>or are they still using 2.3? etc... > > Why do you want to know that? So he can make an informed decision about how far back he should maintain compatibility? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tim.peters at gmail.com Fri Sep 2 10:52:21 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 2 Sep 2005 10:52:21 -0400 Subject: OpenSource documentation problems In-Reply-To: <7xzmqwkvu8.fsf@ruckus.brouhaha.com> References: <4317BEAC.6030804@holdenweb.com> <7xzmqwkvu8.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae05090207522914e0c3@mail.gmail.com> [Paul Rubin] > Until not that long ago, it was possible to submit sf bugs without > being logged into sf. Why did that change? To reduce tracker spam, to reduce tracker vandalism, and to make it possible to contact submitters when needed. From virusalert at zrlocal.net Thu Sep 15 08:11:33 2005 From: virusalert at zrlocal.net (virusalert at zrlocal.net) Date: Thu, 15 Sep 2005 14:11:33 +0200 Subject: FOUND VIRUS IN MAIL from to Message-ID: <200509151211.j8FCBSXA032608@gigant.zrlocal.net> V I R U S A L E R T Our viruschecker found a VIRUS in your email to "". We stopped delivery of this email! Now it is on you to check your system for viruses In file: /usr/local/mav/basedir/j8FCBSXA032608/Part_2.zip Found the W32/Netsky.z at MM!zip virus !!! For your reference, here are the headers from your email: ------------------------- BEGIN HEADERS ----------------------------- Received: from [62.108.101.65] by gigant.zrlocal.net [212.200.56.13] with SMTP id j8FCBSXA032608; Thu Sep 15 14:12:15 2005 +0200 From: python-list at python.org To: postar at zrenjanin.org Subject: Information Date: Thu, 15 Sep 2005 14:11:33 +0200 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0002_000062BC.00007C7C" X-Priority: 1 X-MSMail-Priority: High -------------------------- END HEADERS ------------------------------ From kay.schluehr at gmx.net Wed Sep 7 13:17:10 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 Sep 2005 10:17:10 -0700 Subject: PEP-able? Expressional conditions References: <1126088966.277030.267410@g14g2000cwa.googlegroups.com> Message-ID: <1126113430.910646.69290@g44g2000cwa.googlegroups.com> Terry Hancock wrote: > On Wednesday 07 September 2005 05:29 am, Kay Schluehr wrote: > > Instead of pushing statements into expressions one can try to do it the > > other way round and model expressions with the functionality of > > statements. > > > Alternative syntax proposals: > > > > (a) (COND1,EXPR1) || (COND2,EXPR2) > > (b) (COND1,EXPR1) case (COND2,EXPR2) > > (c) (COND1,EXPR1) owise (COND2,EXPR2) > > (d) (COND1,EXPR1) ? (COND2,EXPR2) > > You appear to be reinventing the C "ternary operator". This is > definitely a dead horse. There was already a PEP, and it was > refused. Well, I'm not inspired by C and the operator is not ternary but binary and associative. Nevertheless the behaviour of the ternary condition operator exists as a limit case. The expression becomes more a kind of a horizontal squeezed switch. Therefore the "case" keyword proposal. It might become more obvious if one chains the expression using more terms: (a') (COND1,EXPR1) || (COND2,EXPR2) || ... || (CONDk,EXPRk) (b') (COND1,EXPR1) case (COND2,EXPR2) case ... case (CONDk,EXPRk) > If you actually want this, you're going to have to implement it > with a function: > > def ternary(condition, true_result, false_result): > if condition: > return true_result > else: > return false_result No, as I explained it is not a ternary operator and it can't easily be implemented using a Python function efficiently because Python does not support lazy evaluation. One usually does not want to evaluate all conditions as well as all the results ( when passing them into the function ) but evaluate conditional expressions sequentially and stop at the first true condition. Well I would indeed like to go even further and introduce lazy tuples this way but I wanted to notice the responses to an obvious use case first. Kay From peter at engcorp.com Tue Sep 20 09:05:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Sep 2005 09:05:49 -0400 Subject: Question about smtplib, and mail servers in general. In-Reply-To: References: Message-ID: <9_6dnY_ct8a0lK3eRVn-qQ@powergate.ca> Chris Dewin wrote: > Hi. I've been thinking about using smtplib to run a mailing list from my website. > > s = smtplib.SMTP("server") > s.sendmail(fromaddress, toaddresess, msg) > > I know that in this instance, the toaddresses variable can be a variable > of type list. > > Suppose the list contains well over 100 emails. Would that create some > sort of drain on the mail server? Would I be better off doing it in some > other way? Definitely consider a proper mailing list program like Mailman, as Daniel suggested. In any case, unless the mail server will allow "relaying", which most don't these days (to prevent spamming), then it won't work the way you are hoping unless *all* the 100 addresses are local ones, to be delivered to users on the server you are sending the mail to. If the addresses are scattered all over the planet, and the server allows relaying, then it's intended for exactly this sort of use (other than if it's spam ;-) ), and no, you won't be putting a "drain" on the server. -Peter From tjreedy at udel.edu Sun Sep 11 15:27:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2005 15:27:29 -0400 Subject: Question about consistency in python language References: <1126220592.277414.41020@o13g2000cwo.googlegroups.com> <1126430089.717219.117770@g49g2000cwa.googlegroups.com> Message-ID: "Robert Kern" wrote in message news:dg11p2$cbd$1 at sea.gmane.org... > In many, many fonts 'l' and '1' look close enough to be easily mistaken > for one another In the default font used by Outlook Express, displayed on my 1078x786 screen, the only difference I can see, using a magnifying glass on side-by-side characters (l1 = el-onel), is that 'el' is one pixel taller than the 'one'. The serifs appear the same, down to the anti-alias gray pixels. (To my surprise, this makes 'lbdk' a pixel taller than uppercase chars!) Now I know ;-). But 1 isolated from l is still difficult to distinguish. Terry J. Reedy From no at spam Fri Sep 16 10:33:31 2005 From: no at spam (D H) Date: Fri, 16 Sep 2005 09:33:31 -0500 Subject: multiple replaces In-Reply-To: <1126868971.917556.214610@g44g2000cwa.googlegroups.com> References: <1126868971.917556.214610@g44g2000cwa.googlegroups.com> Message-ID: You can use python's re.sub function. But also look into full fledged template engines like Cheetah. import re txt="""

whatever

the machine with bing

10% of boo is foo

""" h1=txt.replace("%","%%") h3 = re.sub("", "%(\\1)s", h1) house="something awfull" tree="something beautifull" print h3 % locals() From Ara.T.Howard at noaa.gov Fri Sep 9 17:27:47 2005 From: Ara.T.Howard at noaa.gov (Ara.T.Howard) Date: Fri, 9 Sep 2005 15:27:47 -0600 Subject: python object model diagram Message-ID: anyone out there know where i might find a python object model diagram? cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | Your life dwells amoung the causes of death | Like a lamp standing in a strong breeze. --Nagarjuna =============================================================================== From __peter__ at web.de Thu Sep 8 03:49:06 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2005 09:49:06 +0200 Subject: generator object, next method References: <1126164425.475226.143510@g14g2000cwa.googlegroups.com> Message-ID: simonwittber at gmail.com wrote: >>>> gen = iterator() >>>> gen.next > Behind the scene, gen.next is bound to _, i. e. it cannot be garbage-collected. Then... >>>> gen.next > a new method wrapper is created and assigned to _, and the previous method wrapper is now garbage-collected. The memory location is therefore available for reuse for... >>>> gen.next > yet another method wrapper -- and so on. >>>> gen.next > >>>> gen.next is gen.next > False > > > What is behind this apparently strange behaviour? (The .next method > seems to alternately bind to two different objects) But it isn't. What seems to be the same object are distinct objects at the same memory location. See what happens if you inhibit garbage-collection by keeping a reference of the method wrappers: >>> it = iter("") >>> [it.next for _ in range(5)] [, , , , ] Peter From mark.dufour at gmail.com Tue Sep 20 08:45:10 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 20 Sep 2005 14:45:10 +0200 Subject: Release of Shed Skin 0.0.2: Easy Windows/OSX Installation Message-ID: <8180ef69050920054519e755ab@mail.gmail.com> Hi! Shed Skin is an experimental Python-to-C++ compiler. Along with GNU/Linux, version 0.0.2 should now also install easily under Windows 2000/XP and OSX. Please give it a try and let me know if there are still some problems. If you would like to help me improve Shed Skin, please send me small code snippets, preferrably extracted from real-life use cases, that the compiler has problems with. Thanks to everyone who has helped me out, especially Khalid, Leonardo and Luis here on python-list, and Denis de Leeuw Duarte right here in the street :-) http://shedskin.sourceforge.net http://shed-skin.blogspot.com thanks! mark. From not-even at dispsable.address.this.time Fri Sep 16 01:36:26 2005 From: not-even at dispsable.address.this.time (Jules Dubois) Date: Thu, 15 Sep 2005 23:36:26 -0600 Subject: Self reordering list in Python References: Message-ID: <3671871.jrSUlp4qDF@knode.kde> On Thursday 15 September 2005 07:14, Laszlo Zsolt Nagy () wrote: > Do you know how to implement a really efficient self reordering list in > Python? Yes. > (List with a maximum length. When an item is processed, it > becomes the first element in the list.) Search for "move to front list". If you want a much bigger improvement in speed -- O(N * log N) instead of O(N**2) -- search for "splay tree"; of course, the algorithm is more complex and the optimized algorithm is even more complex. > Of course I could implement this in pure Python, I just wonder if there is > a faster implementation that uses some cool feature of the standard > library. (Maybe a C implementation could be added to the collections > module?) Yes, you could write a C-language extension for more speed. From mail at tuxipuxi.org Thu Sep 29 10:57:28 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Thu, 29 Sep 2005 16:57:28 +0200 Subject: A Moronicity of Guido van Rossum In-Reply-To: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> References: <1128003857.930444.47650@g14g2000cwa.googlegroups.com> Message-ID: <200509291657.28985.mail@tuxipuxi.org> On Thursday 29 September 2005 16:24, Xah Lee wrote: > A Moronicity of Guido van Rossum > > Xah Lee, 200509 > Assuming you want to reach people to convince them your position is right, why don't you try that in proper language? "moron" occured 7 times in your not too long text, that doesn't let you look like a tech moron or a math moron, but just like a moron. From gandalf at designaproduct.biz Fri Sep 16 03:41:05 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Fri, 16 Sep 2005 09:41:05 +0200 Subject: How to clear screen in Python interactive shell mode? In-Reply-To: <1126844313.379059.207200@z14g2000cwz.googlegroups.com> References: <1126844313.379059.207200@z14g2000cwz.googlegroups.com> Message-ID: <432A7711.1050506@designaproduct.biz> A. L. wrote: >In Python interactive mode, is there some function acting like 'clear' >command in bash? Could somebody here give some advice? > > Under Linux/UNIX system (on x86 at least) you can use the CTRL+L combination to clear the screen. I do not now similar for Windows and MACs. Les From leszczynscyATnospam.yahoo.com.nospam Tue Sep 13 19:54:16 2005 From: leszczynscyATnospam.yahoo.com.nospam (Andy Leszczynski) Date: Tue, 13 Sep 2005 18:54:16 -0500 Subject: Manging multiple Python installation In-Reply-To: References: Message-ID: Jeremy Jones wrote: > I guess I'm still having a hard time understanding "what does it > matter?". I was under impression that configure embeds the prefix in the build itself. I was concerned to have to preform the configure/make every time I change the destination path. It turns out that the makefile produced by configure uses prefix only for the install. Thus it is not big deal anymore. Thx for all commnets. A. From dmbkiwi at yahoo.com Fri Sep 2 19:04:34 2005 From: dmbkiwi at yahoo.com (Dumbkiwi) Date: Sat, 03 Sep 2005 11:04:34 +1200 Subject: unicode and os.system Message-ID: I've got a rather large python script that I write and maintain. It has some interaction with other programmes on the linux/kde desktop through the dcop interface. This script also uses the gettext module to enable the output of the script to be translated into several languages, including utf-8 encoded text. However, when I issue a dcop call to an application (which is a docker application that can display text above an icon), the operation fails with: Traceback (most recent call last): File "/home/matt/karamba/lwbkup/liquid_weather.py", line 2970, in widgetUpdated os.system('dcop kxdocker docker changeTextByName Current "%s : %s"' %(_(situtext), weather.temperature())) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 2: ordinal not in range(128) _(situtext) is a variable containing a unicode string. My python environment has ascii as its encoding for stdout >>> import sys >>> print sys.stdout.encoding ANSI_X3.4-1968 the dcop call I'm using requires a QString variable where the _(situtext) is. Can anyone help me to work through this issue? I'm a bit lost as to where to start. Thanks Matt From g.horvath at gmx.at Wed Sep 28 17:56:28 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Wed, 28 Sep 2005 23:56:28 +0200 Subject: Will python never intend to support private, protected and public? In-Reply-To: <7xk6h0zxnm.fsf@ruckus.brouhaha.com> References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > Gregor Horvath writes: > >>>to be able to share private variables with other classes under certain >>>circumstances, it's better to use something like C++'s "friend" >>>declaration, where you can export the variables to a specific other class. >> >>That assumes that you always know for sure that the given variable >>will always be used as a private/friend variable in the lifecycle of >>the software. > > > Obviously if you find you need to use it in another place later, you > update the declaration. The idea is for you (or an automatic tool) to If its your code this is possible, but if not and the maintainer is not willing or able to change it, then you have a problem. The fact that in other languages there are wired tricks to get to private instance variables is a strong indicator that there is a need for that. Guided freedom is better than enforced authority. -- Greg From gsakkis at rutgers.edu Sun Sep 25 20:43:19 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sun, 25 Sep 2005 20:43:19 -0400 Subject: Struggling with basics References: Message-ID: <1127695402.2115a35b5592bb41deafc047eb432880@teranews> "Jason" wrote: > What I'd like to know is do you think it would be better to sort the > list in memory, or print it out sorted? If the latter, then naturally > I'd need to change the showScores section to show the list in a reverse > order. But, would sorting the list in memory be more effective? The list *is* sorted; the thing is that it is in ascending order (from lowest to highest) but you would rather have it in descending. There are (at least) two alternatives: 1. Keep the list as it is now in ascending order and print it in reverse. In python 2.4, this is as elegant and efficient as it can, using the reversed() builtin function. Just replace in showScores "for score,name in self.hiScores" with "for score,name in reversed(self.hiScores)". reversed() returns an iterator over the sequence, not a new list, so the memory overhead is minimal. 2. Instead of storing (score,name) pairs, store (-score,name). When a list of the latter is in ascending order, the former is in descending. In this case of course, you have to make sure that showScores() and lastScore() return the actual (positive) score, not the stored (negative) one. I would go for the first alternative but YMMV. George From no at spam Sun Sep 25 14:05:20 2005 From: no at spam (D H) Date: Sun, 25 Sep 2005 13:05:20 -0500 Subject: cElementTree clear semantics In-Reply-To: References: Message-ID: Igor V. Rafienko wrote: > This gave me the desired behaviour, but: > > * It looks *very* ugly > * It's twice as slow as version which sees 'end'-events only. > > Now, there *has* to be a better way. What am I missing? > Try emailing the author for support. From buffer_88 at hotmail.com Sat Sep 24 13:13:30 2005 From: buffer_88 at hotmail.com (George) Date: 24 Sep 2005 10:13:30 -0700 Subject: Parsing an HTML a tag Message-ID: <1127582010.030044.314500@g44g2000cwa.googlegroups.com> How can I parse an HTML file and collect only that the A tags. I have a start for the code but an unable to figure out how to finish the code. HTML_parse gets the data from the URL document. Thanks for the help def HTML_parse(data): from HTMLParser import HTMLParser parser = MyHTMLParser() parser.feed(data) class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): def handle_endtag(self, tag): def read_page(URL): "this function returns the entire content of the specified URL document" import urllib connect = urllib.urlopen(url) data = connect.read() connect.close() return data From fredrik at pythonware.com Thu Sep 1 15:53:55 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Sep 2005 21:53:55 +0200 Subject: Equivalent for an internal write in Python ? References: <4317591a$0$18643$14726298@news.sunsite.dk> Message-ID: Madhusudan Singh wrote: > I am looking to write a formatted string to a string variable : > > Say I have 1.067e-01, I need to write 106.700 to some string. > > In Fortran 95, this would be accomplished with a : > > character(len=7) :: stringvar > real :: stringval > > ... > > write(stringvar,'(f7.3)') stringval > > How does one do something like this in Python ? I need a string formatted in > this way for one of my applications. stringvar = "%.3f" % stringval for details, see http://docs.python.org/tut/node9.html http://docs.python.org/lib/typesseq-strings.html From vincent at visualtrans.de Sun Sep 4 02:53:26 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 4 Sep 2005 08:53:26 +0200 Subject: Problems with Python for Windows extensions References: <1125760475.488680.17070@z14g2000cwz.googlegroups.com> Message-ID: "KK" schrieb im Newsbeitrag news:1125760475.488680.17070 at z14g2000cwz.googlegroups.com... | the code below is taken from M$ technet as an example on using vb | script to do a replace all in word: | | Const wdReplaceAll = 2 | | Set objWord = CreateObject("Word.Application") | objWord.Visible = True | | Set objDoc = | objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") | Set objSelection = objWord.Selection | | objSelection.Find.Text = "Contoso" | objSelection.Find.Forward = True | objSelection.Find.MatchWholeWord = True | | objSelection.Find.Replacement.Text = "Fabrikam" | objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll | | | | | I did a rewrite and made it pythonic: | | from win32com.client import * | | wdReplaceAll = 2 | | objWord = Dispatch("Word.Application") | objWord.Visible = True | | objDoc = | objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc") | objSelection = objWord.Selection | | objSelection.Find.Text = "Contoso" | objSelection.Find.Forward = True | objSelection.Find.MatchWholeWord = True | | objSelection.Find.Replacement.Text = "Fabrikam" | objSelection.Find.Execute (Replace = wdReplaceAll) | | | However, the document juz loaded up in word but no action was taken. I | am using Word 2003. Any ideas? KK, Your example seemed to work fine for me (Python2.4, Pythonwin build 204, Word 2003) One thing: since you say your document loads up fine I don't know if it is just a typo, but make sure you follow the rules of backslash literals in path names. In other words: "K:\Development\Fabricbase\prod\Test.doc" should read either r"K:\Development\Fabricbase\prod\Test.doc" (note the leading r for raw string or "K:\\Development\\Fabricbase\\prod\\Test.doc" or "K:/Development/Fabricbase/prod/Test.doc" -- Vincent Wehren From om at oliviermigeon.com Mon Sep 5 05:03:26 2005 From: om at oliviermigeon.com (Olivier) Date: Mon, 05 Sep 2005 11:03:26 +0200 Subject: mod_python: what's going on here? In-Reply-To: <1125895128.704350.51270@g47g2000cwa.googlegroups.com> References: <1125895128.704350.51270@g47g2000cwa.googlegroups.com> Message-ID: <431c09d5$0$32757$636a15ce@news.free.fr> Robert J. Hansen a ?crit : > Does anyone have any experience with mod_python on OS X/Apache > environments? Can anyone shed some light on 500s that don't leave > traces in the error logs, or what precise incantation I need to make > mod_python start serving up scripts? Here is a setup that works for me on 10.3, with Apache2 2.54, python 2.4.1 and mod_python 3.1.4, all installed from source. This should probably work also with your python from fink. Apache2: ./configure --enable-mods-shared=all --enable-so Python: ./configure mod_python: ./configure --enable-so > Also, if this is not appropriate for this group, does anyone know of a > Python group for which this is more appropriate? The mod_python mailing list ? At http://www.modpython.org/ . Regards, Olivier From n00m at narod.ru Fri Sep 9 07:17:23 2005 From: n00m at narod.ru (n00m) Date: 9 Sep 2005 04:17:23 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126129942.736374.260770@g44g2000cwa.googlegroups.com> <1126161203.409605.27880@f14g2000cwb.googlegroups.com> <1126196908.479379.22010@z14g2000cwz.googlegroups.com> <1126201801.250692.27750@f14g2000cwb.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> Message-ID: <1126264643.000271.326640@f14g2000cwb.googlegroups.com> Oh! Seems you misunderstand me! See how the last block in your code should look: for tc in range(10): _ = stdin.readline() sequence = [int(ch) for ch in stdin.readline().split()] supers = supernumbers(sequence) print len(supers) for i in supers: print i, When I submitted it (for the 1st time) without > for tc in range(10): the e-judge counted the output of your code as Wrong Answer; just because the e-judge got an answer for only the very 1st testcase (I think in it was not too large input data). From godoy at ieee.org Thu Sep 29 16:20:54 2005 From: godoy at ieee.org (Jorge Godoy) Date: 29 Sep 2005 17:20:54 -0300 Subject: Parser suggestion Message-ID: <87ek77k4m1.fsf@ieee.org> Hi! I'm needing a parser to retrieve some information from source code -- including parts of code -- from Fortran, to use in a project with a documentation system. Any recommendations on a Python app or parser that I could use for that? Thanks, -- Jorge Godoy From jstroud at mbi.ucla.edu Sat Sep 24 15:49:12 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 24 Sep 2005 12:49:12 -0700 Subject: Using '__mul__' within a class In-Reply-To: <1127576164.489710.291280@g49g2000cwa.googlegroups.com> References: <1127576164.489710.291280@g49g2000cwa.googlegroups.com> Message-ID: <200509241249.12125.jstroud@mbi.ucla.edu> I think the gist of your problem is that you are re-binding self in the method. Here is a simpler example of your problem: py> def doit(c): ... c = 5 ... print "c in the method is", c ... py> c = 42 py> print "c before calling the method is", c c before calling the method is 42 py> doit(c) c in the method is 5 py> print "c after calling the method is", c c after calling the method is 42 James On Saturday 24 September 2005 08:36, Gerard Flanagan wrote: > Hello > > I'm pretty new to Python and was wondering why the 'Square' method in > the following code doesn't work. It doesn't fail, just doesn't do > anything ( at least, not what I'd like! ). Why doesn't 'A.a' equal 2 > after squaring? > TIA. > > > class FibonacciMatrix: > def __init__( self ): > self.a = 1 > self.b = 1 > self.c = 0 > > def __mul__( self, other ): > result = FibonacciMatrix() > result.a = self.a * other.a + self.b * other.b > result.b = self.a * other.b + self.b * other.c > result.c = self.b * other.b + self.c * other.c > return result > > def Square( self ): > self *= self > > > A = FibonacciMatrix() > A.Square() > > print A.a #prints '1' > > A = FibonacciMatrix() > B = A * A > > print B.a #prints '2' > > ------------------------------ -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From firstname.lastname at iki.fi-spam Wed Sep 7 02:50:30 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 07 Sep 2005 09:50:30 +0300 Subject: Replacement for lambda - 'def' as an expression? References: <1125996559.130055.154400@z14g2000cwz.googlegroups.com> <7xr7c2w4rl.fsf@ruckus.brouhaha.com> Message-ID: <87psrl1idl.fsf@sme.intra.citec.fi> Paul Rubin writes: > Sybren Stuvel writes: > > An example: > > > > def generate_randomizer(n, m): > > randomizer = def(x): > > return x ** n % m > > > > return randomizer > > You're a little bit confused; "name" doesn't necessarily mean "persistent > name". You could write the above as: > > def generate_randomizer (n, m): > def randomizer(x): > return pow(x, n, m) > return randomizer But if you could do anonymous blocks, you could just write something like: def generate_randomizer (n, m): return def (x): return pow (x, n, m) Personally, I don't mind naming local functions in practice (and Python syntax doesn't lend itself very well to anonymous blocks) but rather, the nuisance is that I feel there's just plain something wrong with it. It's less beautiful than it could be. Luckily, the last time I followed the discussion on this topic in c.l.p, some bright mind whose name escapes me now pointed out the craziness of _having to_ name functions by comparing it to the situation where you'd have to bind any literal objects to symbols before you could use them. Like: def return_fixed_number (): res = 42 return res or: arg1 = "foo" arg2 = 42 arg3 = baz () myfunction (arg1, arg2, arg3.xyzzy ()) Sure, you don't lose any expressiveness in that: if you had to name any object before using it, you could write all the same programs that you can in the current Python. But it's the expressiveness of your mind that gets harpooned: you'll have to keep part of your focus on these extraneous local variables instead of thinking only in terms of values where only values matter. -- firstname.lastname at iki.fi -- Today is the car of the cdr of your life. From snail at objmedia.demon.co.uk Fri Sep 30 19:54:56 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Sat, 1 Oct 2005 00:54:56 +0100 Subject: Python profiler References: Message-ID: In message , Celine & Dave writes >I am trying to find a profiler that can measure the >memory usage in a Python program. >I would like to >gather some statistics about object usages. For Python Memory Validator. Apply for beta here: http://www.softwareverify.com/beta.php?product=PMVB000 >example, I would like to be able to see how much time >it takes to search for an item in a dict object, That is something for a performance profiler, not a memory profiler. Python Performance Validator will help you there. >how >many times it has to access the symbol table to >retrieve a specific item, and things like that. Python Coverage Validator will help you there. Python Performance Validator will help you there. http://www.softwareverify.com Windows NT/2000/XP/and above(vista, etc) Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Sep 5 09:34:23 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 05 Sep 2005 09:34:23 -0400 Subject: Proposal: add sys to __builtins__ References: Message-ID: In article , Rick Wotnaz wrote: > Michael Hoffman wrote in > news:df7jlu$1te$1 at gemini.csx.cam.ac.uk: > > > What would people think about adding sys to __builtins__ so that > > "import sys" is no longer necessary? This is something I must > > add to every script I write that's not a one-liner since they > > have this idiom at the bottom: > > > > if __name__ == "__main__": > > sys.exit(main(sys.argv[1:])) > > > > [...] > > > > In short, given the wide use of sys, its unambiguous nature, and > > the fact that it really is built-in already, although not > > exposed as such, I think we would be better off if sys were > > always allowed even without an import statement. > > +1 here. As far as I'm concerned, both os and sys could be special- > cased that way. That said, I would guess the likelihood of that > happening is 0. While I'm mildly uncomfortable with the precedent that would be set by including the contents of "sys" as built-ins, I must confess my objections are primarily aesthetic: I don't want to see the built-in namespace any more cluttered than is necessary -- or at least, any more than it already is. But "os" is another matter -- the "os" module contains things which might well not be present in an embedded Python environment (e.g., file and directory structure navigation, stat). Do you really want to force everyone to deal with that? Is it so much more work to add "import os" to those Python programs that require it? Of course, you might counter "why should we force everybody else to type `import os' just in case somebody wants to imbed Python?" But then, why don't we just include the whole standard library in __builtins__? Or, since that would be too much, maybe we survey the user community and include the top fifteen most included modules! Where do you draw the line? Do you really want to hard-code user opinions into the language? Right now, we have a nice, simple yet effective mechanism for controlling the contents of our namespaces. I don't think this would be a worthwhile change. -1. -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From mfranklin1 at gatwick.westerngeco.slb.com Thu Sep 8 09:17:45 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 08 Sep 2005 14:17:45 +0100 Subject: Printer List from CUPS In-Reply-To: <1126184719.267127.129850@f14g2000cwb.googlegroups.com> References: <1126175587.426865.138130@g14g2000cwa.googlegroups.com> <1126184719.267127.129850@f14g2000cwb.googlegroups.com> Message-ID: Mike Tammerman wrote: > I am using Ubuntu. pycups seems to be not existed any more. > > Mike > Yeah as I said if you're using a redhat based distro... However you could try getting the redhat / fedora rpm that provides pycups and installing it? I would ask on the Ubuntu list, I know they are a very python friendly bunch :) Martin From mwm at mired.org Fri Sep 30 20:35:23 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 30 Sep 2005 20:35:23 -0400 Subject: Google Not Universal Panacea References: Message-ID: <86hdc2nkfo.fsf@bhuda.mired.org> Steve Holden writes: > However, > > >> Are people really too lazy to do elementary research on Google? > > goes a bit too far in imputing motives to the enquirer and overlooking > the fact that there are some very good reasons for *not* using Google. Ok, *what* are the reasons for not using Google? I agree with Steve - there's no reason to impugn the motives of someone looking for answers. They may not realize what an excellent resource Google is. People have to learn how to find answers, just like they have to learn how to use Python. Suggesting that they check Google - if they didn't say they already did - is perfectly reasonable. Assuming they are to lazy to do so is something else again. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From maxwell.roger at googlemail.com Tue Sep 27 06:24:15 2005 From: maxwell.roger at googlemail.com (Roger) Date: 27 Sep 2005 03:24:15 -0700 Subject: Telephony project References: <1127758835.527555.217870@g47g2000cwa.googlegroups.com> <7x64snbr0l.fsf@ruckus.brouhaha.com> Message-ID: <1127816655.712927.289850@g14g2000cwa.googlegroups.com> "CheckOn" is the working name for my project. Our church community has many elderly who are at home but close to assisted living placements. Many do not have family and rely on volunteer caretakers and lunch providers for their socialization. We are trying to make phone contact with these members to check on their needs, wellbeing, and ability to take care of themselves. In sharing that information with other denominations in our city, we discovered that others were having identical issues. The numbers are larger than we anticipated. Thus the project. Thanks for your interest. From franz.steinhaeusler at gmx.at Wed Sep 14 07:41:30 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 14 Sep 2005 13:41:30 +0200 Subject: some advice about Python GUI apps References: <1126697171.226696.234550@g44g2000cwa.googlegroups.com> Message-ID: <1l2gi1tbng2l32o6ja7gemn91l5hu5aepf@4ax.com> On 14 Sep 2005 04:26:11 -0700, mitsura at skynet.be wrote: >Hi, > >I am writing a program in Python and I am using wx.Python for the GUI. >I have no prior GUI and Python experience so that's why I turn to the >specialists for aid. Hello Kris, I think the specialists are in the wxPython-mailing list ;) http://www.wxpython.org/maillist.php >Basically, my app is a wx.tree object with items. You can click on each >item and set some properties of the item (Pydata). To set the >properties of an item you click on the item and then a 'Set item >properties' window pops up. You mean a wx.TreeCtrl? I don't understand exactly what you mean with "properties". Do you have a sample program? Sorry for not helping much. >However, I am looking for a way that you can only open 1 property >window per item. If I click on an item the 'Set item properties' >windows open but when I return to the tree window and select the same >item, I can open an additional 'set properties' window. >This leads to >all kind of C++ errors because these properties windows seems to >interfere for some reason. I don't have enough OO/Python/GUI knowledge >yet to fully understand what actually happens. >Basically, what I want is that when you want to open an items property >window and the window is alread open that in stead of opening a new >window, the window the is already open pops to the foreground. Any >ideay how I can implement this. > >Another solution would be to start the properties windows in a >'synchronous' mode, meaning that if this window is open, that you can't >manipulate the tree window anymore (~like in Word when you open the >'open file' window, you can't edit your doc until you this window is >closed again). Is the properties window a wx.Dialog? If you show it with ShowModal(), then you must finish with it, before you can select another tree node. >I hope this makes some sense. > >Any help much appreciated. > >Kris > >Ps.: any refs to good OO/Python GUI books are also welcome (or URLs) There is a wxPython book in process, and it is publication is estimated around end of this year. -- Franz Steinhaeusler From dalcinl at gmail.com Fri Sep 30 17:00:09 2005 From: dalcinl at gmail.com (Lisandro Dalcin) Date: 30 Sep 2005 14:00:09 -0700 Subject: Opinion on Pyrex In-Reply-To: References: Message-ID: <1128114009.725631.267890@f14g2000cwb.googlegroups.com> That's the reason I am using SWIG http://www.swig.org For C++ classes, you can get a working Python module autmatically. It also has advanced features, like "directors", enablig subclassing from Python (to be used in de C++ side). However, I should warn you SWIG is not as friendly as Pyrex. But I used it to wrap nontrivial libraries written in C and C++. From billiejoex at fastwebnet.it Mon Sep 12 11:02:31 2005 From: billiejoex at fastwebnet.it (billiejoex) Date: Mon, 12 Sep 2005 17:02:31 +0200 Subject: pcapy listen on multiple devices Message-ID: Hi all. I noticed that with the original pcap sniffing library it is possible to listen on multiple devices by using "select()" or "poll()" function. These function aren't present in pcapy module. Do you got any suggestion to avoid this problem? From rkern at ucsd.edu Wed Sep 7 20:05:50 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 07 Sep 2005 17:05:50 -0700 Subject: Need help with C extension module In-Reply-To: <1126133396.686688.160760@o13g2000cwo.googlegroups.com> References: <1126131877.351395.64850@f14g2000cwb.googlegroups.com> <1126133396.686688.160760@o13g2000cwo.googlegroups.com> Message-ID: chris wrote: > Any tips on what the pyrex should look like for my example? # Untested and off the top of my head; please read the Pyrex # documentation and correct my mistakes before using any of this! # Notably, I'm pretty sure the __init__ and __dealloc__ bits are # slightly wrong. cdef extern from "Python.h": void *PyMem_Malloc(unsigned int size) void PyMem_Free(void *buf) ctypedef struct In: int x char *s # ... ctypedef struct Out: int y char *s # ... cdef Out *func(Int *x, Out *y) cdef class Output: cdef Out *output def __init__(self): self.output = PyMem_Malloc(sizeof(Out)) def __dealloc__(self): PyMem_Free(self.output) property y: def __get__(self): return self.output.y # ... cdef class Input: cdef In *input def __init__(self): self.input = PyMem_Malloc(sizeof(In)) def __dealloc__(self): PyMem_Free(self.input) property x: def __get__(self): return self.input.x def __set__(self, value): self.input.x = value # ... def func(self): output = Output() func(self.input, output.output) return output -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From alessandro.bottoni at infinito.it Mon Sep 12 12:35:58 2005 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Mon, 12 Sep 2005 16:35:58 GMT Subject: Is it possible to detect if files on a drive were changed without scanning the drive? References: <3olkhcF6g6vaU1@individual.net> Message-ID: Claudio Grondi wrote: > After connecting a drive to the system (via USB > or IDE) I would like to be able to see within seconds > if there were changes in the file system of that drive > since last check (250 GB drive with about four million > files on it). > > How to accomplish this? (best if providing > directly a Python receipe for it :-) > Do available file systems have something like > archive attribute assigned to the root directory > of the drive? > I suppose not. Am I right? On Linux there is the FAM (File Alteration Module) for this, as long as I know. Maybe Python has a wrapper/binding for it. > I ask this question having Microsoft Windows 2000 > and Windows proprietary NTFS file system in mind, > but I am also interested to know it about Linux or > Unix file systems. As long as I know, on Windows there are a few specific "hooks" to perform such a task. They are provided by the MS API for the NTFS/HPFS file systems. I do not think Python implements anything so "low level", anyway. Check the docu to be sure. > I know, that looking for the archive attribute of the > top directories doesn't help when the change > happened to files somewhere deeper in the > hierarchy of directories. Right. It does not help. Consider this: if are accessing a network file system, you can intercepts the calls to the virtualization layer (NFS or NetBIOS). Most likely, Python can support you in performing this task. HTH ----------------------------------- Alessandro Bottoni From http Mon Sep 19 10:14:55 2005 From: http (Paul Rubin) Date: 19 Sep 2005 07:14:55 -0700 Subject: C#3.0 and lambdas References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <7xpsr5uotc.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > "Is anyone truly attached to nested tuple function parameters; 'def > fxn((a,b)): print a,b'? /.../ > > Would anyone really throw a huge fit if they went away? I am willing > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > people are up for it." It's not just function parameters, it works in assignments too: s = ((1,2), (3,4)) ... ((x1,y1), (x2,y2)) = s Why is there such eagerness to remove it? The corresponding feature in Lisp is called destructuring-bind and it's quite useful. From amk at amk.ca Thu Sep 1 10:16:18 2005 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 01 Sep 2005 09:16:18 -0500 Subject: OpenSource documentation problems References: <43164595$0$97143$ed2619ec@ptn-nntp-reader03.plus.net> <200508312026.04152.hancock@anansispaceworks.com> <1125571915.715672.178840@g44g2000cwa.googlegroups.com> <1125576273.014582.204850@z14g2000cwz.googlegroups.com> Message-ID: <6MSdnRqq74mvkIreRVn-tQ@speakeasy.net> On 1 Sep 2005 05:04:33 -0700, Paul Boddie wrote: > Please note that I'm not labelling you as a troll. No, he's simply barking mad. I was amused by a rec.arts.sf.written discussion [1] where Lee complains that Jonathan Swift (1667-1745)'s writing was unclear in style; apparently he's not aware that conventions and styles change over time. --amk [1] http://groups.google.com/group/alt.usage.english/msg/0ec9871395fc90d3 From jeremy+python at jeremysanders.net Thu Sep 22 16:40:20 2005 From: jeremy+python at jeremysanders.net (Jeremy Sanders) Date: Thu, 22 Sep 2005 21:40:20 +0100 Subject: Wrapping classes Message-ID: Is it possible to implement some sort of "lazy" creation of objects only when the object is used, but behaving in the same way as the object? For instance: class Foo: def __init__(self, val): """This is really slow.""" self.num = val # this doesn't call Foo.__init__ yet a = lazyclass(Foo, 6) # Foo is only initalised here print a.num What I really want to do is make an object which looks like a numarray, but only computes its contents the first time it is used. Thanks Jeremy From theller at python.net Fri Sep 23 15:54:54 2005 From: theller at python.net (Thomas Heller) Date: Fri, 23 Sep 2005 21:54:54 +0200 Subject: Open PDF References: <36141C39871E4D4DAE92F79D1838543601B176C8@itcnt14.itc.nl> <1127501728.633769.80440@z14g2000cwz.googlegroups.com> Message-ID: "Martin Miller" writes: > IMHO, the fact that there is no way to wait for the application to > finish is major deficiency with os.startfile() -- and why I often > cannot use it instead of other techniques [such as the much more > involved but limited os.spawnv() function]. > > I don't if if this is just a limitation of the implementation in the > Python os module or one with the underlying OS (Windoze) -- I suspect > the latter. os.startfile calls ShellExecute. AFAIK, if ShellExecuteEx were used, this could retrieve a process handle which you could wait for os so. With ctypes you can easily experiment with this kind of stuff. Another interesting feature, imo, is the 'verb' that you can pass to these functions. With this, you could for example specify 'print' to print the file instead of just opening it. Thomas From klappnase at web.de Wed Sep 14 07:00:13 2005 From: klappnase at web.de (klappnase at web.de) Date: 14 Sep 2005 04:00:13 -0700 Subject: tk.createfilehandler() broken with threaded tcl? Message-ID: <1126695613.777207.284790@g14g2000cwa.googlegroups.com> Hello everyone, I am running into troubles with some of my scripts that make use of tk.createfilehandler() to catch the output messages of subprocesses I started with popen2.Popen4() (debian linux, python-2.3.5, tk-8.4.9). Sometimes when those background processes are running it happens that the gui freezes and the processlist shows the subprocess in zombie state. I've been using the same scripts without problems on mandrake (with several versions of python and tk), so I came to think the problem may be the debian build of python / tk. Now I found that on debian (unlike mandrake) tcl/tk is build with --enable-threads, so I thought this *might* be the cause for the problems. I tried and replaced the call to tk.createfilehandler() with a "manual" loop that reads Popen4.fromchild() to catch the output messages and the problems seem to be gone, so it looks like using tk.createfilehandler() with threaded tk is the problem. Does anyone have an idea if this makes sense or am I on the wrong track? Best regards Michael From edhotchkiss at gmail.com Mon Sep 19 00:13:01 2005 From: edhotchkiss at gmail.com (ed) Date: 18 Sep 2005 21:13:01 -0700 Subject: threads/sockets quick question. Message-ID: <1127103181.088804.173820@g14g2000cwa.googlegroups.com> this script should create individual threads to scan a range of IP addresses, but it doesnt, it simple ... does nothing. it doesnt hang over anything, the thread is not being executed, any ideas anyone? ---------- import socket import threading import traceback MAX_THREADS = 50 class scanThread(threading.Thread): def run(self): try: ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ss.connect((ip, port_counter)) print "%s | %d OPEN" % (ip, port_counter) ss.close() print "scanned: ",port_counter,"\n" except: traceback.print_exc() # end class ------------------- def scan(ip, begin, end): port_counter = 0 for port_counter in range(begin, end): while threading < MAX_THREADS: scanThread().start() # end function ------------------- scan("localhost", 0, 10000) From petercable at gmail.com Wed Sep 7 17:44:25 2005 From: petercable at gmail.com (petercable at gmail.com) Date: 7 Sep 2005 14:44:25 -0700 Subject: bug in numarray? In-Reply-To: References: Message-ID: <1126129465.837344.124790@o13g2000cwo.googlegroups.com> python 2.4.1 numarray 1.3.1 works ok here. I'd try numarray 1.3.1 and see if it is unique to your version. Also, if you built it yourself, you might make sure you have sane CFLAGS. pete at monkey ~ $ python Python 2.4.1 (#1, Sep 3 2005, 16:55:52) [GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from numarray import * >>> a = zeros((5,100), Float64) >>> b = kroneckerproduct(a, identity(12)) >>> b array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]) >>> a array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> b array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]) Pete From renting at astron.nl Mon Sep 12 07:57:39 2005 From: renting at astron.nl (Adriaan Renting) Date: Mon, 12 Sep 2005 13:57:39 +0200 Subject: read stdout/stderr without blocking Message-ID: I was not aware you were using Windows, you might need to find something similar to select and pty that works in Windows or maybe go though Cygwin, I don't know. I'm on Linux, the only help I can offer is showing you my working code, that's a mix of Pexpect, subProcess and Parseltongue. I'm not sure if this is 100% correct, it just happens to work and might help you in solving a similar problem: ---- in spawn() (self._errorpipe_end, self._errorpipe_front) = os.pipe() ## need to handle stderr separate from stdout try: (self._pid, self._child_fd) = pty.fork() except OSError, e: raise Exception ('fork failed') if self._pid == 0: ## the new client try: os.dup2(self._errorpipe_front, 2) ## we hardcoded assume stderr of the pty has fd 2 os.close(self._errorpipe_end) os.close(self._errorpipe_front) ## close what we don't need os.execvp(self.task, self.inputs) except: sys.stderr.write('Process could not be started: ' + self.task) os._exit(1) else: ## the parent os.close(self._errorpipe_front) ## close what we don't need fcntl.fcntl(self._child_fd, fcntl.F_SETFL, os.O_NONBLOCK) ---- in handle_messages() tocheck=[] if not self._fd_eof: tocheck.append(self._child_fd) if not self._pipe_eof: tocheck.append(self._errorpipe_end) ready = select.select(tocheck, [], [], 0.25) ##continues after 0.25s for file in ready[0]: try: text = os.read(file, 1024) except: ## probalby Input/Output error because the child died text = '' if text: for x in self._expect: if x[0] in text: ## we need to do something if we see this text returntext = x[1](text) if returntext: os.write(file, returntext) self.handle_text(text) else: if file == self._child_fd: self._fd_eof = 1 elif file == self._errorpipe_end: self._pipe_eof = 1 return 1 if self._fd_eof or self._pipe_eof: # should be an and not an or, but python 2.3.5 doesn't like it return 0 if len(ready[0]) == 0: ## no data in 0.25 second timeout return 1 return 0 ---- in finish() (pid, status) = os.waitpid(self._pid, os.WNOHANG) ## clean up the zombie assert(pid == self._pid) if os.WIFEXITED(status) or os.WIFSIGNALED(status): self._pid = 0 self.exitstatus = status assert(self.finished()) del self._pid os.close(self._child_fd) os.close(self._errorpipe_end) |>>>Jacek Pop*awski 09/12/05 1:14 pm >>> |Adriaan Renting wrote: |>Check out the select module, for an example on how to use it: |>pexpect.sourceforge.net | |Two problems: |- it won't work on Windows (Cygwin) |- how much data should I read after select? 1 character? Can it block if |I read 2 characters? |-- |http://mail.python.org/mailman/listinfo/python-list From n00m at narod.ru Sat Sep 3 19:43:06 2005 From: n00m at narod.ru (n00m) Date: 3 Sep 2005 16:43:06 -0700 Subject: Sockets: code works locally but fails over LAN In-Reply-To: References: <1125493380.805663.16800@g44g2000cwa.googlegroups.com> <1125597092.323375.151570@g44g2000cwa.googlegroups.com> <1125681663.710557.320340@f14g2000cwb.googlegroups.com> <3m6ih1taaeo7kndnbuvfl5geed053ivunl@4ax.com> <1125774529.074965.269720@g44g2000cwa.googlegroups.com> Message-ID: <1125790986.012636.40050@o13g2000cwo.googlegroups.com> Bryan; Look at how I corrected your the very first version (see added arguments in both functions). And now it really can handle multiple connections! import socket, thread sqls_host, sqls_port = '127.0.0.1', 1433 proxy_host, proxy_port = '127.0.0.1', 1434 # How I tested it: # sqls_host, sqls_port = 'www.google.com', 80 def VB_SCRIPT(s2, cn): while 1: data = cn.recv(4096) if not data: return s2.sendall(data) print 'VB_SCRIPT:' + data + '\n' def SQL_SERVER(s2, cn): while 1: data = s2.recv(4096) if not data: return cn.sendall(data) print 'SQL_SERVER:' + data + '\n' s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((proxy_host, proxy_port)) s1.listen(5) while 1: cn, addr = s1.accept() s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.connect((sqls_host, sqls_port)) thread.start_new_thread(VB_SCRIPT,(s2, cn)) thread.start_new_thread(SQL_SERVER,(s2, cn)) Without these corrections I got these error messages when I launched SIMULTANEOUSLY 3 instances of my.vbs: Unhandled exception in thread started by Unhandled exception in thread started by Traceback (most recent call last): Traceback (most recent call last): File "D:\Python23\00\socket_Br10.py", line 18, in SQL_SERVER File "D:\Python23\00\socket_Br10.py", line 13, in VB_SCRIPT data = s2.recv(4096) s2.sendall(data) socket File "", line 1, in sendall .socketerror.: error: (10054, 'Connection reset by peer') (10054, 'Connection reset by peer') From bokr at oz.net Mon Sep 5 20:58:58 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 06 Sep 2005 00:58:58 GMT Subject: Possible improvement to slice opperations. References: <0BZSe.13427$xl6.12703@tornado.tampabay.rr.com> <7xfysjb83b.fsf@ruckus.brouhaha.com> Message-ID: <431cd9d2.708615405@news.oz.net> On 05 Sep 2005 12:58:00 -0700, Paul Rubin wrote: >Steve Holden writes: >> Given that Python has a 1's-complement operator already I don;t see >> why you can't just leave Python alone and use it, > >What's the meaning of the 1's complement operator (for example, what >is ~1), when ints and longs are the same? assert ~x == -1-x # or -1^x The only problem is seeing the result printed, since people insist that hex(a) will be '-'[:a<0]+hex(abs(a)) which brings up base-complement representation for signed numbers, where the first digit is always 0 or base-1 to indicate positive and negative: (BTW, I found a bug when I dug this up from my disk, so a previous post with this might have that bug (bad leading digit check wasn't sign-sensitive)) >>> def basecompl(x, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'): ... if not (2 <= B <= len(digits)): raise ValueError('bad base = %r'%B) ... if not x: return digits[0] ... s = [] ... while x and x != -1: ... x, r = divmod(x, B) ... s.append(digits[r]) ... if not s or s[-1] != (digits[0], digits[B-1])[x<0]: ... s.append(digits[x<0 and B-1 or 0]) ... return ''.join(s[::-1]) ... >>> def bcdecode(s, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'): ... if s == digits[0]: return 0 ... acc = s[0].lower() == digits[B-1] and -B**len(s) or 0 ... for i, c in enumerate(s[::-1]): ... acc += digits.index(c)*B**i ... return acc ... >>> bc = basecompl # easier to type ;-) >>> bc(~3L, 2) '100' >>> bc(-1-3L, 2) '100' >>> bc(-1^3L, 2) '100' >>> bc(~3L, 8) '74' >>> bc(-1-3L, 8) '74' >>> bc(-1^3L, 8) '74' >>> bc(~3L) '96' >>> bc(-1-3L) '96' >>> bc(-1^3L) '96' >>> bc(bcdecode(bc(~3L))) '96' >>> bc(bcdecode(bc(~3L, 2),2),2) '100' >>> bc(~3L, 16) 'fc' >>> bc(-1-3L, 16) 'fc' >>> bc(-1^3L, 16) 'fc' >>> bc(3L) '03' Regards, Bengt Richter From bronger at physik.rwth-aachen.de Mon Sep 26 13:38:04 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 26 Sep 2005 19:38:04 +0200 Subject: ncurses programming References: <1127754862.781184.224480@z14g2000cwz.googlegroups.com> Message-ID: <874q87pw5f.fsf@wilson.rwth-aachen.de> Hall?chen! "ncf" writes: > [...] > > Py Docs: http://docs.python.org/lib/module-curses.html This document suggests that Python+ncurses won't work on windows. What's the reason for this? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From rschroev_nospam_ml at fastmail.fm Mon Sep 19 09:18:49 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 19 Sep 2005 13:18:49 GMT Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh schreef: > meanwhile, over in python-dev land: > > "Is anyone truly attached to nested tuple function parameters; 'def > fxn((a,b)): print a,b'? /.../ > > Would anyone really throw a huge fit if they went away? I am willing > to write a PEP for their removal in 2.6 with a deprecation in 2.5 if > people are up for it." > I for one would not like to see that disappear. I like being able to write, for example: def drawline((x1, y1), (x2, y2)): # draw a line from x1, y1 to x2, y2 foo(x1, y1) bar(x2, y2) instead of def drawline(p1, p2): x1, y1 = p1 x2, y2 = p2 # draw a line from x1, y1 to x2, y2 foo(x1, y1) bar(x2, y2) or def drawline(p1, p2): # draw a line from p1[0], p1[1] to p2[0], p2[1] foo(p1[0], p1[1]) bar(p2[0], p2[1]) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fakeaddress at nowhere.org Wed Sep 14 15:43:29 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 14 Sep 2005 19:43:29 GMT Subject: Builtin classes list, set, dict reimplemented via B-trees In-Reply-To: References: Message-ID: barnesc at engr.orst.edu wrote: > Here overhead is compared to a C array of > 1 million PyObject *s. > > Thus, on average, a > 1 million element B-tree uses 25% less memory > than any other balanced data structure which I am aware of, and 50% > more memory than a raw C array. That's overhead of indexing; it doesn't consider the space already used to store the keys and values. The B-tree can get by with modestly fewer pointers, because it has fewer internal nodes that need to be referenced by other internal pointers. That assumes that the B-tree nodes are kept as linear arrays, which means that either inserting into them will time proportional to the fan-out, or searching them will. [...] > I have no idea how B-trees compare to skip lists (the likely > contender) in terms of speed. I'd expect Red-Black trees to be at least as good a contender. > Are there any *practical* applications for in-memory balanced data > structures (e.g. skip list, AVL tree, RB tree, B tree) ? Yes, absolutely. Efficient ordered sub-ranges; efficient rank queries; sustainable performance with adversarial inputs. -- --Bryan From rutt at bmi.osu.edu Mon Sep 26 09:35:44 2005 From: rutt at bmi.osu.edu (Benjamin Rutt) Date: Mon, 26 Sep 2005 09:35:44 -0400 Subject: extending and embedding python without distutils Message-ID: <5v1x3clznz.fsf@akron.bmi.ohio-state.edu> I have a rather large C++ project which has his own build system (scons) and I would prefer to stay inside scons in order to build some python extensions/embeddings (that is, I prefer to avoid using distutils directly to build my extensions). Can someone confirm that I'm doing the right thing to pick up the necessary dependencies to pick up the compilation flags (the first output line below, once I prefix it with '-I'), location of libpythonX.X.a (the second output line below, once I prefix it with '-L'), and dependent linking libraries (the last three output lines below). This is the type of thing that pkg-config normally solves on linux. (I'd have to add -lpythonX.X to my build commands, which I can do separately by grabbing the major and minor version and building up a string). >>> import distutils.sysconfig >>> for v in 'INCLUDEPY', 'LIBPL', 'LOCALMODLIBS', 'BASEMODLIBS', 'LIBS': ... print distutils.sysconfig.get_config_var(v) ... /home/rutt/.upak/installed/python-2.4/include/python2.4 /home/rutt/.upak/installed/python-2.4/lib/python2.4/config -L/home/rutt/.upak/installed/tcltk/lib -L/usr/X11R6/lib -ltk8.4 -ltcl8.4 -lX11 -lpthread -ldl -lutil The purpose of this posting is to see if anyone jumps in and says "hey, you missed a variable called ...". Thanks, -- Benjamin Rutt From cournape at gmail.com Tue Sep 6 04:25:01 2005 From: cournape at gmail.com (cournape at gmail.com) Date: 6 Sep 2005 01:25:01 -0700 Subject: python profiling, hotspot and strange execution time Message-ID: <1125995101.301148.158900@g47g2000cwa.googlegroups.com> Hi there, I have some scientific application written in python. There is a good deal of list processing, but also some "simple" computation such as basic linear algebra involved. I would like to speed things up implementing some of the functions in C. So I need profiling. I first tried to use the default python profiler, but profiling my application multiplies the execution time by a factor between 10 and 100 ! So I decided to give a try to hotspot. I just followed the example of the python library reference, but I have some strange results concerning cpu time. My profiling script is something like the following: def run_foo(): print time.clock() function_to_profile() print time.clock() prof = hotshot.Profile("essai.prof") benchtime= prof.runcall(run_foo) prof.close() stats = hotshot.stats.load("essai.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) The goal is to profile the function function_to_profile(). Running this script gives me a CPU executime time of around 2 seconds, whereas the difference between the two clock calls is around 10 seconds ! And I don't run any other cpu consuming tasks at the same time, so this cannot come from other running processes. Is there something perticular about hotspot timing I should know ? I am not sure how I can get more accurate results with hotspot. I would appreciate any help, Thanks From yorklee70 at gmail.com Mon Sep 19 17:09:06 2005 From: yorklee70 at gmail.com (York) Date: Mon, 19 Sep 2005 14:09:06 -0700 Subject: very high-level IO functions? In-Reply-To: References: Message-ID: Caleb Hattingh wrote: > York > > Short answer: yes > Brilliant! and what are they? > We use python and R at work, and in general you will find python syntax > a little cleaner for functionality they have in common. R is better > for some of the more hard-wired stats stuff, though. I love python. However, as a biologist, I like some high-levels functions in R. I don't want to spend my time on parse a data file. Then in my python script, I call R to read data file and write them into an MySQL table. If python can do this easily, I don't need R at all. Cheers, -York > > On Mon, 19 Sep 2005 20:04:37 +0200, York wrote: > >> Hi, >> >> R language has very high-level IO functions, its read.table can read >> a total .csv file and recogonize the types of each column. >> write.table can do the reverse. >> >> R's MySQL interface has high-level functions, too, e.g. dbWriteTable >> can automatically build a MySQL table and write a table of R >> data into it. >> >> Is there any python packages do similar things? >> >> >> -York > > From fperez.net at gmail.com Tue Sep 13 14:51:03 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 13 Sep 2005 12:51:03 -0600 Subject: Detailed traceback References: <910885da05091213561bc2d645@mail.gmail.com> Message-ID: Echo wrote: > I have been working on handling unhanded exceptions and making a > detailed print out of the traceback after the exception. I found that > traceback.extract_tb worked nice and was quite simple. > > During my searching around I found out that it might be possible to > get the variables and their respective values for each frame. I found > this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 to > be extremely helpful. > > My only problem with that is that there appears to be no way to get > the line of code for a frame. > > So I was wondering if it was possible to get the line of code for a frame. You might not want to reinvent that particular wheel from scratch. While not rocket science, getting locals/globals correctly requires relatively careful code (it took me quite a few tries to get it right in all possible cases).. IPython's ultraTB module does everything you're asking for, and its CrashHandler module even wraps the whole thing into a tidy file ready for email to the developers. Feel free to use it, it's all BSD licensed after all. Cheers, f ps - suggestion for an enterprising user looking for a project: clean up ultraTB a little, isolate its ANSI terminal dependencies better (probably wrapped up in an abstract markup for coloring), and package it standalone. This question pops up every two weeks here, this makes me suspect that the need for better traceback printing than the primitive stuff supplied by the stdlib is real. Since ultraTB is just an offshoot of cgitb, it would be a nice way to give back to the stdlib. I'll be glad to help (though it's easy), but right now I just don't have the time to do it myself. From nothingcanfulfill at gmail.com Wed Sep 28 12:43:49 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 28 Sep 2005 09:43:49 -0700 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: <1127925829.416058.301380@g43g2000cwa.googlegroups.com> > Do you know any language that has real private and protected attributes? As long as the values are stored in memory, there's always a way to alter and access them. So, IMHO, no program can have truely private/protected values. From grante at visi.com Thu Sep 15 21:33:52 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 16 Sep 2005 01:33:52 -0000 Subject: 2.3 -> 2.4: long int too large to convert to int References: <11ijsh0h2dec0ed@corp.supernews.com> <1126825900.309872.76830@f14g2000cwb.googlegroups.com> Message-ID: <11ik880e7k1bd28@corp.supernews.com> On 2005-09-15, chrisperkins99 at gmail.com wrote: >> fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00)) >> >> I get an OverflowError: long int too large to convert to int > You could sort-of fake it like this, > > def unsigned(val): > return struct.unpack('i', struct.pack('I', val))[0] > > fcntl.ioctl(self.dev.fileno(), unsigned(0xc0047a80), ...) I rather like this if i & 0x8000000: i = -((i^0xffffffff)+1) As long as I'm obfscating the code, who can resist some bitwise operations. Of course it'll break on machines that don't use 2's compliment, but that's just iceing on the cake. -- Grant Edwards grante Yow! I am having FUN... I at wonder if it's NET FUN or visi.com GROSS FUN? From qvx3000 at gmail.com Wed Sep 28 03:25:31 2005 From: qvx3000 at gmail.com (qvx) Date: 28 Sep 2005 00:25:31 -0700 Subject: Help with unicode and sqlobject/pysqlite2 Message-ID: <1127892331.944055.99200@f14g2000cwb.googlegroups.com> I really can't seem to make sqlobject/pysqlite2 save my local Easter European characters. I am a Windows-1250 user and I have sys.setdefaultencoding('dbcs') in my sitecustomize. How can I save data like "?dcc?"? This is equivalent to '\x9a\xf0\xe8\xe6\x9e' I'm using the latest version of sqlobject from SVN. qvx From fakeaddress at nowhere.org Tue Sep 6 16:03:01 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 06 Sep 2005 20:03:01 GMT Subject: killing thread after timeout In-Reply-To: References: Message-ID: Jacek Poplawski had written: >> I am going to write python script which will read python >> command from socket, run it and return some values back to >> socket. >> >> My problem is, that I need some timeout. Jacek Poplawski wrote: > After reading more archive I think that solution may be to raise an > Exception after timeout, but how to do it portable? Python allows any thread to raise a KeyboardInterrupt in the main thread (see thread.interrupt_main), but I don't think there is any standard facility to raise an exception in any other thread. I also believe, and hope, there is no support for lower- level killing of threads; doing so is almost always a bad idea. At arbitrary kill-times, threads may have important business left to do, such as releasing locks, closing files, and other kinds of clean-up. Processes look like a better choice than threads here. Any decent operating system will put a deceased process's affairs in order. Anticipating the next issues: we need to spawn and connect to the various worker processes, and we need to time-out those processes. First, a portable worker-process timeout: In the child process, create a worker daemon thread, and let the main thread wait until either the worker signals that it is done, or the timeout duration expires. As the Python Library Reference states in section 7.5.6: A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The following code outlines the technique: import threading work_is_done = threading.Event() def work_to_do(*args): # ... Do the work. work_is_done.set() if __name__ == '__main__': # ... Set stuff up. worker_thread = threading.Thread( target = work_to_do, args = whatever_params) worker_thread.setDaemon(True) worker_thread.start() work_is_done.wait(timeout_duration) Next, how do we connect the clients to the worker processes? If Unix-only is acceptable, we can set up the accepting socket, and then fork(). The child processes can accept() incomming connections on its copy of the socket. Be aware that select() on the process-shared socket is tricky, in that that the socket can select as readable, but the accept() can block because some other processes took the connection. If we need to run on Windows (and Unix), we can have one main process handle the socket connections, and pipe the data to and from worker processes. See the popen2 module in the Python Standard Library. -- --Bryan From RayFLau at gmail.com Sun Sep 4 12:50:54 2005 From: RayFLau at gmail.com (KK) Date: 4 Sep 2005 09:50:54 -0700 Subject: Problems with Python for Windows extensions References: <1125760475.488680.17070@z14g2000cwz.googlegroups.com> Message-ID: <1125852654.871468.35180@o13g2000cwo.googlegroups.com> thx for ur reply u r rite that i should use a raw string, but that doesn't solve the problem i am q annoyed by this strange behaviour. i tried to run the script on my friend's pc, which is python2.4 + pywin 204 + office 2000, but same thing happened now i am thinking to generate a vbs from python and run it. i know it is dumb but i dont know other solutions... From mwm at mired.org Fri Sep 30 20:54:50 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 30 Sep 2005 20:54:50 -0400 Subject: A Moronicity of Guido van Rossum References: <2773CAC687FD5F4689F526998C7E4E5F4DB681@au3010avexu1.global.avaya.com> <77498FFE-AEC3-4148-A113-E434EE4A4E52@ihug.co.nz> <200509292042.36051.jstroud@mbi.ucla.edu> <43D1E0B3-6A3B-442E-9BDE-6DBC1A2466A7@ihug.co.nz> Message-ID: <86achunjj9.fsf@bhuda.mired.org> Steve Holden writes: > [off-list] > > Peter Hansen wrote: >> Gerrit Holl wrote: >> >>>True. However, most mail to this mailinglist has less than 0.001 spam >>>probability. As you can see, this one had 0.048 - a vast score, almost >>>enough to put it in my unsure box. It seems to be just not hammy enough. >>>It's interesting to see that no none of the foul language words used by >>>Xah Lee ever occurs in any spam I receive - spam is not that stupid. >> "Xah Lee: stupider than spam." (?) >> -neologism-intentional-ly y'rs, >> Peter > I'm responding off-list so's not to give this loony's threads any more > visibility. You seem to have goofed. > FWIW I really like the slogan. Maybe you should register > "stupiderthanspam.com" and make a million? Amused me no end. I smell a google bomb. Add the link "
stupider than spam" to your favorite web page, and in a while typing "stupider than spam" into google and hitting "I feel lucky" will take you to Xah Lee's home page.... http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dr.addn at gmail.com Sun Sep 11 00:03:20 2005 From: dr.addn at gmail.com (adDoc's networker Phil) Date: Sat, 10 Sep 2005 21:03:20 -0700 Subject: First release of Shed Skin, a Python-to-C++ compiler. In-Reply-To: <7x3bocy0vn.fsf@ruckus.brouhaha.com> References: <7x3bocy0vn.fsf@ruckus.brouhaha.com> Message-ID: <8fd4a2fe05091021035847675c@mail.gmail.com> > experimental Python-to-C++ compiler. > > why that instead of Pypy? > . pypy compiles to llvm (low-level virtual machine) bytecode which is obviously not as fast as the native code coming from c++ compilers; but the primary mission of pypy is just having a python system that is written in something like python rather than c or c++ . there is no reason why the pypy project can't have a .NET architecture instead of the java-like arrangement I assume it has now . without such a pypy.NET system, shedskin is offering a service that pypy can't yet provide: a ( python -> c++ )-conversion allows me to smoothly integrate python contributions with my already-staggering c++ library . I'm not suggesting that pypy should be another Mono rewritten in python, because the essential mission of the .NET architecture is being able to compile any language of the user`s choice, to some intermediate language designed to be far more efficiently compiled to any machine language of the user`s choice than any human-readable language such as c++ . perhaps llvm bytecode can serve as such an intermediate language? then llvm could be the new c++ (our defacto IL (intermediate language)) and shedskin (python -> IL=c++) could then be replaced by the combination of pypy (python -> IL=llvm) and some incentive for all target platforms to develope a highly optimized ( llvm -> native code)-compiler -- assuming also, that there is available a highly optimized ( c++ -> llvm bytecode )-compiler . -- American Dream Documents http://www.geocities.com/amerdreamdocs/home/ "(real opportunity starts with real documentation) -------------- next part -------------- An HTML attachment was scrubbed... URL: From juho.schultz at helsinki.fi Fri Sep 30 08:16:41 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Fri, 30 Sep 2005 15:16:41 +0300 Subject: Straight line detection In-Reply-To: <1127939495.032208.272230@z14g2000cwz.googlegroups.com> References: <1127939495.032208.272230@z14g2000cwz.googlegroups.com> Message-ID: PyPK wrote: > Does anyone know of a simple implementation of a straight line > detection algorithm something like hough or anything simpler.So > something like if we have a 2D arary of pixel elements representing a > particular Image. How can we identify lines in this Image. > for example: > > ary = > [[1,1,1,1,1], > [1,1,0,0,0], > [1,0,1,0,0], > [1,0,0,1,0], > [1,0,0,0,1]] > So if 'ary' represents pxl of an image which has a horizontal line(row > 0),a vertical line(col 0) and a diagonal line(diagonal of ary). then > basically I want identify any horizontal or vertical or diagonal line > anywhere in the pxl array. > > Thanks. > I would recommend using a module for computing, my choice would be numarray: www.stsci.edu/resources/software_hardware/numarray You could even write your own version of hough, should not be too complex. A fwee things you need to consider: 1) Are all the lines through the image, or would a row with [0,0,1 ...(a few dozen ones in here) ... 1,0] be a line? 2) Do you also need edge detection? Then you might need to convolve the image with a Laplacian or something like that, e.g. new[i,j] = (4*old[i,j])-old[i-1,j]-old[i+1,j]-old[i,j-1]-old[i,j+1] 3) How "full" are the images? It is much easier if only a small fraction of your image is lines, in your example more than half of image pixels are lines. 4) How big images are you processing? I always have at least one million pixels, so the rest may not work for small images. To do some quicklook checks you can of course go through each row/column and check if the values are different enough, something like mat = numarray.array(ima) x = mat.mean() dx = mat.stddev() then check if some rows are different from others, maybe (mat[:,i].mean() > (x + N*dx)) for "white" lines or (mat[:,i].mean() < (x - N*dx))) for "black" lines you probably need do a few tests to get a good value of N. repeat for columns (mat[j,:]) and diagonals: numarray.diagonal(mat,o) where o is offset from mat[0,0] and if you need non-diagonal elements, say ima = [[1 0 0 0 0] [0 0 1 0 0] [0 0 0 0 1]] would contain a line of ones, then vect = ima.flat gives the image as a rank-1 array and you can then take strides (every nth element) just like with normal lists, array[a:b:n] takes every nth element in array[a:b], so vect[::7] would be [1 1 1] I hope this helps a bit. From greg at notmyrealaddress.com Mon Sep 12 02:21:50 2005 From: greg at notmyrealaddress.com (Greg McIntyre) Date: Mon, 12 Sep 2005 06:21:50 GMT Subject: Appending paths relative to the current file to sys.path Message-ID: Out of interest, are there any standard Python modules that do this: def appendRelativeIncludePath(*relpath): dir = os.path.abspath(os.path.join(os.path.dirname(__file__), *relpath)) if not dir in sys.path: sys.path.append(dir) I ask because I often find myself doing this: ---- # myproject/lib/mymodule/test/test.py if __name__ == '__main__': import os.path import sys dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) if not dir in sys.path: sys.path.append(dir) import mymodule # it's always 2 directories up from here ---- And it seems like a lot to type so often. I can't factor out this functionality unless I create a little module for doing this and install it in a standard include path. You see I dream of doing this: ---- # myproject/lib/mymodule/test/test.py if __name__ == '__main__': import astandardmodule astandardmodule.appendRelativeIncludePath('..', '..') import mymodule ---- Which, as you can see, is much shorter. ;) -- Greg McIntyre From le.dahut at laposte.net Wed Sep 14 04:54:58 2005 From: le.dahut at laposte.net (le dahut) Date: Wed, 14 Sep 2005 10:54:58 +0200 Subject: network parameters Message-ID: <1126688098.14380.131.camel@kls> Hi, Is there a way to get network parameters (number of network interfaces, ip address(es), DNS, gateway) on a linux station using python 2.3 ? Klaas From nyamatongwe+thunder at gmail.com Fri Sep 23 04:03:37 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 23 Sep 2005 08:03:37 GMT Subject: Python argv and special characters In-Reply-To: <1127461767.657015.305770@g49g2000cwa.googlegroups.com> References: <1127461767.657015.305770@g49g2000cwa.googlegroups.com> Message-ID: Jakob Simon-Gaarde: > How can I ensure a safe passing of arguments maybe having speciel > characters within. Use ctypes to call the Windows GetCommandLine function. The CommandLineToArgvW function can be used to break up the command line string into arguments. Neil From asmlinkage at gmail.com Thu Sep 15 20:55:16 2005 From: asmlinkage at gmail.com (asmlinkage) Date: 15 Sep 2005 17:55:16 -0700 Subject: Python Search Engine app In-Reply-To: <43285730$0$21365$db0fefd9@news.zen.co.uk> References: <1126708775.608076.106850@g43g2000cwa.googlegroups.com> <43285730$0$21365$db0fefd9@news.zen.co.uk> Message-ID: <1126832116.824290.238150@g44g2000cwa.googlegroups.com> Will McGugan wrote: > > Wasn't Google's first search engine actualy written in Python? I would'nt be surprised if they actually used python to do some prototyping of their algorithms but I cannot imagine the search engine actually being written in python. Search engines consist of many sub-systems like spidering, tokenizing, indexing, compression, ranking etc ... I think the main portion where google or as a matter of fact many search companies would use python is probably for spidering and for all the glue that supports the system. From mekstran at iastate.edu Mon Sep 19 14:15:54 2005 From: mekstran at iastate.edu (Michael Ekstrand) Date: Mon, 19 Sep 2005 13:15:54 -0500 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> Message-ID: <200509191315.54389.mekstran@iastate.edu> On Monday 19 September 2005 08:18, Roel Schroeven wrote: > def drawline((x1, y1), (x2, y2)): > # draw a line from x1, y1 to x2, y2 > foo(x1, y1) > bar(x2, y2) Yow! I did not know you could even do this. My vote would be +1 for keeping them in the language... they look far too useful to deprecate/remove... -Michael From steve at REMOVETHIScyber.com.au Wed Sep 28 19:33:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 29 Sep 2005 09:33:51 +1000 Subject: Will python never intend to support private, protected and public? References: <311b5ce105092800102da32267@mail.gmail.com> <7xbr2dxqqq.fsf@ruckus.brouhaha.com> <7xk6h0zxnm.fsf@ruckus.brouhaha.com> <7x64skzvas.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 28 Sep 2005 15:23:07 -0700, Paul Rubin wrote: > Gregor Horvath writes: >> If its your code this is possible, but if not and the maintainer is >> not willing or able to change it, then you have a problem. > > Perhaps the maintainer has good reason for not wanting to change it. > After all, he's maintaining the code and you're not. In the course of > that maintenance he might change the internal usage of the private > variable that messes up the way you use it. He's supposed to be > allowed to do that--that's why the variable is private. Is he > supposed to get your permission every time he wants to change how the > private variables in his class work? No, but that is precisely why Python's semi-private variables are usually better. Names like _X and class.__X are warnings to the developer "use these at your own risk", without preventing developers who need them from using them. You have most of the benefits of private variables with none of the disadvantages. -- Steven. From benji at benjiyork.com Fri Sep 9 13:31:51 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 09 Sep 2005 13:31:51 -0400 Subject: Grouping lists In-Reply-To: <1126285304.909396.229440@g49g2000cwa.googlegroups.com> References: <1126285304.909396.229440@g49g2000cwa.googlegroups.com> Message-ID: <4321C707.2020304@benjiyork.com> PyPK wrote: > lst = [1,1,1,1,3,5,1,1,1,1,7,7,7] > I want to group the list so that it returns groups such as > [(0,3),4,5,(6,9),(10,12)]. which defines the regions which are similar. You'll probably want to use "groupby" from the itertools module. See http://docs.python.org/lib/itertools-functions.html -- Benji York From __peter__ at web.de Tue Sep 6 14:57:12 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Sep 2005 20:57:12 +0200 Subject: Linux to Windows porting question References: Message-ID: SHELTRAW, DANIEL wrote: > I am trying to port some code to Windows that works fine under Linux. The > offending line is: > > blk = fromstring(f_fid.read(BLOCK_LEN), > num_type).byteswapped().astype(Float32).tostring() > > The error I get is: > > ValueError: string size must be a multiple of element size > > Does anyone have an idea where the problem might be? BLOCK_LEN is > specified in bytes and num_type is Int32. Is the file f_fid opened in binary mode? Peter From poissonnier at gmail.com Sun Sep 18 08:19:22 2005 From: poissonnier at gmail.com (poissonnier at gmail.com) Date: 18 Sep 2005 05:19:22 -0700 Subject: Brute force sudoku cracker References: <1126903524.482259.235970@g14g2000cwa.googlegroups.com> Message-ID: <1127045962.616456.80560@z14g2000cwz.googlegroups.com> Had the same reaction as everyone when I saw theses puzzles a month or so ago, so here is my solution... the solve function is recursive, so it can also solve the 'deadlock set' (example3). find_cell looks for an empty cell with the most filled cells in it's row and column, so the search tree doesn't grow too 'wide'. ----------------------------------- example1 = """8 9 - - - - 3 - 4 - - 5 - 3 - - - - - 7 - - 8 1 5 - - - 4 - - - 7 - - 3 - - - 5 4 3 - - - 2 - - 1 - - - 5 - - - 7 9 1 - - 4 - - - - - 7 - 2 - - 9 - 8 - - - - 7 5""" example2 = """- 5 2 - - - - - - 9 - - 1 - - - 5 - - - 4 8 3 - - - 2 - 3 - - 9 - 1 - 5 - - - - - - - - - 5 - 7 - 6 - - 4 - 1 - - - 7 3 6 - - - 7 - - - 9 - - 3 - - - - - - 2 7 -""" example3 = """- 3 - 5 - - 8 1 - 1 - - 7 6 - - 9 - 4 - - - - - - - - 8 4 3 9 7 5 1 2 6 - 1 - 6 - - - 7 8 6 - - 8 - 1 9 3 - - - - 1 5 7 - - 9 - 9 - - 8 6 - - 1 - 6 1 - 9 2 - 8 -""" class ImpossibleException(Exception): pass def field_from_string(field_str): def mapper(x): if x == '-': return None else: return int(x) return [map(mapper, line.split()) for line in field_str.split('\n')] def field_from_file(filename): f = open(filename) field = field_from_string(f.read()) f.close() return field def print_field(field): def mapper(x): if x == None: return ' ' else: return str(x)+' ' str_rows = [map(mapper, x) for x in field] str_rows = ['| ' + " ".join(str_row) + '|' for str_row in str_rows] print 'x'+'-'*27+'x' print "\n".join(x for x in str_rows) print 'x'+'-'*27+'x' def check_constraint(field, (x,y), num): """Checks if putting num at (x,y) is valid.""" #row constraint occ = [elem for elem in field[x] if elem == num] if occ: return False #column constraint occ = [field[k][y] for k in range(9) if field[k][y] == num] if occ: return False #subfield constraint sub_x, sub_y = x//3, y//3 occ = [field[k+3*sub_x][l+3*sub_y] for k in range(3) for l in range(3) if field[k+3*sub_x][l+3*sub_y] == num] if occ: return False return True def find_cell(field): """Returns coords of an empty cell or None if all cells are filled. Returns cells with most row and column 'neighbours' first.""" def count(row): return len([x for x in row if x is not None]) #[(count, index), ... ] x_counts = zip((count(row) for row in field), range(9)) sorted_x_counts = sorted(x_counts, reverse=True) x_keys = [l for k,l in sorted_x_counts] columns = [[field[k][y] for k in range(9)] for y in range(9)] y_counts = zip((count(column) for column in columns), range(9)) sorted_y_counts = sorted(y_counts, reverse=True) y_keys = [l for k,l in sorted_y_counts] for x in x_keys: for y in y_keys: if field[x][y] == None: return (x,y) else: return None def set_value(field, (x,y), num): """Returns copy of field with cell (x,y) set to num.""" #new_field = copy.deepcopy(field) new_field = [row[:] for row in field] new_field[x][y] = num return new_field def solve(field): xy = find_cell(field) if not xy: return field poss = [e for e in range(1,10) if check_constraint(field, xy, e)] for e in poss: new_field = set_value(field, xy, e) try: return solve(new_field) except ImpossibleException: pass #try next possibility raise ImpossibleException() if __name__ == '__main__': field = field_from_string(example3) print 'initial field:' print_field(field) print 'solution:' try: print_field(solve(field)) except ImpossibleException: print 'not solvable' From trentm at ActiveState.com Fri Sep 9 16:55:03 2005 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 9 Sep 2005 13:55:03 -0700 Subject: How to upgrade to 2.4.1 on Mac OS X tiger In-Reply-To: <86hdcu2chu.fsf@bhuda.mired.org> References: <1126102477.882046.95490@z14g2000cwz.googlegroups.com> <523uh11vjfg01r30ohq4dsqcmhghcc8ees@4ax.com> <1126196055.843689.208130@g43g2000cwa.googlegroups.com> <1126275430.044429.72830@g49g2000cwa.googlegroups.com> <86hdcu2chu.fsf@bhuda.mired.org> Message-ID: <20050909205503.GC10927@ActiveState.com> [Mike Meyer wrote] > stri ker writes: > > Has anyone here upgraded from 2.3 to 2.4 on Tiger? > > If so how'd ya do it? > > You don't. You install 2.4 in parallel with 2.3. You can do pretty > much whatever you want with /usr/bin/python, /usr/local/bin/python, > etc. - Tiger doesn't seem to use those. I don't remember if I replaced > one or not, but don't touch anything else about the 2.3 installtion. > > I installed the darwinports version of 2.4, and have been using it > ever since for all my stuff. There are also the following install options: - ActivePython: http://www.activestate.com/Products/ActivePython/ (disclaimer: I make this distro) - MacPython: http://undefined.org/python/#python by Bob Ippolito - fink (similar in spirit to the darwinports project) also has a Python I believe Trent -- Trent Mick TrentM at ActiveState.com From hugh.macdonald at gmail.com Wed Sep 7 05:58:54 2005 From: hugh.macdonald at gmail.com (Hugh Macdonald) Date: 7 Sep 2005 02:58:54 -0700 Subject: Reading in external file - error checking and line numbers... In-Reply-To: References: <1126083162.994845.20850@z14g2000cwz.googlegroups.com> Message-ID: <1126087134.340571.51980@o13g2000cwo.googlegroups.com> Thankyou! That was much easier than I expected..... One more thing on a similar note..... When raising exceptions, is it possible to remove a few items from the top of the stack trace? My stack trace is looking something like: File "ripple", line 160, in ? File "ripple", line 94, in executeRipple File "test.rip", line 8, in ? dependsOnFrame = new) File "ripple", line 133, in __init__ File "ripple", line 148, in addDependsOnFrame __main__.RippleError: 'Cannot add frame dependency to non frame-based node' I'd like to be able to remove the last two items in the stack so that it just shows the user: File "ripple", line 160, in ? File "ripple", line 94, in executeRipple File "test.rip", line 8, in ? dependsOnFrame = new) __main__.RippleError: 'Cannot add frame dependency to non frame-based node' Unfortunately, I don't know how many 'ripple' stack items there will be... This is why I'd much rather, if I can, do this without exceptions and just be able to print out my own error message with the problem line number marked.... Or am I asking too much? ;) -- Hugh Macdonald From gandalf at designaproduct.biz Tue Sep 20 11:07:08 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Tue, 20 Sep 2005 17:07:08 +0200 Subject: win32 service and time.sleep() In-Reply-To: <1127227753.11591.12.camel@athop1.ath.vt.edu> References: <1127227753.11591.12.camel@athop1.ath.vt.edu> Message-ID: <4330259C.90907@designaproduct.biz> rbt wrote: >I have a win32 service written in Python. It works well. It sends a >report of the status of the machine via email periodically. The one >problem I have is this... while trying to send an email, the script >loops until a send happens and then it breaks. Should it be unable to >send, it sleeps for 10 minutes with time.sleep(600) and then wakes and >tries again. This is when the problem occurs. I can't stop the service >while the program is sleeping. When I try, it just hangs until a reboot. >Can some suggest how to fix this? > > Yes. Generally, most of the win32 services work like this: - the main thread listens to win32 service commands - when starting the service, you should create a new worker thread that does the job for you - when stopping the service, your service should report win32service.SERVICE_STOP_PENDING immediately, and ask the worker thread to terminate - you should be continuously reporting win32service.SERVICE_STOP_PENDING until your workder thread has stopped Here is a simple module that uses a 'Processor' class and a new thread to do the work. (The full program is here: http://mess.hu/download/SimpleHTTPService.zip ) class Service(win32serviceutil.ServiceFramework): _svc_name_ = SERVICE_NAME _svc_display_name_ = SERVICE_DISPLAY def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stopped = threading.Event() self.stopped.clear() self.logger = getLogger(SERVICE_NAME) def SvcStop(self): self.logger.info("Got SvcStop, trying to stop service...") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.stopped.set() def SvcDoRun(self): """Write an event log record - in debug mode we will also see this message printed.""" try: import servicemanager servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '') ) self.logger.info("Started.") self.logger.debug("Creating processor instance") processor = Processor(self.stopped) self.logger.debug("Starting processor thread") thread.start_new_thread(processor.Process,()) self.logger.debug("Waiting for the processor thread to finish") self.stopped.wait() self.logger.debug("Stopping") time.sleep(1) while not processor.stopped.isSet(): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) time.sleep(5) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, "") ) self.logger.info("Stopped") except: self.logger.error('',exc_info = sys.exc_info()) if __name__=='__main__': win32serviceutil.HandleCommandLine(Service) From n00m at narod.ru Sat Sep 10 18:38:22 2005 From: n00m at narod.ru (n00m) Date: 10 Sep 2005 15:38:22 -0700 Subject: List of integers & L.I.S. (SPOILER) In-Reply-To: <1126342344.307873.210780@g44g2000cwa.googlegroups.com> References: <1126111732.737925.287300@z14g2000cwz.googlegroups.com> <1126129942.736374.260770@g44g2000cwa.googlegroups.com> <1126161203.409605.27880@f14g2000cwb.googlegroups.com> <1126196908.479379.22010@z14g2000cwz.googlegroups.com> <1126201801.250692.27750@f14g2000cwb.googlegroups.com> <1126245784.338701.76480@g43g2000cwa.googlegroups.com> <1126258392.762642.152180@g44g2000cwa.googlegroups.com> <1126264643.000271.326640@f14g2000cwb.googlegroups.com> <1126290288.668989.147850@g49g2000cwa.googlegroups.com> <1126342344.307873.210780@g44g2000cwa.googlegroups.com> Message-ID: <1126391902.037029.72550@z14g2000cwz.googlegroups.com> Bryan; My own version also timed out. And now I can tell: it's incredibly SLOW. Nevertheless it would be interesting to compare speed of my code against yours. I can't do it myself because my Python is of 2.3.4 version. Just uncomment "your" part. import bisect def oops(w,a,b): for m in w: j=bisect.bisect_left(a,m) a.insert(j,m) b.insert(j,max(b[:j]+[0])+1) def n00m(n,w): a,b=[],[] oops(w,a,b) v=map(lambda x: -x, w[::-1]) c,d=[],[] oops(v,c,d) e=map(sum, zip(b, d[::-1])) mx=max(e) f=[] for i in xrange(n): if e[i]==mx: f.append(i+1) print len(f) def one_way(seq): n = len(seq) dominators = [n + 1] * (n * 1) score = [None] * n end = 0 for (i, x) in enumerate(seq): low, high = 0, end while high - low > 10: mid = (low + high) >> 1 if dominators[mid] < x: low = mid + 1 else: high = mid + 1 while dominators[low] < x: low += 1 dominators[low] = x score[i] = low end = max(end, low + 1) return score def supernumbers(seq): forscore = one_way(seq) opposite = [len(seq) - x for x in reversed(seq)] backscore = reversed(one_way(opposite)) score = map(sum, zip(forscore, backscore)) winner = max(score + [0]) return sorted([seq[i] for i in range(len(seq)) if score[i] == winner]) def b_olson(sequence): supers = supernumbers(sequence) print len(supers) import random, time n=50000 w=range(1,n+1) random.shuffle(w) t=time.time() n00m(n,w) print 'n00m:',time.time()-t """ t=time.time() b_olson(w) print 'b_olson:',time.time()-t """ From fuzzyman at gmail.com Thu Sep 8 11:24:50 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Sep 2005 08:24:50 -0700 Subject: ANN: pythonutils 0.2.1 Message-ID: Hello Python Folk, pythonutils 0.2.1 is now available. This is a *major* update since 0.1.0 http://www.voidspace.org.uk/python/modules.shtml#pythonutils http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=pythonutils-0.2.1.win32.zip http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=pythonutils-0.2.1.zip What is pythonutils ? ===================== The Voidspace Pythonutils package is a simple way of installing the Voidspace collection of modules. Several of the Voidspace Projects depend on these modules. They are also useful in their own right of course. They are primarily general utility modules that simplify common programming tasks in Python. The modules included are all fully documented. They are : ConfigObj - simple config file handling validate - validation and type conversion system listquote - string to list conversion StandOut - simple logging and output control object pathutils - for working with paths and files cgiutils - cgi helpers urlpath - functions for handling URLs odict - Ordered Dictionary Class Note: These modules have changed quite significantly since 0.1.0. Only install if you're sure this won't break your applications :-) What Has Changed Since 0.1.0 ? ============================== The *major* change is that *all* these modules now have their own online documentation (and almost all of them have been refactored). There are links to them all via : http://www.voidspace.org.uk/python/pythonutils.html#documentation 2005/09/04 - Version 0.2.1 -------------------------- Version 0.2.1 Updated to ConfigObj 4.0.0 beta 4 This contains bugfixes to ConfigObj. 2005/08/31 - Version 0.2.0 -------------------------- Refactored and redocumented. **Major** update to ConfigObj and validate. Removed caseless, and added odict and urlpath. * ConfigObj 4.0.0 beta 3 * listquote 1.4.0 * validate 0.2.0 * StandOut 2.1.0 * pathutils 0.2.1 * cgiutils 0.3.2 * odict 0.1.0 * urlpath 0.1.0 From maxerickson at gmail.com Mon Sep 19 23:56:52 2005 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 20 Sep 2005 03:56:52 -0000 Subject: web scrapping - POST and auto-login References: <432f4f04$0$10624$a726171b@news.hal-pc.org> <432f787e$0$10630$a726171b@news.hal-pc.org> <432f85db$0$10627$a726171b@news.hal-pc.org> Message-ID: "james hal-pc.org" wrote in news:432f85db$0$10627$a726171b at news.hal-pc.org: > Max Erickson wrote: >>>>the entire 26 character string from site A, but [1] how do i >>>>crop it to 10 characters. >> >> strings are slicable: > > The only reason i've gotten this far is a basic understanding of > syntax and programming in general :) > care to enlighten me a little on how to do that? I did. If you have some text in VARIABLE, and do something like: substring=VARIABLE[:10], substring will be the first 10 characters of VARIABLE. From c at cdot.de Tue Sep 6 16:55:37 2005 From: c at cdot.de (Chris) Date: Tue, 06 Sep 2005 22:55:37 +0200 Subject: __dict__ of object, Was: Regular Expression IGNORECASE different for findall and split? In-Reply-To: References: Message-ID: Peter Otten wrote: > Chris wrote: > > >> >>> re.split('x', '1x2X3', re.I) >>['1', '2X3'] > > > >>I expected ['1', '2', '3'] but in this case re.I bahaves exactly as not >>present at all... > > > >>Is that an expected behaviour or a fault? > > > This is expected: > > >>>>help(re.split) > > Help on function split in module sre: > > split(pattern, string, maxsplit=0) > Split the source string by the occurrences of the pattern, > returning a list containing the resulting substrings. > > You are setting maxsplit to > > >>>>re.I > > 2 > > Use re.compile() to get the desired behaviour: > > >>>>re.compile("x", re.I).split("1x2X3") > > ['1', '2', '3'] > > Peter thanks, I should read the docs but but more of a basic question following, I was doing the following before: method = 'split' # came from somewhere else of course result = re.__dict__[method].(REGEX, TXT) precompiling the regex r = compile(REGEX) does give an regex object which has the needed methods print dir(r) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] but how do I evaluate them without explicitly calling them? result = r.__???MAGIC???__[method](TXT) obviously I am not a Python pro ;) thanks chris From sjmaster at gmail.com Wed Sep 14 16:36:53 2005 From: sjmaster at gmail.com (Steve M) Date: 14 Sep 2005 13:36:53 -0700 Subject: O'Reilly book on Twisted In-Reply-To: <87YVe.514$Jr.3739@twister2.libero.it> References: <87YVe.514$Jr.3739@twister2.libero.it> Message-ID: <1126730213.734243.129900@g43g2000cwa.googlegroups.com> Does anybody know: Is this book fully up to date with Twisted 2.0? Does the book cover Nevow at all? Does the book cover general programming concepts related to concurrency? I'm reminded of those high quality articles about Deferreds and event programming by one of the Twisted developers? What is the relationship between the primary developers of Twisted and the book? From tziade at nuxeo.com Thu Sep 29 11:23:53 2005 From: tziade at nuxeo.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Thu, 29 Sep 2005 17:23:53 +0200 Subject: portable way to get process infos Message-ID: <433C0709.2090805@nuxeo.com> Hi, I am getting infos on the current process, under linux, by reading the file pointed by: '/proc/%d/status' % os.getpid() huh :( There's probably another way to do it on win32 but, i was wondering if there's a way or an existing extension out there to do make it work on any platform. Regards, Tarek From google at phaedro.com Thu Sep 1 12:54:49 2005 From: google at phaedro.com (google at phaedro.com) Date: 1 Sep 2005 09:54:49 -0700 Subject: Writing Multithreaded Client-Server in Python. In-Reply-To: References: <1125376325.572881.163770@g44g2000cwa.googlegroups.com> <7x3bos55vb.fsf@ruckus.brouhaha.com> <1125389989.030999.172080@g47g2000cwa.googlegroups.com> <7xll2jhlb6.fsf@ruckus.brouhaha.com> Message-ID: <1125593689.838888.139650@z14g2000cwz.googlegroups.com> Steve Holden schreef: > Paul Rubin wrote: > > google at phaedro.com writes: > > > >>What it doesn't do (and what Sidd seems to search as is suggested by > >>his 'select()' remark) is handle each client in a separate thread. > > > > > > I don't know what you mean by that. It launches a new thread for each > > client connection. The connection is two-way and can last as long as > > desired. If you're imagining something like a web server handling > > http requests, using http 1.1 keepalive, you could handle any number > > of requests in that connection. > > > I suspect he was trying to say that BaseHTTPServer has no mechanism for > handling state. As you know, of course, this is most relevant across > multiple successive connections to a server from the same client, and > has little to do with threads. > see below: I must apologize for not being able to use the standard CS vernacular but indeed I meant session (persistent state over multiple requests) - I still think that the thread-starter looks for a mechanism that handles each *session* in a thread where the 'mother' server-thread selects the thread belonging to a session. > > > >>If you want to apply SocketServer such that each client corresponds to > >>one thread that handles its' requests (and maintains its state), don't > >>use ThreadingMixIn - only the thread-selection will be executed in a > >>separate thread. > > > > > > What do you mean by "each client"? If a client connects, does some > > stuff, disconnects, and later reconnects, how do you know that it's > > the same client that's come back? > > The assertion that ThreadingMixIn doesn't handle *sessions* might be > more appropriate, but then there's no reason why it really should (since > if they were handled at all they would be better handled in the base > server classes). By "each client" I suspect the OP really meant "each > session", and was ignoring the fact that the same client can have > multiple sessions to the same server. > Correct. My own 'brew' is multi-session-clients enabled (in fact I test with two applets from the same PC) but indeed I used confusing language saying 'client' for 'session'. Again: ThreadingMixIn doesn't give you 'session threads' in which you store persistent information - a candidate for some generic extension of SocketServer ? When doing research for my own hobby project, I stumbled upon "Twisted" , it seems to give a lot in terms client-server features/functionality compared to SocketServer ? Is it indeed a 'generic network programming framework'? Anyone has experience with it ? Yours, -- Thijs - phaedro.com From stefano at pragma2000.com Sat Sep 10 02:53:24 2005 From: stefano at pragma2000.com (Stefano Masini) Date: Sat, 10 Sep 2005 08:53:24 +0200 Subject: Why do Pythoneers reinvent the wheel? In-Reply-To: References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> Message-ID: <432742240509092353108362e5@mail.gmail.com> On 10 Sep 2005 02:10:59 EDT, Tim Daneliuk wrote: > As someone who implemented their own configuration mini-language > with validation, blah, blah, blah (http://www.tundraware.com/Software/tconfpy/) Well, a configuration mini language with validation and blahs is not exactly what I would call _simple_... :) so maybe it doesn't even fit into my idea of testing-stdlib, or "quick and dirty" section of the manual (see my other post). But certainly it would be worth mentioning in the list of available solutions under the subsection "Configuration files handling". > 1) The existing tool is inadequate for the task at hand and OO subclassing > is overrated/overhyped to fix this problem. Even when you override > base classes with your own stuff, you're still stuck with the larger > *architecture* of the original design. You really can't subclass > your way out of that, hence new tools to do old things spring into > being. That's true, but usually only when the original design if too simple comparing to the complexity of the problem. Instead a very general solution can usually be subclassed to easily handle a simpler problem. You still have to actually understand the general and complex design in order to be able to write subclasses, so maybe one can be tempted to punt on it, and write its own simple solution. But in this case it would just be enough to propose a few solutions in the testing-stdlib: a) one simple implementation for simple problems, easy to understand, but limited. b) one complex implementation for complex problems, c) one simplified implementation for simple problems, easy to understand, but subclassed from a complex model, that leaves room for more understanding and extension just in case one needs more power. I fully understand the difficulty of reusing code, as it always forces you to a learning curve and coming to compromises. But I've also wasted a lot of time reinventing the wheel and later found stuff I could have happily lived with if I only had known. > 2) It's a learning exercise. Well, so we might as well learn a little more and rewrite os.path, the time module and pickle. Right? :) > 3) You don't trust the quality of the code for existing modules. > (Not that *I* have this problem :-p but some people might.) That's a good point, but it really boils down to being a wise programmer on one side, being able to discern the Good from the Bad, and an active community on the other side, able to provide good solutions and improve them. If either one is missing, then a lot of bad stuff can happen, and we can't really take community decisions basing on the assumption that programmers won't be able to understand, or that the community won't be able to provide. So we might as well assume that we have good programmers and an active community. Which I think is true, by the way! So, let's talk about a way to more effectively present available solutions to our good programmers! :) cheers, stefano From kay.schluehr at gmx.net Thu Sep 29 02:39:06 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 28 Sep 2005 23:39:06 -0700 Subject: Will python never intend to support private, protected and public? In-Reply-To: References: <311b5ce105092800102da32267@mail.gmail.com> Message-ID: <1127975946.942487.214990@g47g2000cwa.googlegroups.com> Steve Holden wrote: > could ildg wrote: > > Python is wonderful except that it has no real private and protected > > properties and methods. > > Every py object has dict so that you can easily find what fields and > > methods an obj has, > > this is very convenient, but because of this, py is very hard to support > > real private and > > protected? > > If private and protected is supported, python will be perfect. > > > You only say that because you assume private and protected give you a > security that they actually don't. They certainly make it more difficult > to *spot* the security errors. Honestly I like to use private/protect/public modifiers in C++ for the sake of code documentation. I like to know which attributes are dedicated to be known by other objects, which ones are for internal use only and which ones should be at least publicly accessible within a class hierarchy. This helps structuring code in the large and spotting attention. Code becomes easier accessible. But if we have Sunday or I get asked by serious programmers I also know the right technical answers about protection rights, security etc. Kay From Scott.Daniels at Acm.Org Wed Sep 21 12:02:18 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 21 Sep 2005 09:02:18 -0700 Subject: C#3.0 and lambdas In-Reply-To: References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <433155ae$0$2935$626a14ce@news.free.fr> <43315dd9$0$3051$626a14ce@news.free.fr> Message-ID: <43316ffd$1@nntp0.pdx.net> Roel Schroeven wrote: > ... > Christophe schreef: >> ... >>And what about a function which computes the line length ? > > That would have been a better example indeed, since the *p1 trick > doesn't work there. > > def euclidian_distance((x1, y1), (x2, y2)): > return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) > > That's a lot nicer, I think, than this: > > def euclidian_distance(p1, p2): > return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) But not massively nicer than: def euclidian_distance(p1, p2): (x1, y1), (x2, y2) = p1, p2 return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) --Scott David Daniels Scott.Daniels at Acm.Org From jpopl at interia.pl Fri Sep 16 05:07:28 2005 From: jpopl at interia.pl (=?ISO-8859-2?Q?Jacek_Pop=B3awski?=) Date: Fri, 16 Sep 2005 11:07:28 +0200 Subject: read stdout/stderr without blocking In-Reply-To: References: <11ib4sfhuj94m0b@corp.supernews.com> Message-ID: Donn Cave wrote: > I don't recall the beginning of this thread, so I'm not sure > if this is the usual wretched exercise of trying to make this > work on both UNIX and Windows, It is used in "test framework" which runs on Linux, Windows (Cygwin) and QNX. I can't forget about Windows. From xah at xahlee.org Sun Sep 18 06:46:03 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Sep 2005 03:46:03 -0700 Subject: Python Doc Problem Example: os.path.split Message-ID: <1127040363.949490.248560@z14g2000cwz.googlegroups.com> Python Doc Problem Example Quote from: http://docs.python.org/lib/module-os.path.html ---------- split( path) Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path (the only exception being when there were multiple slashes separating head from tail). ---------- Can anyone tell me what this verbiage is trying to fucking say? what the fuck is with the head and tail thing? is the doc writer, trying to write the doc with some austereness, but is confused about the behavior of split, or confused about expressing it? Did his pretension fucked him up? i was working on a program where i needed to split a path into dirname, corename, and suffix. But this fucking python doc diverted my work and wasted my time. It normally isn't a problem to find imperfections in the world except the fucking OpenSourcers fuck with their fucking moronicity and moronitude and propagate haughtily their fucking lies and stupidity. Die. Suggested rewrite: split(path) returns a pair (dirname,filename), where dirname is the part of path up to the last slash, and filename is the rest of the string after the last slash. Exceptional cases are: ? if path is a single slash (or repeated), then path == dirname and filename is empty. ? If the ?last? slash is repeated, they are treated as one single slash. ------------ Fuck the motherfucking liers of OpenSourcing fuckheads. (Note: my use of OpenSource here does not include people of GNU community.) For more about Python Doc problems, see http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html Xah xah at xahlee.org ? http://xahlee.org/ From gnb at itga.com.au Mon Sep 26 01:01:50 2005 From: gnb at itga.com.au (Gregory Bond) Date: Mon, 26 Sep 2005 15:01:50 +1000 Subject: C#3.0 and lambdas In-Reply-To: <86k6h8gddv.fsf@bhuda.mired.org> References: <1127049737.654113.84440@z14g2000cwz.googlegroups.com> <1127426064.277907.251710@g47g2000cwa.googlegroups.com> <3pgqp0Fagh77U1@individual.net> <86k6h8gddv.fsf@bhuda.mired.org> Message-ID: <433780BE.90605@itga.com.au> Mike Meyer wrote: > This is a well-known phenomenon, having picked up the name "bikeshed" > something like 40 years ago. Google for "bikeshed color". My favourite "bikeshed" story: A colleague just joined his local Primary School council. On the agenda for his first meeting was that the shelter shed needed painting. There were groans all around and someone said with a loud sigh, "I suppose we'll have to get the colour consultants back." From http Wed Sep 14 04:05:55 2005 From: http (Paul Rubin) Date: 14 Sep 2005 01:05:55 -0700 Subject: Software bugs aren't inevitable References: <1126545422.836549.234790@o13g2000cwo.googlegroups.com> Message-ID: <7xwtlkrs4c.fsf@ruckus.brouhaha.com> "Paddy" writes: > A work colleague circulated this interesting article about reducing > software bugs by orders of magnitude: > http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905ext.html This gets a not found error. Got a different link? > Some methods they talk about include removing error prone and ambiguous > expressions from their ADA based language Sparc - The example they give > is on why they removed the increment operators x++, x-- . There's a famous paper by John Hughes called "Why Functional Programming Matters" that (cheap oversimplification) says you should never modify the value of any variable. So, no increments, not even for loops (use recursion instead). From fredrik at pythonware.com Thu Sep 29 11:08:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Sep 2005 17:08:08 +0200 Subject: A rather unpythonic way of doing things References: <37ll1gci8v.fsf@chiark.greenend.org.uk> <433bff40$0$13513$626a14ce@news.free.fr> Message-ID: "fraca7" wrote: > print ''.join(map(lambda x: chr((((ord(x) - ord('a')) + 13) % 26) + ord('a')), 'yvfc')) that's spelled print "yvfc".decode("rot-13") or, if you prefer, print "yvfc".encode("rot-13") , in contemporary python. From frank at chagford.com Mon Sep 12 12:46:17 2005 From: frank at chagford.com (Frank Millman) Date: 12 Sep 2005 09:46:17 -0700 Subject: How to protect Python source from modification In-Reply-To: <4325ab35$0$14825$626a54ce@news.free.fr> References: <1126532085.825944.105720@g43g2000cwa.googlegroups.com> <4325ab35$0$14825$626a54ce@news.free.fr> Message-ID: <1126543577.463317.171370@g47g2000cwa.googlegroups.com> bruno modulix wrote: > Frank Millman wrote: > > Hi all > > > > I am writing a multi-user accounting/business system. Data is stored in > > a database (PostgreSQL on Linux, SQL Server on Windows). I have written > > a Python program to run on the client, which uses wxPython as a gui, > > and connects to the database via TCP/IP. > > > > The client program contains all the authentication and business logic. > > It has dawned on me that anyone can bypass this by modifying the > > program. > > If your program relies on a RDBMS, then it's the RDBMS job to enforce > security rules. > Two possible responses to this - 1. You are right (90% probability) 2. I have certain requirements which can not easily be expressed in the RDBMS, so it is easier to use the application to enforce certain rules (10% probability) Unfortunately I am stuck with number 2 at present. > > As it is written in Python, with source available, this would > > be quite easy. > > Then there's probably something wrong with the way you manage security. > Probably - I am learning the hard way > NB: splitting business logic from the GUI is still a good idea anyway. > I do have it fairly well split, but it all ends up being processed on the client, which I think is the root of my problem. > -- > bruno desthuilliers - unpythonic sig: > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" Thanks Frank From lily.poon at gmail.com Thu Sep 8 12:51:30 2005 From: lily.poon at gmail.com (Lil) Date: 8 Sep 2005 09:51:30 -0700 Subject: Help! Python either hangs or core dumps when calling C malloc Message-ID: <1126198290.288644.247510@o13g2000cwo.googlegroups.com> Hi Everyone! I've been trying to figure out this weird bug in my program. I have a python program that calls a C function that reads in a binary file into a buffer. In the C program, buffer is allocated by calling malloc. The C program runs perfectly fine but when I use python to call the C function, it core dumps at malloc. I've tried multiple binary files with different sizes and the result is: if file size is < 20 bytes , works fine if file size is > 20 bytes, it hangs or core dumps. Please help!! Lil From no at spam Sun Sep 25 10:06:43 2005 From: no at spam (D H) Date: Sun, 25 Sep 2005 09:06:43 -0500 Subject: Django Vs Rails In-Reply-To: <1niynympe3ctd$.15t28jttgkbah.dlg@40tude.net> References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <3o54knF46solU1@uni-berlin.de> <1126171655.554721.304130@g43g2000cwa.googlegroups.com> <1126802157.139711.226740@f14g2000cwb.googlegroups.com> <871x3q19m9.fsf@ieee.org> <1127627320.065510.238990@g47g2000cwa.googlegroups.com> <1niynympe3ctd$.15t28jttgkbah.dlg@40tude.net> Message-ID: Jaroslaw Zabiello wrote: > Dnia 24 Sep 2005 22:48:40 -0700, maluke at gmail.com napisa?(a): > > >>You should give TurboGears a try. > > ....This project is good only for fun and playing not for enterprise. That's my kind of project :) From gdub at ece.utexas.edu Fri Sep 16 09:59:17 2005 From: gdub at ece.utexas.edu (Gary Wilson Jr) Date: Fri, 16 Sep 2005 08:59:17 -0500 Subject: My First Python Script In-Reply-To: References: Message-ID: <432ACFB5.3080804@ece.utexas.edu> Ed Hotchkiss wrote: > def ZeroThrough255(): > x = 0 > while x <= 255: > if len(x) == 1: > mySet = '00' + str(x) > elif len(x) == 2: > mySet = '0' + str(x) > else: > mySet = x > print mySet > x +=1 > > ZeroThrough255() Instead of using the while loop and a counter, you can use the range() function. Using range() and string formatting you could to something like: def ZeroThrough255(): for num in range(256): print "%03d" % num which, using a list comprehension and the string join() function, could also be written as: def ZeroThrough255(): print "\n".join(["%03d" % num for num in range(256)]) From thorsten at thorstenkampe.de Mon Sep 26 11:17:05 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 26 Sep 2005 16:17:05 +0100 Subject: Simple Dialogs References: <1127500418.970813.321910@g44g2000cwa.googlegroups.com> <1127515161.138744.159240@g14g2000cwa.googlegroups.com> Message-ID: <10qe6xxwykrhj.x0q0yynsn6z$.dlg@40tude.net> * neil.fraser at gmail.com (2005-09-23 23:39 +0100) > James Stroud wrote: >> from tkMessageBox import showerror >> showerror('Problem','Program Crashed before Starting') > > Thanks. That works great when interpreted (though a blank window seems > to open as well). Unfortunately it still takes 40 seconds to execute > after it has been 'compiled' with py2exe (I've only got a P3). This > probably has something to do with the fact that the resulting files for > this two-liner weigh in at just under 8MB. Try with Pyinstaller. There are issues with py2exe and EasyGui. I have a script that uses either EasyGui or EasyDialog (on Windows) and the Tkinter part crashes constantly (newest py2exe) while EasyDialogs works just fine. Compiled with Pyinstaller they both work fine (and the exe is at 1.7 MB) From arobert at townisp.com Wed Sep 7 18:57:43 2005 From: arobert at townisp.com (Andrew Robert) Date: Wed, 07 Sep 2005 18:57:43 -0400 Subject: Using Python to interact with BMC Patrol Message-ID: <11hus2uq6hh0jcc@corp.supernews.com> Hi Everyone, Has anyone done any Python coding to manage/interact/customize BMC Patrol? If anyone has, could you please point me to where I can find documentation/guides on this? I checked the Python SIGs and Vault of Parnasus but didn't see anything available. Any insight you might have on this would be greatly appreciated. Thank you, Andy From jason at jasonmhirst.co.uk Sun Sep 18 19:48:57 2005 From: jason at jasonmhirst.co.uk (Jason) Date: Mon, 19 Sep 2005 00:48:57 +0100 Subject: How am I doing? Message-ID: Please don't laugh, this is my FIRST Python script where I haven't looked at the manual for help... import string import random class hiScores: hiScores=['10000Alpha','07500Beta','05000Gamma','02500Delta','00000Epsilon'] def showScores(self): for entry in self.hiScores: print entry[0:5]," - ",entry[5:] def addScore(self,score,name): newScore=string.zfill(score,5) self.hiScores.append(newScore+name) self.hiScores.sort(reverse=True) if len(self.hiScores)==6: del self.hiScores[-1] a=hiScores() print "Original Scores\n---------------" a.showScores() while 1: newScore=random.randint(0,10000) if string.zfill(newScore,5)>a.hiScores[4][0:5]: print "Congratulations, you scored %d " % newScore name=raw_input("Please enter your name :") a.addScore(newScore,name) a.showScores() continue Anything I could have done differently or any "bad-habits" you think I have which could lead to ultimate doom I really appreciate to know. TIA From fuzzymanNO at SPAMvoidspaceDOTorg.uk Thu Sep 1 08:12:14 2005 From: fuzzymanNO at SPAMvoidspaceDOTorg.uk (Fuzzyman) Date: Thu, 01 Sep 2005 13:12:14 +0100 Subject: cgi, reusing html. common problem? References: Message-ID: <1125577021.dee9d2fd10bccb7d4b35db942982fb21@teranews> On Thu, 01 Sep 2005 03:10:07 -0400, "John M. Gabriele" wrote: >I'm putting together a small site using Python and cgi. > >(I'm pretty new to this, but I've worked a little with >JSP/servlets/Java before.) > >Almost all pages on the site will share some common (and >static) html, however, they'll also have dynamic aspects. >I'm guessing that the common way to build sites like this >is to have every page (which contains active content) be >generated by a cgi script, but also have some text files >hanging around containing incomplete html fragments which >you read and paste-in as-needed (I'm thinking: >header.html.txt, footer.html.txt, and so on). > >Is that how it's usually done? If not, what *is* the >usual way of handling this? > Having a template and inserting dynamic values into it is very common. You'll have more luck looking for 'python templating systems'. I use a module called 'embedded code' - which is part of firedrop by Hans Nowak. See http://www.voidspace.org.uk/python/firedrop2/ Popular templating engines include Cheetah and TAL. You can also roll your own basic one using the string method ``replace``. I'm pretty sure their is an entry on the Python.org WIKI about templating. All the best, Fuzzy http://www.voidspace.org.uk/python >Thanks, >---John From carsten at uniqsys.com Sun Sep 18 00:32:50 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 18 Sep 2005 00:32:50 -0400 Subject: MySQLdb error - PLEASE SAVE ME! In-Reply-To: References: Message-ID: <20050918032805.M20557@uniqsys.com> On Sat, 17 Sep 2005 15:50:29 -0400, Ed Hotchkiss wrote > Ok. I am trying to read a csv file with three strings separated by commas. > I am trying to insert them into a MySQL DB online. > MySQLdb is installed, no problems. > > I think that I am having some kind of error with my csv going into > the fields and being broken apart correctly. Can someone please > help? I attached the code below, it does work with that SQL server > also if you want to try and run it. Thanks in advance .. There are two obvious faults in your code: 1) You're using the % operator to plug your parameters directly into the query string. Don't do that. Pass the parametrized query as the first argument to execute(), pass the parameter tuple as the second argument to execute(), and leave it to execute() to plug in the parameters. Once 1) is fixed, you'll run into... 2) The ID column is a NOT NULL column. There is no default value for it, nor is there an AUTO_INCREMENT flag on it. You're not specifying a value for ID in the insert statement. Either this will fail on the first insert (attempting to insert a NULL value into a NOT NULL column), or in case MySQL helpfully defaults the ID to 0, it'll fail on the second row when the primary key constraint is violated by attempting to insert another 0. To fix 2), you'll wither want to make the ID column an AUTO_INCREMENT column or explicitly specify a value for the ID column in the insert statement. (Using AUTO_INCREMENT is easier.) Hope this helps, Carsten. P.S. You need to learn how to describe your problem accurately. Phrases like "no problems" and "it does work" juxtaposed with "some kind of error" do nothing to describe what actually works and what doesn't work. I'm betting python raised an exception when you ran your code. Instead of guessing randomly (and incorrectly) that there is some kind of error in your csv parsing, you could have, for example, included a copy of the exception message. From amk at amk.ca Fri Sep 2 09:15:05 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 02 Sep 2005 08:15:05 -0500 Subject: OpenSource documentation problems References: <7xzmqwkvu8.fsf@ruckus.brouhaha.com> Message-ID: <1LOdnZ2dnZ1lRSK7nZ2dncTNhd6dnZ2dRVn-y52dnZ0@speakeasy.net> On Fri, 2 Sep 2005 01:28:22 -0500, Terry Hancock wrote: > Hmm. Still sounds like "there ought to be a wiki". I've seen references > to two different ones on this thread. One was then debunked as a "failed > experiment". The other just gave me a DNS lookup failure (maybe the > URL was wrong). The Python wiki is at ; I didn't see the earlier posting and don't know if it gave the right URL or not. --amk From fakeaddress at nowhere.org Wed Sep 14 00:20:37 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 14 Sep 2005 04:20:37 GMT Subject: high performance hyperlink extraction In-Reply-To: <1126635070.605561.208790@g44g2000cwa.googlegroups.com> References: <1126635070.605561.208790@g44g2000cwa.googlegroups.com> Message-ID: Adam Monsen wrote: > The following script is a high-performance link ( href="...">...) extractor. [...] > * extract links from text (most likey valid HTML) [...] > import re > import urllib > > whiteout = re.compile(r'\s+') > > # grabs hyperlinks from text > href_re = re.compile(r''' > [^>]* # start of tag > href=(?P["']) # delimiter > (?P[^"']*) # link > (?P=delim) # delimiter > [^>]*)> # rest of start tag > (?P.*?) # link content > # end tag > ''', re.VERBOSE | re.IGNORECASE) A few notes: The single or double quote delimiters are optional in some cases (and frequently omitted even when required by the current standard). Where blank-spaces may appear is HTML entities is not so clear. To follow the standard, one would have to acquire the SGML standard, which costs money. Popular browsers allow end tags such as "" which the RE above will reject. I'm not good at reading RE's, but it looks like the first line will greedily match the entire start tag, and then back-track to find the href attribute. There appear to many other good opportunities for a cleverly-constructed input to force big-time backtracking; for example, a '>' will end the start-tag, but in within the delimiters, it's just another character. Can anyone show a worst-case run-time? Writing a Python RE to match all and only legal anchor tags may not be possible. Writing a regular expression to do so is definitely not possible. [...] > def getLinks(html_data): > newdata = whiteout.sub(' ', html_data) > matches = href_re.finditer(newdata) > ancs = [] > for match in matches: > d = match.groupdict() > a = {} > a['href'] = d.get('link', None) The statement above doesn't seem necessary. The 'href' just gets over-written below, as just another attribute. > a['content'] = d.get('content', None) > attr_matches = attrs_re.finditer(d.get('attrs', None)) > for match in attr_matches: > da = match.groupdict() > name = da.get('name', None) > a[name] = da.get('value', None) > ancs.append(a) > return ancs -- --Bryan From sp1d3rx at gmail.com Thu Sep 1 19:06:18 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 1 Sep 2005 16:06:18 -0700 Subject: telnet.read_until() from telnetlib In-Reply-To: References: <1125075800.736986.28480@g43g2000cwa.googlegroups.com> <1125434258.386506.125620@f14g2000cwb.googlegroups.com> Message-ID: <1125615978.931590.247350@g43g2000cwa.googlegroups.com> then you are using a regex expression that is a wildcard match, and that is non-deterministic. From cam.ac.uk at mh391.invalid Mon Sep 12 13:16:43 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 12 Sep 2005 18:16:43 +0100 Subject: fully-qualified namespaces? In-Reply-To: <1126544843.312846.180640@o13g2000cwo.googlegroups.com> References: <1126538992.707768.225820@z14g2000cwz.googlegroups.com> <1126540017.5d79e5cb11ee5be796e9da1774a2e202@teranews> <1126543493.394548.319770@g14g2000cwa.googlegroups.com> <1126544843.312846.180640@o13g2000cwo.googlegroups.com> Message-ID: Lenny G. wrote: > It sounds like you are saying that there either isn't a way to make the > interpreter utilize this type of namespace difference, or that doing so > is so convoluted that it is certainly worse than just living with > Hippo.HippoCrypto. I can live with these facts (with a little bit of > discomfort ;) ) -- just wanted to make sure that I understood. There are some steps to solve this issue outlined here: http://www.python.org/peps/pep-0328.html But the fix was not included in Python 2.4 as planned. Maybe in Python 2.5? -- Michael Hoffman From godwinburby at gmail.com Tue Sep 20 07:32:35 2005 From: godwinburby at gmail.com (Godwin Burby) Date: 20 Sep 2005 04:32:35 -0700 Subject: print there! Message-ID: <1127215955.371254.248380@f14g2000cwb.googlegroups.com> Dear Pythoneer, I am writing a python script which inserts or updates a database from a csv file. i've done the functionality. But i would to like to show the user the current row being inserted or updated in the screen. This can be done as follows: print 'c:\godwin\bl.csv', for i,row in enumerate(reader): # inserts or updates the database print i, This displays on the screen as : c:\godwin\bl.csv 1 2 3 4 5 6 7 8 ^ But i want it to show the above numbers on the same spot denoted by the carat character. Can it be done with print statement or any other trick? From andreas.zwinkau at googlemail.com Mon Sep 19 14:15:34 2005 From: andreas.zwinkau at googlemail.com (beza1e1) Date: 19 Sep 2005 11:15:34 -0700 Subject: Roguelike programmers needed In-Reply-To: <1127023510.646515.8720@g49g2000cwa.googlegroups.com> References: <1127023510.646515.8720@g49g2000cwa.googlegroups.com> Message-ID: <1127153734.938744.155450@z14g2000cwz.googlegroups.com> I was hacking on something similar. It could be called a collaborative story-telling adventure game or something. My idea was to parse natural language text not "commands". The game manages locations and objects. This is for story-telling roleplay. No stats, levels or monsters (at least no self acting ones). The prototype is nearly ready (Object and location creation lacking). But i am not sure, how far this can go. Natural language processing is quite interesting. Check out what the MIT did recently: http://www.trnmag.com/Stories/2005/032305/Tool_turns_English_to_code_032305.html From Bulkan at gmail.com Sun Sep 4 23:07:18 2005 From: Bulkan at gmail.com (placid) Date: 4 Sep 2005 20:07:18 -0700 Subject: learning python In-Reply-To: <1125887831.3fb3e29f106c8f78f93b86aa1197a085@teranews> References: <1125886211.816019.201070@z14g2000cwz.googlegroups.com> <1125887831.3fb3e29f106c8f78f93b86aa1197a085@teranews> Message-ID: <1125889638.110220.172010@z14g2000cwz.googlegroups.com> Christopher Culver wrote: > "placid" writes: > > I was just wondering about good books that teach python (either with > > programming or no programming experience at all) ? Or some online > > tutorial? > > Did you even bother doing a web search? "Learn Python" or "Python > tutorial" would be enough. yeah, see i didnt even think of that. thanks man > > Christopher From steve at rueb.com Sun Sep 25 13:35:42 2005 From: steve at rueb.com (Steve Bergman) Date: Sun, 25 Sep 2005 12:35:42 -0500 Subject: Most direct way to strip unoprintable characters out of a string? In-Reply-To: References: <1127599437.e4ab33f8d8f65cbcfb07427b68e97909@teranews> <1127632577.e5813e979598f2b9b2af5afda5a88b85@teranews> Message-ID: <4336DFEE.8070905@rueb.com> Fredrik Lundh wrote: >("sanitizing" HTML data by running filters over encoded 8-bit data is hardly >ever the right thing to do...) > > > > I'm very much open to suggestions as to the right way to do this. I'm working on this primarily as a learning project and security is my motivation for wanting to strip the unprintables. Is there a better way? (This is a mod_python app , just for reference.) Thanks, Steve From steve at holdenweb.com Sat Sep 3 01:12:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Sep 2005 00:12:08 -0500 Subject: Problem with response object In-Reply-To: <000801c5b045$af65e610$3c0510ac@hydro.rbi.org.in> References: <000801c5b045$af65e610$3c0510ac@hydro.rbi.org.in> Message-ID: <431930A8.3000702@holdenweb.com> Harish Kotian wrote: > Hi Steve > Thank you for getting back. I suspect I am having problem with the > response object in Python. > > I also tried with response.write it didn't work. > I pasted your code into my page and tried it. I am again pasting the > code followed by the error page. > I shall be grateful if you can figure out the problem. > harish. > <%@ LANGUAGE = Python%> > > <% > response.redirect("http://yahoo.com/") ^^^^^^^ > > %> > The page cannot be displayed > > The page cannot be displayed > > There is a problem with the page you are trying to reach and it cannot > be displayed. > > Please try the following: > List of 2 items > ? Click the > Refresh > button, or try again later. > ? Open the > kotian > home page, and then look for links to the information you want. > list end > > HTTP 500.100 - Internal Server Error - ASP error > Internet Information Services > > Technical Information (for support personnel) > List of 5 items > ? Error Type: > Python ActiveX Scripting Engine (0x80020009) > invalid syntax > /test/test7.asp, line 4, column 4 > response.redirect("http://yahoo.com/") > ---^ > > ? Browser Type: > Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322) > > ? Page: > GET /test/test7.asp > > ? Time: > Saturday, September 03, 2005, 10:32:03 AM > > ? More information: > Microsoft Support > > list end > The traceback explains the problem: Python programs must start with no indentation. Even when writing in ASP code-brackets (<% ... %>) each code block must be a valid Python snippet. Also each code block stands alone, so you start afresh with no indentation whenever you open a new code-bracket. Try <% response.redirect("http://www.holdenweb.com/") %> and see if that works. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gsakkis at rutgers.edu Mon Sep 26 20:15:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 26 Sep 2005 20:15:26 -0400 Subject: PEP 350: Codetags References: <7x64sniedz.fsf@ruckus.brouhaha.com> Message-ID: <1127780130.96bd63b553b43ea1053fc2091c6052d0@teranews> "Paul Rubin" wrote: > I'm opposed to pretty much every proposal of this sort. If you want > to propose adding a feature to the language, add it in a way that the > compiler can know about it and notice when it's not used correctly. > Mere conventions that are not checked by the compiler are just more > stuff for people to remember. That doesn't say they're always useless > but in general they should not be the subject of PEP's. There are more than a dozen "informational PEPs" so far, or two dozens if you count the meta-PEPs as well (http://www.python.org/peps/). This PEP states upfront that it is informational, so I don't see the problem, unless are you suggesting a (meta-)PEP against informational PEPs in general :-) George From fredrik at pythonware.com Tue Sep 27 16:41:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Sep 2005 22:41:22 +0200 Subject: Silly function call lookup stuff? References: Message-ID: Lucas Lemmens wrote: > Why isn't the result of the first function-lookup cached so that following > function calls don't need to do the function-lookup at all? > > And if the context changes (an import-statement say) reset the > cached 'function-lookups'. import isn't the only way for the "context" to change. how many other ways can you think of ? > This way any function would only need to be looked up once. you haven't really thought this over, have you? From viridia at gmail.com Fri Sep 2 13:06:41 2005 From: viridia at gmail.com (talin at acm dot org) Date: 2 Sep 2005 10:06:41 -0700 Subject: 'isa' keyword References: <1125561174.062259.255890@g47g2000cwa.googlegroups.com> <1125577823.da914aee91f630e1c5ca0bb07d0fa224@teranews> Message-ID: <1125679294.724013.133350@z14g2000cwz.googlegroups.com> Thanks for all the respones :) I realized up front that this suggestion is unlikely to gain approval, for reasons eloquently stated above. However, there are still some interesting issues raised that I would like to discuss. Let me first respond to a few of the comments: >What's the difference between this and ``isinstance`` ? What's the difference between 'in' and 'has_key()"? 1) Its shorter and more readable, 2) it can be overridden to mean different things for different container types. > What's wrong with: > if image.isa(gif): > elif image.isa(jpeg): > elif image.isa(png): That forces the classification logic to be put into the instance, rather than in the category. With the "in" keyword, the "__contains__" function belongs to the container, not the contained item, which is as it should be, since an item can be in multiple containers. > Especially conidering that checking parameters with "isinstance" is > considered bad form with Python's duck typing. Here's an example where the strict OOP style of programming breaks down. I'll use SCons as an example. In SCons, there is a "Depends" function that can take a filename, a list of filenames, or a build target (which is a python object). So the logic looks like this: def Depends( target ): if isinstance( target, str ): ... elif isinstance( target, list ): ... elif isinstance( target, BuildTarget ): ... else: error You can't use method overloading here, because you are dealing with builtin python objects (except for the BuildTarget). I can think of several different cases where you would have to resort to logic like this: -- Where you are trying to distinguish between built-n python types -- Where you are trying to distinguish between types that are created by another, independent module and which you can't modify -- Where you are trying to do multi-method dispatch logic. As an example of the latter, imagine a music sequencer application that edits a stream of Midi events. Lets suppose that there are various "classes" of events: Note On Note Off Aftertouch Pitchbend Control Change In addition, lets suppose that we have a variety of different ways of editing these events: "Piano Roll" Editor - edits in horizontal "piano roll" form "Drum Machine" editor - notes are placed on a grid Event List Editor - a text list of events Music Notation Editor - uses conventional notes and staves All of these editors operate on the same underlying data, which is a stream of events. Each of these editors has a "repaint" function to render the stream of events. So the rendering of the event depends *both* on the class of the event, and the class of the editor. So you could organize it this way: class PianoRollEditor: def repaint( event ): if isinstance( event, Note ): # draw note elif isinstance( event, Aftertouch ): # draw ...etc You could also invert the logic (which is somewhat clumsier): class Note: def repaint( context ): if isinstance( context, PianoRollEditor ): ... etc... Now, I realize that some folks have built multi-method dispatch systems for Python (I did one myself at one point.) However, these tend to be somewhat slow and clunky without language support (and no, I am not asking for Python to become Dylan or CLOS.) But it would be nice to know if there was a cleaner way to solve the above problems... From hipertracker at gmail.com Sun Sep 25 06:57:16 2005 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: Sun, 25 Sep 2005 12:57:16 +0200 Subject: Django Vs Rails References: <1125972411.415944.109400@g47g2000cwa.googlegroups.com> <1125975396.544552.200000@o13g2000cwo.googlegroups.com> <3o54knF46solU1@uni-berlin.de> <1126171655.554721.304130@g43g2000cwa.googlegroups.com> <1126802157.139711.226740@f14g2000cwb.googlegroups.com> <871x3q19m9.fsf@ieee.org> <1127627320.065510.238990@g47g2000cwa.googlegroups.com> Message-ID: <1niynympe3ctd$.15t28jttgkbah.dlg@40tude.net> Dnia 24 Sep 2005 22:48:40 -0700, maluke at gmail.com napisa?(a): > You should give TurboGears a try. http://www.turbogears.org/about/status.html "TurboGears should be considered *alpha* software. This means that there can be *breaking API* changes between now and 1.0." It uses CherryPy (beta!), SQLObject (beta) and Kid (which has a couple of bugs that need fixing) This project is good only for fun and playing not for enterprise. -- JZ From yairchu at gmail.com Wed Sep 7 15:45:33 2005 From: yairchu at gmail.com (yairchu at gmail.com) Date: 7 Sep 2005 12:45:33 -0700 Subject: Yielding a chain of values In-Reply-To: <1125558706.752900.8180@g43g2000cwa.googlegroups.com> References: <4314bf65.177562962@news.oz.net> <3nk0e4F1snjcU2@individual.net> <4314e9fe.188467011@news.oz.net> <431553db.215568641@news.oz.net> <3nli8nF23ge4U1@individual.net> <1125490081.383463.322120@z14g2000cwz.googlegroups.com> <3nm4n7F26v7eU2@individual.net> <1125514778.955076.255950@z14g2000cwz.googlegroups.com> <1125558706.752900.8180@g43g2000cwa.googlegroups.com> Message-ID: <1126122332.995244.266440@g49g2000cwa.googlegroups.com> dude - this business is so confusing that you actually have to *think* about it! but python is all about simplicity. with python, when I program - I don't think *about* it - I think it. or something - don't make me think about it. so how about a "reyield" or some other new keyword (cause reyield is too quircky) instead of joining stuff which once ment something (one thing)? huh? Yair. yairchu a at T gmail From finite.automaton at gmail.com Tue Sep 13 13:50:26 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 13 Sep 2005 10:50:26 -0700 Subject: wxPython StyledTextCtrl and tabs? Message-ID: <1126633826.509655.250540@g14g2000cwa.googlegroups.com> Does anyone know of a way to make the wxPython StyledTextCtrl expand tabs into spaces? (yes, I'm trying to use it to edit Python code :P) From news at NOwillmcguganSPAM.com Sun Sep 4 09:41:00 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sun, 04 Sep 2005 14:41:00 +0100 Subject: Replacing large number of substrings Message-ID: <431af96c$0$29438$da0feed9@news.zen.co.uk> Hi, Is there a simple way of replacing a large number of substrings in a string? I was hoping that str.replace could take a dictionary and use it to replace the occurrences of the keys with the dict values, but that doesnt seem to be the case. To clarify, something along these lines.. >>> dict_replace( "a b c", dict(a="x", b="y") ) "x y c" Regards, Will McGugan -- http://www.kelpiesoft.com From jason at jasonmhirst.co.uk Sun Sep 25 17:16:05 2005 From: jason at jasonmhirst.co.uk (Jason) Date: Sun, 25 Sep 2005 22:16:05 +0100 Subject: Struggling with basics In-Reply-To: References: Message-ID: Rather than reply to those individuals, just a big "thanks" to those that have helped. It's definitely making sense, the fact that I need to show the two-element tuple to show correctly was one of those head-slapping moments. And Dennis Lee Bieber hit the nail on the head when he mentioned that I'd declared the initial scores as strings, yet I was comparing them against integers. I simply removed the single-quotes from the scores and everything slotted into place. Again, I now have the list working, apart from the list is reversed (as per Dennis Lee Bieber mentioned). I'm afraid I don't understand what you mean about the DIFF report but I'll investigate further and learn a bit more. Again, thanks for the assistance. From tjreedy at udel.edu Sat Sep 17 15:07:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Sep 2005 15:07:01 -0400 Subject: Possible bug in "metaclass resolution order" ? References: <1126972310.484861.138970@o13g2000cwo.googlegroups.com> <20050917144655.2e7ec1b7.pedro.werneck@terra.com.br> Message-ID: "Pedro Werneck" wrote in message news:20050917144655.2e7ec1b7.pedro.werneck at terra.com.br... > I still think this is a bug, not a documentation issue. As an sometimes bug report reviewer, I appreciate your posting this issue here to get a wider and quicker variety of responses than you might have on SF. If, after any further responses, you still think you have discovered a bug, do file a report on SourceForge. Since the examples and your speculations on what is wrong are relatively lengthy, you might consider putting a summary in the somewhat cramped report box and attaching a separate 'metaclass.txt' file with a complete report. Do mention your post here and any relavant responses. Since this is a relatively specialized and advanced issue (one I can't comment on, for instance), please don't be too impatient for responses. Terry J. Reedy From neil.fraser at gmail.com Fri Sep 23 14:33:39 2005 From: neil.fraser at gmail.com (neil.fraser at gmail.com) Date: 23 Sep 2005 11:33:39 -0700 Subject: Simple Dialogs Message-ID: <1127500418.970813.321910@g44g2000cwa.googlegroups.com> I'm looking for a lightweight dialog boxes from Python. JavaScript uses: alert(), confirm() and prompt() VB uses: MsgBox() and InputBox() EasyGui seemed perfect, but a "Hello World" application takes nearly a minute to execute after the program has been compiled by py2exe. There appear to be dozens of windowing toolkits avilable for Python, could someone point me in the direction of something lightweight? Thanks. From matt.hammond at rd.bbc.co.uk Fri Sep 2 07:02:31 2005 From: matt.hammond at rd.bbc.co.uk (Matt Hammond) Date: Fri, 02 Sep 2005 12:02:31 +0100 Subject: scroll a frame to display several lines of widgets at a time References: Message-ID: I don't quite understand (if I'm interpreting you correctly) why you want separate widgets, all displayed at once, for several hundred records - surely better to just reuse the one set of widgets and have the scrollbar or back-forward buttons change which record is being displayed in the widgets. If you're after replacing widgets, then you need to destroy them first. Use the self.destroy method and unset/change any variables referencing the widget so it get a chance to be garbage collected. However, if you want a scrollable view onto a larger area, what you need to do is use a Canvas, with a window shape on it. You then put a frame into that window. canvas = Tkinter.Canvas( ) canvas.grid( ... ) winID = self.canvas.create_window(0,0, anchor=Tkinter.NW) Then later you can add a frame to that window on the canvas: canvas.itemconfigure( winID, window = ) canvas['scrollregion'] = canvas.bbox('all') Make sure you've created the frame and perhaps called update_idletasks() to give it a chance to size itself before shoving it onto the canvas. And of course, the scrollbar! yscroll = Tkinter.Scrollbar( , orient=Tkinter.VERTICAL) yscroll.grid( ... ) yscroll['command'] = canvas.yview canvas['yscrollcommand'] = yscroll.set On Thu, 01 Sep 2005 14:33:36 +0100, William Gill wrote: > I need to display a couple of labels and a checkbox from each entry in > my database. Simple enough, but there are several hundred records, and > I only want to display 5 or 10 at a time. Can this be accomplished by > putting everything in a Frame(), using width, height, grid_propagate(0) > , and a scrollbar? or do I have to grid 5 rows at a time? If the > latter, can I just grid over the previous 5 or do they have to be > explicitly removed first. > > Thanks. > > Bill -- | Matt Hammond | R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK. From fredrik at pythonware.com Thu Sep 8 11:28:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 8 Sep 2005 17:28:35 +0200 Subject: Video display, frame rate 640x480 @ 30fps achievable? References: <1126184629.911333.221220@z14g2000cwz.googlegroups.com> Message-ID: Peter Hansen wrote: >> I need to develop an application that displays video 640x480 16-bit per >> pixel with 30 fps. >> >> I would prefer to do that with Python (wxPython) but don't have any >> experience whether it is possible to achieve that frame rate and still >> have some resources for other processing left? My development PC would >> be a Celeron 1 GHz. The final system could be a faster system. > > At the very least, you should be looking at Pygame instead, as wxPython > is not really intended for that kind of thing. Whether or not you can > manage the desired frame rate depends entirely on what you will be > displaying... a single pixel moving around, full-screen video, or > something in between? ;-) no contemporary hardware should have any problem reaching that framerate at that resolution, even if you stick to standard "blit" inter- faces. getting the data into the "blittable" object fast enough may be more of a problem, though. I don't know how good wxPython is in that respect; Tkinter's PhotoImage is probably not fast enough for video, but a more lightweight object like PIL's ImageWin.Dib works just fine (I just wrote a test script that reached ~200 FPS at 1400x900, but my machine is indeed a bit faster than a 1 GHz Celeron). From onurb at xiludom.gro Tue Sep 13 11:41:31 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 13 Sep 2005 17:41:31 +0200 Subject: [OT] Zope, ZPT and slots In-Reply-To: <1tiy3gsgaivar$.qp191pncicer.dlg@40tude.net> References: <1tiy3gsgaivar$.qp191pncicer.dlg@40tude.net> Message-ID: <4326f32c$0$14379$636a55ce@news.free.fr> Jaroslaw Zabiello wrote: > I would like to lauch macro from another zpt file. (snip - tech answer in private) Please stop posting Zope and ZPT related questions here. There are mailing-lists dedicated to Zope. That's where you'll get the good answers. -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" From rkern at ucsd.edu Tue Sep 20 16:59:50 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 20 Sep 2005 13:59:50 -0700 Subject: Classes derived from dict and eval In-Reply-To: References: Message-ID: Jeremy Sanders wrote: > Hi - > > I'm trying to subclass a dict which is used as the globals environment of > an eval expression. For instance: > > class Foo(dict): > def __init__(self): > self.update(globals()) > self['val'] = 42 > > def __getitem__(self, item): > # this doesn't get called from the eval statement > print "*", item > return dict.__getitem__(self, item) > > a = Foo() > > print a['val'] > print eval('val*2+6', a) > > The first print statements also prints "* val", but __getitem__ is never > called by the evaluation in the eval statement. > > Is this a bug? Does anyone have an idea for a workaround? I'm using > Python 2.3.3. In [1]: eval? Type: builtin_function_or_method Base Class: String Form: Namespace: Python builtin Docstring: eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mappping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. globals needs to be a real dictionary. The implementation uses the C API, it doesn't use the overridden __getitem__. The locals argument, apparently can be some other kind of mapping. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at rueb.com Sat Sep 24 12:44:40 2005 From: steve at rueb.com (Steve Bergman) Date: Sat, 24 Sep 2005 11:44:40 -0500 Subject: Most direct way to strip unoprintable characters out of a string? Message-ID: <43358278.10709@rueb.com> When sanitizing data coming in from HTML forms, I'm doing this (lifted from the Python Cookbook): from string import maketrans, translate, printable allchars = maketrans('','') delchars = translate(allchars, allchars, printable) input_string = translate(input_string, allchars, delchars) Which is OK. But it seems like there should be more straightforward way that I just haven't figured out. Is there? Thanks, Steve Bergman From lists at panka.com Fri Sep 9 13:33:23 2005 From: lists at panka.com (Hilbert) Date: 9 Sep 2005 10:33:23 -0700 Subject: "grep" database Message-ID: <1126287203.938630.98600@g44g2000cwa.googlegroups.com> Hello, I've heard of a software on linux that creates a recursive database of text files and then provides an interface for grep-like queries. I'd like to use it to find procedures/variables in a large code base. Any suggestions appreciated. Thanks, Hilbert From reinhold-birkenfeld-nospam at wolke7.net Sun Sep 25 17:22:40 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 25 Sep 2005 23:22:40 +0200 Subject: Struggling with basics In-Reply-To: References: Message-ID: <3poip0FbelgcU1@individual.net> Jason wrote: > Rather than reply to those individuals, just a big "thanks" to those > that have helped. > > It's definitely making sense, the fact that I need to show the > two-element tuple to show correctly was one of those head-slapping moments. > > And Dennis Lee Bieber hit the nail on the head when he mentioned that > I'd declared the initial scores as strings, yet I was comparing them > against integers. I simply removed the single-quotes from the scores > and everything slotted into place. > > Again, I now have the list working, apart from the list is reversed (as > per Dennis Lee Bieber mentioned). I'm afraid I don't understand what > you mean about the DIFF report but I'll investigate further and learn a > bit more. Please bear in mind: If you just remove the quotes from '00050', you will get a value of 40. This is because integer literals with leading zeroes are inter- preted as octal. Reinhold From jsgaarde at gmail.com Wed Sep 21 04:26:21 2005 From: jsgaarde at gmail.com (Jakob Simon-Gaarde) Date: 21 Sep 2005 01:26:21 -0700 Subject: Digest MD5 authentication over using ZSI In-Reply-To: <1125788600.022554.154010@g43g2000cwa.googlegroups.com> References: <1125788600.022554.154010@g43g2000cwa.googlegroups.com> Message-ID: <1127291181.362375.51710@o13g2000cwo.googlegroups.com> Just for the record. After accepting that pythons build-in digest authentication (HTTPDigestAuthHandler) does *NOT* work, I made my own digest authentication handler and built it into ZSI, they have recieved and accepted the patch so it should be part of the next ZSI release (current 1.7). I have tested the implementation with Microsoft MapPoint services, seems OK: #------------------------------------- #Usage example (MapPoint SOAP Services): #------------------------------------- from CommonService_services import * loc = FindServiceLocator() import sys import ZSI kw={'tracefile':sys.stdout, 'auth' : ( ZSI.AUTH.httpdigest, 'username', 'passwd') } portType = loc.getFindServiceSoap(**kw) AddressLine='Lergravsvej 28' PostalCode='8660' CountryRegion='DK' InputAddress = ns1.Address_Def() InputAddress._AddressLine = AddressLine InputAddress._PostalCode = PostalCode InputAddress._CountryRegion = CountryRegion specification = ns1.FindAddressSpecification_Def() specification._InputAddress = InputAddress specification._DataSourceName = 'MapPoint.EU' request = FindAddressSoapInWrapper() request._specification = specification res = portType.FindAddress(request) #----------------------------------------- Best regards Jakob Simon-Gaarde From rkern at ucsd.edu Mon Sep 19 16:19:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 19 Sep 2005 13:19:40 -0700 Subject: slice lists In-Reply-To: <1127159200.078343.113560@f14g2000cwb.googlegroups.com> References: <1127159200.078343.113560@f14g2000cwb.googlegroups.com> Message-ID: jbperez808 at yahoo.com wrote: > Reading: > > http://docs.python.org/ref/slicings.html > > it would seem to indicate that the ff will work: > > L=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > however, you get: > > >>> l[3:4:,5:8:] > Traceback (most recent call last): > File "", line 1, in ? > l[3:4:,5:8:] > TypeError: list indices must be integers > > in Python 2.3... are they only available in 2.4? Lists are one-dimensional. They can only take one slice, not two. > Also, > > http://www.python.org/doc/2.3/whatsnew/section-slices.html > > mentions that: > > "Ever since Python 1.4, the slicing syntax > has supported an optional third 'step' or 'stride' > argument. For example, these are all legal Python syntax: > L[1:10:2], L[:-1:1], L[::-1]." > > and yet, we see in: > > http://pyds.muensterland.org/weblog/2004/12/25.html > > that something as simple as: > > l = range(0,10) > print l[1:5] # this works > print l[1:5:2] # this barfs > > fails in Python 2.2. What gives? The syntax was there since 1.4 for the Numeric module[1], but the list object itself wasn't updated to utilize that syntax until later. [1] http://numeric.scipy.org -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From spam.csubich+spam+block at subich.nospam.com Tue Sep 6 16:25:34 2005 From: spam.csubich+spam+block at subich.nospam.com (Christopher Subich) Date: Tue, 06 Sep 2005 16:25:34 -0400 Subject: Proposal: add sys to __builtins__ In-Reply-To: References: Message-ID: Michael J. Fromberger wrote: > While I'm mildly uncomfortable with the precedent that would be set by including the contents of "sys" as built-ins, I must confess my objections are primarily aesthetic: I don't want to see the built-in namespace any more cluttered than is necessary -- or at least, any more than it already is. I agree with this sentiment, and I'll also additionally say that 'import sys' doesn't seem to be needed when writing sufficiently high-level code. My python mud client (forever in development, but the structure-code is mostly done) uses TKinter, Twisted, and glue code for just about everything. In currently 1,080 lines of Python code (reported by wc -l, so it includes a few blank lines) in 9 files, I needed "import sys" once. [1] After I import sys, I use it exactly once -- I check the platform so I can use the higher resolution time.clock on win32 [time.time on win32 (win2k) seems to have a resolution of 10ms, while on a 'nix I tested with time.time has at least ms resolution]. I'll probably use sys again somewhere to build an automagic version/platform string, but uses for it seem to be very limited. I also have 0 imports of 'os', and the only immediately useful case that comes to mind is implementation of a #dir scripting command -- providing a minimal shell functionality, and this is certainly not a core component of the program. In my opinion, using 'sys' and 'os' are extreme examples of "low-level" Python programming. This sort of thing is probably very useful for writing actual scripts that replace the sort of work done by shell scripts, but as programs get more complicated I think they'd be used (proportionally) less and less. I'm -0.9 on sys (really don't like the idea but it wouldn't be awful to see it included in __builtins__, provided it's namespaced appropriately) and -1 on os. [1] Actually, it's in there three times, but they're all in the same file -- I'd just left a legacy 'import sys' in a couple local scopes and forgot to remove them. From mwm at mired.org Sun Sep 18 12:36:54 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 18 Sep 2005 12:36:54 -0400 Subject: Why do Pythoneers reinvent the wheel? References: <1126193090.613127.4480@z14g2000cwz.googlegroups.com> <1126340055.955682.88870@g49g2000cwa.googlegroups.com> <97mav2-lc3.ln1@eskimo.tundraware.com> Message-ID: <86hdci1gex.fsf@bhuda.mired.org> Jorgen Grahn writes: > On Sat, 10 Sep 2005 20:24:32 -0400, Fran?ois Pinard wrote: > Yeah. I've often wished for some overview or guide that translates the > current buzzwords to old concepts I'm familiar with. For example, I'm sure > you can capture the core ideas of something like .NET in a couple of > sentences. Just taking a stab in the dark, since I'm only vaguely familiar with .NET: P-code for multiple languages? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From maxm at mxm.dk Thu Sep 22 10:01:06 2005 From: maxm at mxm.dk (Max M) Date: Thu, 22 Sep 2005 16:01:06 +0200 Subject: Convert from unicode to int In-Reply-To: References: Message-ID: <4332b859$0$37104$edfadb0f@dread12.news.tele.dk> Tor Erik S?nvisen wrote: > Hi > > Is there any simpler way to convert a unicode numeric to an int than: > > int(u'1024'.encode('ascii')) why doesn't: int(u'104') work for you? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From sjmaster at gmail.com Wed Sep 7 11:35:11 2005 From: sjmaster at gmail.com (Steve M) Date: 7 Sep 2005 08:35:11 -0700 Subject: encryption with python In-Reply-To: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> References: <1126101629.243503.299310@g44g2000cwa.googlegroups.com> Message-ID: <1126107311.842165.139750@g49g2000cwa.googlegroups.com> >My goal is to combine two different numbers and encrypt them to create a new number that cann't be traced back to the originals. Here's one: def encrypt(x, y): """Return a number that combines x and y but cannot be traced back to them.""" return x + y From Nainto at gmail.com Sat Sep 17 09:08:02 2005 From: Nainto at gmail.com (Nainto) Date: 17 Sep 2005 06:08:02 -0700 Subject: FTP status problems. (Again) In-Reply-To: <1126959503.745828.124600@g47g2000cwa.googlegroups.com> References: <1126924074.901404.214550@g49g2000cwa.googlegroups.com> <1126932146.25366.3.camel@blackwidow> <1126933138.25366.7.camel@blackwidow> <1126959503.745828.124600@g47g2000cwa.googlegroups.com> Message-ID: <1126962482.066731.61010@g47g2000cwa.googlegroups.com> When I execute the folllowing code with all of the address, username, and passwords filled out I gt an error saying: "/Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python" "/Users/zacim/Documents/FireUpFTP/foramttedthing" ; exit Traceback (most recent call last): File "/Users/zacim/Documents/FireUpFTP/foramttedthing", line 26, in ? fname = sys.argv[1] IndexError: list index out of range logout [Process completed] This is the code: import ftplib class ProgressFile(file): def read(self, size = None): from sys import stdout if size is not None: buff = file.read(self, size) if buff: stdout.write('.') else: stdout.write('\n') return buff else: buff = '' while True: new_str = file.read(self, 1024) stdout.write('.') if new_str: buff = buff + new_str else: stdout.write('\n') break return buff if __name__ == '__main__': import sys fname = sys.argv[1] f = ProgressFile(fname) f.read() ftp = ftplib.FTP("ftp.sadpanda.cjb.cc") ftp.login("sadpanda","s4dp4nd4b1g") file = "/FrenchBrochure.pages.zip.gz" ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024) ftp.quit() From dont at spam.me Tue Sep 6 00:02:13 2005 From: dont at spam.me (Bugs) Date: Mon, 05 Sep 2005 21:02:13 -0700 Subject: py2exe 0.6.1 released In-Reply-To: References: Message-ID: Thomas Heller wrote: > Changes in this release: > > * py2exe can now bundle binary extensions and dlls into the > library-archive or the executable itself. This allows to > finally build real single-file executables. > > The bundled dlls and pyds are loaded at runtime by some special > code that emulates the Windows LoadLibrary function - they are > never unpacked to the file system. > Wow, that is fantastic Thomas, congratulations! So far, I've only seen where Thinstall has been able to accomplish this and at STEEP licensing cost, not free and open-source like py2exe! Can this technology be applied to other platforms? Could this all be modified in such a way that other scripting languages could take advantage of your bundling technology? Thanks! From noway at sorry.com Mon Sep 19 05:37:09 2005 From: noway at sorry.com (Giovanni Bajo) Date: Mon, 19 Sep 2005 09:37:09 GMT Subject: What XML lib to use? References: <0001HW.BF4CD7C600321189F0407550@news.individual.de><878xy06j31.fsf@titan.staselog.com> Message-ID: <9FvXe.8369$9l.263781@twister1.libero.it> Fredrik Lundh wrote: > Edvard Majakari wrote: > >> Using a SAX / full-compliant DOM parser could be good for learning >> things, though. As I said, depends a lot. > > since there are no *sane* reasons to use SAX or DOM in Python, that's > mainly a job security issue... One sane reason is that ElementTree is not part of the standard library. There are cases where you write a simple python script of 400 lines and you want it to stay single-file. While ElementTree is very easy to distribute (for basic features it's just a single file), it still won't fit some scenarios. So, why did it not make it to the standard library yet, given that it's so much better than the alternatives? -- Giovanni Bajo From jgrahn-nntq at algonet.se Sat Sep 3 12:33:29 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 3 Sep 2005 16:33:29 GMT Subject: Find day of week from month and year References: <1125688505.492837.199870@g47g2000cwa.googlegroups.com> <7xzmqvnu2e.fsf@ruckus.brouhaha.com> <1125693964.021011.111040@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 02 Sep 2005 20:53:44 -0400, Peter Hansen wrote: > Carsten Haese wrote: >> On Fri, 2005-09-02 at 16:46, Laguna wrote: >>>def expiration(year, month): >>> weekday = calendar.weekday(year, month, 1) >>> table = [19, 18, 17, 16, 15, 21, 20] >>> return table[weekday] ... > True, but do you find that more readable? If I saw that in code I was > maintaining I would likely rewrite it, probably to look a lot like the > first one (though likely with a more descriptive name than "table"... > maybe expirationTable?). That doesn't explain anything, IMHO. What 'table' really is is a list of day-of-month candidates for the third Friday. For some pieces of code, I find that it's better to document what it /does/ than to try to document /how/ it does it. And maybe add a bunch of unit tests to /demonstrate/ that it seems to work. The next programmer can then choose to either (a) understand the code or (b) rip it out and replace it. I would leave the body alone, but rename the function 'third_friday_of_month', and do 'expiration = third_friday_of_month'. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From richie at entrian.com Thu Sep 29 06:18:04 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 29 Sep 2005 11:18:04 +0100 Subject: A rather unpythonic way of doing things In-Reply-To: <37ll1gci8v.fsf@chiark.greenend.org.uk> References: <37ll1gci8v.fsf@chiark.greenend.org.uk> Message-ID: [Peter] > http://www.pick.ucam.org/~ptc24/yvfc.html Beautiful! Greenspun's Tenth Rule[1] performed before your very eyes! (Not quite, because you started with Python so you were already half way there. And yours probably isn't buggy. 8-) [1] http://en.wikipedia.org/wiki/Greenspun's_Tenth_Rule -- Richie Hindle richie at entrian.com From steve at holdenweb.com Sat Sep 3 01:54:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Sep 2005 00:54:28 -0500 Subject: Problem with response object In-Reply-To: <000301c5b048$81918a20$3c0510ac@hydro.rbi.org.in> References: <000801c5b045$af65e610$3c0510ac@hydro.rbi.org.in> <431930A8.3000702@holdenweb.com> <000301c5b048$81918a20$3c0510ac@hydro.rbi.org.in> Message-ID: <43193A94.2080304@holdenweb.com> Harish Kotian wrote: > Hi Steve > I copied the lines from your mail and again got the error. > I am only pasting the relevant error lines below. > > ? Error Type: > Python ActiveX Scripting Engine (0x80020009) > Traceback (most recent call last): File "