From ldo at geek-central.gen.new_zealand Wed Oct 8 20:27:07 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 09 Oct 2008 13:27:07 +1300 Subject: distributing apps without the Python source? References: Message-ID: In message , Joe Strout wrote: > We have a client who's paranoid about distributing the Python source > to his commercial app. "Commercial" is not synonymous with "closed source". If he wanted to keep the source closed, Python was a poor choice. You could redo it in C or C++, and charge the client appropriately* for all the extra time and effort etc. *i.e. lots From bdesth.quelquechose at free.quelquepart.fr Thu Oct 16 12:21:38 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 16 Oct 2008 18:21:38 +0200 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? In-Reply-To: References: <48f4ed4b$0$6127$426a74cc@news.free.fr> Message-ID: <48f785f5$0$6537$426a74cc@news.free.fr> Carl Banks a ?crit : > On Oct 14, 1:05 pm, Bruno Desthuilliers > wrote: >> - a slightly less but still annoying problem (I wouldn't > call it a bug) >> is the handling of indentation for nested litteral dicts/lists/tuples. > > > The python-mode.el on Subversion (python-mode's Subversion on source > forge, not the ancient version of python-mode in the Python > repository) has a fix for this issue. Great !-) > It doesn't look like there's > any way to browse the subversion any more, though. Doh :( Is there any way to get this version then ??? From google at mrabarnett.plus.com Tue Oct 28 12:34:04 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 28 Oct 2008 09:34:04 -0700 (PDT) Subject: using modules in destructors References: <0906f8a2-b043-4c29-983e-3cf267380de7@e2g2000hsh.googlegroups.com> Message-ID: <7fbcddd1-fe1c-470a-8447-89a42651796d@n33g2000pri.googlegroups.com> On Oct 27, 5:40?pm, Scott David Daniels wrote: > samtyg... at gmail.com wrote: > > It seems to me that deleting local instances before imported modules > > would solve the problem. Is it not possible for the interpreter to get > > this right? Or are there cases where this would break stuff. > > > It seems rather unpythonic for the __del__() method to become > > unpredictable at exit. > > What would you have different? How would you define the end of a > Python program? ?Would all modules and globals remain, and then > darkness? ?Would the modules get removed in alphabetical order? > .... > I suppose the modules could be removed in the reverse order in which they were loaded, excepting cross-references (two objects from different modules referring to their own modules and each other). Even neglecting modules, if two objects have destructors and refer to each other, which should be collected first? > The core of the problem is that there is ((and possibly can be) > no good definition of what happens after SystemExit leaves the > __main__ module. > > --Scott David Daniels > Scott.Dani... at Acm.Org From castironpi at gmail.com Thu Oct 16 00:02:14 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 15 Oct 2008 21:02:14 -0700 (PDT) Subject: IDE Question References: <76c6100e0810151019q5d829c06k9dc551c6c4b3ac23@mail.gmail.com> Message-ID: <6026d64a-ccfe-4099-bf9f-2a932f64a429@v72g2000hsv.googlegroups.com> On Oct 15, 1:07?pm, Stef Mientki wrote: > Steve Phillips wrote: > > Hi All, > > I am just wondering what seems to be the most popular IDE. The reason > > I ask is I am currently at war with myself when it comes to IDE's. It > > seems like every one I find and try out has something in it that > > others don't and viceversa. I am in search for the perfect IDE and > > after many months of searching, I always come back to IDLE to do what > > I need to do. I want to use Komodo badly but the one issue I have with > > that is sometimes the auto-complete works and other times it doesn't. > > Even if I carbon copy a script. > > So what are the specs of the "perfect IDE" ? snip I think the editors you see are too high-contrast in their color scheme. I look at PyCrust, etc., and NetBeans Java. The bold, plus italics, plus color, is too much. I know it's exciting to be recognizing patterns and changing fonts, but they overdo it, at least in these cases. If you're browsing code contrast is important, but if you're looking at one screen or two for an extended time, you'll pick out subtleties after a short time. I look, sorry all, at Google Groups for an example of mild color gradients. I see two different grays and three blues on the current screen alone. I could see that as being popular one day. As for keyboard action, the response time from a keystroke to the visual reaction, I like mine as fast as possible, lowest lag. I don't think that's necessarily as popular, or necessarily as important, especially if the IDE is written in Python. You might like to, for the step-through functionality, add a 'settrace' on every thread if possible, overriding the thread module if necessary. I would also have appreciated a step through in the ver. 2.6. 'multiprocessing' module, but that could get difficult, since each separate instruction pointer spawns a new process. It would be even more valuable, and even pedagogically instructive, if you could control what thread takes its turn next when you're running more than one. Keyboard shortcuts are one thing I like about my editor (the one I prefer), which has hardly any non-essential features at all (in contrast to emacs I understand). You can select shortcut groups and assign number keys. 'Bloodshed-Dev' did not overdo that one, since they are developing for multiple platforms, and the conventions vary considerably-- ctrl vs. alt, function keys, &c. Arrow-movement is emphasized in mine, with ctrl-arrow, alt-arrow, shift-arrow, all having functions, plus ctrl-tab for changing file displayed. The scope of the projects you're gearing to support is a variable-- you want fast startup times if the target projects are going to be small, but good browsing abilities if they are large. I haven't liked the default behavior when identifiers are found that can't be placed in a namespace, namely lumping them all together and sorting. 10 pixels vs. 12 can make a difference in overall look and feel in the icons in your browser, and if you have one week to your release date, I'd rather have an extra week into key response time, than in the icons. My $.02. From wgheath at gmail.com Mon Oct 6 20:59:53 2008 From: wgheath at gmail.com (William Heath) Date: Mon, 6 Oct 2008 17:59:53 -0700 Subject: self signing a py2exe windows executable In-Reply-To: References: Message-ID: I don't know, how can I tell, sorry I am new to this. -Tim On Mon, Oct 6, 2008 at 5:57 PM, Roger Upole wrote: > > William Heath wrote: > > Hi Roger, > > I managed to get the dll and register it. I am now getting this error: > > > > Traceback (most recent call last): > > File > > "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > > line 312, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\Documents and Settings\blech\My > > Documents\qb_bridge_client_easy\dist\sign_exe.py", line 4, in > > s.Sign(None) > > File > > > "C:\Python25\lib\site-packages\win32com\gen_py\BD26B198-EE42-4725-9B23-AFA912434229x0x2x1.py", > > line 2067, in Sign > > return self._oleobj_.InvokeTypes(6, LCID, 1, (24, 0), ((9, > > 49),),pISigner2 > > com_error: (-2147352567, 'Exception occurred.', (0, None, u'The > > certificate > > store does not contain any certificate.\r\n', None, 0, -2138570191), > None) > > > > Line 4 is this: > > > > s.Sign(None) > > > > I don't think this can be none can it? > > > > -Tim > > > > P.S. > > > > Thanks for your help! > > If the signer is not specified, it should auto-select the appropriate > certificate. Do you have a code signing certificate installed in > the current user's certificate store ? > > Roger > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Thu Oct 30 15:26:43 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 30 Oct 2008 20:26:43 +0100 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <16acff7d-e3a4-4be0-a042-e74845501cb3@k16g2000hsf.googlegroups.com> <49057647$0$26690$9b622d9e@news.freenet.de> <49078e11$0$8568$9b622d9e@news.freenet.de> <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> Message-ID: <490A0A73.5090007@v.loewis.de> >> Why do you think so? For C code that is carefully written, the GIL >> allows *very well* to write CPU bound scripts running on other threads. >> (please do get back to Jesse's original remark in case you have lost >> the thread :-) >> > > I don't follow you there. If you're referring to multiprocessing No, I'm not. I refer to regular, plain, multi-threading. >>> It's turns out that this isn't an exotic case >>> at all: there's a *ton* of utility gained by making calls back into >>> the interpreter. The best example is that since code more easily >>> maintained in python than in C, a lot of the module "utility" code is >>> likely to be in python. >> You should really reconsider writing performance-critical code in >> Python. > > I don't follow you there... Performance-critical code in Python?? I probably expressed myself incorrectly (being not a native speaker of English): If you were writing performance-critical in Python, you should reconsider (i.e. you should rewrite it in C). It's not clear whether this calling back into Python is in the performance-critical path. If it is, then reconsider. > I tried to list some abbreviated examples in other posts, but here's > some elaboration: > > - Pixel-level effects and filters, where some filters may use C procs > while others may call back into the interpreter to execute logic -- > while some do both, multiple times. Ok. For a plain C proc, release the GIL before the proc, and reacquire it afterwards. For a proc that calls into the interpreter: a) if it is performance-critical, reconsider writing it in C, or reformulate so that it stops being performance critical (e.g. through caching) b) else, reacquire the GIL before calling back into Python, then release the GIL before continuing the proc > - Image and video analysis/recognition where there's TONS of intricate > data structures and logic. Those data structures and logic are > easiest to develop and maintain in python, but you'll often want to > call back to C procs which will, in turn, want to access Python (as > well as C-level) data structures. Not sure what the processing is, or what processing you need to do. The data structures themselves are surely not performance critical (not being algorithms). If you really run Python algorithms on these structures, then my approach won't help you (except for the general recommendation to find some expensive sub-algorithm and rewrite that in C, so that it both becomes faster and can release the GIL). > It's just not practical to be > locking and locking the GIL when you want to operate on python data > structures or call back into python. This I don't understand. I find that fairly easy to do. > You seem to have placed the burden of proof on my shoulders for an app > to deserve the ability to free-thread when using 3rd party packages, > so how about we just agree it's not an unreasonable desire for a > package (such as python) to support it and move on with the > discussion. Not at all - I don't want a proof. I just want agreement on Jesse Noller's claim # A c-level module, on the other hand, can sidestep/release # the GIL at will, and go on it's merry way and process away. >> If neither is likely to result, killing the discussion is the most >> productive thing we can do. >> > > Well, most others here seem to have a lot different definition of what > qualifies as a "futile" discussion, so how about you allow the rest of > us continue to discuss these issues and possible solutions. And, for > the record, I've said multiple times I'm ready to contribute > monetarily, professionally, and personally, so if that doesn't qualify > as the precursor to "code contributions from one of the participants" > then I don't know WHAT does. Ok, I apologize for having misunderstood you here. Regards, Martin From luke.leighton at googlemail.com Mon Oct 13 04:53:25 2008 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 13 Oct 2008 01:53:25 -0700 (PDT) Subject: urllib equivalent for HTTP requests References: <4b9f23a2-75e8-4e4d-a05b-1ecd71ce3b58@t18g2000prt.googlegroups.com> <6l364gFaf29cU1@mid.uni-berlin.de> Message-ID: On Oct 8, 7:34 am, "Diez B. Roggisch" wrote: > > I would like to keep track of that but I realize that py does not have > > a JS engine. :( Anyone with ideas on how to track these items or yep. > What you can't do though is to get the requests that are issued byJavascriptthat is *running*. yes you can. see recent post i made just a few minutes ago giving some insights into each of the available options. look up pyv8; pykhtml; spidermonkey; webkit with the python bindings to its glib bindings - pywebkitgtk - use my patched version and see http://pyjd.sf.net to get precompiled versions; pyxpcomext and pydom on developer.mozilla.org; webkit's DumpRenderTree with the --html option, to name but a few. there are _tons_ of options. they're just an absolute bastard to track down, because javascript is such a popular keyword to search for, the results are almost useless. l. From bj_666 at gmx.net Sun Oct 26 03:15:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Oct 2008 07:15:19 GMT Subject: Ordering python sets References: <2513d8ae-97ec-4b81-9ce0-f9e78bb5fa7c@r66g2000hsg.googlegroups.com> <0112ddf3$0$20624$c3e8da3@news.astraweb.com> Message-ID: <6mijo7FgonppU1@mid.uni-berlin.de> On Sat, 25 Oct 2008 21:53:10 +0000, Lie Ryan wrote: > Oh no, the two dict implementation would work _exactly_ the same from > the outside, they are transparently interchangeable. Only the > performance characteristic differs because of the different > implementation. They are not 100% interchangeably. Dictionaries as implemented need keys to be hashable objects and sorted dictionaries need the keys to have an order defined. So switching mapping types may fail unless the key objects already have the needed magic methods implemented to do the right thing. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Sat Oct 4 20:34:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Oct 2008 00:34:07 GMT Subject: garbage collector and slowdown (guillaume weymeskirch) References: <48E74447.3090504@jetable.org> Message-ID: <00f8050b$0$20633$c3e8da3@news.astraweb.com> On Sat, 04 Oct 2008 10:57:25 -0400, Terry Reedy wrote: > guillaume weymeskirch wrote: >> Hello everybody, >> >> >> To test the python 2.5 garbage collector, I wrote a trivial script >> allocating dummy objects of various sizes, then forgetting them in a >> loop. The garbage collector seems working well, limiting the memory >> used. >> >> But I've noticed a near linear slowdown of the execution : after a few >> minutes - and several millions of allocated and freed objects, each >> iteration take more and more time to execute. > > On a related note, there have been past threads reporting that > allocating and freeing increasingly long arrays, especially of tuples > (as I remember) can take more than linearly increasing time. The > solution was to turn off gc during the allocation phase so it did not > get triggered and spend increasing long times searching for collectible > objects when there were not any. If you're talking about this thread: http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/77e5d747c4a727cb it turned out that gc wasn't involved, it was tuples and dicts, and it seemed to be hardware specific. -- Steven From gauravkec2005 at gmail.com Tue Oct 21 01:32:44 2008 From: gauravkec2005 at gmail.com (gaurav kashyap) Date: Mon, 20 Oct 2008 22:32:44 -0700 (PDT) Subject: How to execute a makefile from LINUX system. Message-ID: Hi all, I am using Link-41b parser in my program. The windows version of it has an .exe file that can be executed using os.system command On Linux version,I have a makefile. so my question is: How to run the makefile using some python function. Thanks From lie.1296 at gmail.com Sat Oct 25 18:07:30 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 25 Oct 2008 22:07:30 +0000 (UTC) Subject: How can I handle the char immediately after its input, without waiting an endline? References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> <29de18070810220417p331e17c1rbd9db9cb1fd9d578@mail.gmail.com> <0112d9f3$0$20624$c3e8da3@news.astraweb.com> <011333d4$0$20616$c3e8da3@news.astraweb.com> Message-ID: On Sat, 25 Oct 2008 15:27:32 +0000, Steven D'Aprano wrote: > On Sat, 25 Oct 2008 16:30:55 +0200, Roel Schroeven wrote: > >> Steven D'Aprano schreef: >>> I can't think of any modern apps that use one character commands like >>> that. One character plus a modifier (ctrl or alt generally) perhaps, >>> but even there, it's mostly used in GUI applications. >> >> less, vi, info, top, cfdisk, lynx, links, ... come to mind. I suppose >> there are many more that I can't think of at the moment. > > I said modern *wink* > > But seriously... point taken. > I uses some of them a lot... less and top is on the top of my list (pun intended). I sometimes used vi(m), although I never really liked it, but it's sometimes unavoidable. info is replaced by man. lynx and links... well I remember a time when I tried to install Gentoo on a VMWare, lynx/ links (I forgot which one) was a life-saver because I wouldn't need to get out to the Windows host every two seconds to see the installation instruction (I was new to Linux at that time), and that was on a VMWare, what if I installed it directly, not on a virtual machine? And as far as I know, it is impossible to implement a "press any key" feature with python in a simple way (as it should be). And if std input's character buffering is easy, it'd contribute a lot to command-line real time action games (and of course many other programs, but that is the first genre of programs that crosses my mind). PS: >>> modern != GUI True >>> commandline == old False From prologic at shortcircuit.net.au Thu Oct 23 23:01:43 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 24 Oct 2008 13:01:43 +1000 Subject: Question about interpreter In-Reply-To: References: Message-ID: On Fri, Oct 24, 2008 at 12:55 PM, Usman Ajmal wrote: > An interpreter which Python also uses, translates and checks for errors in > code, one line at a time. > > Question: Does interpreter also executes the translated code? http://en.wikipedia.org/wiki/Evaluate --JamesMills -- -- -- "Problems are solved by method" From safecom at gmail.com Wed Oct 1 16:57:51 2008 From: safecom at gmail.com (Leon Zhang) Date: Thu, 2 Oct 2008 04:57:51 +0800 Subject: Socket Question In-Reply-To: <48E15E2E.30901@gmail.com> References: <48E15E2E.30901@gmail.com> Message-ID: <4fc9afc50810011357u2cd90058ve3d2384c7ce8b5ab@mail.gmail.com> Maybe you need to close the socket somewhere else, rather than to close it when you receive the your response. On Tue, Sep 30, 2008 at 7:01 AM, Ali Hamad wrote: > Hello All : > > A socket question from a networking newbie. I need to create > a server that: > > 1) receive a message from client. > 2) check that message and response to it. > 3) the client get the server message and send another message. > 4) finally, the server receive the message and close the connection. > > I have successfully done this. However, I couldn't use the same socket > to send the second message > to the server. I have googled but all the examples are only for sending > one message and receiving the response. > > in my client code, I have : > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("1st message") > response = s.recv(1024) > validate(response) > s.send("2nd message") > response2 = s.recv(1024) > s.close() > > However, I got the first response just fine from the server but the > second message didn't get to the server. > > So, the solution I came up with is to send the 1st message, close the > socket, create new socket, > and send the 2nd message. > > I came up with something like : > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("1st message") > response = s.recv(1024) > s.close() > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("2nd message") > response = s.recv(1024) > s.close() > > and it works ! > > My Question : > > is it possible to send/receive from the same socket more than one message ? > > Thank you for your assistance in advance, > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Tue Oct 21 00:02:43 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 21 Oct 2008 04:02:43 GMT Subject: How is the logical processing being done for strings like 'Dog' and 'Cat' References: <299cad90-7aed-40ba-9d57-f1daa9cd1b9e@u57g2000hsf.googlegroups.com> Message-ID: Sumitava Mukherjee wrote: >Hi all, >I am a novice programmer in Python. >Please could you explain me the results (regarding logical operators). > >I get this: > >>>> print bool('God' and 'Devil') >True > >[This is ok because (any) string is True, so; (True and True) gives >True] Your statement is accurate, but that's not why it returns true. >>>> print('God' and 'Devil') >Devil Right. And bool('Devil') is True, because a non-empty string is a true value. >[This is what I don't get ] >and for that matter,I also checked out this: > >>>> 01 and 10 >10 > >What is python doing when we type in ('God' and 'Devil') or key in (01 >and 10) ? "and" and "or" are a bit more than logical operators. The exact definition of "x and y" is "if x has a false value, return x, otherwise return y". If both sides are booleans, this does exactly what you expect. Similarly, "x or y" is actually done as "if x has a true value, return x, otherwise return y". This allows for one of the cuter Python hacks: xxx = x and y or z which is essentially the same as the C ternary operator: xxx = x ? y : z; -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Mon Oct 27 14:10:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 27 Oct 2008 14:10:06 -0400 Subject: big objects and avoiding deepcopy? In-Reply-To: <4d7c867e-2d58-4520-b4ca-bfeb5d59e50c@v28g2000hsv.googlegroups.com> References: <5e5bfdda-9f90-44c5-a558-f089538f6831@q30g2000prq.googlegroups.com> <4d7c867e-2d58-4520-b4ca-bfeb5d59e50c@v28g2000hsv.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Robert Kern: >> This is similar to implementing "Undo" functionality in applications.< > > In a quite-high-level language (like Python, but not necessarily in > Python itself) it may become eventually advantageous to add some (even > limited) built-in form of undo. Right now, I believe, one could develop an undo module with undolist and undodict classes that wrap instance mutations with an append to an undoinfo list. From castironpi at gmail.com Thu Oct 2 04:15:40 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 2 Oct 2008 01:15:40 -0700 (PDT) Subject: Odd Errors References: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> Message-ID: <0a724214-0dea-43ff-947e-9d073581573c@u65g2000hsc.googlegroups.com> On Oct 2, 12:52?am, Lawrence D'Oliveiro wrote: > In message , Steven > > D'Aprano wrote: > > On Wed, 01 Oct 2008 22:14:49 +1300, Lawrence D'Oliveiro wrote: > > >> In message > >> <1b1ed34d-f386-4389-a7f1-ce68be4e2... at k30g2000hse.googlegroups.com>, > >> Aaron "Castironpi" Brady wrote: > > >>> Do you ever want to scream from the rooftops, "'append' operates by > >>> side-effect!"? > > >> No. It's an effect, not a side-effect. > > > "Side-effect" has the technical meaning in functional languages of any > > change of state that isn't the creation and return of a function result. > > "Side" means that it happens as the by-product of returning a function > result. ".append" isn't a function, it's a procedure. Hence the > modification of the list is the primary effect, not a side effect. I was using the technical definition from functional languages, not the literal "per word" definition. Maybe the FL crowd chose their words poorly, who knows? From kurdayon at yahoo.com Wed Oct 1 11:44:21 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Wed, 1 Oct 2008 08:44:21 -0700 (PDT) Subject: How to give a global variable to a function which is in a module? Message-ID: <8e0eceeb-6a58-4ffb-a521-6ff63b5856c6@m44g2000hsc.googlegroups.com> Hi, I would like to declare a global variable, which is seen to a particular function. If I do as the following it works: x = 1 def test(): global x print x return 1 However, it does not helps since my function is in a separate file. In other words I have a main program which has the following structure: from test import test x = 1 y = test() and I have a test.py file which contains the "test" function: def test(): global x print x return 1 In this case the test does not see the global variable x. How can I make the x to be visible? Thank you. From pruebauno at latinmail.com Wed Oct 22 15:44:51 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 22 Oct 2008 12:44:51 -0700 (PDT) Subject: Possible read()/readline() bug? References: <380b01dc-eaef-425d-bb93-dbb838c20175@u28g2000hsc.googlegroups.com> Message-ID: <8fb4a4d5-df46-4c36-9ea7-6b3f9390b41d@p49g2000hsd.googlegroups.com> On Oct 22, 2:54 pm, Mike Kent wrote: > Before I file a bug report against Python 2.5.2, I want to run this by > the newsgroup to make sure I'm not being stupid. > > I have a text file of fixed-length records I want to read in random > order. That file is being changed in real-time by another process, > and my process want to see the changes to the file. What I'm seeing > is that, once I've opened the file and read a record, all subsequent > seeks to and reads of that same record will return the same data as > the first read of the record, so long as I don't close and reopen the > file. This indicates some sort of buffering and caching is going on. > > Consider the following: > > $ echo "hi" >foo.txt # Create my test file > $ python2.5 # Run Python > Python 2.5.2 (r252:60911, Sep 22 2008, 16:13:07) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> f = open('foo.txt') # Open my test file > >>> f.seek(0) # Seek to the beginning of the file > >>> f.readline() # Read the line, I get the data I expected > 'hi\n' > >>> # At this point, in another shell I execute 'echo "bye" >foo.txt'. 'foo.txt' now has been changed > >>> # on the disk, and now contains 'bye\n'. > >>> f.seek(0) # Seek to the beginning of the still-open file > >>> f.readline() # Read the line, I don't get 'bye\n', I get the original data, which is no longer there. > 'hi\n' > >>> f.close() # Now I close the file... > >>> f = open('foo.txt') # ... and reopen it > >>> f.seek(0) # Seek to the beginning of the file > >>> f.readline() # Read the line, I get the expected 'bye\n' > 'bye\n' > > It seems pretty clear to me that this is wrong. If there is any > caching going on, it should clearly be discarded if I do a seek. Note > that it's not just readline() that's returning me the wrong, cached > data, as I've also tried this with read(), and I get the same > results. It's not acceptable that I have to close and reopen the file > before every read when I'm doing random record access. > > So, is this a bug, or am I being stupid? This has to do how the OS file-system operates. This is equivalent of doing: echo "hi" >foo.txt vi foo.txt in another session type: echo "bye" > foo.txt the text in the vi session doesn't change. you can even type 'rm foo.txt' and vi will still have the text there. From notvalid2 at sbcglobal.net Sun Oct 12 18:07:57 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sun, 12 Oct 2008 15:07:57 -0700 Subject: Pylab Fails with Runtime Error on Win XP Under Python 2.4 In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sun, 12 Oct 2008 12:56:26 -0700, "W. eWatson" > declaimed the following in comp.lang.python: > > >> Oddly when I use cmd, it gets me to settings and docs. If I try c:\whatever >> I get a msg, and it remains in the same folder. > > That's likely the defined "home directory" on your machine. > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\Dennis Lee Bieber>cd c:\bin > > C:\bin>e: > > E:\>cd "UserData\Dennis Lee Bieber\My Documents\Python Progs" > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>dir > Volume in drive E is Data > Volume Serial Number is 2626-D991 > > Directory of E:\UserData\Dennis Lee Bieber\My Documents\Python Progs > > 08/23/2008 01:26 PM . > 08/23/2008 01:26 PM .. > 08/23/2008 01:26 PM 1,089 azel_interp.py > 04/22/2007 04:43 PM 1,622 binadd.py > 04/22/2007 06:03 PM 1,485 binadd2.py > 12/11/2006 10:21 PM 119,889 BookList.zip > > 06/13/2008 08:46 PM 1,929 timing.py > 11/03/2007 10:31 PM 56 trips.dat > 03/31/2006 11:31 PM 10 update_log > 11/30/2005 10:11 AM 104 ut_00.py > 112 File(s) 397,123,218 bytes > 2 Dir(s) 270,550,671,360 bytes free > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs> > > NOTE: to change directory you need to enter the command: > cd new-directory > Without the "cd" your entry is being treated as the path to an > executable program -- and directories, of course, are not executable. To > change to a different partition/drive, you do enter just the drive > letter and a colon. And you need to do that separately -- each drive > maintains a "current directory" > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>cd c:\bin > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>dir > Volume in drive E is Data > Volume Serial Number is 2626-D991 > > Directory of E:\UserData\Dennis Lee Bieber\My Documents\Python Progs > > > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>c: > > C:\bin> > > Notice how changing drive to C: put me into the bin directory > specified earlier. If I now enter e:, I'll be back to the Python Progs > directory. > >> I guess PythonWin is a download for another IDE than IDLE. Will modules be >> available like mathplotlib if I install it, or do I have to establish them >> for it? I'll look PythonWin once I get past the cmd operation. >> > It comes supplied with the ActiveState Python download (which also > includes the win32 extensions). I believe it can also be obtained as a > stand-alone with the win32 stuff. > > The win32 extensions are: > http://sourceforge.net/project/platformdownload.php?group_id=78018 (just > checked, PythonWin is included) I worked my way into the folder where the py program is, but couldn't executed. Just entering aprog.py, run aprog.py or exec aprog.py didn't work. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From castironpi at gmail.com Tue Oct 7 12:55:01 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 7 Oct 2008 09:55:01 -0700 (PDT) Subject: type-checking support in Python? References: <1df0ae7e-d5c5-4839-9788-703cd58232c5@q9g2000hsb.googlegroups.com> Message-ID: On Oct 7, 5:24?am, Bas wrote: > On Oct 7, 8:36 am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > In message , Gabriel > > > Genellina wrote: > > > As an example, in the oil industry here in my country there is a mix of > > > measurement units in common usage. Depth is measured in meters, but pump > > > stroke in inches; loads in lbs but pressures in kg/cm?. > > > Isn't the right way to handle that to attach dimensions to each number? > > What they taught me as a physics undergrad is to always convert random > units given as input to SI units as soon as possible, do all your > calculations internally in SI units and (only if really needed) > convert back to arbitrary units on output. (snip) If you think it's a potential source of error, a lightweight version wouldn't be hard to implement. This one is absolute minimal, using strings for the units. Multiplication is harder, since you want 'foot pounds' == 'pound feet'. >>> class UnitScalar: ... def __init__( self, val, type ): ... self.val, self.type= val, type ... def __add__( self, other ): ... assert self.type== other.type, 'Must be same type' ... return self.__class__( self.val+ other.val, self.type ) ... def __repr__( self ): ... return ''% ( self.val, self.type ) ... >>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'feet' ) >>> a+ b >>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'inches' ) >>> a+ b Traceback (most recent call last): File "", line 1, in File "", line 5, in __add__ AssertionError: Must be same type From bj_666 at gmx.net Wed Oct 8 11:26:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Oct 2008 15:26:35 GMT Subject: distributing apps without the Python source? References: Message-ID: <6l41pbFaj22eU1@mid.uni-berlin.de> On Wed, 08 Oct 2008 09:18:47 -0600, Joe Strout wrote: > We have a client who's paranoid about distributing the Python source to > his commercial app. Is there some way I can distribute and use just the > .pyc files, so as to not give away the source? Yes. Just use the *.pyc files. Ciao, Marc 'BlackJack' Rintsch From tino at wildenhain.de Tue Oct 28 09:59:59 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 28 Oct 2008 14:59:59 +0100 Subject: Sorting a list In-Reply-To: References: Message-ID: <49071ADF.9020303@wildenhain.de> RC wrote: > unsortedList = list(["XYZ","ABC"]) > > sortedList = unsortedList.sort() > print sortedList > > > Why this return None? Because you did not read the documentation. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From kusumi.tomohiro at gmail.com Thu Oct 23 12:28:45 2008 From: kusumi.tomohiro at gmail.com (tomohiro kusumi) Date: Fri, 24 Oct 2008 01:28:45 +0900 Subject: Perl/Python regular expressions vs. Boost.regex? In-Reply-To: <18688.36548.111115.927147@montanaro-dyndns-org.local> References: <18688.36548.111115.927147@montanaro-dyndns-org.local> Message-ID: I was confused when I first used Boost regualr expressions, but I got used to it now. Aside from it, I think Boost regular expression makes you write too much code just to do a simple pattern matching. Tomohiro Kusumi 2008/10/23 > A colleague wrote a C++ library here at work which uses the Boost.regex > library. I quickly discovered an apparent problem with how it searches. > Unlike re.match the regex_match function in that library effectively > anchors > the match at both the start and the end. Can other people confirm this? > > Thx, > > Skip Montanaro > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Wed Oct 15 16:07:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 15 Oct 2008 13:07:12 -0700 (PDT) Subject: OOP books? References: <4b0f5$48f63024$4553@news.teranews.com> Message-ID: <8b4a564e-4761-4743-baf9-6f496ba58d83@2g2000hsn.googlegroups.com> On Oct 15, 1:57?pm, Alan G Isaac wrote: > Mike Driscoll wrote: > > I have yet to read a Python book that only focuses on the OOP part, > > http://www.amazon.com/Scripting-Objects-Comparative-Presentation-Obje... > > fwiw, > Alan Isaac Wow! That's a pricey book! Have you read it? Is it good? Mike From gherron at islandtraining.com Thu Oct 9 04:31:05 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 09 Oct 2008 01:31:05 -0700 Subject: replace numbers in a string In-Reply-To: References: Message-ID: <48EDC149.7050500@islandtraining.com> Beema Shafreen wrote: > hi All, > > i have few lines in file > "ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg" > i need to replace the number and get only the alphabet in such a case > what should i do. > Can any body suggest me >From the regular expression module, use re.sub like this: >>> import re >>> re.sub('[0-9]', '', "ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg") 'ttccatttctggacatgacgtctgtggtttaagctttgtgaaagaatgtgctttgattcg' Gary Herron > > -- > Beema Shafreen > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > From nospam at spamhaters.com Sat Oct 4 00:36:07 2008 From: nospam at spamhaters.com (sc) Date: Fri, 03 Oct 2008 23:36:07 -0500 Subject: Python for the Playstation 3 References: <27CC3060AF71DA40A5DC85F7D5B70F38054B69D7@AWMAIL04.belcan.com> Message-ID: <6mCFk.2367$D32.762@flpi146.ffdc.sbc.com> Terry Reedy wrote: > machine. So this seems a timely idea. But I don't have a Playstation > -- yet. > tjr have you priced them recently? I just looked and they are $200 less than the last time I looked -- eeks! Now _I_ want one! From darcy at druid.net Sun Oct 19 10:55:16 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 19 Oct 2008 10:55:16 -0400 Subject: Linux.com: Python 3 makes a big break In-Reply-To: References: Message-ID: <20081019105516.a29b00ad.darcy@druid.net> On 19 Oct 2008 07:44:52 -0700 aahz at pythoncraft.com (Aahz) wrote: > > sys.stdout.write \ > > ( > > Why are you using a backslash? Because he hasn't opened the paren yet. He could have put the open paren on the same line as the write obviating the need for the backslash but then his open/close parens wouldn't line up. It just a matter of style. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From gordyt at gmail.com Fri Oct 3 09:25:49 2008 From: gordyt at gmail.com (gordyt) Date: Fri, 3 Oct 2008 06:25:49 -0700 (PDT) Subject: SQLite References: <6kmhnoF8kljqU1@mid.uni-berlin.de> Message-ID: <3e4cb0bf-2d2c-4ec4-a649-e9b6026fd41b@a1g2000hsb.googlegroups.com> Howdy Matthias! The delete operation will set the rowcount member of your cursor. Let's assume you have an sqlite3 database with a table called 'test' with an id column. It does have a record with id=1. It does not have a record with id=2. >>> import sqlite3 >>> connection = sqlite3.connect('test.sqlite3') >>> cursor = connection.cursor() >>> cursor.execute('delete from test where id=1') >>> print cursor.rowcount 1 >>> cursor.execute('delete from test where id=2') >>> print cursor.rowcount 0 >>> cursor.close() >>> connection.close() --gordy From pruebauno at latinmail.com Mon Oct 6 15:23:00 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 6 Oct 2008 12:23:00 -0700 (PDT) Subject: Builing Python 2.6 on AIX 5.2 References: <238e9869-b645-47a3-bd4a-e5d567667a40@64g2000hsu.googlegroups.com> Message-ID: On Oct 6, 11:03 am, "Jesse Noller" wrote: > Looks like AIX is missing sem_timedwait - see:http://bugs.python.org/issue3876 > > Please add your error to the bug report just so I can track it. > > -jesse > > On Mon, Oct 6, 2008 at 4:16 AM, brasse wrote: > > Hello! > > > I am having some trouble building Python 2.6 on AIX. The steps I have > > taken are: > > > export PATH=/usr/bin/:/usr/vacpp/bin/ > > ./configure --with-gcc=xlc_r --with-cxx=xlC_r --disable-ipv6 > > make > > > This is the error message I'm seeing: > > ./Modules/ld_so_aix xlc_r -bI:Modules/python.exp build/ > > temp.aix-5.2-2.6/home/mabr/Python-2.6/Modules/_multiprocessing/ > > multiprocessing.o build/temp.aix-5.2-2.6/home/mabr/Python-2.6/Modules/ > > _multiprocessing/socket_connection.o build/temp.aix-5.2-2.6/home/mabr/ > > Python-2.6/Modules/_multiprocessing/semaphore.o -L/usr/local/lib -o > > build/lib.aix-5.2-2.6/_multiprocessing.so > > ld: 0711-317 ERROR: Undefined symbol: .sem_timedwait > > ld: 0711-317 ERROR: Undefined symbol: .CMSG_SPACE > > ld: 0711-317 ERROR: Undefined symbol: .CMSG_LEN > > ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more > > information. > > *** WARNING: renaming "_multiprocessing" since importing it failed: No > > such file or directory > > error: No such file or directory > > make: The error code from the last command is 1. > > > Have someone on this list had similar problems? Am I missing some > > libraries? The configure script runs without errors, I would have > > expected some kind of error there if I was missing something. > > > Regards, > > Mattias > > -- > >http://mail.python.org/mailman/listinfo/python-list FYI I read that some people use: HAVE_BROKEN_POSIX_SEMAPHORES in pyconfig.h. for AIX, although I never do. Maybe I am not doing anything advanced enough for problems related to semaphores to show up. From bdesth.quelquechose at free.quelquepart.fr Tue Oct 14 14:50:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 14 Oct 2008 20:50:13 +0200 Subject: default value in __init__ In-Reply-To: References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> Message-ID: <48f505c8$0$20216$426a74cc@news.free.fr> David C. Ullrich a ?crit : > In article <48ef37fe$0$22798$426a34cc at news.free.fr>, > Bruno Desthuilliers > wrote: > >> David C. Ullrich a ?crit : (snip) >>> Seems to me that people often site the "important warning" in >>> the tutorial. Of course there's no reason anyone would bother >>> going through the tutorial >> Indeed. No reason at all. >> >>> - just for fun I looked in the >>> official Python Reference Manual to see whether they're explicit >>> about this or require the reader to figure it out from something >>> else they say. >>> >>> There's a section titled "7.6 Function definitions". About halfway >>> through that section there's a _bold face_ statement >>> "Default parameter values are evaluated when the function definition is >>> executed.", followed by an explanation of how that can lead to >>> the sort of problem above. >> But there's no reason to read the reference manual neither. >> >>> So I guess it _is_ awfully dangerous. They Hum... Who are "they", exactly ? >>> should really explain >>> this aspect of the language's behavior to people who don't read >>> the formal definition and also don't work through the tutorial. >> You mean : "to people that don't bother reading the FineManual *nor* >> searching the newsgroup / ML archives ?" > > Yes. Also add "don't read any books". Indeed. > I think I started with some > book As far as I'm concerned, I started with the FineManual(tm)'s tutorial. (snip) >> Well... How to say.. Is there any chance these people will read anything >> *at all* ? > > No. That's exactly the point! Yeps. But I don't think we derive the same conclusions from that point. > Basic Python is so transparent that > you can start using it without reading anything, just looking at > a few examples. And immediatly fall into a well-known (and well-documented) "gotcha" - like forgetting to apply the call operator to function, using mutable default arguments, using mutable class attributes instead of instance attributes, etc, etc, etc... While it has been heavily publicized that Python is easy to get started with - which, AFAICT, seems to still be true for any programmer already having some experience *and* serious enough to actually _read_ that fucking manual -, it doesn't mean that, by the virtue of some extraterrestrial magic, one could master the language just reading a couple dummy examples. Learning a language requires some home work, period. > _Because_ of that it's their who are "they" in this "their" ? > responsibility to > ensure that if you look at a few examples you then have a complete > understanding of the language. I'm afraid I have to say this is *totally* utopic - except perhaps for the most braindead and limited language one could imagine. Heck, even Java - which has explicitely been designed for morons^Mdummies - would fail this test. How could "a few examples" provide complete understanding of attribute lookup rules, the descriptor protocol, metaclasses, iterators, and generator expression - just to name a few ? Granted, Python is easy to get started with. This doesn't mean anyone should expect it to work like any language XXX they already know. Every language has it's own pecularities, every language requires a serious learning effort, and Python is no exception here. FWIW, on most programming language-related newgroups, the only answer to such FAQs would be (at best) a raw RTFM. Not that I'd advertise such a behaviour here - this newsgroup is mostly newbies-friendly and I *really* appreciate it to be that way (and happily answer the same 101 questions year after year FWIW), but I really fail to see how anything more could be done for points that are 1/ clearly documented and 2/ reexplained here month after month. > In particular default parameters should work the way the user > expects! The fact that different users will expect different > things here is no excuse... If different users expect different - mostly incompatible - things, how would it be possible to have it working "the way the user expect" ? Should Python grow some telepathic features to guess the user's expectations and modifies itself to meet these expectations ?-) From bdesth.quelquechose at free.quelquepart.fr Fri Oct 3 14:51:54 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 03 Oct 2008 20:51:54 +0200 Subject: One class per file? In-Reply-To: <6km17kF8kemdU1@mid.individual.net> References: <48e347af$0$19545$426a74cc@news.free.fr> <6km17kF8kemdU1@mid.individual.net> Message-ID: <48e685b2$0$10441$426a34cc@news.free.fr> greg a ?crit : > Bruno Desthuilliers wrote: > >> OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++ >> (which both have namespaces one way or another) > > In Java you don't get a choice, because the compiler > assumes a class can be found in the correspondingly > named file. For public classes only. > > While C++ has namespaces, they don't have any defined > relationship to source files, so they don't help you > find which file something is defined in. Nope. But IIRC, one-class-per-file helps saving on compile/link time. A problem we don't have with dynamic languages !-) From gaohawk at gmail.com Thu Oct 30 10:04:52 2008 From: gaohawk at gmail.com (hawk) Date: Thu, 30 Oct 2008 07:04:52 -0700 (PDT) Subject: how to get full-text search of pysqlite3 work in python2.5.2 References: <6bd6a76a-ce23-40cb-aa53-432a937fc5fa@u28g2000hsc.googlegroups.com> Message-ID: <52d6287c-fc6d-4bae-98cd-a0ae5df20ed3@z6g2000pre.googlegroups.com> On Oct 30, 8:21?pm, "Guilherme Polo" wrote: > On 10/30/08, hawk wrote: > > > > > Hi, > > ?my environment is debian, python 2.5.2. > > ?when i call con.enable_load_extension(True), the following message > > ?prompt out. > > ?debian:~# python2.5 > > ?Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) > > ?[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > ?Type "help", "copyright", "credits" or "license" for more information. > > ?>>> import sqlite3 > > ?>>> con = sqlite3.connect(":memory:") > > ?>>> con.enable_load_extension(True) > > ?Traceback (most recent call last): > > ? File "", line 1, in > > ?AttributeError: 'sqlite3.Connection' object has no attribute > > ?'enable_load_extension' > > enable_load_extension was added in pysqlite 2.5, but python 2.5.2 > includes an older version of pysqlite. > > > ?Thanks > > ?Hawk > > > -- > > ?http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves i have solved this problem by install from latest source package. but, another issue raised, when i called con.execute("select load_extension('./fts3.so')") and con.execute("CREATE VIRTUAL TABLE posts using FTS3(title, body);"). the error message is, >>> from pysqlite2 import dbapi2 as sqlite3 >>> con = sqlite3.connect(":memory:") >>> con.enable_load_extension(True) >>> con.execute("select load_extension('./fts3.so')") Traceback (most recent call last): File "", line 1, in pysqlite2.dbapi2.OperationalError: extension loading is disabled i checked whole file system for fts.so. but there is no fts3.so anymore. then i downloaded the full source code of latest sqlite, and compiled it. but also, no fts2.so exists under build folder. finally, i downloaded sqlite-amalgamation-3_6_4.zip and compiled it with CFLAGS="-DSQLITE_ENABLE_FTS3=1" option. the whole command line is "CFLAGS="-DSQLITE_ENABLE_FTS3=1" ./configure". unfortunately, the fts3.so cannot be found too. how can i get the fts2.so!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! From incomecash123 at gmail.com Wed Oct 22 04:40:40 2008 From: incomecash123 at gmail.com (jaggu) Date: Wed, 22 Oct 2008 01:40:40 -0700 (PDT) Subject: GOODNEWS Message-ID: <57790934-da4c-4147-9899-d67812439c55@q35g2000hsg.googlegroups.com> GOODNEWS EARN BY JUST READING SMS ON UR MOBILE- UR INCOMMING SMS PAY'S U INCOME ONE CLICK AWAY FROM EARNING THROUGH INCOMMING SMS http://www.mGinger.com/index.jsp?inviteId=623396 http://www.paisa4sms.com/Index.aspx?Inviteid=134129 http://www.youmint.com/network-jagguzwx2 http://mGinger.com/index.jsp?inviteId=1820537 http://mGinger.com/index.jsp?inviteId=1820510 { HEART SURGERY FREE OF COST FOR CHILDRENS, "SRI SATYA SAI INSTITUTE" "BANGLORE" PH: 08028411500 } PLEASE PASS THIS MESSAGE TO ALL IT MAY BE HELPFUL TO SOMEONE...... ADD YOUR NAME PLSSSS JAGADISH, IBRAHIM, DHARNIDHAR, DAYAKAR RAO, SAMIKSHYA DUGGAL RAMI REDDY, SUMALATHA, VENA, RANJIT, PETER, PASURAM, LAKSHMI, NAROTHAM RAO VENKAT, PERMASH, RAMESH, RATHI , SUSHANT SAI, DEVISREE,GOPI, DIVYASHREE, SRINIVAS,HARI BABU,PADMAJA RANI, SAVITRI, JAWHAR, From ldo at geek-central.gen.new_zealand Sun Oct 26 19:40:52 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Oct 2008 12:40:52 +1300 Subject: Porting VB apps to Python for Window / Linux use References: <48fcd5c3$0$8723$426a34cc@news.free.fr> <87d4huq3rr.fsf@asus-190829777.TeleWell.gateway> Message-ID: In message , Stef Mientki wrote: > ... although I realize closed source is not completely possibly in Python, > but that's no problem if the program is large/complex enough compared to > it's market value ;-) Software has no market value. Business models that try to assign it one are doomed to fight an uphill battle against market forces. From dotancohen at gmail.com Tue Oct 14 09:28:01 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 14 Oct 2008 15:28:01 +0200 Subject: Can Python fix vcard files? In-Reply-To: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> References: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> Message-ID: <880dece00810140628w3eeb0096w1c64cfede131f089@mail.gmail.com> 2008/10/14 Paul Boddie : >> Can Python go through a directory of files and replace each instance >> of "newline-space" with nothing? The system is Ubuntu 8.04 with KDE if >> it matters. Thanks. > > You should file a bug against Kontact: the KDE developers love fixing > bugs, especially in their old work. ;-) > I had to reopen an old bug on this: https://bugs.kde.org/show_bug.cgi?id=68350 I would really appreciate it if the knowledgeable folks here would chime in on that bug. Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From alex.gaynor at gmail.com Sat Oct 4 16:15:12 2008 From: alex.gaynor at gmail.com (Alex_Gaynor) Date: Sat, 4 Oct 2008 13:15:12 -0700 (PDT) Subject: lint for Python? References: Message-ID: <470ed07d-9ec1-4124-abf1-1558c96ed60e@64g2000hsu.googlegroups.com> On Oct 3, 5:38?pm, Pat wrote: > I've been searching for a good multi-module lint checker for Python and > I haven't found one yet. > > Pylint does a decent job at checking for errors only within a single module. > > Here's one of my problems. ?I have two modules. > > In module one, I have a function: > > def foo( host, userid, password ): > ? ? ?pass > > In module two, I call that function: > > foo( userid, password) > > lint doesn't find that error and it won't be caught until it's called > while the program is running. ?I don't want that error found at 3AM. > > I've never used a language that didn't catch that type of error. ?I'm > quite surprised that Python is being used by a number of major > companies. ?How you catch these types of errors? > > I've spoken to tech support at Wing and they weren't aware of a > multi-module lint but they're considering putting their own lint into > their IDE. > > Thank you I doubt you will find a tool that can find that kind of error(at least not reliably), python is a highly dynamic language, and so foo() can easily be reassigned at any point in the execution. From tjreedy at udel.edu Thu Oct 9 00:11:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2008 00:11:51 -0400 Subject: how to get the thighest bit position in big integers? In-Reply-To: <6l51iqFaag6aU1@mid.individual.net> References: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> <1a007084-ca6c-448b-aa69-4d2bb0da2ad9@t65g2000hsf.googlegroups.com> <2a8d47dd-7906-48e0-ad99-1b9df7ef5281@y79g2000hsa.googlegroups.com> <6l51iqFaag6aU1@mid.individual.net> Message-ID: greg wrote: > Terry Reedy wrote: > >> str.find is an historical anomaly that should not be copied. It >> was(is?) a wrapper for C's string find function. C routinely uses -1 >> to mean None for functions statically typed to return ints. The >> Python version logically should return None and usually does for other >> functions. I consider str.find to be an anomaly in two senses. First, it is the only function/method I can think of that directly duplicates another function/method by replace raising an exception with returning an error indicator. Some developers wanted to drop it from 3.0, and I too wish it had been. We get along fine without list.find and a whole slew of other such duplicates that one could think of. Second, it is the only function/method I can think of that follows the Unix/C convention of using '-1' as an error/exception/no-can-do indicator. When it is so used, it is not really an int, but an error indication represented as an int because there is no other choice. In Python, there is another choice -- None -- which is used routinely, including its use as the default return when there is nothing else to return. > Although Guido has defended it on the grounds that it can > be inconvenient having a function that returns different > types under different circumstances. Also it discourages > making the mistake of treating the return value as a > boolean. I consider this backwards. Since -1 is a legal index in Python (unlike some other languages) as well as a legal int, returning -1 allows if not encourages the mistake of treating the fake return value as if it were a real value. Returning None would completely prevent any use of the error indicator other than to test it, which is the only thing one should be able to do with it. It should not be usable as an index or number in further calculations. I consider it a principle that error indicators that are returned rather than raised should be an illegal-to-use value if not a different type. As for convenience, "if s.find(t) is None:" is as easily to write (and clearer to read) as "if s.find(t) == -1:". As far as I can see, different return types are only an issue, if at all, if values of both types are to be used in further calculations. Terry Jan Reedy From tjreedy at udel.edu Thu Oct 16 22:39:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Oct 2008 22:39:25 -0400 Subject: Finding the instance reference of an object In-Reply-To: <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> References: <3zIJk.5599$YU2.3294@nlpi066.nbdc.sbc.com> <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> Message-ID: Astley Le Jasper wrote: > I'm creating mulitple instances, putting them in a list, iterating > through the list to send them to some functions where process them > with some instance specific parameters. Something along the lines of: > > bob = someobject() > harry = someobject() > fred = someobject() > > parameterdict = {'bob':(0,1,2),'harry':(3,4,5),'fred':(6,7,8)} > people_list = (bob, harry, fred) > > for person in people_list: > add_parameters(person) > > def add_parameters(person) > mytuple = parameterdict[??????instance.name????] > person.x = mytuple[0] > person.y = mytuple[1] > person.z = mytuple[2] If you want an object to have a 'personal' name, give it a name attribute, just like python does to modules, classes, and functions. class someob(): def __init__(self,name): self.name = name people = {someob('bob'), someob('harry'), someob('fred') ... def add_param(person): mytuple = parameterdict[person.name] ... From hackamore_travel at yahoo.com Thu Oct 9 01:14:41 2008 From: hackamore_travel at yahoo.com (Hackamore) Date: Thu, 09 Oct 2008 00:14:41 -0500 Subject: Porn Addiction Solutions? In-Reply-To: References: Message-ID: pavements01 at yahoo.com wrote: > Help, I'm addicted to porn. I've been spending a lot of time > downloading hardcore porn and masturbating to it. It's ruining my > life. I just found out that one of these sites somehow hacked my card > and rang up $5K in charges which they won't even refund me. Even with > that I haven't stopped my habit and it's only getting worse. How can I > end this addiction? > > Any suggestions? Hi, they didn't "hack" your account, you gave it to them. if they're unauthorized charges (not you subscribed to expensive porn sites and now don't to pay, or you didn't bother to cancel your subscription) contest them From kreno at yumaed.org Fri Oct 10 12:36:31 2008 From: kreno at yumaed.org (Kerri Reno) Date: Fri, 10 Oct 2008 10:36:31 -0600 Subject: Python Boot Camp 11/10-11/14 Message-ID: Anyone thinking about attending the Python Boot Camp at Big Nerd Ranch? This is the time. If they don't get one more person they will cancel the session. So if you're on the fence, take one for the Gipper, and sign up for the November session. http://www.bignerdranch.com/classes/python.shtml Kerri -- Yuma Educational Computer Consortium Compass Development Team Kerri Reno kreno at yumaed.org (928) 502-4240 .?:*??*:?. .?:*??*:?. .?:*??*:?. From stef.mientki at gmail.com Tue Oct 21 14:29:37 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 21 Oct 2008 20:29:37 +0200 Subject: Don't understand syntax error: unqualified exec is not allowed .. In-Reply-To: References: <48FCEC76.6080202@gmail.com> Message-ID: <48FE1F91.105@gmail.com> Terry Reedy wrote: > Stef Mientki wrote: >> hello, >> >> I've syntax error which I totally don't understand: >> >> ########## mainfile : >> import test_upframe2 >> >> if __name__ == '__main__': >> var1 = 33 >> code = 'print var1 + 3 \n' >> test_upframe2.Do_Something_In_Parent_NameSpace ( code ) >> >> ########### file = test_upframe2 : >> class Do_Something_In_Parent_NameSpace ( object ) : >> def __init__ ( self, code ) : >> def do_more ( ) : ## Indentation corrected here >> nonvar = [3,4] >> while len ( nonvar ) > 0 : # <<<=== >> nonvar.pop() # <<<=== > > Indendation is screwed. Is the above all do_more body? sorry, don't know how this happened, as I always copy/paste ? > >> import sys >> p_locals = sys._getframe(1).f_locals > > Which locals does this get you? __init__'s? (locals()?) AFAIK locals() == sys._getframe(0).f_locals > >> p_globals = sys._getframe(1).f_globals > > Isn't this just the same as globals()? AFAIK, again one level up > >> try : >> exec ( code, p_globals, p_locals ) > > This is 3.0 exec function syntax. weird, I use it in 2.5 and if I remember well it already worked in 2.4. but exchanging the function with the statement yields exactly the same results > Postings should specify which interpreter you are running, > especially when mucking with > internals. > >> except : >> print 'ERROR' >> >> >> gives me: >> SyntaxError: unqualified exec is not allowed in function '__init__' >> it contains a nested function with free variables (gui_support.py, >> line 408) "unqualified exec" : I thought that meant there >> is some ambiguity in the namespace, but I explictly definied the >> namespace >> >> The function "do_more" is never called, so what does it matter >> what's in there ? >> >> If I remove the while-loop (which of course I can't) the syntax error >> disappears. >> >> I can place the function either as a class method or as a normal >> function outside the class, >> which both works well. >> But I want the method / function not to be hidden. > > Since you are hiding it, I presume you mean to be, not not to be. Yes ;-) >> >> Why does the above syntax error appear ? >> Are there other ways to hide the function ? > > Either use module level __all__ or name the function _do_more and > anyone will know it is private to the module. > done. And now I still don't understand the problem in the above code ;-) thanks, Stef From deets at nospam.web.de Wed Oct 22 10:05:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 22 Oct 2008 16:05:07 +0200 Subject: Two-dimensional array tutorial? References: <6m8p4vFfnd9nU2@mid.individual.net> Message-ID: <6m8q88Ffc6r2U2@mid.uni-berlin.de> Martin Schneider wrote: > Hi! > > I'd like to handle two-dimensional arrays. My first choice, the numpy > library, doesn't seem to be an option due to compatibility issues (see > my other thread about python22.dll). > > Is there a tutorial somewhere how to handle 2d-arrays with vanilla Python? there isn't much to them, simply create an use: foo = [[0 for _ in xrange(height)] for _ in xrange(width)] or something similar. Then you just use foo[x][y] to access individual elements. Alternatively, you can use the module "array" for the inner list to be more memory-efficient. Obviously you don't get any further operations on arrays such as transposition, multiplication and the like. Can't you just get Numpy (or it's predecessors, Numeric) compiled against ptyhon2.2? Diez From bdesth.quelquechose at free.quelquepart.fr Fri Oct 17 14:51:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 17 Oct 2008 20:51:57 +0200 Subject: Python certification In-Reply-To: References: Message-ID: <48f8fab0$0$1138$426a34cc@news.free.fr> srinivasan srinivas a ?crit : > Hi, > I m planning to do certification in Python?? > Is therr any good certification available in Python like Sun certification for java?? Yes, indeed : actively contribute to some major python project (or even better to the language itself or its stdlib), and become an helpful regular here. !-) Gosh - i HATE this "certification" racket bizness. The only thing they "certify" is that you paid the fees. period. From deets at nospam.web.de Mon Oct 6 02:22:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Oct 2008 08:22:06 +0200 Subject: "'int' object is not iterable" iterating over a dict In-Reply-To: References: Message-ID: <6ktp4eF9kevtU1@mid.uni-berlin.de> mmiikkee13 schrieb: >>>> a_list = range(37) >>>> list_as_dict = dict(zip(range(len(a_list)), [str(i) for i in a_list])) >>>> for k, v in list_as_dict: > ... print k, v > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object is not iterable > > What 'int' object is this referring to? I'm iterating over a dict, not > an int. Because for name in dictionary: will bind name to the *keys* of dictionary. Thus you end up with an int. Then the tuple-unpacking occurs: k, v = Which is equivalent to k = [0] v = [1] And because isn't iterable, it will fail. Use for k, v in dictionary.iteritems(): instead. Diez From prologic at shortcircuit.net.au Sun Oct 26 21:52:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 27 Oct 2008 11:52:32 +1000 Subject: Improving interpreter startup speed In-Reply-To: References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> Message-ID: On Mon, Oct 27, 2008 at 4:12 AM, Benjamin Kaplan wrote: > You must be in a real big hurry if half a second matters that much to you. > Maybe if it took 5 seconds for the interpreter to start up, I could > understand having a problem with the start up time. +1 This thread is stupid and pointless. Even for a so-called cold startup 0.5s is fast enough! --JamesMills -- -- -- "Problems are solved by method" From crebert at ucsd.edu Fri Oct 17 13:27:24 2008 From: crebert at ucsd.edu (Chris Rebert) Date: Fri, 17 Oct 2008 10:27:24 -0700 Subject: Script can't find input file despite being in the same directory In-Reply-To: <8c4b42bb-a9de-45b7-b282-f8981d3245bb@u27g2000pro.googlegroups.com> References: <8c4b42bb-a9de-45b7-b282-f8981d3245bb@u27g2000pro.googlegroups.com> Message-ID: <47c890dc0810171027o5d6df78cpbc3d0226f48b2c1a@mail.gmail.com> On Fri, Oct 17, 2008 at 10:07 AM, Robocop wrote: > I have a simple little script that reads in postscript code, appends > it, then writes it to a new postscript file. Everything worked fine a > month ago, but after rearranging my directory tree a bit my script > fails to find the base postscript file. > > The line in question is: > > for line in fileinput.input(['base.ps']): > output.write(line) What directory is output if you insert the lines: from os import getcwd print "CWD:", getcwd() just before the line is question? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > I'm kind of at a loss as the script is executing in the same directory > as base.ps, yet it can't find it. I'm relatively new to python > scripting, so i'm expecting it's just something i haven't learned > about python that is causing the problem. Any suggestions would be > greatly appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list > From see.signature at no.spam Fri Oct 3 04:31:32 2008 From: see.signature at no.spam (Eric Brunel) Date: Fri, 03 Oct 2008 10:31:32 +0200 Subject: tkinter textwidget problem References: <48e5278e$0$6543$426a74cc@news.free.fr> Message-ID: On Thu, 02 Oct 2008 21:57:01 +0200, kib2 wrote: > Hi, > > In a tkinter TextWidget I would like to retrieve the last typed word. > > I've tried this with the 'wordstart' Expression [From the effbot site, > "wordstart" and "wordend" moves the index to the beginning (end) of the > current word. Words are sequences of letters, digits, and underline, or > single non-space characters.], but it fails : > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > from Tkinter import * > root = Tk() > text = Text(root, font=("Calibri")) > text.pack() > > # Insert some text inside (13 chars long) > text.insert(INSERT, "one two three") > > # idx_st : the position of the cursor > # idx_ed : same but translated to the beginning of the last word ? > idx_st = text.index( "insert" ) # returns 1.13 > idx_ed = text.index( "insert wordstart" ) # returns 1.13 too : why ? Tk/Tkinter apparently considers the position 1.13 to be after the last word in the text. You get the same problem if you set the insertion point just after the word 'two' for example: text.index('insert') returns 1.7 and text.index('insert wordstart') returns 1.7 too... My solution would simply be to go back one character before asking the word start: text.index('insert - 1 chars wordstart') Don't know if that'll do what you want if there are spaces at the end of the text. And BTW, if you actually want the *last* word in the text, you may want to use text.index('end - 2 chars wordstart'). Here, you have to use '- 2 chars' because end points to the first non-existent index (2.0 in your case...). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From steve at holdenweb.com Sun Oct 19 12:47:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 19 Oct 2008 12:47:06 -0400 Subject: keyword in package name. In-Reply-To: <6m0bk2Fe8qbdU1@mid.uni-berlin.de> References: <6m0bk2Fe8qbdU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sat, 18 Oct 2008 23:05:38 -0700, Abhishek Mishra wrote: > >> I have the habit of using domain names (of either the application or >> company) in reverse in package names. [...] > The `__init__.py` of which vendor > should live at the `com/` directory level? If you install them into two > different directories but want to import modules from both vendors -- how? > Obviously the "com" namespace wouldn't belong to any vendor, and the __init__.py should be empty. Though I do think it's an inappropriate choice for Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From vriolk at gmail.com Fri Oct 17 12:35:24 2008 From: vriolk at gmail.com (coldpizza) Date: Fri, 17 Oct 2008 09:35:24 -0700 (PDT) Subject: 'Hidden Features of Python' References: <4fd267a1-a0fe-4010-96ec-eb1c0b27e17c@p59g2000hsd.googlegroups.com> Message-ID: If you are using and IDE, such as Eclipse, PyScripter, etc, then CTR +click on 'this' should do the trick. In ipython you can do 'import this' and then type 'this??' Or if you are *not* lazy, you could try locating the file in the Python tree. > import this > # btw look at this module's source :) > > I don't see what I'm supposed to get from that. ?If I'm supposed to ? > see the magic (and explanation) be examining the source for the 'this' ? > module, well, I don't see how I can do that either. ?Can someone who ? > gets this share a clue? > > Thanks, > - Joe From bruno.42.desthuilliers at websiteburo.invalid Wed Oct 1 12:09:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 01 Oct 2008 18:09:20 +0200 Subject: Event-driven framework (other than Twisted)? In-Reply-To: References: <4d191607-14e3-42c4-8622-0cc4c7339550@d31g2000hsg.googlegroups.com> <6khibnF7p971U2@mid.individual.net> Message-ID: <48e3a08b$0$12658$426a74cc@news.free.fr> Phillip B Oldham a ?crit : > On Oct 1, 4:12 pm, Thomas Guettler wrote: >> Please explain what you want to do. > > I'm primarily looking for alternatives to MVC frameworks for web > development, particularly SAAS. I've looked around, and some > whitepapers suggest that event-based frameworks often perform better > than MVC. Since I'm looking at SAAS, having a "view" is pretty > pointless since I'll either be using Thrift, returning simple HTTP > headers, or returning some sort of JSON/YAML/XML content (possibly > based on accept headers). "view" doesn't imply (x)html - any valid HTTP response is ok. The whole point of decoupling controler from view (in web MVC) is to allow the same controler to return different views. From __peter__ at web.de Wed Oct 29 10:45:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Oct 2008 15:45:03 +0100 Subject: Fastest way to convert sql result into a dict or list ? References: Message-ID: rewonka at gmail.com wrote: > Hello, > > I'm trying to find the fastest way to convert an sql result into a > dict or list. > What i mean, for example: > my sql result: > contact_id, field_id, field_name, value > sql_result=[[1, 1, 'address', 'something street'], > [1, 2, 'telnumber', '1111111111'], > [1, 3, 'email', 'something at something.net'], > [2, 1, 'address','something stree'], > [2, 3, 'email','something at something.net']] > the dict can be: > dict={1:['something street', '1111111111' , > 'something at something.net'], > 2:['something street', '', 'something at something.net' ]} > or a list can be: > list=[[1,'something street', '1111111111' , > 'something at something.net'], > [2,'something street', '', 'something at something.net' ]] > > I tried to make a dict, but i think it is slower then make a list, and > i tried the "one lined for" to make a list, it's look like little bit > faster than make a dict. > > def empty_list_make(sql_result): > return [ [line[0],"", "", ""] for line in sql_result] > > than fill in the list with another for loop. > I hope there is an easyest way to do something like this ?? > any idea ? I think it won't get much easier than this: dod = {} to_index = [None] + range(3) for contact_id, field_id, field_name, value in data: if contact_id not in dod: dod[contact_id] = [""]*len(to_index) dod[contact_id][to_index[field_id]] = value A database expert might do it in SQL, but my try got a bit messy: import sqlite3 as sqlite conn = sqlite.connect(":memory:") cs = conn.cursor() cs.execute("create table tmp (contact_id, field_id, field_name, value);") data = [[1, 1, 'address', 'one-address'], [1, 2, 'telnumber', 'one-telephone'], [1, 3, 'email', 'one at email'], [2, 1, 'address','two-address'], [2, 3, 'email','two at email']] cs.executemany("insert into tmp values (?, ?, ?, ?)", data) def make_query(field_defs, table="tmp"): field_defs = [("alias%s" % index, id, name) for index, (id, name) in enumerate(field_defs)] fields = ", ".join("%s.value as %s" % (alias, name) for alias, id, name in field_defs) format = ("left outer join %(table)s as %(alias)s " "on main.contact_id = %(alias)s.contact_id " "and %(alias)s.field_id=%(field_id)s ") joins = "\n".join(format % dict(table=table, alias=alias, field_id=id) for alias, id, name in field_defs) return ("select distinct main.contact_id, %(fields)s " "from %(table)s as main\n %(joins)s" % dict( table=table, fields=fields, joins=joins)) field_defs = list( cs.execute("select distinct field_id, field_name from tmp")) # XXX sanitize field ids and names sql = make_query(field_defs) for row in cs.execute(sql): print row Note that you get None for empty fields, not "". Peter From __peter__ at web.de Thu Oct 9 09:20:48 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Oct 2008 15:20:48 +0200 Subject: template strings for matching? References: Message-ID: Joe Strout wrote: > Catching up on what's new in Python since I last used it a decade ago, > I've just been reading up on template strings. These are pretty > cool! I don't think they've gained much traction and expect them to be superseded by PEP 3101 (see http://www.python.org/dev/peps/pep-3101/ ) > However, just as a template string has some advantages over % > substitution for building a string, it seems like it would have > advantages over manually constructing a regex for string matching. > > So... is there any way to use a template string for matching? I > expected something like: > > templ = Template("The $object in $location falls mainly in the > $subloc.") > d = templ.match(s) > > and then d would either by None (if s doesn't match), or a dictionary > with values for 'object', 'location', and 'subloc'. > > But I couldn't find anything like that in the docs. Am I overlooking > something? I don't think so. Here's a DIY implementation: import re def _replace(match): word = match.group(2) if word == "$": return "[$]" return "(?P<%s>.*)" % word def extract(template, text): r = re.compile(r"([$]([$]|\w+))") r = r.sub(_replace, template) return re.compile(r).match(text).groupdict() print extract("My $$ is on the $object in $location...", "My $ is on the biggest bird in the highest tree...") As always with regular expressions I may be missing some corner cases... Peter From jason.heeris at gmail.com Thu Oct 30 19:42:27 2008 From: jason.heeris at gmail.com (Jason) Date: Thu, 30 Oct 2008 16:42:27 -0700 (PDT) Subject: Graphical object browser References: <79e10196-3943-4fc1-9161-fb6600a458a4@d36g2000prf.googlegroups.com> <96c62f3a-37f4-44b7-8906-fbdff57d4752@i18g2000prf.googlegroups.com> <6bdfe2c8-7db2-4d83-b042-04a989847b09@j22g2000hsf.googlegroups.com> Message-ID: <43ddda75-a949-4935-af3f-2d83dece1dfc@r37g2000prr.googlegroups.com> Yeah, PyCrust is in wxPython now. But I take back my initial excitement ? it's freaking hard to use, despite its provision of a "pywrap" script (batch file under Windows). You certainly can't just replace "python /path/to/blah.py" with "pywrap /path/to/blah.py", especially if your script requires knowledge of where it is. (It also seems to freeze an awful lot under my Windows testing environment.) From birarai at gmail.com Fri Oct 31 15:18:15 2008 From: birarai at gmail.com (BiraRai) Date: Fri, 31 Oct 2008 12:18:15 -0700 (PDT) Subject: convert string literal to object attribute References: <6f5a1bb7-e89d-4062-b23d-7db45de58b95@c22g2000prc.googlegroups.com> <6n12trFj5ggvU4@mid.uni-berlin.de> Message-ID: <0ed2d91b-aded-4eea-a1f7-4b39c89baafe@t18g2000prt.googlegroups.com> On Oct 31, 3:00?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 31 Oct 2008 11:40:02 -0700, BiraRai wrote: > > def getAttributeForProperty(self,rollnumber,attribute): > > ? ?# attribute have the value _ward > > ? ?''' > > ? ?If year is null then use current year. Returns the value of the > > ? ?attribute for the given roll number ''' > > ? ?print 'Searching for attribute', attribute for index, i in > > ? ?enumerate(self._aa): > > ? ? ? ?if (rollnumber == i._roll_number) and ( hasattr > (i,attribute) ) : > > ? ? ? ? ? ?print index,i.attribute (COMPILER ERROR HERE) return > i.attribute > > ? ? ? ? ? ?return > > ? ?print "\n" > > ? ?return > > > i want i.attribute to be treated as i._ward > > Look at the `getattr()` function. > > > I get a compile error "instance has no attribute 'attribute' " which i > > understand. ?how do i fix this > > It's not a compile error but a runtime error. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks Marc, worked great. From fuzzyman at gmail.com Tue Oct 7 18:12:31 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 7 Oct 2008 15:12:31 -0700 (PDT) Subject: Python 2.6: Determining if a method is inherited References: <0b330a07-75bb-41a8-8ded-98a2f6ea76b1@v53g2000hsa.googlegroups.com> Message-ID: <4c43be19-5b6d-4599-9f55-335dfc7044d0@x16g2000prn.googlegroups.com> On Oct 7, 2:29?am, Terry Reedy wrote: > Fuzzyman wrote: > > On Oct 6, 7:02 pm, Terry Reedy wrote: > >> fuzzyman wrote: > >>> Doesn't sound like a particularly *good* solution to me. :-) > >> ?From what you posted, 'type object at' should work. > > > It's still a hack... > > I am sorry if I offended you by pointing out to you a quick and dirty > solution that would solve your problem immediately. Your smiley parsing is obviously broken. Michael From sbassi at clubdelarazon.org Wed Oct 22 11:57:22 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 22 Oct 2008 12:57:22 -0300 Subject: IDLE home page? In-Reply-To: References: <9e2f512b0810211801x67a39556u5f132def7937ed52@mail.gmail.com> Message-ID: <9e2f512b0810220857ubf72feay11a317fc35c4b95d@mail.gmail.com> On Wed, Oct 22, 2008 at 3:49 AM, Terry Reedy wrote: > Depending on the answer you get here, you might send the same observation > and question to webmaster at python.org OK, I've just sent it. Thank you. From ppearson at nowhere.invalid Fri Oct 24 10:53:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 24 Oct 2008 14:53:19 GMT Subject: dictionary References: <0111c3f1$0$20632$c3e8da3@news.astraweb.com> Message-ID: <6me5quFg38isU1@mid.individual.net> On 24 Oct 2008 13:17:45 GMT, Steven D'Aprano wrote: > > What are programmers coming to these days? When I was their age, we were > expected to *read* the error messages our compilers gave us, not turn to > the Interwebs for help as soon there was the tiniest problem. Yes, and what's more, the text of the error message was "IEH208". After reading it several times, one looked it up in a big fat set of books, where one found the explanation: IEH208: Your program contains an error. Correct the error and resubmit your job. An excellent system for purging the world of the weak and timid. -- To email me, substitute nowhere->spamcop, invalid->net. From musiccomposition at gmail.com Sat Oct 25 21:44:46 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 25 Oct 2008 18:44:46 -0700 (PDT) Subject: set/dict comp in Py2.6 References: <28b0fe12-9a82-4d14-b3fa-3cd203000ba0@l77g2000hse.googlegroups.com> Message-ID: <932c3f4a-ac25-49c4-b358-b8fceb19ffaf@34g2000hsh.googlegroups.com> On Oct 25, 3:13?am, bearophileH... at lycos.com wrote: > I'd like to know why Python 2.6 doesn't have the syntax to create sets/ > dicts of Python 3.0, like: Because nobody bothered to backport them. > > {x*x for x in xrange(10)} > {x:x*x for x in xrange(10)} > > Bye, > bearophile From darcymason at gmail.com Mon Oct 20 23:06:19 2008 From: darcymason at gmail.com (Darcy Mason) Date: Mon, 20 Oct 2008 20:06:19 -0700 (PDT) Subject: Python Imaging Library (PIL) question References: Message-ID: <26aaac69-81dc-4dd2-af7a-3e9f32105130@k30g2000hse.googlegroups.com> On Oct 20, 2:14?pm, Sid wrote: > Hi, > > ? I am tryin to copy an image into my own data structure(a sort of 2d array ? > for further FFT). I've banged my head over the code for a couple of hours ? > now. The simplified version of ?my problem is below. > > #-----------------Code------------------------ > > import Image > pic = Image.open("Images/a.jpg") > (picdata,width,height) ?= (pic.load(),pic.size[0],pic.size[1]) > > picMap = [[0] * width ] * height ? ? ? ?#matrix needed for FFT > > print "------Printing PIC MAP------" > for h in range(0,height): > ? ? ?for w in range(0,width): > ? ? ? ? ?print picMap[h][w]," ", #everything initialized to ZERO...this is ? > ok > ? ? ?print "\n" > > print "------Copying to ?PIC MAP------" > for h in range(0, height): > ? ? ?for w in range(0, width): > ? ? ? ? ?picMap[h][w] = picdata[w,h] #problem lies here???? > ? ? ? ? ?print picMap[h][w]," ", ?#Seems to copy perfectly here as the ? > output shows > ? ? ?print "\n" > > print "------Printing PIC MAP AGAIN------" > for h in range(0,height): > ? ? ?for w in range(0,width): > ? ? ? ? ?print picMap[h][w]," ", ?#Should print the values as above, but ? > doesn't > ? ? ?print "\n" > > #-----------------Code End------------------------ > > Hopefully someone would take a look and let me know what i'm doing ? > something wrong here. > > Thanks a lot > -Sid The problem is likely to do with the line picMap = [[0] * width ] * height The first [0]*width creates a list, then the *height repeats the reference to the same list. See, for example http://mail.python.org/pipermail/tutor/2001-December/010414.html. It prints okay in the middle section because the items have just been stored. Later iterations in that same loop are replacing array elements that have already been printed. The link explains the problem and shows a way to avoid this. You might also consider using Numpy, it has explicit functions to zero any dimension array. From rgacote at AppropriateSolutions.com Sun Oct 12 12:15:57 2008 From: rgacote at AppropriateSolutions.com (Raymond Cote) Date: Sun, 12 Oct 2008 12:15:57 -0400 Subject: please solve In-Reply-To: References: Message-ID: <48F222BD.2050706@AppropriateSolutions.com> shweta mani wrote: > hi folks, > i have been assigned a project on Python. i need to execute a remote > shell script file from a windows machine through SSH twisted or > paramiko. if it is a normal file then directly with the command sh > .sh it is getting executed. > self.conn.sendRequest(self, 'exec', common.NS(sh test1.sh), wantReply > = 1) You could take a look at the Fabric project for some ideas as to how to do this: --R From castironpi at gmail.com Sat Oct 4 02:14:07 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 3 Oct 2008 23:14:07 -0700 (PDT) Subject: how to get a class instance name during creation? References: <0453dfc1-fa3e-4d6d-840b-0e93b3d845d6@79g2000hsk.googlegroups.com> <48e68462$0$10441$426a34cc@news.free.fr> Message-ID: On Oct 3, 1:46?pm, Bruno Desthuilliers wrote: > dmitrey a ?crit : > > > hi all, > > I have a code > > z = MyClass(some_args) > > can I somehow get info in MyClass __init__ function that user uses "z" > > as name of the variable? > > > I.e. to have __init__ function that creates field z.name with value > > "z". > > This has been debated to hell and back. To make a long story short, here > are two common use cases: > > x = MyClass() > y = x > del x > > objects = [MyClass() for i in range(100)] > > If you can come with a meaningfull answer to "what's *the* name of any > of the MyClass instance(s)" in both cases, then please let us know... Hmmm, just thinking: What about a function: autoname( 'x= MyClass' ) which calls exec as well as determines the name? That could use 'code' and 'ast' modules and 'parse', or just take the first \w characters, assuming assignment, or: autoname( 'x', MyClass() ) which executes assignment and sets an attr or calls a method on the second arg. From ishoej at gmail.com Mon Oct 6 07:41:37 2008 From: ishoej at gmail.com (Holger) Date: Mon, 6 Oct 2008 04:41:37 -0700 (PDT) Subject: how to get the thighest bit position in big integers? References: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> <4a740d13-ad4d-4d20-b03d-11497c89662d@w7g2000hsa.googlegroups.com> Message-ID: <34fbee1b-1095-4fa6-9afa-b53c6289b158@f63g2000hsf.googlegroups.com> def highest_bit(n, maxbits = 256): bit = 0 while maxbits > 1: maxbits >>= 1 a = n >> maxbits if a: bit += maxbits n = a return bit is sligtly better From cournape at gmail.com Mon Oct 27 01:15:16 2008 From: cournape at gmail.com (David Cournapeau) Date: Mon, 27 Oct 2008 14:15:16 +0900 Subject: Improving interpreter startup speed In-Reply-To: References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> Message-ID: <5b8d13220810262215k16991346w9153bd37c31c409a@mail.gmail.com> On Mon, Oct 27, 2008 at 10:52 AM, James Mills wrote: > On Mon, Oct 27, 2008 at 4:12 AM, Benjamin Kaplan > +1 This thread is stupid and pointless. > Even for a so-called cold startup 0.5s is fast enough! Not if the startup is the main cost for a command you need to repeat many times. David From Scott.Daniels at Acm.Org Sun Oct 19 14:05:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 19 Oct 2008 11:05:00 -0700 Subject: better scheduler with correct sleep times In-Reply-To: References: Message-ID: <4uednWXN-8ga7mbVnZ2dnUVZ_sHinZ2d@pdx.net> Scott David Daniels wrote: > def time_server(commands): > '''Process all scheduled operations that arrive on queue commands''' > ... > > queue = Queue.Queue() > thread.thread.start_new_thread(queue) > queue.put((time.time() + dt, callable, args, {})) > ... And of course of the three lines that were not cut and pasted, one was mis-transcribed. It should have read: thread.start_new_thread(time_server, (queue,)) Sheepishly, --Scott David Daniels Scott.Daniels at Acm.Org From bearophileHUGS at lycos.com Mon Oct 6 21:19:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 6 Oct 2008 18:19:01 -0700 (PDT) Subject: Array of dict or lists or ....? References: Message-ID: Tim Chase: > __repr__ = __str__ I don't know if that's a good practice. > try: > data.setdefault( > state, {}).setdefault( > county, {}).setdefault( > cls, Attendence(max_students)).accrue(enrolled) > except TooManyAttendants: I suggest to decompress that part a little, to make it a little more readable. Bye, bearophile From sandricionut at yahoo.com Wed Oct 1 12:41:57 2008 From: sandricionut at yahoo.com (sandric ionut) Date: Wed, 1 Oct 2008 09:41:57 -0700 (PDT) Subject: string concatenate Message-ID: <668653.29942.qm@web51303.mail.re2.yahoo.com> Hi: I have the following situation: ??? nameAll = [] ??? for i in range(1,10,1): ??????? n = "name" + str([i]) ??????? nameAll += n ??? print nameAll I get: ['n', 'a', 'm', 'e', '[', '1', ']', 'n', 'a', 'm', 'e', '[', '2', ']', 'n', 'a', 'm', 'e', '[', '3', ']', 'n', 'a', 'm', 'e', '[', '4', ']', 'n', 'a', 'm', 'e', '[', '5', ']', 'n', 'a', 'm', 'e', '[', '6', ']', 'n', 'a', 'm', 'e', '[', '7', ']', 'n', 'a', 'm', 'e', '[', '8', ']', 'n', 'a', 'm', 'e', '[', '9', ']'] but I would like to have it as: name1 name2 name3 ...name10 How can I do it? Thank you, Ionut -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Oct 22 15:55:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 22 Oct 2008 21:55:58 +0200 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <68f52f45-ed6d-4473-b241-898f35a0eb7c@v53g2000hsa.googlegroups.com> References: <48ff6d72$0$30141$9b622d9e@news.freenet.de> <68f52f45-ed6d-4473-b241-898f35a0eb7c@v53g2000hsa.googlegroups.com> Message-ID: <48ff854e$0$5367$9b622d9e@news.freenet.de> > I would *love* for our company to be 10 times larger and be able to > add another zero to what we'd be able to hire/offer the python dev > community for work that we're looking for, but we unfortunately have > limits at the moment. There is another thing about open source that you need to consider: you don't have to do it all on your own. It needs somebody to take the lead, start a project, define a plan, and small steps to approach it. If it's really something that the community desperately needs, and if you make it clear that you will just lead, but get nowhere without contributions, then the contributions will come in. If there won't be any contributions, then the itch in the the community isn't that strong that it needs scratching. Regards, Martin From miki.tebeka at gmail.com Tue Oct 14 14:07:12 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 14 Oct 2008 11:07:12 -0700 (PDT) Subject: C API with *args and **kw Message-ID: Hello All, I'm try to write the C equivalent of: def kw(*args, **kw): print "%d args" % len(args), if "default" in kw: print "default is %s" % kw["default"] else: print "no default" I've written: static PyObject * kw(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *defval = NULL; long nargs; char *str; nargs = PyTuple_GET_SIZE(args); printf("%d args ", nargs); defval = PyDict_GetItemString(kwds, "default"); if (NULL == defval) { printf("no default\n"); } else { str = PyString_AsString(defval); printf("default is %s\n", str); } return Py_BuildValue(""); } However when running the test: from kw import kw kw(default="2") kw(1) kw() I get "bus error" on the 2'nd call (OS X Python 2.5.2). Any idea? TIA, -- Miki http://pythonwise.blogspot.com From weiguo6 at gmail.com Thu Oct 9 14:28:34 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Thu, 9 Oct 2008 11:28:34 -0700 Subject: A question about funcation parameter and self defined object In-Reply-To: References: <47c890dc0810081750s6325251ewaaf5eaf698b9ee02@mail.gmail.com> Message-ID: Hi Terry, Thanks for your reply. But the reason I want to have that is for not changing the functions which already based on translation functions. If there is any idea how to bring parameter in static method, that will be great. Wei On Wed, Oct 8, 2008 at 8:24 PM, Terry Reedy wrote: > Wei Guo wrote: > >> Hi Chris, >> Thanks a lot for reply, you are right. I want to use this method as a >> static method as: >> translation = staticmethod( translation ) >> > > static methods are mostly useless in Python. Just put the definition of > translation outside of any class. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Oct 21 03:22:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Oct 2008 05:22:20 -0200 Subject: PythonWin --> drwatson References: <9lsKk.77948$sg2.23073@fe09.news.easynews.com> Message-ID: En Sat, 18 Oct 2008 18:14:46 -0300, Frank L. Thiel escribi?: > On 18-Oct-08 16:31, this message was sent by Dennis Lee Bieber: >> Do you have a version of python 2.6 installed? (I'm surprised the >> standalone win32 package for Python 2.6 is even available already). > > Yes, Dennis, I have Python 2.6 installed, and it works perfectly from a > cmd window and from IDLE. FWIW, I have Python 2.6 + pywin32 build 212 installed on XP SP3 and both the command line interpreter, IDLE, and Pythonwin they all work fine. -- Gabriel Genellina From goon12 at gmail.com Wed Oct 8 14:15:12 2008 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 8 Oct 2008 14:15:12 -0400 Subject: Apache log munging In-Reply-To: References: Message-ID: <6a2ccd190810081115x6bf227a0i8a168f604cb751a0@mail.gmail.com> On Wed, Oct 8, 2008 at 1:55 PM, Joe Python wrote: > I want to find the top '100' hosts (sorted in descending order of total > requests) like follows: > Is there a fast way to this without scanning the log file many times? As you encounter a new "host" add it to a dict (or another type of collection), and if encountered again, use that "host" as the key to retrieve the dict entry and increment it's request count. You should only have to read the file once. From bdesth.quelquechose at free.quelquepart.fr Thu Oct 2 12:16:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Oct 2008 18:16:30 +0200 Subject: javascript to python In-Reply-To: References: Message-ID: <48e50fc8$0$31513$426a74cc@news.free.fr> Joe Hrbek a ?crit : > Could someone help me translate to something that would close to it in > python? The anonymous functions are giving me problems. > > var dataListener = { > data : "", > onStartRequest: function(request, context){}, > onStopRequest: function(request, context, status){ > instream.close(); > outstream.close(); > listener.finished(this.data); > }, > onDataAvailable: function(request, context, inputStream, offset, > count){ > this.data += instream.read(count); > }, > }; class DataListener(object): def __init__(self): self.data = '' def on_start_request(self, request, context): pass def on_stop_request(self, request, context, status): instream.close() oustream.close() listener.finished(self.data) def on_data_available(self, request, context, input_stream, offset, count): self.data += instream.read(count) data_listener = DataListener() Or if you want a more straightforward (but less pythonic) translation: class dataListener(object): data = '' @classmethod def onStartRequest(this, request, context): pass @classmethod def onStopRequest(this, request, context, status): instream.close() oustream.close() listener.finished(this.data) @classmethod def onDataAvailable(this, request, context, inputStream, offset, count): this.data += instream.read(count) From ldo at geek-central.gen.new_zealand Sun Oct 5 23:58:32 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 06 Oct 2008 16:58:32 +1300 Subject: paramiko.SSHException : No existing session ??? References: Message-ID: In message , sa6113 wrote: > print "doing authentication" ... > > ----------------- > the result is : ... > donig authentication Interesting that these two don't match up. When you're supposed to copy and paste, you should copy and paste, not type it in. From jillian.calderon at gmail.com Sun Oct 12 22:18:42 2008 From: jillian.calderon at gmail.com (Jillian Calderon) Date: Sun, 12 Oct 2008 19:18:42 -0700 (PDT) Subject: Define a 2d Array? References: <32e3d9b0-041b-48d8-afa0-414a3607f693@m73g2000hsh.googlegroups.com> Message-ID: <18647285-a6b5-47a7-8cf0-00b5ab1713f6@f63g2000hsf.googlegroups.com> Thanks, everyone. All of your help solved at least my data storage problem! From stiwari at nvidia.com Wed Oct 15 20:57:41 2008 From: stiwari at nvidia.com (sactiw) Date: Wed, 15 Oct 2008 17:57:41 -0700 (PDT) Subject: How to get the output of channel.exec_command(cmd) while using paramiko ? Message-ID: <20005226.post@talk.nabble.com> Hi Friends, I am trying to create a file on remote machine and then setting its file permissions to remote only thus now this file will act as a lock for me and as any body else now can't create same file on that machine and when my work is over I will reset the file permissions and then delete the file. Thus in our team we can use this mechanism to acquire and release lock on a remote machine. Problem is that I using Python thus to run remote command means I have to use paramiko module present in site-package. Now problem which I am facing are: - How can I make the channel.exec_command(cmd) to return its exit code. - Problem is that when i run the lock acquiring code then even though in that code after creating the file using touch command it changes the file's permissions to read only but then also any other person is able to create file with same name on same location running the same lock acquiring code that I had ran. In short for the second person the lock acquiring code should fail ahs he is using touch command to create a file of same name which already exists with RO file permissions. So how can I avoid that ? Thanks in Advance. -sactiw -- View this message in context: http://www.nabble.com/How-to-get-the-output-of-channel.exec_command%28cmd%29-while-using-paramiko---tp20005226p20005226.html Sent from the Python - python-list mailing list archive at Nabble.com. From philip at semanchuk.com Fri Oct 17 13:30:18 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 17 Oct 2008 13:30:18 -0400 Subject: Script can't find input file despite being in the same directory In-Reply-To: <8c4b42bb-a9de-45b7-b282-f8981d3245bb@u27g2000pro.googlegroups.com> References: <8c4b42bb-a9de-45b7-b282-f8981d3245bb@u27g2000pro.googlegroups.com> Message-ID: <954DFBB4-F590-4269-AA7A-2C8F2C9A11A2@semanchuk.com> On Oct 17, 2008, at 1:07 PM, Robocop wrote: > I have a simple little script that reads in postscript code, appends > it, then writes it to a new postscript file. Everything worked fine a > month ago, but after rearranging my directory tree a bit my script > fails to find the base postscript file. > > The line in question is: > > for line in fileinput.input(['base.ps']): > output.write(line) > > I'm kind of at a loss as the script is executing in the same directory > as base.ps, yet it can't find it. I'm relatively new to python > scripting, so i'm expecting it's just something i haven't learned > about python that is causing the problem. Any suggestions would be > greatly appreciated. Put this before the line that fails and see what it tells you: print os.getcwd() getcwd = get current working directory From bruno.42.desthuilliers at websiteburo.invalid Thu Oct 16 06:46:21 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 16 Oct 2008 12:46:21 +0200 Subject: install Django under PYTHONPATH In-Reply-To: <0875a93e-0881-463b-9bc5-de255004579b@c22g2000prc.googlegroups.com> References: <0875a93e-0881-463b-9bc5-de255004579b@c22g2000prc.googlegroups.com> Message-ID: <48f71b6b$0$15500$426a74cc@news.free.fr> limas a ?crit : > please help me...... > i want to install django under PYTHONPATH with out root permission. > Can i do it without setup.py You don't need root permissions to edit your own PYTHONPATH. It's just an environment variable, you know ?-) From clay at lakeserv.net Mon Oct 6 14:45:43 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Mon, 06 Oct 2008 14:45:43 -0400 Subject: PyOpenGL double-buffered hardware surface In-Reply-To: <48E90498.2000609@vrplumber.com> References: <1223226099.4146.1.camel@generator> <48E90498.2000609@vrplumber.com> Message-ID: <1223318743.16631.1.camel@generator> On Sun, 2008-10-05 at 14:16 -0400, Mike C. Fletcher wrote: > Clay Hobbs wrote: > > How do I create a double-buffered hardware surface with PyOpenGL? I > > knew how to once, but forgot. > > > > > Depends on your GUI library, most of them have a flag-set that you pass > to the initializer of the OpenGL-holding widget. If you're using > Pygame, see Pygame's display module. If wxPython, see their GLcanvas > object. If GLUT, see glutInitDisplayMode, etceteras. > > Good luck, > Mike > I'm using wxPython. My real problem is that everything flashes when it moves. I thought the way to fix this was to make a double-buffered hardware surface, but I may be wrong. Thank you for the help so far, --Ratfink From mr.spoon21 at gmail.com Thu Oct 16 06:14:00 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Thu, 16 Oct 2008 12:14:00 +0200 Subject: Overloading operators In-Reply-To: <84fb33aa-64ad-49c0-9ae0-0a40bbc763a0@i24g2000prf.googlegroups.com> References: <84fb33aa-64ad-49c0-9ae0-0a40bbc763a0@i24g2000prf.googlegroups.com> Message-ID: <8f67b6f80810160314k56feb8c9w2003866c83f0bafe@mail.gmail.com> Thanks for the suggestion. I think I'm gonna try the multimethods way, that I didn't know about it. From frank at chagford.com Fri Oct 3 01:19:39 2008 From: frank at chagford.com (Frank Millman) Date: Thu, 2 Oct 2008 22:19:39 -0700 (PDT) Subject: Sample code required to validate a xml file against XSD References: Message-ID: <0901914c-0cd8-44c4-911e-856ebd596332@u26g2000hsd.googlegroups.com> On Oct 2, 3:32?pm, hrishy wrote: > Hi > > Does anybody have a python xample program to validate a xml file against a XSD. > > regards > Hrisy I have used minixsv successfully in a test environment - http://www.familieleuthe.de/MiniXsv.html Here is some sample code - #--------------------------------- from minixsv import pyxsval as xsv try: etw = xsv.parseAndValidateXmlInput( 'bpmn1.xml', 'bpmn.xsd', xmlIfClass=xsv.XMLIF_ELEMENTTREE) et = etw.getTree() root = et.getroot() except xsv.XsvalError,errstr: print errstr #--------------------------------- It supports minidom, 4DOM, and ElementTree. It is written in pure python. It is not very fast - around 0.5 sec for a small xml file - but I have not compared it with any others, so I don't know what is typical. I believe that lxml also handles xsd files, but I have not tried it, so I can't give any details. HTH Frank Millman From chemila at 163.com Thu Oct 23 05:22:25 2008 From: chemila at 163.com (chemila66@hotmail.com) Date: Thu, 23 Oct 2008 02:22:25 -0700 (PDT) Subject: Append a new value to dict In-Reply-To: <48ff3d36$1@news.uni-ulm.de> References: <48F33AC3.80505@wu-wien.ac.at> <48ff3d36$1@news.uni-ulm.de> Message-ID: <20127415.post@talk.nabble.com> Frank Niemeyer wrote: > >> However incrementing a non-existing key throws an exception. > > Right. And that's exactly what I would expect, according to the > "principle of least surprise" Python tries to obey. There's simply no > way to increment a non-existent value - not without performing some > obscure implict behind-the-scenes stuff. > >> So you >> either have to use a workaround: >> >> >>> try: >> ... counter['B'] += 1 >> ... except KeyError: >> ... counter['B'] = 1 > > Or you could simply use > > if counter.has_key('B'): > counter['B'] += 1 > else: > counter['B'] = 1 > > Regards, > Frank > -- > http://mail.python.org/mailman/listinfo/python-list > > or if 'B' in counter: counter['B'] += 1 else: ocunter['B'] = 1 -- View this message in context: http://www.nabble.com/Append-a-new-value-to-dict-tp19953085p20127415.html Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Fri Oct 17 19:03:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 17 Oct 2008 16:03:44 -0700 (PDT) Subject: How to transfer data structure or class from Python to C/C++? References: <7085c400-94ef-441f-b727-48ec7b66051d@p10g2000prf.googlegroups.com> <4b2c771b-7be0-47a6-8c64-346f97a3fefb@v39g2000pro.googlegroups.com> Message-ID: <2a81471a-b38a-4e17-8b6b-55c3a6a915cb@y21g2000hsf.googlegroups.com> On Oct 16, 9:10?am, Hongtian wrote: > Not exactly. > > In my C/C++ application, I have following function or flow: > > void func1(....) > { > ? ? call PyFunc(struct Tdemo, struct &Tdemo1); > > } > > I mean I want to invoke Python function 'PyFunc' and transfer a data > structure 'Tdemo' to this function. After some process in Python, I > want it return 'Tdemo1' back to the C/C++ application. > > I research boost.python and think it is not a reasonable solution > because it make the C/C++ application too complex. > > Thanks. snip Solution produced here. Includes dirty kludge, which will welcome correction. /C file: #include typedef struct { int a; float b; } TypeA; static PyObject * methA(PyObject *self, PyObject *args) { TypeA a; TypeA b; PyObject* fun; PyObject* res; PyArg_ParseTuple( args, "O", &fun ); a.a= 10; a.b= 20.5; res= PyObject_CallFunction( fun, "II", &a, &b ); printf( "%i %f\n", b.a, b.b ); Py_DECREF( res ); return PyInt_FromLong( 0 ); } static PyMethodDef module_methods[] = { {"methA", methA, METH_VARARGS, "No doc"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initng27ext(void) { PyObject* m; m = Py_InitModule3("ng27ext", module_methods, "Custom."); if (m == NULL) return; } /Py file: import ng27ext import ctypes as c class TypeA( c.Structure ): _fields_= [ ( 'a', c.c_int ), ( 'b', c.c_float ) ] from _ctypes import _cast_addr _data_cast= c.PYFUNCTYPE( c.py_object, c.c_void_p, c.py_object, c.py_object)( _cast_addr ) #dirty kludge def exposed( obj1, obj2 ): cob1= _data_cast( obj1, None, c.POINTER( TypeA ) ) cob2= _data_cast( obj2, None, c.POINTER( TypeA ) ) print cob1.contents.a, cob1.contents.b cob2.contents.a= c.c_int( 60 ) cob2.contents.b= c.c_float( 70.5 ) print cob2.contents.a, cob2.contents.b print ng27ext.methA( exposed ) /Compile & link: c:/programs/mingw/bin/gcc ng27ext.c -c -Ic:/programs/python25/include c:/programs/mingw/bin/gcc -shared ng27ext.o -o ng27ext.pyd -Lc:/ programs/python25/libs -lpython25 /Output: 10 20.5 60 70.5 60 70.500000 0 Press any key to continue . . . From mikejanse at yahoo.com Wed Oct 8 15:30:09 2008 From: mikejanse at yahoo.com (mikejanse at yahoo.com) Date: Wed, 8 Oct 2008 12:30:09 -0700 (PDT) Subject: Porn Addiction Solutions? References: Message-ID: <963ea4ac-54e6-4911-9a15-846b86de5cea@u40g2000pru.googlegroups.com> On Oct 8, 3:07 pm, pavement... at yahoo.com wrote: > Help, I'm addicted to porn. I've been spending a lot of time > downloading hardcore porn and masturbating to it. It's ruining my > life. I just found out that one of these sites somehow hacked my card > and rang up $5K in charges which they won't even refund me. Even with > that I haven't stopped my habit and it's only getting worse. How can I > end this addiction? > > Any suggestions? You need to install a porn filter on your computer. Don't ever surf unprotected. A good filter program is Optenet PC which you can get at optenetpc.com. Be sure to change the password to something you won't remember so that you won't be tempted to circumvent the filter. You have made the first step by recognizing excessive pornography use is a problem in your life. Now you need to change your habits. Use the filter as a first line of defense to block access to this material from your computer. Then look at how you can alter the factors that lead to this behavior. See these tips: "Change routines and environments that lead to pornography usage. Avoid high risk situations." "Learn new ways of coping with strong feelings like anxiety, loneliness, anger, depression, and boredom." "Identify activities that can help you relax, enjoy yourself, and feel refreshed." From: http://www.utdallas.edu/counseling/selfhelp/porn-addiction.html You can conquer this thing. Let us know how you make out. Regards, Mike From jura.grozni at gmail.com Mon Oct 13 12:11:26 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 13 Oct 2008 09:11:26 -0700 (PDT) Subject: Suggestion for the PythonDevelopment for next version References: Message-ID: I know that. enumerate is a great function. But this way it always adds some complexity. I think that it is more better to give a man a better tool then to let him play with a not so good one. People like Python because of his simplicity in comparison with c++. Maybe People would like him even more it would be a bit more simple but the same powerfull. From bruno.42.desthuilliers at websiteburo.invalid Thu Oct 23 12:28:27 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 23 Oct 2008 18:28:27 +0200 Subject: re.search over a list In-Reply-To: References: <48fb83cb$0$20787$426a74cc@news.free.fr> Message-ID: <4900a617$0$12849$426a34cc@news.free.fr> Steve Holden a ?crit : > Pat wrote: >> Bruno Desthuilliers wrote: (snip) >>> words = ['foo', 'bar', 'somestring', 'baaz'] >>> re.search(r"^somestring$", "\n".join(words), re.MULTILINE) (snip) >> > I suspect that > > any(re.match(pat, word) for word in words) > > might be a more efficient way to do this. Indeed. I'm not yet used to have all and any builtins, thanks for the reminder. From clp at rebertia.com Wed Oct 1 11:15:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 1 Oct 2008 08:15:57 -0700 Subject: indirectly addressing vars in Python In-Reply-To: <6bb1$48e38ed8$d1d96e63$28976@PRIMUS.CA> References: <6bb1$48e38ed8$d1d96e63$28976@PRIMUS.CA> Message-ID: <47c890dc0810010815r453bab03k45863583d28b5b12@mail.gmail.com> On Wed, Oct 1, 2008 at 7:53 AM, Ross wrote: > Forgive my newbieness - I want to refer to some variables and indirectly > alter them. Not sure if this is as easy in Python as it is in C. > > Say I have three vars: oats, corn, barley > > I add them to a list: myList[{oats}, {peas}, {barley}] You mean: myList = [oats, peas, barley] And you're not adding *variables* to a list, you're adding *values* to the list. The list elements (and the Python runtime) have *no idea* what variables they are/were bound to. > > Then I want to past that list around and alter one of those values. That is > I want to increment the value of corn: > > myList[1] = myList[1] + 1 This won't do what you're expecting. Integers in Python are immutable, so instead of changing the value of 'corn', you're calculating a new int object and overwriting the first element of the list with it. > > Is there some means to do that?. Here's my little session trying to figure > this out: > >>>> oats = 1 >>>> peas = 6 >>>> myList=[] >>>> myList > [] >>>> myList.append(oats) >>>> myList > [1] >>>> myList.append(peas) >>>> myList > [1, 6] >>>> myList[1]= myList[1]+1 >>>> myList > [1, 7] >>>> peas > 6 >>>> > > So I don't seem to change the value of peas as I wished. I'm passing the > values of the vars into the list, not the vars themselves, as I would like. > > Your guidance appreciated... Python uses *call-by-object*, not call-by-value or call-by-reference semantics, so unlike C/C++ but like Java you can't make a "reference" to a variable and use that to non-locally rebind the variable to a new value. To do what you want, you need to create a mutable value that can be updated. You could code a "MutableInt" class wrapping 'int', or you could use a dictionary to hold the values and then always refer to the values using the dictionary. There are a few other ways to do it. Hope that elucidates it for you somewhat. Then again I am a little short on sleep :) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Ross. > -- > http://mail.python.org/mailman/listinfo/python-list > From sharpblade1 at gmail.com Tue Oct 28 20:42:16 2008 From: sharpblade1 at gmail.com (sharpblade) Date: Wed, 29 Oct 2008 00:42:16 +0000 Subject: Using threads to quit the main python process Message-ID: Is there a way I can use threads to quit the main python process? In brief, I have a python script that starts when my computer starts. It chooses a random wallpaper background out of a specified path, and sets it as the desktop wallpaper. It also hooks some windows hot keys so I can cycle through all the wallpapers, or choose another one, or quit it, by using F8, F7 and F6 respectively. However, I would quite like the script to self-terminate if no user input is received after X seconds. At first this seemed simple - Create a separate thread that used time.sleep() to sleep for X seconds, then run a callback. The callback would check a simple Boolean (Set to True if a hot key is pressed, set to False at start of the script), and if the Boolean was False, it would simply run exit(), and this would close the window. However, it is not that simple. The callback and the thread work fine, but the exit() seems to close the THREAD, not the main process. I have tried sys.exit(), and some other forms I found on the Internet (Raising exceptions and setting the thread to a daemon), but none seemed to close the actual interpreter. I tried using the .join() function, but this called an exception that told me the thread could not be joined. Here is my threaded_test.py code: http://pastebin.com/f6060d15a Thanks for reading, ~Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Mon Oct 20 07:50:06 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 20 Oct 2008 04:50:06 -0700 (PDT) Subject: better scheduler with correct sleep times References: <658e2b0f-2551-4ec9-bcd5-ce98092a3f7b@a1g2000hsb.googlegroups.com> Message-ID: <5b97d8fb-aa61-4a68-aca3-d77a07cd6cbd@t18g2000prt.googlegroups.com> On Oct 19, 4:01?am, sokol wrote: > > > I started googling for scheduler and found one in standard library > > > but ih has the same code as mine (it calls the ?functions in the > > > right order and my doesn't, but it still waits too long). > > > The other schedulers from web are dealing with > > > repeating tasks and such. > > > I believe you're looking for the 'sched' module:http://www.python.org/doc/2.5.2/lib/module-sched.html > > The sched module behaves just like mine version because > it uses almost the same code. My observations include the > sched module as well. Check it's source code. It is flawed: > it calls the sleep method and while it sleeps (presumably > for a long time) all newly scheduled events are on hold. > See my example in original post. > > My code solves this problem (or so it looks to me right now). Alternatively, if you're only handling Timers, you could use an event loop that would check a list of timers and check their expiry time, and execute the appropriate callback when the timer expired. From gooberts at gmail.com Fri Oct 31 10:35:19 2008 From: gooberts at gmail.com (Dale Roberts) Date: Fri, 31 Oct 2008 07:35:19 -0700 (PDT) Subject: Finding the instance reference of an object References: <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <6mvmkqFja1mrU1@mid.individual.net> Message-ID: <08049779-9fa6-43eb-93d2-39dd1201980e@p31g2000prf.googlegroups.com> On Oct 31, 2:27?am, greg wrote: > Dale Roberts wrote: > > Are you > > saying that C++ is capable of using the Call By Reference idiom, but C > > is not, because C does not have a reference designation for formal > > function parameters? > > Call by reference is not an "idiom", it's a *language > feature*. > ... > You can use an idiom in C to get the same effect, but this > is not the same thing as the language having it as a feature. Okay, I'll grant that, but is there a language other than Python that uses the Call By Value feature that does not do it by assigning/ copying the result of an expression into the formal parameter? The terms "result" and "value" are generally understood to refer to the working data of the program, not the internal workings of the interpreter, VM, or compiler. So, yes, internally the C Python runtime does use Call By Value. It's written in C after all - that's all it can do. But Call By Value is not a feature of the Python language. dale [Somebody unplug my network cable! I can't stop!] From fuzzyman at gmail.com Thu Oct 30 08:12:08 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 30 Oct 2008 05:12:08 -0700 (PDT) Subject: Finding the instance reference of an object References: <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <794b44fa-5a60-4d2f-a4c2-46eb6b085ec2@l64g2000hse.googlegroups.com> On Oct 30, 1:13 am, Joe Strout wrote: > On Oct 29, 2008, at 4:52 PM, Fuzzyman wrote: > > > You're pretty straightforwardly wrong. In Python the 'value' of a > > variable is not the reference itself. > > That's the misconception that is leading some folks around here into > tangled nots of twisty mislogic, ultimately causing them to make up > new terms for what every other modern language is perfectly happy > calling Call-By-Value. > > I've thought a lot about why this misconception is so widespread here, > and I think it must be one of the following: > > 1. There was one community leader with this idea, who has been > successful at promoting it widely, much to the detriment of all; or, > > 2. Because everything in Python is an object, you're not forced to > think clearly (and more generally) about references as values as you > are in languages (such as Java, VB.NET, etc.) which have both simple > types and object types. > To make it clearer for you, call by value means that the value is copied in - and therefore changes to the value won't be visible to the caller. In .NET this is true of mutable value types - changes made are made to a copy and not visible to the caller. In Python we *only* have reference types, so changes to *any* mutable object are visible to the caller. In .NET you can call by reference with a value type - and the runtime does boxing for you so that you can see the changes. You have to explicitly ask for call by reference though. Michael > Either way, it's wrong (or at least, a needlessly complicated way of > looking at things). > > > .NET does draw a distinction between 'value types' and reference types > > - where using reference types are called by reference (the reference > > is passed) and value types are called by value (the value itself is > > copied). > > Quite right. Now, note that "ByRef" and "ByVal" apply to both. > Generalize to Python. There you go. > > Best, > - Joe > > P.S. I really am trying to quit responding to this thread. Sometimes > the urge is too strong. But I'll keep trying! From __peter__ at web.de Wed Oct 22 13:23:39 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2008 19:23:39 +0200 Subject: Ordering python sets References: <8f67b6f80810220522r49b0f588qf9d6001f62c080f0@mail.gmail.com> <6m92plFfp081U1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Wed, 22 Oct 2008 15:37:03 +0200, Peter Otten <__peter__ at web.de> wrote: >> Tim Chase wrote: >> >>> Though for each test, in 2.3, 2.4, and 2.5 that I've got >>> installed on my local machine, they each printed "s" in-order, >>> and the iteration occurred in-order as well, even without the >>> added "sorted(list(s))" code. >> >> You need more tests then ;) >> >>>>> list(set([1,1000])) >> [1000, 1] > > So one wonders, of course, why Mr. Otten chose 1000; and one explores: > > $ python > Python 2.4.3 (#2, Jul 31 2008, 21:56:52) > [snip] >>>> for x in 2, 100, 199, 200, 300, 400, 500, 600: > ... list( set( [ 1, x ] ) ) > ... > [1, 2] > [1, 100] > [1, 199] > [200, 1] > [1, 300] > [400, 1] > [1, 500] > [600, 1] >>>> Here's another one: >>> set([1,9]) set([1, 9]) >>> set([9,1]) set([9, 1]) This time I did indeed search systematically... Peter From tjreedy at udel.edu Mon Oct 20 16:22:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Oct 2008 16:22:02 -0400 Subject: Python certification In-Reply-To: <92da89760810200552t2d0e736dp5eade6ffd77dd1c7@mail.gmail.com> References: <8763nr9yh7.fsf@benfinney.id.au> <1ddcea72-7773-42f0-8ada-0ede7f2cdf3d@p59g2000hsd.googlegroups.com> <92da89760810200552t2d0e736dp5eade6ffd77dd1c7@mail.gmail.com> Message-ID: Eric Wertman wrote: > On Mon, Oct 20, 2008 at 3:52 AM, olive wrote: >>> Certification prooves you're an idiot who needs to spend money to work >>> for another idiot who doesn't know enough about programming to know if >>> they hire competent programmers and need an idiot paper to make them >>> feel better and sleep better at night. >>> >> So true ! >> +1 QOTW >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > While in the current state of affairs I agree completely, I do think > that IT in general would be a much better field to work in if there > were some industry standard certifications that were required. More > like the medical and legal fields than the vendor specific ones we see > today from Microsoft, IBM, etc. Given the way that medical/legal licensing is used to stifle competition, prevent innovation, and keep people from earning a living delivering simple services that people need at prices they can afford, 'more like' would have to be done very carefully. From gslindstrom at gmail.com Thu Oct 30 15:28:50 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 30 Oct 2008 14:28:50 -0500 Subject: PyCon 2009 (US) - Call for tutorials Extended to 11/3 Message-ID: We have had requests to extend the deadline for submitting Tutorial Proposals for PyCon 2009 (US) through the weekend and are willing to do so. We will accept tutorial proposals through Monday, November 3. --greg ================================== The period for submitting tutorial proposals for Pycon 2009 (US) is open and will continue through Monday, November 3rd. This year features two "pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday March 26 in Chicago. This allows for more classes than ever. Tutorials are 3-hours long on a specific topic of your choice. Last year we featured classes on Learning Python, Web Development, Scientific Computing, and many more. Class size varied from 10 to over 60 students. The extended time spent in class allows teachers to cover a lot of material while allowing for interaction with students. The full Call for Tutorial Proposals, including submission details, an example proposal as well as a template, is available at < http://us.pycon.org/2009/tutorials/proposals/>. Tutorial selections will be announced in early December to give you time to prepare your class and PyCon will compensate instructors US$1,500 per tutorial. If you have any questions, please contact pycon-tutorials at python.org. Greg Lindstrom Tutorial Coordinator, PyCon 2009 (US) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Oct 15 08:24:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 15 Oct 2008 05:24:09 -0700 (PDT) Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> Message-ID: <03b9711b-1240-4646-951b-1e3b4157c074@w39g2000prb.googlegroups.com> On Oct 15, 10:19?pm, Michele wrote: > Hi, > I'm trying to encode a byte data. Let's not focus on the process of > encoding; in fact, I want to emphasize that the method > create_random_block takes 0.5s to be executed (even Java it's faster) on > a Dual-Core 3.0Ghz machine: > > took 46.746999979s, avg: 0.46746999979s > > Thus I suppose that the xor operation between bytes raise the execution > time to 0.5; why I suppose that? > Because in Python there's no support for bytes and even for xoring > bytes, so I used a workaround: > I cycle on the two strings to be xor-red > ? ? for every char in the strings > ? ? ? ? convert one char on integer and then xor them; (ord) > ? ? ? ? insert one char in the result, transforming the previous integer > in char (chr) > > I suppose that ord() and char() are the main problems of my > implementation, but I don't know either way to xor two bytes of data > (bytes are represented as strings). > For more information, see the code attached. > > How should I decrease the execution time? > > Thank you > > from __future__ import division > import random > import time > import sha > import os > > class Encoder(object): > ? ? def create_random_block(self, data, seed, blocksize): > ? ? ? ? number_of_blocks = int(len(data)/blocksize) > ? ? ? ? random.seed(seed) > ? ? ? ? random_block = ['0'] * blocksize You possibly mean '\0' i.e. the byte all of whose bits are zero. > ? ? ? ? for index in range(number_of_blocks): > ? ? ? ? ? ? if int(random.getrandbits(1)) == 1: getrandbits(1) produces a *long* with one random bit. Any good reason for preferring this to randrange(2) and randint(0, 1)? So there's a 50% chance that this block will be XORed into the result; is that what you intend? > ? ? ? ? ? ? ? ? block = data[blocksize*index:blocksize*index+blocksize] You don't need to slice out block, certainly not so awkwardly. > ? ? ? ? ? ? ? ? for bit in range(len(block)): Perhaps you mean "byte_index", not "bit". On my assumption that range(len(block)) is invariant: calculate it once. That assumption is incorrect, so is your code for calculating the number of blocks; it ignores a possible short block at the end. > ? ? ? ? ? ? ? ? ? ? random_block[bit] = > chr(ord(random_block[bit])^ord(block[bit])) The chr() and one ord() are utterly wasteful; leave random_block as a list of ints and do the chr() thing in the return statement. > # workaround per fare xor > bit a bit di str; xor e' solo supportato per int -> ord > ? ? ? ? return ''.join(random_block) this will become return ''.join(map(chr, random_block)) or return ''.join(chr(i) for i in random_block) as taste or speed dictates :-) So the whole thing becomes [not tested]: def create_random_block(self, data, seed, blocksize): datalen = len(data) assert datalen % blocksize == 0 random.seed(seed) random_block = [0] * blocksize block_range = range(blocksize) for start in xrange(0, datalen, blocksize): if random.randrange(2): for x in block_range: random_block[x] ^= ord(data[start + x]) return ''.join(map(chr, random_block)) Looks slightly more athletic than before :-) BTW, +1 misleading subject of the week; it's not XOR that's slow!! Cheers, John From s.payandeh at gmail.com Tue Oct 7 08:40:46 2008 From: s.payandeh at gmail.com (sa6113) Date: Tue, 7 Oct 2008 05:40:46 -0700 (PDT) Subject: ssh problem using paramiko? Message-ID: <19857268.post@talk.nabble.com> I use this code : import paramiko import socket hostname = "192.168.1.4" username = "test" port = 22 password = ''123456" # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception, e: print 'Connect failed: ' + str(e) traceback.print_exc() sys.exit(1) ------------------ and I got this error : sock.connect((hostname, port)) File "", line 1 , in connect error:(10061 ,'Connection refused') ------------------- what is the problem? I have a computer with this Ip and username , password in my network. Do I have to install ssh or somthing else in that computer(server) or run any script? -- View this message in context: http://www.nabble.com/ssh-problem-using-paramiko--tp19857268p19857268.html Sent from the Python - python-list mailing list archive at Nabble.com. From lipun4u at gmail.com Sun Oct 26 13:16:42 2008 From: lipun4u at gmail.com (asit) Date: Sun, 26 Oct 2008 10:16:42 -0700 (PDT) Subject: XML-RPC Message-ID: what is XML-RPC System ???? From circularfunc at gmail.com Sun Oct 5 23:30:04 2008 From: circularfunc at gmail.com (process) Date: Sun, 5 Oct 2008 20:30:04 -0700 (PDT) Subject: Pr. Euler 18, recursion problem Message-ID: I am trying to solve project euler problem 18 with brute force(I will move on to a better solution after I have done that for problem 67). http://projecteuler.net/index.php?section=problems&id=18 However I can't get the recursive function right. I always have to use return right? Unless I am printing? So I can?t stack to diffferent recursive calls after each other like so: recur_left(t, p) recur_right(t,p+1) Some stuff I have tried: def recur(tree, pos): if not tree: return [] else: return [[tree[0][pos]] + recur(tree[1:], pos)] + \ [[tree[0][pos]] + recur(tree[1:], pos+1)] >>> recur([[1],[2,3],[4,5,6]],0) [[1, [2, [4], [4]], [2, [5], [5]]], [1, [3, [5], [5]], [3, [6], [6]]]] SO it is kind of working, just not exactly like I want. A more easily parseable/readable result would be nice, I want to be able to sum() over each path preferrably. So the result should be: [[1,2,4],[1,2,5],[1,3,5],[1,3,6]] I know conceptually what has to be done. Base case: empty tree, return [] Else: recur to the left and to the right. From bdesth.quelquechose at free.quelquepart.fr Fri Oct 3 14:46:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 03 Oct 2008 20:46:17 +0200 Subject: how to get a class instance name during creation? In-Reply-To: <0453dfc1-fa3e-4d6d-840b-0e93b3d845d6@79g2000hsk.googlegroups.com> References: <0453dfc1-fa3e-4d6d-840b-0e93b3d845d6@79g2000hsk.googlegroups.com> Message-ID: <48e68462$0$10441$426a34cc@news.free.fr> dmitrey a ?crit : > hi all, > I have a code > z = MyClass(some_args) > can I somehow get info in MyClass __init__ function that user uses "z" > as name of the variable? > > I.e. to have __init__ function that creates field z.name with value > "z". This has been debated to hell and back. To make a long story short, here are two common use cases: x = MyClass() y = x del x objects = [MyClass() for i in range(100)] If you can come with a meaningfull answer to "what's *the* name of any of the MyClass instance(s)" in both cases, then please let us know... From rhamph at gmail.com Thu Oct 23 17:24:50 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Thu, 23 Oct 2008 14:24:50 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: On Oct 23, 11:30?am, Glenn Linderman wrote: > On approximately 10/23/2008 12:24 AM, came the following characters from > the keyboard of Christian Heimes: > > > Andy wrote: > >> 2) Barriers to "free threading". ?As Jesse describes, this is simply > >> just the GIL being in place, but of course it's there for a reason. > >> It's there because (1) doesn't hold and there was never any specs/ > >> guidance put forward about what should and shouldn't be done in multi- > >> threaded apps (see my QuickTime API example). ?Perhaps if we could go > >> back in time, we would not put the GIL in place, strict guidelines > >> regarding multithreaded use would have been established, and PEP 3121 > >> would have been mandatory for C modules. ?Then again--screw that, if I > >> could go back in time, I'd just go for the lottery tickets!! :^) > > I've been following this discussion with interest, as it certainly seems > that multi-core/multi-CPU machines are the coming thing, and many > applications will need to figure out how to use them effectively. > > > I'm very - not absolute, but very - sure that Guido and the initial > > designers of Python would have added the GIL anyway. The GIL makes > > Python faster on single core machines and more stable on multi core > > machines. Other language designers think the same way. Ruby recently > > got a GIL. The article > >http://www.infoq.com/news/2007/05/ruby-threading-futuresexplains the > > rationales for a GIL in Ruby. The article also holds a quote from > > Guido about threading in general. > > > Several people inside and outside the Python community think that > > threads are dangerous and don't scale. The paper > >http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdfsums > > it up nicely, It explains why modern processors are going to cause > > more and more trouble with the Java approach to threads, too. > > Reading this PDF paper is extremely interesting (albeit somewhat > dependent on understanding abstract theories of computation; I have > enough math background to follow it, sort of, and most of the text can > be read even without fully understanding the theoretical abstractions). > > I have already heard people talking about "Java applications are > buggy". ?I don't believe that general sequential programs written in > Java are any buggier than programs written in other languages... so I > had interpreted that to mean (based on some inquiry) that complex, > multi-threaded Java applications are buggy. ?And while I also don't > believe that complex, multi-threaded programs written in Java are any > buggier than complex, multi-threaded programs written in other > languages, it does seem to be true that Java is one of the currently > popular languages in which to write complex, multi-threaded programs, > because of its language support for threads and concurrency primitives. ? > These reports were from people that are not programmers, but are field > IT people, that have bought and/or support software and/or hardware with > drivers, that are written in Java, and seem to have non-ideal behavior, > (apparently only) curable by stopping/restarting the application or > driver, or sometimes requiring a reboot. > > The paper explains many traps that lead to complex, multi-threaded > programs being buggy, and being hard to test. ?I have worked with > parallel machines, applications, and databases for 25 years, and can > appreciate the succinct expression of the problems explained within the > paper, and can, from experience, agree with its premises and > conclusions. ?Parallel applications only have been commercial successes > when the parallelism is tightly constrained to well-controlled patterns > that could be easily understood. ?Threads, especially in "cooperation" > with languages that use memory pointers, have the potential to get out > of control, in inexplicable ways. Although the paper is correct in many ways, I find it fails to distinguish the core of the problem from the chaff surrounding it, and thus is used to justify poor language designs. For example, the amount of interaction may be seen as a spectrum: at one end is C or Java threads, with complicated memory models, and a tendency to just barely control things using locks. At the other end would be completely isolated processes with no form of IPC. The later is considered the worst possible, while the latter is the best possible (purely sequential). However, the latter is too weak for many uses. At a minimum we'd like some pipes to communicate. Helps, but it's still too weak. What if you have a large amount of data to share, created at startup but otherwise not modified? So we add some read only types and ways to define your own read only types. A couple of those types need a process associated with them, so we make sure process handles are proper objects too. What have we got now? It's more on the thread end of the spectrum than the process end, but it's definitely not a C or Java thread, and it's definitely not an OS process. What is it? Does it have the problems in the paper? Only some? Which? Another peeve I have is his characterization of the observer pattern. The generalized form of the problem exists in both single-threaded sequential programs, in the form of unexpected reentrancy, and message passing, with infinite CPU usage or infinite number of pending messages. Perhaps threading makes it much worse; I've heard many anecdotes that would support that. Or perhaps it's the lack of automatic deadlock detection, giving a clear and diagnosable error for you to fix. Certainly, the mystery and extremeness of a deadlock could explain how much it scales people. Either way the paper says nothing. > > Python *must* gain means of concurrent execution of CPU bound code > > eventually to survive on the market. But it must get the right means > > or we are going to suffer the consequences. > > This statement, after reading the paper, seems somewhat in line with the > author's premise that language acceptability requires that a language be > self-contained/monolithic, and potentially sufficient to implement > itself. ?That seems to also be one of the reasons that Java is used > today for threaded applications. ?It does seem to be true, given current > hardware trends, that _some mechanism_ must be provided to obtain the > benefit of multiple cores/CPUs to a single application, and that Python > must either implement or interface to that mechanism to continue to be a > viable language for large scale application development. > > Andy seems to want an implementation of independent Python processes > implemented as threads within a single address space, that can be > coordinated by an outer application. ?This actually corresponds to the > model promulgated in the paper as being most likely to succeed. ?Of > course, it maps nicely into a model using separate processes, > coordinated by an outer process, also. ?The differences seem to be: > > 1) Most applications are historically perceived as corresponding to > single processes. ?Language features for multi-processing are rare, and > such languages are not in common use. > > 2) A single address space can be convenient for the coordinating outer > application. ?It does seem simpler and more efficient to simply "copy" > data from one memory location to another, rather than send it in a > message, especially if the data are large. ?On the other hand, > coordination of memory access between multiple cores/CPUs effectively > causes memory copies from one cache to the other, and if memory is > accessed from multiple cores/CPUs regularly, the underlying hardware > implements additional synchronization and copying of data, potentially > each time the memory is accessed. ?Being forced to do message passing of > data between processes can actually be more efficient than access to > shared memory at times. ?I should note that in my 25 years of parallel > development, all the systems created used a message passing paradigm, > partly because the multiple CPUs often didn't share the same memory > chips, much less the same address space, and that a key feature of all > the successful systems of that nature was an efficient inter-CPU message > passing mechanism. ?I should also note that Herb Sutter has a recent > series of columns in Dr Dobbs regarding multi-core/multi-CPU parallelism > and a variety of implementation pitfalls, that I found to be very > interesting reading. Try looking at it on another level: when your CPU wants to read from a bit of memory controlled by another CPU it sends them a message requesting they get it for us. They send back a message containing that memory. They also note we have it, in case they want to modify it later. We also note where we got it, in case we want to modify it (and not wait for them to do modifications for us). Message passing vs shared memory isn't really a yes/no question. It's about ratios, usage patterns, and tradeoffs. *All* programs will share data, but in what way? If it's just the code itself you can move the cache validation into software and simplify the CPU, making it faster. If the shared data is a lot more than that, and you use it to coordinate accesses, then it'll be faster to have it in hardware. It's quite possible they'll come up with something that seems quite different, but in reality is the same sort of rearrangement. Add hardware support for transactions, move the caching partly into software, etc. > > I have noted the multiprocessing module that is new to Python 2.6/3.0 > being feverishly backported to Python 2.5, 2.4, etc... indicating that > people truly find the model/module useful... seems that this is one way, > in Python rather than outside of it, to implement the model Andy is > looking for, although I haven't delved into the details of that module > yet, myself. ?I suspect that a non-Python application could load one > embedded Python interpreter, and then indirectly use the multiprocessing > module to control other Python interpreters in other processors. ?I > don't know that multithreading primitives such as described in the paper > are available in the multiprocessing module, but perhaps they can be > implemented in some manner using the tools that are provided; in any > case, some interprocess communication primitives are provided via this > new Python module. > > There could be opportunity to enhance Python with process creation and > process coordination operations, rather than have it depend on > easy-to-implement-incorrectly coordination patterns or > easy-to-use-improperly libraries/modules of multiprocessing primitives > (this is not a slam of the new multiprocessing module, which appears to > be filling a present need in rather conventional ways, but just to point > out that ideas promulgated by the paper, which I suspect 2 years later > are still research topics, may be a better abstraction than the > conventional mechanisms). > > One thing Andy hasn't yet explained (or I missed) is why any of his > application is coded in a language other than Python. ?I can think of a > number of possibilities: > > A) (Historical) It existed, then the desire for extensions was seen, and > Python was seen as a good extension language. > > B) Python is inappropriate (performance?) for some of the algorithms > (but should they be coded instead as Python extensions, with the core > application being in Python?) > > C) Unavailability of Python wrappers for particularly useful 3rd-party > libraries > > D) Other? "It already existed" is definitely the original reason, but now it includes single-threaded performance and multi-threaded scalability. Although the idea of "just write an extension that releases the GIL" is a common suggestion, it needs to be fairly coarse to be effective, and ensure little of the CPU time is left in python. If the apps spreads around it's CPU time it is likely impossible to use python effectively. From ldo at geek-central.gen.new_zealand Sun Oct 5 05:11:38 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 05 Oct 2008 22:11:38 +1300 Subject: del and sets proposal References: <48e7b775$0$1120$426a34cc@news.free.fr> <00f80c6a$0$20633$c3e8da3@news.astraweb.com> Message-ID: In message <00f80c6a$0$20633$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Would it really be "confusing" if sets used the same interface as dicts > use? I don't think so. What else could "del aset[x]" mean other than > "delete element x"? Yes, but "x" in what sense? In dicts it's a key, in sets, shouldn't it also be a key and not a value? Sets have no keys, only values. One might suggest assignment of keys, ? la array indexes, but that means assigning an ordering to the values, whereas sets are explicitly unordered. From clp at rebertia.com Fri Oct 3 18:08:37 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 3 Oct 2008 15:08:37 -0700 Subject: lint for Python? In-Reply-To: References: Message-ID: <47c890dc0810031508s63da1e37t5cfbbe477120f3be@mail.gmail.com> On Fri, Oct 3, 2008 at 2:38 PM, Pat wrote: > I've been searching for a good multi-module lint checker for Python and I > haven't found one yet. > > Pylint does a decent job at checking for errors only within a single module. > > Here's one of my problems. I have two modules. > > In module one, I have a function: > > def foo( host, userid, password ): > pass > > In module two, I call that function: > > foo( userid, password) > > lint doesn't find that error and it won't be caught until it's called while > the program is running. I don't want that error found at 3AM. > > I've never used a language that didn't catch that type of error. I'm quite > surprised that Python is being used by a number of major companies. How you > catch these types of errors? In a word (or phrase rather): unit testing. Lots of unit testing, which catches both silly errors like this and more complicated logic errors. Check out the 'unittest' module [http://docs.python.org/library/unittest.html] and any of the many writings on the subject for more information. And I'm sure some other posters will respond with more thorough explanations. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > I've spoken to tech support at Wing and they weren't aware of a multi-module > lint but they're considering putting their own lint into their IDE. > > Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > From blabla at dungeon.de Wed Oct 15 05:57:28 2008 From: blabla at dungeon.de (hofer) Date: Wed, 15 Oct 2008 02:57:28 -0700 (PDT) Subject: replace mothod for only one object but not for a class References: <48f4e89d$0$8551$426a74cc@news.free.fr> <48f5ada3$0$10410$426a34cc@news.free.fr> Message-ID: <1f801d6f-6e5e-4276-9852-2e7f31e8b798@u29g2000pro.googlegroups.com> Hi > > hofer a ?crit : > >> I have multiple objects all belonging to the same class > >> (which I didn't implement and whose code I don't want to modify) > > >> Now I'd like to change one method for one object only (after it has > >> been created) without adding any overhead > >> to the call of the other object's methods. Thanks for all of your answers: Here an example with three of the suggested solutions: (I didn't succeed in implementing Jason's solution with my example) ######################################################## import threading # some objects a = threading.Event() b = threading.Event() c = threading.Event() d = threading.Event() def run_dly(o): # a test function print o,"start", o.wait(1) print "stop" # unmodified test run_dly(a) run_dly(b) run_dly(c) run_dly(d) # The new Method def verbose_wait(self,dly): print "VERBOSE", threading._Event.wait(self,dly) ### Implemented with partial from functools import partial b.wait = partial(verbose_wait,b) ### with __get__ for new classes c.wait = verbose_wait.__get__(c,type(c)) ## with new for old classes import new d.wait = new.instancemethod(verbose_wait,d,type(d)) run_dly(a) run_dly(b) run_dly(c) run_dly(d) ############# end thanks again Hofer From hejibo at gmail.com Thu Oct 30 00:04:51 2008 From: hejibo at gmail.com (He Jibo) Date: Wed, 29 Oct 2008 21:04:51 -0700 (PDT) Subject: download image from flickr.com Message-ID: Dear Pythoners, Could you please help me look at a code, which is to download image from flickr.com? I wish to download images from flickr.com automatically. You can get the code at http://cid-bbc15003189d7799.skydrive.live.com/self.aspx/Public/FImageCrawl.py. There is still some problem with the code. I do not know much about regular expression. There seems to be something wrong with the line of "compile_obj = re.compile(r'dyn.Img\(".*?",".*?",".*?","(.*?)"')". Could you please help me debug it? And I aslo hope to download the first 10 pages of the images, how can I do this? Thank you so much ! Good night! He Jibo hejibo at gmail.com jibohe2 at cyrus.psych.uiuc.edu --------------------------- He Jibo Department of Psychology, Beckman Institute for Advanced Science and Technology University of Illinois, Urbana Champaign, 603 East Daniel St., Champaign, IL 61820 Tel: 217-244-4461(office) 217-244-6763(lab) Email: hejibo at gmail.com Yogi Berra - "Half the lies they tell about me aren't true." From mg at daimi.au.dk Sun Oct 5 04:42:22 2008 From: mg at daimi.au.dk (Martin Geisler) Date: Sun, 05 Oct 2008 10:42:22 +0200 Subject: Tuple parameter unpacking in 3.x References: <871vyyy8mb.fsf@hbox.dyndns.org> <87fxnco0v1.fsf@hbox.dyndns.org> <00f800fd$0$20633$c3e8da3@news.astraweb.com> Message-ID: <87iqs7cu1d.fsf@hbox.dyndns.org> Steven D'Aprano writes: > On Sat, 04 Oct 2008 17:07:14 +0200, Martin Geisler wrote: > >> A somewhat related question: do I pay a performance penalty when I >> let a function define an inner function like this: >> >> def foo(): >> >> def bar() >> ... >> >> bar() >> >> compared to just defining it once outside: >> >> def bar(): >> ... >> >> def foo(): >> ... >> bar() >> >> I'm thinking that each execution of the first foo could spend a >> little time defining a new bar each time, or is that not how things >> work? >> >> I realize that defining bar as an inner function has the advantage of >> being able to see variables in the namespace of foo. > > That is the main advantage, followed by reducing namespace pollution, > but yes there is a very small performance penalty. > > >>>> def outer(x): > ... return x+1 > ... >>>> def func(x): > ... return outer(x+1) > ... >>>> >>>> def func2(x): > ... def inner(x): > ... return x+1 > ... return inner(x+1) > ... >>>> assert func(37) == func2(37) >>>> from timeit import Timer >>>> t1 = Timer('func(23)', 'from __main__ import func') >>>> t2 = Timer('func2(23)', 'from __main__ import func2') >>>> t1.repeat() > [1.5711719989776611, 0.82663798332214355, 0.82708191871643066] >>>> t2.repeat() > [1.8273210525512695, 1.1913230419158936, 1.1786220073699951] Very interesting, thanks for measuring this! -- Martin Geisler VIFF (Virtual Ideal Functionality Framework) brings easy and efficient SMPC (Secure Multi-Party Computation) to Python. See: http://viff.dk/. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From kyosohma at gmail.com Thu Oct 23 15:49:05 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 23 Oct 2008 12:49:05 -0700 (PDT) Subject: why would 'import win32com' fail? References: Message-ID: <30d0de46-91ad-46f6-8255-0d423ae91142@m32g2000hsf.googlegroups.com> On Oct 23, 2:21?pm, bill wrote: > All, > > I am trying to access Excel from Python. Many of the examples started > with: > > ? ? ? import win32com > ? ? ? .... > ? ? ? blah, blah > > I try that from my Python shell and it fails. What am I missing here? > > TIA, > > Bill Dunno. Does it give a traceback? Does the interpreter just die? Or what? My guess is you need to uninstall Pywin32 and then reinstall it. I've seen it get goofy like this when I upgrade Pywin32 too. Mike From haraldarminmassa at gmail.com Mon Oct 20 11:20:21 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Mon, 20 Oct 2008 08:20:21 -0700 (PDT) Subject: indentation References: <010b3ea2$0$20653$c3e8da3@news.astraweb.com> <48fb8441$0$20787$426a74cc@news.free.fr> <010ba6be$0$20653$c3e8da3@news.astraweb.com> <48fc48df$0$12027$426a74cc@news.free.fr> Message-ID: <90aad42d-218d-4523-b4a0-f2293a4b5f6f@g17g2000prg.googlegroups.com> > I can't remember having seen any other "standard" so far. there is this meme flowing around: Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. I Allways thought that was some of the interpretations of the ZEN of Python, so, who can enlighten me of the origin? Harald From aisaac at american.edu Sat Oct 25 23:55:43 2008 From: aisaac at american.edu (Alan G Isaac) Date: Sat, 25 Oct 2008 23:55:43 -0400 Subject: [Numpy-discussion] [SciPy-user] ANN: Python programs for epidemic modelling In-Reply-To: <3ff92a550810251507q3696aa15x46f5b96684ff7f3c@mail.gmail.com> References: <3ff92a550810251314m18d0596fxffb0a09658a21260@mail.gmail.com> <490393B1.7030904@american.edu> <3ff92a550810251507q3696aa15x46f5b96684ff7f3c@mail.gmail.com> Message-ID: <4903EA3F.2070504@american.edu> On 10/25/2008 6:07 PM I. Soumpasis wrote: > The programs are GPL licensed. More info on the section of copyrights > http://wiki.deductivethinking.com/wiki/Deductive_Thinking:Copyrights. > I hope it is ok, Well, that depends what you mean by "ok". Obviously, the author picks the license s/he prefers. But a GPL license means that some people will avoid your code, so you make wish to make sure you thought the licensing issue for this code carefully. As a point of comparison, note that all your package dependencies have a new BSD license. Alan Isaac From tjreedy at udel.edu Tue Oct 7 14:16:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 07 Oct 2008 14:16:24 -0400 Subject: Race condition when generating .pyc files In-Reply-To: References: <48eb92a3$0$19340$426a34cc@news.free.fr> Message-ID: yogamatt1970 at gmail.com wrote: >> If you package your apps using setup, pyc should be automatically >> generated. Don't know if it can apply to your problem. But surely I'd go >> this way (ie : automating pyc creation one way or another). > > Yeah, I don't package up my code, it's all integrated into my build > system, > not an actual deliverable. Can you integrate compileall into the build process (probably used by setup)? >>> import compileall >>> help(compileall) Help on module compileall: NAME compileall - Module/script to "compile" all .py files to .pyc (or .pyo) file. FILE c:\programs\python30\lib\compileall.py DESCRIPTION When called as a script with arguments, this compiles the directories given as arguments recursively; the -l option prevents it from recursing into directories. Without arguments, if compiles all modules on sys.path, without recursing into subdirectories. (Even though it should do so for packages -- for now, you'll have to deal with packages separately.) See module py_compile for details of the actual byte-compilation. FUNCTIONS compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None, quiet=0) Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date quiet: if 1, be quiet during compilation compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0) Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) quiet: as for compile_dir() (default 0) DATA __all__ = ['compile_dir', 'compile_path'] From joe at strout.net Thu Oct 30 23:07:08 2008 From: joe at strout.net (Joe Strout) Date: Thu, 30 Oct 2008 21:07:08 -0600 Subject: Finding the instance reference of an object In-Reply-To: <6mv3bnFj2qd8U1@mid.individual.net> References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <6mv3bnFj2qd8U1@mid.individual.net> Message-ID: <6B4AF691-2478-4EDC-9ED8-33EEC81538FD@strout.net> On Oct 30, 2008, at 6:58 PM, greg wrote: > For what it's worth, I happen to agree that telling > someone that Python passes parameters "by value" without > being sure they understand exactly what "by value" > means, is not a good idea -- not because the term > isn't well-defined, but because of the widespread > confusion out there about it. > > But equally I wouldn't tell someone that it's *not* > by value, because if they do happen to correctly > understand what it means, that will confuse them just > as much. > > So my recommendation is just to tell them that it > works by assigning the result of evaluating the actual > parameter to the formal parameter. > > If they understand how assignment works in Python, that > tells them all they need to know. > > If they don't understand how assignment works, then they > have a more fundamental knowledge gap that needs to be > corrected first. That's a very sensible stance. +1! Best, - Joe From ewertman at gmail.com Sun Oct 19 13:49:39 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sun, 19 Oct 2008 13:49:39 -0400 Subject: What's the perfect (OS independent) way of storing filepaths ? In-Reply-To: References: Message-ID: <92da89760810191049s7d0fa4e5p675ae584d7b7bfbc@mail.gmail.com> >> I (again) wonder what's the perfect way to store, OS-independent, >> filepaths ? I'm in agreement that perfect probably isn't applicable. If I were doing this myself, I might store the information in a tuple: base = 'some root structure ('/' or 'C') path = ['some','set','of','path','names'] filename = 'somefile.ext' pathdata = (root,path,filename) and write a couple of simple functions to reconstruct them based on the os. From castironpi at gmail.com Tue Oct 14 23:17:35 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 14 Oct 2008 20:17:35 -0700 (PDT) Subject: docpicture References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> <010374c5$0$20641$c3e8da3@news.astraweb.com> <18675.34993.962044.115182@montanaro-dyndns-org.local> <0103c2da$0$20671$c3e8da3@news.astraweb.com> <01049eb4$0$20671$c3e8da3@news.astraweb.com> <0f00167d-96d2-4592-a3c2-fcf4812616df@31g2000prz.googlegroups.com> <307d55ed-9081-41bd-8a38-c6dc45e425e7@u27g2000pro.googlegroups.com> Message-ID: <831e88ff-891c-4dca-852f-a6dac18155c5@31g2000prz.googlegroups.com> On Oct 14, 11:56?am, bearophileH... at lycos.com wrote: > Andr?: > > > Ok, the following is my first attempt at implementing this idea. > > I suggest you to change the program you use to encode your images, > because it's 1000 bytes, while with my program the same 256 colors > image needs just 278 bytes: > > iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAMAAAAfOR5kAAAABGdBTUEAAL > GPC/xhBQAAAAd0SU1FB9gKDhAtOfvfKucAAAAYUExURf///wAAADMzM1tb > W4CAgKSkpMDAwP8AAEQE8ZoAAAABdFJOUwBA5thmAAAACXBIWXMAAA50AA > AOdAFrJLPWAAAAdElEQVQoU63Q0QrAIAgFUO/U9f9/vIxqpRIMdqOXQ6lF > RHBhsgAXs4zofXPzTZujlMayRjdmaMZDjXvtEy9FFp75zOXI/pX5n6D/lQ > v1WHnUJarTjGuRxpIxkLHtyIinx4tcy2S694Kjfzn2HDNqYM54H/wB55QF > O+Mp5mAAAAAASUVORK5CYII= > > (and it contains just 8 colors, so it can be saved as a 4 bit PNG, > saving even more bytes). Generally I suggest to use as few bits/pixel > as possible, just 1 if possible. > For the encoding/decoding you can use str.encode("base64") and > str.decode("base64"), you don't need to import modules. > > Bye, > bearophile +.5 docpicture. For encoding, it might read in from a file, try multiple different formats, including SVG, and uses whichever one is shortest. It might be nice, if they take too many lines, to store them at the end of the file, and make sure docpicture looks for them there. It could be more hassle (maybe less, actually), to store them as attributes of the objects they're accompanying, and still locate them at the bottom-- sort of like an appendix or something. def foo(): code code def bar(): '''doc str''' code code foo.__docpic__= ''' hexhexhex hexhexhex''' bar.__docpic__= ''' hexhexhex''' From prologic at shortcircuit.net.au Sun Oct 19 18:18:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 20 Oct 2008 08:18:29 +1000 Subject: better scheduler with correct sleep times In-Reply-To: <6fb41a92-a4ef-43a0-a489-eec585987f8a@j22g2000hsf.googlegroups.com> References: <6fb41a92-a4ef-43a0-a489-eec585987f8a@j22g2000hsf.googlegroups.com> Message-ID: On Mon, Oct 20, 2008 at 5:31 AM, sokol wrote: > >> from circuits.core import Manager, Component, Event, listener >> from circuits.timers import Timer > > what is circuits? If you're interested: An event framework with a focus on Component architectures. It can be downloaded currently via Mercurial at: http://hg.softcircuit.com.au/circuits/ or http://freehg.org/u/prologic/circuits/ Website coming soon at: http://trac.softcircuit.com.au/circuits/ 1.0 Release also coming soon... cheers James -- -- -- "Problems are solved by method" From duncan.booth at invalid.invalid Mon Oct 27 07:58:33 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Oct 2008 11:58:33 GMT Subject: Do I need a lock here? References: <2c4e058e-ac16-4d98-a8b0-87cdc974607b@j22g2000hsf.googlegroups.com> Message-ID: jasiu85 wrote: > Hey, > > Please take a look at the code of the two threads below: > > COMMON_DICT = {} > > def thread_1(): > global COMMON_DICT > local_dict = prepare_dict() > COMMON_DICT = local_dict > > def thread_2(): > global COMMON_DICT > local_dict = COMMON_DICT > use_dict(local_dict) > > Do I need a lock to protect the COMMON_DICT dictionary? AFAIK bytecode > operations are atomic and in each thread there's only one crucial > bytecode op: STORE_NAME in the first thread and LOAD_NAME in the > second one. So I suspect that everything will work just fine. Am I > right? > Possibly, but without further information it is impossible to tell. You have one thing wrong though: bytecode operations are not all atomic. For example STORE_NAME will remove a reference to the object previously stored under a name and that could trigger code in a __del__ method or a weak reference callback. That callback code will execute in the same thread as the STORE_NAME, but while it is executing you could get a context switch to another thread. None of that will prevent the store working, and it may not be at all applicable to your data structures, but in general any operation which can release complex objects is not thread safe. -- Duncan Booth http://kupuguy.blogspot.com From skip at pobox.com Thu Oct 23 10:48:36 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 23 Oct 2008 09:48:36 -0500 Subject: Perl/Python regular expressions vs. Boost.regex? Message-ID: <18688.36548.111115.927147@montanaro-dyndns-org.local> A colleague wrote a C++ library here at work which uses the Boost.regex library. I quickly discovered an apparent problem with how it searches. Unlike re.match the regex_match function in that library effectively anchors the match at both the start and the end. Can other people confirm this? Thx, Skip Montanaro From clp at rebertia.com Mon Oct 20 06:08:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 20 Oct 2008 03:08:22 -0700 Subject: what's the python for this C statement? In-Reply-To: <48fc55bf$0$1084$4fafbaef@reader1.news.tin.it> References: <48fc55bf$0$1084$4fafbaef@reader1.news.tin.it> Message-ID: <47c890dc0810200308q752f0567s3f521e75835c8ad1@mail.gmail.com> On Mon, Oct 20, 2008 at 2:56 AM, Michele wrote: > Hi there, > I'm relative new to Python and I discovered that there's one single way > to cycle over an integer variable with for: > for i in range(0,10,1) Actually, you want: for i in range(10): Since starting at 0 and using a step of 1 are the defaults. > > which is equivalent to: > for (i = 0; i < 10; i++) > > However, how this C statement will be translated in Python? > > for (j = i = 0; i < (1 << H); i++) There's no nice way to translate more complex 'for' statements like that (unless you can calculate the end value somehow). You basically just have to use a 'while' loop instead: i = j = 0 while i < 1 << H: #body goes here i += 1 Since bit-shifting doesn't get used much in Python and iteration through a generator or the items of a collection is more common, this doesn't end up being a problem in practice. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Sun Oct 5 17:15:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 05 Oct 2008 23:15:12 +0200 Subject: Problem with lower() for unicode strings in russian In-Reply-To: References: Message-ID: <6ksp30F9j2mtU1@mid.uni-berlin.de> Alexey Moskvin schrieb: > Hi! > I have a set of strings (all letters are capitalized) at utf-8, > russian language. I need to lower it, but > my_string.lower(). Doesn't work. > See sample script: > # -*- coding: utf-8 -*- > [skip] > s1 = self.title > s2 = self.title.lower() > print s1 == s2 > > returns true. > I have no problems with lower() for english letters:, or with > something like this: > u'russian_letters_here'.lower(), but I don't need constants, I need to > modify variables, but there is no any changs, when I apply lower() > function to mine strings. Can you give a concrete example? I doubt that there is anything different between lowering a unicode object given as literal or acquired somewhere else. And because my russian skills equal my chinese - total of zero - I can't create a test myself :) From lie.1296 at gmail.com Thu Oct 2 15:48:57 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 2 Oct 2008 19:48:57 +0000 (UTC) Subject: why? __builtins__ key added from eval References: Message-ID: On Tue, 30 Sep 2008 16:04:34 -0500, William Purcell wrote: > I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python > from adding the __builtins__ key to mydict when I use it with eval? > Other wise I have to __delitem__('__builtins__') everytime I use eval? > >>>> mydict = {'a':2,'b':3} >>>> eval('a*b',mydict) > 6 >>>> mydict > {'a': 2, '__builtins__': {'IndexError': , > ...(I'll spare you the rest)...}, 'b': 3} > > Also, how come eval has this behavior? Is it desirable? > > -Bill when you pass mydict, it is used as the global variables in the eval, right? Then, you passed a code to eval('...', mydict), sometimes you might create global variable inside eval, and you want to see the value of that inner global, that's why python modified mydict as a side-effect. Then what is __builtins__ doing there? Because when eval created an environment for the code to run, python interpreter need to define things that it used by itself. The __builtins__ contained all built-in names that is always available in python (python have to store it somewhere, the built-in names couldn't be bound by magic, right?). You could remove the builtin if you don't think it is necessary for you. Or you could do "dictionary comprehension" that collects only names you require (actually use generator comprehension then do a dict() conversion, dictionary comprehension was rejected some time ago) e.g.: newdict = dict(k, v for k, v in mydict.iteritems() if k in ['a', 'b']) or you could make a copy of mydict before passing it to eval. Last note: eval is evil. (no pun intended) From lie.1296 at gmail.com Sun Oct 26 07:57:48 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 26 Oct 2008 11:57:48 +0000 (UTC) Subject: How can I handle the char immediately after its input, without waiting an endline? References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> <29de18070810220417p331e17c1rbd9db9cb1fd9d578@mail.gmail.com> <0112d9f3$0$20624$c3e8da3@news.astraweb.com> <011333d4$0$20616$c3e8da3@news.astraweb.com> Message-ID: On Sun, 26 Oct 2008 09:23:41 +0000, Duncan Booth wrote: > Lie Ryan wrote: > >> And as far as I know, it is impossible to implement a "press any key" >> feature with python in a simple way (as it should be). > > "press any key" is a misfeature at the best of times. Quite apart from > the people who can't find the key with 'any' written on it there are > also the people who can't figure out why it 'Ctrl', 'Alt', 'Shift', > 'Caps Lock' aren't keys (not to mention the smartass's who think > Ctrl+Break is a key). It is better to always ask for a specific key. I know about those jokes. And it's the reason why I mentioned that (the serious point is about getting one-char input for "command-line GUI" applications like curse-based apps that is too simple to include the whole curse). From healey.rich at gmail.com Sun Oct 5 20:02:30 2008 From: healey.rich at gmail.com (Rich Healey) Date: Mon, 06 Oct 2008 11:02:30 +1100 Subject: how to get the thighest bit position in big integers? In-Reply-To: <48E91180.2050608@gmail.com> References: <48E91180.2050608@gmail.com> Message-ID: <48E95596.6060403@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Aaron "Castironpi" Brady wrote: > Duncan Booth wrote: >> mmgarvey at gmx.de wrote: >> >>> My question to the group: Does anyone know of a non-hackish way to >>> determine the required bit position in python? I know that my two >>> ideas >>> can be combined to get something working. But is there a *better* way, >>> that isn't that hackish? >>> >> How about using the hex representation of the value? >> >> OFFSET = dict(("%x"%i, int(c)) for i,c in enumerate("5433222211111111")) >> def get_highest_bit_num(r): >> s = "%x"%r >> return len(s) * 4 - OFFSET[s[0]] >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > You can replace the dict if it's faster. > > OFFSET= tuple( int(x) for x in "5433222211111111" ) > def get_highest_bit_num(r): > s = "%x"%r > return len(s) * 4 - OFFSET[int(s[0],16)] > > P.S. Back home, this sort of 'nitpicking' would be judged > unconstructive. Worth pointing out, or not worth saying? > > P.S.S. 'Thighest' bit? I thought the spam filters would catch that. > That should be P.P.S. PS: This is also unconstructive nitpicking. Kind regards Rich ;) - -- Rich Healey - iTReign \ .''`. / healey.rich at gmail.com Developer / Systems Admin \ : :' : / healey.rich at itreign.com AIM: richohealey33 \ `. `' / richo at psych0tik.net MSN: bitchohealey at hotmail.com \ `- / richohealey at hellboundhackers.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkjpVZUACgkQLeTfO4yBSAcgeACgr45Hu4XKyMjCf0jwq1LR35tU Lv8AnRn2RgHCxJ3QwYpNO8/DjLncKv2t =/WZa -----END PGP SIGNATURE----- From robert.kern at gmail.com Wed Oct 22 10:35:38 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 22 Oct 2008 09:35:38 -0500 Subject: Two-dimensional array tutorial? In-Reply-To: <6m8r1jFfn7onU1@mid.individual.net> References: <6m8p4vFfnd9nU2@mid.individual.net> <6m8q88Ffc6r2U2@mid.uni-berlin.de> <6m8r1jFfn7onU1@mid.individual.net> Message-ID: Martin Schneider wrote: > Diez B. Roggisch schrieb: >> Can't you just get Numpy (or it's predecessors, Numeric) compiled against >> ptyhon2.2? > > I tried Numeric, but e.g. it doesn't seem to feature transpose... Yes, it does. Numeric.transpose() > How do I compile Numpy against python2.2? :-) You cannot. The first version of numpy required Python >= 2.3. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Thu Oct 16 05:00:36 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 16 Oct 2008 22:00:36 +1300 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? References: <48f66642$0$8018$426a74cc@news.free.fr> <7921db67-00fb-4da7-a925-b631fba85f82@t18g2000prt.googlegroups.com> Message-ID: In message <7921db67-00fb-4da7-a925-b631fba85f82 at t18g2000prt.googlegroups.com>, rustom wrote: > Reminds me of a funny story about one of our university profs. > At a time when we used DOS and unix (on terminals) he got a very high > end SGI workstation. > And promptly shouted at the sysads because he could not see his > C:> > prompt. The joke was on them, of course. To be fair, SGI did try to oblige, with a short-lived, ill-fated foray into Dimdows NT workstations. Probably hastened their end... From george.sakkis at gmail.com Sat Oct 18 00:18:41 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 17 Oct 2008 21:18:41 -0700 (PDT) Subject: Parsing a file with iterators References: <6lrtpmFdqe8iU2@mid.uni-berlin.de> Message-ID: <9ca8b2ef-8092-43ce-819a-ad0c8bf6003f@t42g2000hsg.googlegroups.com> On Oct 17, 12:45?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 17 Oct 2008 11:42:05 -0400, Luis Zarrabeitia wrote: > > I need to parse a file, text file. The format is something like that: > > > TYPE1 metadata > > data line 1 > > data line 2 > > ... > > data line N > > TYPE2 metadata > > data line 1 > > ... > > TYPE3 metadata > > ... > > [?] > > because when the parser iterates over the input, it can't know that it > > finished processing the section until it reads the next "TYPE" line > > (actually, until it reads the first line that it cannot parse, which if > > everything went well, should be the 'TYPE'), but once it reads it, it is > > no longer available to the outer loop. I wouldn't like to leak the > > internals of the parsers to the outside. > > > What could I do? > > (to the curious: the format is a dialect of the E00 used in GIS) > > Group the lines before processing and feed each group to the right parser: > > import sys > from itertools import groupby, imap > from operator import itemgetter > > def parse_a(metadata, lines): > ? ? print 'parser a', metadata > ? ? for line in lines: > ? ? ? ? print 'a', line > > def parse_b(metadata, lines): > ? ? print 'parser b', metadata > ? ? for line in lines: > ? ? ? ? print 'b', line > > def parse_c(metadata, lines): > ? ? print 'parser c', metadata > ? ? for line in lines: > ? ? ? ? print 'c', line > > def test_for_type(line): > ? ? return line.startswith('TYPE') > > def parse(lines): > ? ? def tag(): > ? ? ? ? type_line = None > ? ? ? ? for line in lines: > ? ? ? ? ? ? if test_for_type(line): > ? ? ? ? ? ? ? ? type_line = line > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? yield (type_line, line) > > ? ? type2parser = {'TYPE1': parse_a, > ? ? ? ? ? ? ? ? ? ?'TYPE2': parse_b, > ? ? ? ? ? ? ? ? ? ?'TYPE3': parse_c } > > ? ? for type_line, group in groupby(tag(), itemgetter(0)): > ? ? ? ? type_id, metadata = type_line.split(' ', 1) > ? ? ? ? type2parser[type_id](metadata, imap(itemgetter(1), group)) > > def main(): > ? ? parse(sys.stdin) I like groupby and find it very powerful but I think it complicates things here instead of simplifying them. I would instead create a parser instance for every section as soon as the TYPE line is read and then feed it one data line at a time (or if all the data lines must or should be given at once, append them in a list and feed them all as soon as the next section is found), something like: class parse_a(object): def __init__(self, metadata): print 'parser a', metadata def parse(self, line): print 'a', line # similar for parse_b and parse_c # ... def parse(lines): parse = None for line in lines: if test_for_type(line): type_id, metadata = line.split(' ', 1) parse = type2parser[type_id](metadata).parse else: parse(line) George From benjamin.kaplan at case.edu Sun Oct 26 14:12:17 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 26 Oct 2008 14:12:17 -0400 Subject: Improving interpreter startup speed In-Reply-To: <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> Message-ID: On Sun, Oct 26, 2008 at 1:45 PM, BJ?rn Lindqvist wrote: > 2008/10/26 James Mills : > > On Sun, Oct 26, 2008 at 11:23 AM, BJ?rn Lindqvist > wrote: > >> How are you getting those numbers? 330 ?s is still pretty fast, isn't > >> it? :) Most disks have a seek time of 10-20 ms so it seem implausible > >> to me that Ruby would be able to cold start in 47 ms. > > > > $ time python -c "pass" > > > > real 0m0.051s > > user 0m0.036s > > sys 0m0.008s > > Pedro was talking about cold startup time: > > $ sudo sh -c "echo 3 > /proc/sys/vm/drop_caches" > $ time python -c "pass" > > real 0m0.627s > user 0m0.016s > sys 0m0.008s > > That is quite a lot and for short scripts the startup time can easily > dominate the total time. > > > And yes I agree. the CPython interpreter startup times is > > a stupid thing to be worrying about, especially since that > > is never the bottleneck. > > I disagree. The extra time Python takes to start makes it unsuitable > for many uses. For example, if you write a simple text editor then > Pythons longer startup time might be to much. > You must be in a real big hurry if half a second matters that much to you. Maybe if it took 5 seconds for the interpreter to start up, I could understand having a problem with the start up time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Wed Oct 29 14:51:47 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 29 Oct 2008 11:51:47 -0700 (PDT) Subject: how to get the thighest bit position in big integers? References: <3c25c2cd-0357-47b0-b51d-fb38a55bd54e@t18g2000prt.googlegroups.com> Message-ID: <5ad76973-e776-4654-bc6f-6913eb4f99f0@c60g2000hsf.googlegroups.com> On Oct 29, 1:26?am, Nick Mellor wrote: > On Oct 6, 3:40?am, Gary Herron wrote: > > > > > > > mmgar... at gmx.de wrote: > > > Hi, > > > > I'm using python to develop some proof-of-concept code for a > > > cryptographic application. My code makes extended use of python's > > > native bignum capabilities. > > > > In many cryptographic applications there is the need for a function > > > 'get_highest_bit_num' that returns the position number of the highest > > > set bit of a given integer. For example: > > > > ? ?get_highest_bit_num( (1 << 159)) ? ? == 159 > > > ? ?get_highest_bit_num( (1 << 160) - 1) == 159 > > > ? ?get_highest_bit_num( (1 << 160)) ? ? == 160 > > > How about a binary search? > > > >>> from bisect import bisect > > >>> BITS = [1< > >>> bisect(BITS, 1<<159) > > 159 > > >>> bisect(BITS, 1<<160-1) > > 159 > > >>> bisect(BITS, 1<<160) > > 160 > > > I have no clue if this is faster or not. ?The comparison function used > > in the search is (potentially) slow, but the search is O(log n) on the > > number of bits rather than O(n), so its worth a test. > > > If you run timing test, let us know the results. > > > Gary Herron > > > > I implemented this the following way: > > > > def get_highest_bit_num(r): > > > ? ? i = -1 > > > ? ? while r > 0: > > > ? ? ? ? r >>= 1 > > > ? ? ? ? i = i + 1 > > > ? ? return i > > > > This works, but it is a very unsatisfying solution, because it is so > > > slow. > > > > My second try was using the math.log function: > > > > import math > > > r = (1 << 160) - 1 > > > print highest_bit_num(r) ? ? ? ? ? ? ?# prints out 159 > > > print math.floor(math.log(r, 2)) ? ? ?# prints out 160.0 > > > > We see that math.log can only serve as a heuristic for the highest bit > > > position. For small r, for example r = (1 << 16) - 1, the result from > > > math.log(, 2) is correct, for big r it isn't any more. > > > > My question to the group: Does anyone know of a non-hackish way to > > > determine the required bit position in python? I know that my two > > > ideas > > > can be combined to get something working. But is there a *better* way, > > > that isn't that hackish? > > > > cheers, > > > mmg > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > The following might be worth a try. It's faster the fewer set bits > there are in the original number, and lightning fast if there are only > one or two: > > def get_highest_bit_num(i): > ? ? while i>0: highestbit, i = i, i & (i-1) > ? ? return highestbit > > >>> highestbit(1<<31) > 2147483648L > >>> highestbit(1<<4) > 16 > >>> highestbit(3<<4) > > 32 > > Note that it returns the value of the highest bit, not its position. > > All it's doing is successively ANDing i with (i-1) until i is zero, > then returning the previous value of i. > > It works because i & (i-1) has a useful property: it returns i less > its least significant set bit: > > i=6 (binary 110) => i & (i-1)==4 (binary 100) > i=3328 => (binary 1101_0000_0000) then i & (i-1)==3072 (binary > 1100_0000_0000) > > (underscores for readability) > > As far as I know there isn't another piece of logic that helps you > extract the most significant bit as simply :-) import gmpy print 'highest bit position: %d' % (len(gmpy.digits(3328,2))-1) highest bit position: 11 or in 2.6 print 'highest bit position: %d' % (len(bin(3328)[2:])-1) highest bit position: 11 > > Best wishes, > > Nick From greg at cosc.canterbury.ac.nz Sat Oct 25 01:54:04 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 25 Oct 2008 18:54:04 +1300 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> Message-ID: <6mfr23Ffk1khU1@mid.individual.net> Andy O'Meara wrote: > - each worker thread makes its own interpreter, pops scripts off a > work queue, and manages exporting (and then importing) result data to > other parts of the app. I hope you realize that starting up one of these interpreters is going to be fairly expensive. It will have to create its own versions of all the builtin constants and type objects, and import its own copy of all the modules it uses. One wonders if it wouldn't be cheaper just to fork the process. Shared memory can be used to transfer large lumps of data if needed. -- Greg From steve at REMOVE-THIS-cybersource.com.au Fri Oct 17 07:56:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Oct 2008 11:56:07 GMT Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <3fe70d4b-0dfe-4c60-8b16-1bc70ce96d25@j68g2000hsf.googlegroups.com> <80b69331-e241-4c05-8df9-03f8bdbfe0bb@y21g2000hsf.googlegroups.com> Message-ID: <01087685$0$20638$c3e8da3@news.astraweb.com> On Fri, 17 Oct 2008 23:04:52 +1300, Lawrence D'Oliveiro wrote: > In message , Duncan Booth wrote: > >> We already get people asking why code like this doesn't return 3: >> >>>>> fns = [ lambda: x for x in range(10) ] fns[3]() >> 9 >> >> ... making this change to default arguments would mean the solution >> usually proposed to the function scoping question above would no longer >> work: >> >>>>> fns = [ lambda y=x: y for x in range(10) ] fns[3]() >> 3 > > The right solution, of course, is > > fns = [(lambda x : lambda : x)(x) for x in range(10)] Only if by "right solution" you mean "excessively verbose, confusing, and the sort of thing that makes even supporters of lambda cringe". Yes yes, it's just a factory function written with lambdas. It's still ugly and exactly the sort of thing that gives ammunition to lambda- haters. Unlike the solution given by Duncan, which is understandable to any newbie who has learned about default values and lambda, your solution requires an understanding of higher-level functions (functions that return functions, for anyone who doesn't recognise the term) that most newbies won't have. And while I don't much care for premature optimization, I will point out that creating a factory function just to call it once then throw it away is very wasteful, and that waste is demonstrated by the running time being more than double that of Duncan's solution: >>> timeit.Timer('[ lambda y=x: y for x in range(10) ]').repeat() [7.6332600116729736, 6.9825620651245117, 7.0891578197479248] >>> timeit.Timer('[(lambda x : lambda : x)(x) for x in range(10)]').repeat() [18.984915971755981, 17.808281898498535, 18.432481050491333] -- Steven From sjmachin at lexicon.net Fri Oct 17 01:49:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Oct 2008 22:49:15 -0700 (PDT) Subject: Unicode File Names References: <72f742a5-25fd-4e5c-8eaa-d234f226ac02@p31g2000prf.googlegroups.com> <311aa0af-6acd-45b6-b89b-c5aebe957afe@75g2000hso.googlegroups.com> Message-ID: On Oct 17, 2:56 pm, Jordan wrote: > I'm not quite sure now if the problem is me, windows, or zipfile > (which I kinda failed to mention before). Using > os.listdir(unicode(os.listdir())) You mean os.listdir(unicode(os.getcwd())), I presume. > seems to have been a step in the > right direction (thanks Chris and John). When testing things in the > python interpreter, I don't seem to hit issues after using the above > mentioned line. > > [code]>>> l = os.listdir(unicode(os.getcwd())) > >>> l > > u'01-\u3072\u3089\u304c\u306a.jpg' > u'02-\u3072\u3089\u304c\u306a.jpg' > u'03-\u3072\u3089\u304c\u306a.jpg' > > >>>for thing in l: > > ... print thing > 01-????.jpg > 02-????.jpg > 03-????.jpg > > [/code] > Yay. > > Having a file that tries "for thing in l: print thing" fails with: > > File "C:\Python25\Lib\encodings\cp437.py", line 12, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode characters in > position 13-16: character maps to > > I'm perfectly willing to let command prompt refuse to print that (it's > debugging only) if the next issue was resolved >_>: use print repr(thing) for debugging. > > """ > Note: There is no official file name encoding for ZIP files. If you > have unicode file names, please convert them to byte strings in your > desired encoding before passing them to write(). WinZip interprets all > file names as encoded in CP437, also known as DOS Latin. > """ > > I'm simply not sure what this means and how to deal with it. Step 1: Read appendix D of http://www.pkware.com/documents/casestudies/APPNOTE.TXT Step 2: Note the change history at the start of that document: """ 6.3.0 -Added tape positioning storage 09/29/2006 parameters [snip] -Added option for Unicode filename storage """ Step 3: Read http://bugs.python.org/issue1734346 Step 4: Either wait for Python 2.7 or apply the patch to your own copy of zipfile ... From paul at boddie.org.uk Wed Oct 15 12:08:35 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 15 Oct 2008 09:08:35 -0700 (PDT) Subject: Python equivalent to SharePoint? References: Message-ID: <0b60a505-7c04-4d4a-a656-ad9e18eb9b76@p10g2000prf.googlegroups.com> On 15 Okt, 17:17, Joe Strout wrote: > We've got a client who has been planning to use SharePoint for ? > managing their organization documents, but has recently dropped that ? > idea and is looking for an alternative. ?Is there any Python package ? > with similar functionality? Here's a starting point: http://wiki.python.org/moin/ContentManagementSystems Plone is probably the first thing that comes to mind. > I confess that I've never used SharePoint myself, and what I know ? > about is mainly from these sources: > > ? ?http://en.wikipedia.org/wiki/SharePoint > ? ?http://discuss.joelonsoftware.com/default.asp?joel.3.66103.7 The Wiki vs. CMS thing is relevant, even though I imagine that corporate types like to "pooh-pooh" the idea of Wikis, preferring as they do to use their CMS or intranet solution as yet another "shared folder" for their Word documents. What I know from experiences trying to build a willing editing community around the EuroPython site was that people didn't like to stray anywhere near CPS, but people could be coerced into editing Wiki content; the PyCon UK site had even more contributions from random conference attendees. Of course, a corporate CMS typically involves the imposition of such a system on employees - that's one way not to bother about user acceptance since everyone implicitly says "yes" once the roll-out begins - but as one commenter on Joel's article notes, even the fanciest solutions require a degree of willing maintenance, and if it all starts to rot then the whole point of introducing such a system is undermined. > I found a reference to CPS, but its developers have dropped the Python ? > source to rewrite it in Java. ?That's disturbing, and I don't want to ? > recommend an abandoned platform. ?Anything else I should consider? There may be other solutions not included on the page I mention above. I remember being shown SharePoint a few years back by a fellow consultant, and apart from the fancy drag-and-drop layout tools I was strongly reminded of Slashdot, of which the consultant was naturally unaware. At that time, for the basics of a "community site" such as certain kinds of intranets, Zope plus Squishdot would have been acceptable, but any absence of steep licensing costs isn't necessarily an advantage in the consulting business since such stuff usually gets passed onto the brand-obsessed customer. With regard to "proper" document management, I think we'll increasingly see developments around the revitalised area of version control systems and their integration with Web-based solutions. Subversion, for example, is already a Web-based solution in itself - you'd just need to put a presentation logic layer on top. Paul From tjreedy at udel.edu Mon Oct 6 14:43:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 06 Oct 2008 14:43:31 -0400 Subject: do something in time interval In-Reply-To: <8aa5d90d-0647-47d4-88bb-8784a31866cf@t54g2000hsg.googlegroups.com> References: <8aa5d90d-0647-47d4-88bb-8784a31866cf@t54g2000hsg.googlegroups.com> Message-ID: Petr Jakes wrote: > I have infinitive loop running script and I would like to check > something periodically after 5 seconds (minutes, hours...) time period > (I do not mean time.sleep(5) ). Till now, I have following script, but > I think there must be something more elegant. > > eventFlag = False > while 1: > time.sleep(0.01) > seconds = time.time() > if not int(seconds % (5)): > if eventFlag: > print "5 seconds, hurray" > eventFlag = False > else: > eventFlag = True The eventFlag is confusing. Better: dt = 5 # for instance event_time = time.time() while 1: #do every loop stuff now = time.time() if now >= event_time: event_time = now + dt event() If you have multiple delayed events, quite possibly each with a different or even variable delta, store (future_time,func_to_call) pairs in a priority queue (heapq module). Terry Jan Reedy From http Fri Oct 31 14:30:41 2008 From: http (Paul Rubin) Date: 31 Oct 2008 11:30:41 -0700 Subject: python openssl x509 CA References: <381603cf-f0c1-4a51-bced-46b7c5065b3f@w1g2000prk.googlegroups.com> Message-ID: <7xvdv8obvy.fsf@ruckus.brouhaha.com> Marcin Jurczuk writes: > I want to create pure python implementation without use of openssl > wrapped with python code. There was a CA written in Python quite a while back, http://pyca.de . I don't know if it's maintained these days. From python at rcn.com Sat Oct 18 23:43:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 18 Oct 2008 20:43:24 -0700 (PDT) Subject: heapreplace, methodcaller References: <848dd2c3-d13f-4922-9991-63d7664d4123@y79g2000hsa.googlegroups.com> Message-ID: On Oct 18, 7:01?am, bearophileH... at lycos.com wrote: > To improve name coherence I think this method of the heapq module: > heapq.heapreplace(heap, item) > > can grow an alias in Python 2.6.1/2.7 and 3.0/3.1: > heapq.heappoppush(heap, item) > > So later the heapreplace() name can be deprecated. Too late for 2.6 and possibly too late and too disruptive for 3.0 (which needs to minimize transitions from 2.6). Raymond From todd at mapssg.com Fri Oct 24 14:35:18 2008 From: todd at mapssg.com (harvey) Date: Fri, 24 Oct 2008 11:35:18 -0700 (PDT) Subject: Python/Django Developer Message-ID: <20155587.post@talk.nabble.com> My client in Jersey City, NJ 07302 is looking for a Python Developer. Below is the job description: Job Summary: This is a programming position in the technical department of Advance Internet, working on application development, application integration, automated testing and deployment of applications, publishing structure and unit testing in various development environments. Job Functions: ? Develop extensible online applications ? Integrate vendor code into web tier ? Write and Maintain Unit Tests ? Develop and Maintain Automated Testing Frameworks ? Perform Load/Performance Testing ? Maintain & Enhance Build & Deployment Scripts ? Liaise with programmers (internal & external) ? Ability to set development standards ? Oversee incorporation of applications into web tier ? Assess stability of existing applications ? Coordinate conversion from legacy systems Supervisory Responsibilities: ? None Required Knowledge, Skills and Abilities: Candidate needs to be aggressive in learning new things as well as taking responsibility for work product and meeting deadlines with minimal supervision. They need to have worked in an online environment and have published applications that have withstood live deployment. ? Open source familiarity ? Django framework ? Python ? Other frameworks ? At least 2 standard templating languages such as Velocity, PHP, JSP ? Knowledge of quality control methods and philosophy ? Linux command line proficiency ? ANT/Maven, Build, Make ? Project management experience ? Excellent written and oral communication skills Desired Skills/Experience: ? Moveable Type application knowledge ? Developing for a clustered server environment ? Ability to read/understand C ? OO Perl -- View this message in context: http://www.nabble.com/Python-Django-Developer-tp20155587p20155587.html Sent from the Python - python-list mailing list archive at Nabble.com. From netimen at gmail.com Mon Oct 20 08:01:07 2008 From: netimen at gmail.com (=?KOI8-R?B?7cnU0Q==?=) Date: Mon, 20 Oct 2008 05:01:07 -0700 (PDT) Subject: dumping in destructor References: <1fec9da2-4ef6-4e8b-9015-8eb6c43cc397@m36g2000hse.googlegroups.com> <618c9b29-0bbf-4a95-aa4f-e41c6b8c581f@j68g2000hsf.googlegroups.com> Message-ID: <6f03bf3f-e86c-43b5-9157-fd139a249280@m73g2000hsh.googlegroups.com> Thank you for your answers! my g_register is a global object, and it lives all the program's lifetime, so 'with' is not appliable. Am I right? I tried to use atexit and wrote following: class _Register(object): def dump(self): .... class Registerable(object): .... g_register = _Register() atexit.register(g_register.dump) ... ... g_register.add(Registerable('aa')) But now I get: cPickle.PicklingError: Can't pickle : attribute lookup __main__.Registerable failed Does that mean that by the time of atexit execution my Registerable class is already dead? Michele Simionato wrote: > On Oct 20, 10:12?am, ???? wrote: > > But when g_register is being destroyed, dump seems to be already dead, > > so I get: > > > > Exception exceptions.TypeError: "'NoneType' object is not callable" in > > > at 0x835a74c>> ignored > > > > can I somehow save my data from destructor? > > The best thing is to use the 'with' statement, but it requires you to > rewrite all > of your code. Alternatively you can use the atexit module. I wrote > once a > recipe that may be of interest to you: > > http://code.activestate.com/recipes/523007/ From bdesth.quelquechose at free.quelquepart.fr Sun Oct 19 13:01:31 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 19 Oct 2008 19:01:31 +0200 Subject: re.search over a list In-Reply-To: References: Message-ID: <48fb83cb$0$20787$426a74cc@news.free.fr> Pat a ?crit : > While I can use a for loop looking for a match on a list, I was > wondering if there was a one-liner way. > > In particular, one of my RE's looks like this '^somestring$' so I can't > just do this: re.search( '^somestring$', str( mylist ) ) > > I'm not smart enough (total newbie) to code up a generator expression > and I was wondering if I'm missing something obvious. words = ['foo', 'bar', 'somestring', 'baaz'] re.search(r"^somestring$", "\n".join(words), re.MULTILINE) > I love succinct but clearly understandable code. separator.join(sequence_of_strings) is a very common python idiom, so you can consider it as readable. From wescpy at gmail.com Wed Oct 15 14:43:41 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Oct 2008 11:43:41 -0700 Subject: [ANN] final 2008 Python courses, San Francisco In-Reply-To: <78b3a9580809050121t517a93f4uca7b1918dac66f9c@mail.gmail.com> References: <78b3a9580809050116w2cfd7a98s10b7b9d201a979d8@mail.gmail.com> <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> <78b3a9580809050121t517a93f4uca7b1918dac66f9c@mail.gmail.com> Message-ID: <78b3a9580810151143y2f9b629fj4be4b014d84a0b69@mail.gmail.com> *** FINAL REMINDER also, the course begins on monday immediately following the *free* CodeCamp conference http://siliconvalley-codecamp.com (click Program => Sessions to see all the talks)... 5 straight days of learning in the San Francisco Bay Area!! *** ---------- Forwarded message ---------- From: wesley chun Date: Fri, Sep 5, 2008 at 1:21 AM Subject: [ANN] final 2008 Python courses, San Francisco To: python-list at python.org, python-announce-list at python.org Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python Programming," for another comprehensive intro course plus a 1-day Internet programming course coming up in November in beautiful Northern California! I look forward to meeting you! (Comprehensive) Introduction to Python Mon-Wed, 2008 Nov 10-12, 9am-5pm Internet Programming with Python Sat, 2008 Nov 15, 9am-5pm courses can be taken separately or combined for a discounted price. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON This is a one-day course with lecture and lab exposing attendees to FOUR distinct areas of Internet programming: * Network Programming using Sockets -- we introduce client/server architecture and how to program sockets using Python. * Internet Client Programming -- we learn how to use Python's standard library to create FTP, NNTP, POP3, and SMTP clients * Web Programming -- before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser to prepare you better when jumping to a full-stack web framework * Intro to Django -- a lightweight introduction to the Django web framework including whipping up a very simple blog application in 20min! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") FLYER: http://starship.python.net/crew/wesc/flyerPP1combo.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From andis59 at gmail.com Thu Oct 16 02:31:51 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Thu, 16 Oct 2008 08:31:51 +0200 Subject: [NEWBIE] csv to excel format problem References: Message-ID: Hello Marco and welcome to the wonderful world of Python, Your problem is that the file is a text file so the values you are reading are text which you then write to the Excel sheet. So you need to convert the text value to a float value. Now the Big Cahonas has already been there so it's included: float( [x]) Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python's floating point precision) is returned. If no argument is given, returns 0.0. Note: When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary If you do this change it might work ;-) Add these functions: def isNaN(x): return isinstance(x, float) and x!=x def isInf(x): return !isNaN(x) && isNaN( (x) - (x) ) in writeExcelRow change: for column in columns: fcolumn = float(column) if(isNaN(fcolumn) or isInf(fcolumn)): # do some error handling else: worksheet.write(lno, cno, column,style) cno = cno + 1 I'm sure that there are smarter ways of doing this and someone will probably point them out ;-) // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! On Tue, 14 Oct 2008 03:03:52 -0700 (PDT), MM wrote: > Hi to all, > > I'm trying to import a tab separated values file onto Excel with the > following script: > > import csv > from pyExcelerator import * > > w = Workbook() > worksheet = w.add_sheet('sim1') > > def writeExcelRow(worksheet, lno, columns): > style = XFStyle() > style.num_format_str = '0.00E+00' > cno = 0 > for column in columns: > worksheet.write(lno, cno, column,style) > cno = cno + 1 > > nrow = 0 > csvfile = file('res1.txt','r') > csvreader = csv.reader(csvfile, delimiter='\t') > > for line in csvreader: > writeExcelRow(worksheet,nrow,line) > nrow += 1 > > csvfile.close() > w.save('numbers.xls') > > All goes well and the resulting file "numbers.xls" has all the numbers > in the right place.... > > The problem is that excel sees the numbers as text and gives the error > "numbers stored as text" that I have to correct manually. > > The file res1.txt has the structure of a tab separated values of > floating point numbers. > > Thank you for the help. > > Marco From afgf999 at gmail.com Sun Oct 19 13:43:05 2008 From: afgf999 at gmail.com (hi) Date: Sun, 19 Oct 2008 10:43:05 -0700 (PDT) Subject: The truth about Prophet Muhammad (Peace Be Upon Him) Message-ID: <443be41a-b6a5-4db0-b06b-16d06522d4c2@75g2000hso.googlegroups.com> The truth about Prophet Muhammad (Peace Be Upon Him) Loving him is following him Muslims all over the world are deeply hurt by the recent caricatures of our beloved Prophet Muhammad , in Danish and several other publications. Every now and then, some Western media outlets provoke Muslims by insulting the Prophet Muhammad . The baiting often succeeds in eliciting Muslims' outrage and sporadic violence. The latest incident started with a Danish newspaper's caricature portraying the Prophet Muhammad as a terrorist. To add insult to injury, Norwegian, French, German, Dutch and a few other newspapers reprinted the defamatory cartoons to "defend"?they claimed?the freedom of expression. The real issue is not the freedom of expression. Free speech is not and was never meant to be absolute. There are laws in the West that ban certain kinds of speech, including those that incite anti- Semitism, racism and violence. Moreover, some countries have laws against blasphemy and defamation. To Muslims, banning blasphemy against Allah and the Prophet Muhammad has a higher priority. For the European newspapers to reprint the offensive cartoons to show solidarity with their Danish counterpart seems akin to the plot the leaders of Quraysh had hatched to assassinate Prophet Muhammad . The Quraysh masterminds had figured that including representatives from major tribes of Makkah in the heinous plot would make it impossible for the Prophet's clan, Banu Hashim, to avenge. But Allah willed that the Prophet Muhammad would migrate to Madinah unscathed while the plotters laid siege to his house. The West often underestimates the Muslims' reverence for their beloved Prophet Muhammad, (sallallallahu alayhi wa sallam) and is, therefore, staltred by the fierce Islamic reaction to an insult against him. Few in the West know that for Muslims, loving their Prophet more than themselves is a matter of faith, not choice. Further, the depiction of the Prophet Muhammad , as a terrorist is a falsification of history. He was considered "Al-Ameen," the trustworthy, by his people even before he received the Prophethood. Once, when asked by some of his followers to invoke Allah's wrath on the enemies, he refused saying he had been sent as a mercy unto mankind. Objective Western intellectuals have acknowledged the superior character of Prophet Muhammad . In his ?The 100, a Ranking of the Most Influential Persons in History," Michael H. Hart ranked Prophet Muhammad, (sallallallahu alayhi wa sallam) No. 1 because "He was the only man in history who was supremely successful on both the religious and secular levels.? Alphonse de Lamartine, a renowned 19th Century French writer, had this to say about the Prophet Muhammad : "As regards all standards by which human greatness may be measured, we may well ask, is there any man greater than him?? Unfortunately, some Muslims forget that loving their Prophet Muhammad (Peace be upon him) means following him. Burning Danish embassies, as they did in Damascus and Beirut, to avenge the insult to the Prophet Muhammad is a complete disservice to him. Our violent reaction only plays into the hands of those who wish to reinforce the negative stereotypes about Muslims. Do Muslims need reminding that Prophet Muhammad , forgave the people of Ta'if who had rejected his message of monotheism and pelted him with stones, bloodying him? Islamic tradition has it that when Jibreel (Archangel Gabriel) sought his permission to punish the perpetrators, the Prophet , instead prayed that some day the inhabitants of Ta'if would leave their idols and worship Allah alone. Within a few years they did. Prophet Muhammad's, (sallallallahu alayhi wa sallam) servant once noted his forgiving disposition, said, "I served the Prophet , for ten years, and he never said ?uf? (a word indicating impatience or discontent) to me and never blamed me by saying, `Why did you do so or why didn't you do so?" (Al-Bukhari and Muslim) Prophet Muhammad's, (sallallallahu alayhi wa sallam) archenemies hated his Message and hurled malicious insults at him, to which he responded with forbearance. Years later when he, sallallallahu alayhi wa sallam returned as victor to Makkah, his city of birth which he was forced to leave, he asked its awed citizens, "What do you think I'm going to do to you." They said, "You are a noble brother, son of a noble brother; we expect only good from you." The Prophet responded with a general amnesty. Let Muslims not forget that the Prophet , encouraged freedom of expression. In the Battle of Badr, he changed the battlefield against his own opinion due to the passionate advice of some young soldiers. Part of the West's success today is the freedom of expression, of thought, of religion?that draws Muslims to it from their oppressed societies. For that, Muslims should be thankful to the West. After all, freedom is an Islamic value that the West has embraced while Muslim societies have forsaken. Defending Prophet Muhammad requires allowing freedom and practicing compassion and forgiveness, like he did. In his lifetime he , bore insults with magnanimity and devoted his time to spreading the Message of Allah. In fact, he never avenged anyone for a personal offence. Can we really respect him by violent retaliation? Muslims should turn this extremely painful incident into something positive, by teaching the world what the Prophet , means to us and what his life was like. As for the West, there really is a need to reexamine the notion of free speech. Without safeguards, the exercise of this freedom can be lethal, as we have seen. One may ask, is it morally defensible to provoke violence, cause death, and create a civilizational conflict for one cartoonist's freedom of expression? The West already has laws to protect religious freedom, which Muslims and other peoples of faith admire. What it now needs to do is protect this freedom from being trampled by unbridled free speech. No one should have to insult Prophet Muhammad, Jesus, or Moses, may Allah exalt their mention to speak freely. We can turn these negative, malicious cartoons into something positive by learning about the Prophet , by following him, and educating others about his teachings. Allah described the Prophet in the verse (which means): "And verily, you (O Muhammad) are on an exalted standard of character." (Quran 68:4) And (what means): "Indeed in the Messenger of Allah there is a good example to follow for him who hopes in (the meeting with) Allah and the Last Day and remembers Allah much." (Quran 33:21) By a divine decision, the status of Muhammad was raised forever, as in the verse (which means): "And (has Allah not) raised high your fame?" (Quran 94:4) Muslims were commanded to lower their voices low in the presence of the Prophet , out of respect, as in the verse (which means): "O you who believe, raise not your voices above the voice of the Prophet, nor speak aloud to him as you speak aloud to one another lest your deeds be rendered fruitless while you perceive not. Verily, those who lower their voices in the presence of Allah's Messenger, they are the ones whose hearts Allah has tested for piety. For them there is forgiveness and a great reward." (Quran 49:2-3) While other prophets were sent to their own people, Muhammad was appointed as the Messenger to all mankind. And such he was asked to declare (what means): "Say (O Muhammad): `O mankind, verily I am sent to you all as the Messenger of Allah - to Whom belongs the Dominion of the heavens and the earth." (Quran 7:158) On the Day of Judgement he will be the only Messenger to intercede with Allah to seek forgiveness for the wrongdoers. As blasphemous as the drawings are, we believe that behind all events there is Allah's pre-decree and wisdom that mortal beings fully understand only in hindsight. In the end, this deeply hurtful incident would be seen as benefiting the image of the Prophet . A case in point is the verse (which means): "Verily, We have given you (O Muhammad) a manifest victory." (Quran 48:1) When this verse was revealed, even some of the most exemplary Muslims could not understand how being prevented from performing pilgrimage by the enemies could be a manifest victory. Prophet Muhammad had just signed a treaty with non-Muslims of Makkah that imposed unfair restrictions on Muslims. The Prophet swore by Allah that no matter how restrictive this treaty seemed, it was a clear victory for Muslims. Within a few years, the victory became abundantly clear when Muslims marched into Makkah, not just as pilgrims but as victors. Our love for the Prophet Muhammad cannot be expressed except by following him. If we did that, we will see how Allah can change this painful incident into a great opportunity for the Islamic cause. http://www.islamhouse.com/ From steven.p.clark at gmail.com Mon Oct 27 17:03:37 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Mon, 27 Oct 2008 17:03:37 -0400 Subject: Unpacking byte strings from a file of unknown size In-Reply-To: <5adcb40f-3b97-4fb7-b534-ab323bdb7636@s1g2000prg.googlegroups.com> References: <5adcb40f-3b97-4fb7-b534-ab323bdb7636@s1g2000prg.googlegroups.com> Message-ID: <663744510810271403j18b62ae7q2b45124269049ff1@mail.gmail.com> On Mon, Oct 27, 2008 at 4:29 PM, Mark wrote: > Hi; > > I'm trying to use the struct.unpack to extract an int, int, char > struct info from a file. I'm more accustomed to the file.readlines > which works well in a 'for' construct (ending loop after reaching > EOF). > > # This does OK at fetching one 10-byte string at a time: > # (4, 4, 2 ascii chars representing hex) > info1, info2, info3 = struct.unpack(' > # Now to do the entire file, putting into a loop just gives error: > # TypeError: 'int' object is not iterable > for info1, info2, info3 in struct.unpack(' > In trying to shoehorn this into a 'for' loop I've been unsuccessful. > I also tried other variations that also didn't work but no point > wasting space. Using Python 2.5, WinXP > > Thx, > Mark > > -- > http://mail.python.org/mailman/listinfo/python-list > I usually do something like: s = myfile.read(10) while len(s) == 10: info1, info2, info3 = struct.unpack(' <87zllkm630.fsf@hbox.dyndns.org> Message-ID: <00f7fee1$0$20633$c3e8da3@news.astraweb.com> On Sat, 04 Oct 2008 22:57:23 +0200, Martin Geisler wrote: > Dennis Lee Bieber writes: > >> On Sat, 04 Oct 2008 13:14:40 +0200, Peter Otten <__peter__ at web.de> >> declaimed the following in comp.lang.python: >> >>> In 3.0 it has to be rewritten as >>> >>> def f(ab): >>> a, b = ab >>> return a*b >>> >>> i. e. it needs a statement and an expression and is therefore no >>> longer suitable for a lambda. >>> >>> >> Given that most lambda's are rather short, is it really that >> much of a pain to just use (for the above example) ab[0]*ab[1] without >> unpacking? > > Well -- it is because the code used to be short and sweet that it feels > ugly to me to change > > lambda (a, b): a * b > > into > > lambda ab: ab[0] * ab[1] > > The first looks perfect -- it matches the math behind the code that I am > writing. The second does not look so nice. Here's another alternative. Compare: >>> x = (2, 3) >>> (lambda (a,b): a*b)(x) 6 with this: >>> (lambda a,b: a*b)(*x) 6 > From reading the PEP-3113 I got the impression that the author thought > that this feature was unused and didn't matter. With this I wish to say > that it matters to me. Alas, I think it's too late. I feel your pain. The final release of Python 3.0 hasn't been made yet. If you really care strongly about this, you could write to the python-dev mailing list and ask if it is worth trying to change their mind about tuple unpacking. They'll almost certainly say no, but there's a chance it might be reverted in 3.1. A tiny chance. -- Steven From brianlong at cox.net Sun Oct 26 20:15:17 2008 From: brianlong at cox.net (brianrpsgt1) Date: Sun, 26 Oct 2008 17:15:17 -0700 (PDT) Subject: IDLE stopped working Message-ID: Using OS X 10.5.5 Python 2.5.1 IDLE was working, then all of a sudden, the window size went off of the screen.... could not resize it. I closed IDLE and rebooted and now IDLE will not start. Below is the Traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/Current/bin/ IDLE", line 5, in main() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/PyShell.py", line 1402, in main shell = flist.open_shell() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/PyShell.py", line 275, in open_shell self.pyshell = PyShell(self) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/PyShell.py", line 811, in __init__ OutputWindow.__init__(self, flist, None, None) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/OutputWindow.py", line 16, in __init__ EditorWindow.__init__(self, *args) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/EditorWindow.py", line 121, in __init__ height=idleConf.GetOption('main','EditorWindow','height') ) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/idlelib/MultiCall.py", line 299, in __init__ apply(widget.__init__, (self,)+args, kwargs) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/lib-tk/Tkinter.py", line 2828, in __init__ Widget.__init__(self, master, 'text', cnf, kw) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/lib-tk/Tkinter.py", line 1930, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: bad screen distance "60gill" Any assistance in getting this back up and running would be great Thanks B From patrickstinson.lists at gmail.com Wed Oct 29 03:36:57 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Tue, 28 Oct 2008 23:36:57 -0800 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> Message-ID: <6214d7a20810290036w5bdebdacy440439da690ab328@mail.gmail.com> On Fri, Oct 24, 2008 at 12:51 PM, Andy O'Meara wrote: > > Another great post, Glenn!! Very well laid-out and posed!! Thanks for > taking the time to lay all that out. > >> >> Questions for Andy: is the type of work you want to do in independent >> threads mostly pure Python? Or with libraries that you can control to >> some extent? Are those libraries reentrant? Could they be made >> reentrant? How much of the Python standard library would need to be >> available in reentrant mode to provide useful functionality for those >> threads? I think you want PyC >> > > I think you've defined everything perfectly, and you're you're of > course correct about my love for for the PyC model. :^) > > Like any software that's meant to be used without restrictions, our > code and frameworks always use a context object pattern so that > there's never and non-const global/shared data). I would go as far to > say that this is the case with more performance-oriented software than > you may think since it's usually a given for us to have to be parallel > friendly in as many ways as possible. Perhaps Patrick can back me up > there. And I will. > > As to what modules are "essential"... As you point out, once > reentrant module implementations caught on in PyC or hybrid world, I > think we'd start to see real effort to whip them into compliance-- > there's just so much to be gained imho. But to answer the question, > there's the obvious ones (operator, math, etc), string/buffer > processing (string, re), C bridge stuff (struct, array), and OS basics > (time, file system, etc). Nice-to-haves would be buffer and image > decompression (zlib, libpng, etc), crypto modules, and xml. As far as > I can imagine, I have to believe all of these modules already contain > little, if any, global data, so I have to believe they'd be super easy > to make "PyC happy". Patrick, what would you see you guys using? > We don't need anything :) Since our goal is just to use python as a scripting language/engine to our MIDI application, all we really need is to make calls to the api that we expose using __builtins__. You know, the standard python library is pretty siiiiiick, but the syntax, object model, and import mechanics of python itself is an **equally exportable function** of the code. Funny that I'm lucky enough to say: "Screw the extension modules - I just want the LANGUAGE". But, I can't have it. > >> > That's the rub... In our case, we're doing image and video >> > manipulation--stuff not good to be messaging from address space to >> > address space. The same argument holds for numerical processing with >> > large data sets. The workers handing back huge data sets via >> > messaging isn't very attractive. >> >> In the module multiprocessing environment could you not use shared >> memory, then, for the large shared data items? >> > > As I understand things, the multiprocessing puts stuff in a child > process (i.e. a separate address space), so the only to get stuff to/ > from it is via IPC, which can include a shared/mapped memory region. > Unfortunately, a shared address region doesn't work when you have > large and opaque objects (e.g. a rendered CoreVideo movie in the > QuickTime API or 300 megs of audio data that just went through a > DSP). Then you've got the hit of serialization if you're got > intricate data structures (that would normally would need to be > serialized, such as a hashtable or something). Also, if I may speak > for commercial developers out there who are just looking to get the > job done without new code, it's usually always preferable to just a > single high level sync object (for when the job is complete) than to > start a child processes and use IPC. The former is just WAY less > code, plain and simple. > > > Andy > > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Mon Oct 6 11:36:16 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 6 Oct 2008 10:36:16 -0500 Subject: The recent SPAM messages, and a suggested solution In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6022A79C1@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A79C1@enbmail01.lsi.com> Message-ID: <18666.12400.19212.39896@montanaro-dyndns-org.local> Ron> I think most of us are annoyed by the recent SPAM messages that Ron> crept onto our list. I'd like to suggest a possible solution, and Ron> maybe start a thread that eventually will rid us of this Ron> unpleasantness. Ron> My idea: Ron> Once every few messages from the list owners, they would send a new Ron> numerical string that will have to be included in members' list Ron> submission. A message being submitted without this numeric string Ron> will be re-routed to /dev/null. The current string will be Ron> announced on the messages being send to new members upon Ron> registration. Ron> Since SPAM is sent in bulk, this may be a rather complete solution. Those of us who manage the the python.org mailing lists are overloaded enough as it is. We don't have time to add extra tasks to our daily checklists. In addition, ad hoc solutions frequently don't scale well. Check http://mail.python.org/ for the full scope of the management problem. We run a single SpamBayes instance on mail.python.org which scans for spam in almost all those mailing lists. A couple are unfiltered for various reasons. If you read python-list via Usenet (comp.lang.python in its various guises) there's not much we can do to help you. If someone posts crap via Usenet you will see it before it reaches the spam filter on mail.python.org. Some Usenet servers may provide decent spam filtering. Google Groups appears not to, and their spam reporting process requires several steps on your part. If you are reading python-list at python.org please feel free to mail me (skip at pobox.com) any spam which sneaks through SpamBayes. I will train them as I can, generally about once a day. It would really help if you could attach a zip'd or gzip'd copy of the message. Don't just paste a spam message into any mail you send me. If you read email you get spam. That is an unfortunate fact of life today. You should run some sort of spam filter on your system and not rely on sysadmins or mailing list admins to filter your mail. My email goes through Gmail and I run SpamBayes on my laptop as well. That presents its own set of issues (I have to poke around in both filters' traps to find spams which sneak through the mail.python.org filters for example), but I generally see very little spam. You can get SpamBayes (it's free and written in Python) from . There are a number of ways to use it, including an Outlook plugin and several more Unix-oriented apps. All use the same core classifier. There is a Thunderbird plugin available (google for ThunderBayes) which is currently unsupported but which we would like to incorporate into the SpamBayes code base. Unfortunately, we are short of round tuits. If you'd like to help we can always use more brainpower. -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From hjtoi-better-remove-when_replying at comcast.net Wed Oct 8 03:38:44 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Wed, 08 Oct 2008 00:38:44 -0700 Subject: ANN: Solu 0.1 - Office Resource Finder Message-ID: Solu is a simple web application meant for making it easy to find colleagues, meeting rooms and other resources in an office. Great when you are new in a company and don't know where everyone and everything is located in! In other words, Solu is the "cubicle finder". And if you have ever configured a printer for a computer and being frustrated with the printer dialog that only showed the IP address but not where the printer was located, Solu can help! It has a self service model without any authentication or permission checks, where anyone can find and update any resource's information. Besides the easy installation, all you need to set up an instance is your office map or office floorplan or blueprints stored as an image file. This is the first public release. Solu Project Homepage: http://www.heikkitoivonen.net/solu/ Enjoy! -- Heikki Toivonen - http://www.heikkitoivonen.net From bieffe62 at gmail.com Mon Oct 6 10:36:03 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 6 Oct 2008 07:36:03 -0700 (PDT) Subject: Cookielib in Jython References: <42054e2d-d49d-4237-af9e-d6b3c796a4a6@e17g2000hsg.googlegroups.com> Message-ID: On 6 Ott, 13:19, Felipe De Bene wrote: > Hi There, > I'm trying to run an App I wrote in Python 2.5.2 in Jython 2.2.1 and > everything works fine except when I try to import the Standard > CPython's cookielib. I know this may sound stupid, I could use an > advice here on what's wrong. Thanks in advance, > Felipe. > > Output: > Jython 2.2.1 on java1.6.0_07 > Type "copyright", "credits" or "license" for more information.>>> import cookielib > > Traceback (innermost last): > ? File "", line 1, in ? > ImportError: no module named cookielib>>> from cookielib import * > > Traceback (innermost last): > ? File "", line 1, in ? > ImportError: no module named cookielib>>> from CookieLib import * > > Traceback (innermost last): > ? File "", line 1, in ? > ImportError: no module named CookieLib Obviously, choockielib is not in your jython installation. If this module is a pure python module and not a wrupper of an underlying C module, you could try simple to get is from a CPython installation, try and compile it with Jython inside the code. If the module does not use any feature of the language introduced after Python 2.2, or other unsupported modules, it could work and you can use it inside your program as it was one of your modules. HTH ---- FB From tjreedy at udel.edu Tue Oct 7 13:42:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 07 Oct 2008 13:42:07 -0400 Subject: Python pre-release announcements In-Reply-To: <87myhglta6.fsf@benfinney.id.au> References: <87myhglta6.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "Martin v. L?wis" writes: > >> Within a few weeks, we will release Python 2.5.3. > > I'm glad to see this. Thank you to all involved in the ongoing work of > coordinating Python releases. > > Can I request, in the interest of reducing confusion, that any > announcements of pre-release versions of 2.5.3 (or any other Python > release) be announced *without* saying ?RELEASED: A not-really-release > version of Python?. > > It's very confusing to see a progression of announcements with subject > fields like: > > RELEASED: Python 2.8.not-ready-yet > RELEASED: Python 2.8.alpha-1 > RELEASED: Python 2.8.beta-1 > RELEASED: Python 2.8.beta-2 > RELEASED: Python 2.8 release candidate 1 > RELEASED: Python 2.8 release candidate 2 > RELEASED: Python 2.8 final I disagree. These say exactly what has happened and tell me what I want to know, which is that something new has been released, which is to say, made available for download. > [ANN] Python 2.8.not-ready-yet > [ANN] Python 2.8.alpha-1 > [ANN] Python 2.8.beta-1 > [ANN] Python 2.8.beta-2 > [ANN] Python 2.8 release candidate 1 > [ANN] Python 2.8 release candidate 2 > [ANN] Python 2.8 final > > That, to me at least, communicates what's actually happening far > better and leads to less confusion about what the state of release is. I disagree. [ANN] could mean anything: planned? canceled? needs help? ("Oh, 'released', why didn't you say so?") It says nothing about what is happening or the state of a 'distribution' but merely states a topic. Martin's post announced Python 2.5.3 as the topic, but then went on to request a specific type of help. I presume you would not be happy either with "[ANN] Python x.y.whatever released". If you want RELEASED replaced, suggest something short and not too ugly that communicates "posted at python.org and available to be downloaded, installed, tested, and used" at least as well. (I am currently using 3.rc1; the remaining problems do not currently affect me and I accept the risk, which I view as small, that further changes will affect code I write now.) tjr From gagsl-py2 at yahoo.com.ar Tue Oct 28 01:28:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Oct 2008 03:28:16 -0200 Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: En Tue, 28 Oct 2008 00:58:10 -0200, greg escribi?: > Steven D'Aprano wrote: > >> By common usage and technical definition, C is call by value. Argument >> passing in Python does not behave like C. So why insist that Python is >> also call by value? > > Whether it behaves like C is not the test. > > Let's look at the definitions of the terms: > > (1) Call by value: The actual parameter is an expression. It is > evaluated and the result is assigned to the formal parameter. > Subsequent assignments to the formal parameter do not affect > the actual parameter. > > (2) Call by reference: The actual parameter is an lvalue. The > formal parameter becomes an alias for the actual parameter, > so that assigning to the formal parameter has the same > effect as assigning to the actual parameter. > > Seems to me that (1) describes exactly how parameter passing > works in Python. So why insist that it's *not* call by value? Those definitions are only applicable to unstructured, primitive types, where the only relevant operations are "get value" and "assign value". Structured types provide other operations too - like selection (attribute get/set in Python). It is unspecified on both definitions above what happens in those cases. Other posts in this same thread showed that Python behaves similarly to call-by-reference in C++ with regard to data members inside a structure (that is, mutable objects *can* be changed, and the caller sees the change). Combined with your previous conclusion that Python implements call-by-value, one should finally conclude that it can't be neither cbv nor cbr - it's a different thing. The term "call by object" was coined in the late '70s to describe this behavior. More info about this ever-recurring topic can be found at http://effbot.org/zone/call-by-object.htm -- Gabriel Genellina From shymonb at poczta.onet.pl Thu Oct 9 06:46:53 2008 From: shymonb at poczta.onet.pl (shymon) Date: Thu, 9 Oct 2008 03:46:53 -0700 (PDT) Subject: SimpleXmlRpcServer and character encoding Message-ID: <19896427.post@talk.nabble.com> I'm using SimpleXmlRpcServer class. Although I set encoding parameter in the constructor, I have to return all strings in default platform encoding (windows-1250/win32 or iso-8859-2/linux in my case). When I send values in, for example, UTF-8, string received by client is messed up. The client is written in java using Apache XmlRpc library 2.0. Is there any solution other than sending all string values in Base64 encoding? -- View this message in context: http://www.nabble.com/SimpleXmlRpcServer-and-character-encoding-tp19896427p19896427.html Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Mon Oct 6 14:23:28 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 6 Oct 2008 11:23:28 -0700 (PDT) Subject: Python 2.6 / 3.0: Determining if a method is inherited References: <0862144a-bc06-40ef-ad1a-019bf08a6768@y71g2000hsa.googlegroups.com> <2d9d0fb1-9526-49d4-aeb5-95818d7b2451@8g2000hse.googlegroups.com> <2fddb2b3-888a-4a73-9bcf-6202b661504e@j68g2000hsf.googlegroups.com> <724faed6-4977-43eb-b9bc-3e6446df57f1@d70g2000hsc.googlegroups.com> Message-ID: On Oct 6, 1:17?pm, Fuzzyman wrote: > On Oct 6, 7:01?pm, "Aaron \"Castironpi\" Brady" > wrote: > > It's a very object oriented solution. ?Essentially you're inheriting > > all the classes that you want to fail, from a class that does. > > But not a very good solution to the problem... > > The specific problem is to determine if an arbitrary class implements > a specified comparison method. The general problem (that gives rise to > the specific problem) is to write a class decorator that can implement > all comparison methods from a class that implements only one. > > See:http://code.activestate.com/recipes/576529/ > > Michael > --http://www.ironpythoninaction.com/ Nope, I'm out of ideas, I'm afraid. From clp at rebertia.com Wed Oct 8 20:55:17 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 8 Oct 2008 17:55:17 -0700 Subject: Safe eval of insecure strings containing Python data structures? In-Reply-To: <896B75251BA19745A529B1B867893FA50677D6@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50677D6@planet.delsci.local> Message-ID: <47c890dc0810081755j7e67b2fcsf4ab5042e5d0fabe@mail.gmail.com> On Wed, Oct 8, 2008 at 5:34 PM, Warren DeLano wrote: > > I would like to parse arbitrary insecure text string containing nested > Python data structures in eval-compatible form: > > # For example, given a "config.txt" such as: > > { > 'my_atom' : 1.20, > 'my_dict' : { 2:50 , 'hi':'mom'}, > 'my_list' : [ (1,2,3), [4.5,6.9], 'foo', 0 ] > } > > # I would like to do something like this: > > empty_space = {'__builtins__' : {}} > > try: > config = eval(open("config.txt").read(), empty_space, empty_space) > except: > config = {} > > print config > > # But I know for certain that the above approach is NOT secure since > object attributes can still be accessed... > > So is there an equally convenient yet secure alternative available for > parsing strings containing Python data structure definitions? Assuming the data structures are sufficiently basic, i.e. no class instanciations, you can just use the json (AKA simplejson) library to deserialize the data in the string. Python and JSON conveniently happen to share the same syntax for literals (except for booleans IIRC). Also, if this is your program's config file, you might consider changing it to INI-format and using ConfigParser (http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html) instead. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance for any pointers! > > Cheers, > Warren > > > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Tue Oct 7 18:37:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 8 Oct 2008 08:37:32 +1000 Subject: HARD REAL TIME PYTHON In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380554720D@AWMAIL04.belcan.com> Message-ID: On Tue, Oct 7, 2008 at 7:27 PM, Kurt Mueller wrote: > To be more helpful, we should know what you mean by "HARD REAL TIME". > Do you mean: > - Handle at least 70 interrupt per second ("SPEED") > - If one fails, this is catastrophic for the application ("HARD") > - Deliver an response to an interrupt within 5-10[ms] ("REAL TIME") Great! :) Wonderful clarification! cheers James -- -- -- "Problems are solved by method" From patrickstinson.lists at gmail.com Fri Oct 24 11:26:09 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Fri, 24 Oct 2008 07:26:09 -0800 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <4900B4BC.70906@g.nevcal.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <4900B4BC.70906@g.nevcal.com> Message-ID: <6214d7a20810240826t134fe46pc4402d9ed0b3228c@mail.gmail.com> I'm not finished reading the whole thread yet, but I've got some things below to respond to this post with. On Thu, Oct 23, 2008 at 9:30 AM, Glenn Linderman wrote: > On approximately 10/23/2008 12:24 AM, came the following characters from the > keyboard of Christian Heimes: >> >> Andy wrote: >>> >>> 2) Barriers to "free threading". As Jesse describes, this is simply >>> just the GIL being in place, but of course it's there for a reason. >>> It's there because (1) doesn't hold and there was never any specs/ >>> guidance put forward about what should and shouldn't be done in multi- >>> threaded apps (see my QuickTime API example). Perhaps if we could go >>> back in time, we would not put the GIL in place, strict guidelines >>> regarding multithreaded use would have been established, and PEP 3121 >>> would have been mandatory for C modules. Then again--screw that, if I >>> could go back in time, I'd just go for the lottery tickets!! :^) > > > I've been following this discussion with interest, as it certainly seems > that multi-core/multi-CPU machines are the coming thing, and many > applications will need to figure out how to use them effectively. > >> I'm very - not absolute, but very - sure that Guido and the initial >> designers of Python would have added the GIL anyway. The GIL makes Python >> faster on single core machines and more stable on multi core machines. Other >> language designers think the same way. Ruby recently got a GIL. The article >> http://www.infoq.com/news/2007/05/ruby-threading-futures explains the >> rationales for a GIL in Ruby. The article also holds a quote from Guido >> about threading in general. >> >> Several people inside and outside the Python community think that threads >> are dangerous and don't scale. The paper >> http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf sums it up >> nicely, It explains why modern processors are going to cause more and more >> trouble with the Java approach to threads, too. > > Reading this PDF paper is extremely interesting (albeit somewhat dependent > on understanding abstract theories of computation; I have enough math > background to follow it, sort of, and most of the text can be read even > without fully understanding the theoretical abstractions). > > I have already heard people talking about "Java applications are buggy". I > don't believe that general sequential programs written in Java are any > buggier than programs written in other languages... so I had interpreted > that to mean (based on some inquiry) that complex, multi-threaded Java > applications are buggy. And while I also don't believe that complex, > multi-threaded programs written in Java are any buggier than complex, > multi-threaded programs written in other languages, it does seem to be true > that Java is one of the currently popular languages in which to write > complex, multi-threaded programs, because of its language support for > threads and concurrency primitives. These reports were from people that are > not programmers, but are field IT people, that have bought and/or support > software and/or hardware with drivers, that are written in Java, and seem to > have non-ideal behavior, (apparently only) curable by stopping/restarting > the application or driver, or sometimes requiring a reboot. > > The paper explains many traps that lead to complex, multi-threaded programs > being buggy, and being hard to test. I have worked with parallel machines, > applications, and databases for 25 years, and can appreciate the succinct > expression of the problems explained within the paper, and can, from > experience, agree with its premises and conclusions. Parallel applications > only have been commercial successes when the parallelism is tightly > constrained to well-controlled patterns that could be easily understood. > Threads, especially in "cooperation" with languages that use memory > pointers, have the potential to get out of control, in inexplicable ways. > > >> Python *must* gain means of concurrent execution of CPU bound code >> eventually to survive on the market. But it must get the right means or we >> are going to suffer the consequences. > > This statement, after reading the paper, seems somewhat in line with the > author's premise that language acceptability requires that a language be > self-contained/monolithic, and potentially sufficient to implement itself. > That seems to also be one of the reasons that Java is used today for > threaded applications. It does seem to be true, given current hardware > trends, that _some mechanism_ must be provided to obtain the benefit of > multiple cores/CPUs to a single application, and that Python must either > implement or interface to that mechanism to continue to be a viable language > for large scale application development. > > Andy seems to want an implementation of independent Python processes > implemented as threads within a single address space, that can be > coordinated by an outer application. This actually corresponds to the model > promulgated in the paper as being most likely to succeed. Of course, it > maps nicely into a model using separate processes, coordinated by an outer > process, also. The differences seem to be: > > 1) Most applications are historically perceived as corresponding to single > processes. Language features for multi-processing are rare, and such > languages are not in common use. > > 2) A single address space can be convenient for the coordinating outer > application. It does seem simpler and more efficient to simply "copy" data > from one memory location to another, rather than send it in a message, > especially if the data are large. On the other hand, coordination of memory > access between multiple cores/CPUs effectively causes memory copies from one > cache to the other, and if memory is accessed from multiple cores/CPUs > regularly, the underlying hardware implements additional synchronization and > copying of data, potentially each time the memory is accessed. Being forced > to do message passing of data between processes can actually be more > efficient than access to shared memory at times. I should note that in my > 25 years of parallel development, all the systems created used a message > passing paradigm, partly because the multiple CPUs often didn't share the > same memory chips, much less the same address space, and that a key feature > of all the successful systems of that nature was an efficient inter-CPU > message passing mechanism. I should also note that Herb Sutter has a recent > series of columns in Dr Dobbs regarding multi-core/multi-CPU parallelism and > a variety of implementation pitfalls, that I found to be very interesting > reading. > > I have noted the multiprocessing module that is new to Python 2.6/3.0 being > feverishly backported to Python 2.5, 2.4, etc... indicating that people > truly find the model/module useful... seems that this is one way, in Python > rather than outside of it, to implement the model Andy is looking for, > although I haven't delved into the details of that module yet, myself. I > suspect that a non-Python application could load one embedded Python > interpreter, and then indirectly use the multiprocessing module to control > other Python interpreters in other processors. I don't know that > multithreading primitives such as described in the paper are available in > the multiprocessing module, but perhaps they can be implemented in some > manner using the tools that are provided; in any case, some interprocess > communication primitives are provided via this new Python module. > > There could be opportunity to enhance Python with process creation and > process coordination operations, rather than have it depend on > easy-to-implement-incorrectly coordination patterns or > easy-to-use-improperly libraries/modules of multiprocessing primitives (this > is not a slam of the new multiprocessing module, which appears to be filling > a present need in rather conventional ways, but just to point out that ideas > promulgated by the paper, which I suspect 2 years later are still research > topics, may be a better abstraction than the conventional mechanisms). > > One thing Andy hasn't yet explained (or I missed) is why any of his > application is coded in a language other than Python. I can think of a > number of possibilities: > > A) (Historical) It existed, then the desire for extensions was seen, and > Python was seen as a good extension language. > > B) Python is inappropriate (performance?) for some of the algorithms (but > should they be coded instead as Python extensions, with the core application > being in Python?) > > C) Unavailability of Python wrappers for particularly useful 3rd-party > libraries > > D) Other? We develop virtual instrument plugins for music production using AudioUnit, VST, and RTAS on Windows and OS X. While our dsp engine's code has to be written in C/C++ for performance reasons, the gui could have been written in python. But, we didn't because: 1) Our project lead didn't know python, and the project began with little time for him to learn it. 2) All of our third-party libs (for dsp, plugin-wrappers, etc) are written in C++, so it would far easier to write and debug our app if written in the same language. Could I do it now? yes. Could we do it then? No. ** Additionally **, we would have run into this problem, which is very appropriate to this thread: 3) Adding python as an audio scripting language in the audio thread would have caused concurrency issues if our GUI had been written in python, since audio threads are not allowed to make blockign calls (f.ex. acquiring the GIL). OK, I'll continue reading the thread now :) > > -- > Glenn -- http://nevcal.com/ > =========================== > A protocol is complete when there is nothing left to remove. > -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking > > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Wed Oct 8 18:09:28 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 8 Oct 2008 15:09:28 -0700 (PDT) Subject: distributing apps without the Python source? References: <6l41pbFaj22eU1@mid.uni-berlin.de> <6l4b30Fakp4rU1@mid.uni-berlin.de> <48ed159a$0$17334$426a74cc@news.free.fr> Message-ID: <1a656097-db79-4784-a7b1-658c969cd5e5@w13g2000prm.googlegroups.com> On 8 Okt, 23:50, "James Mills" wrote: > > I must point out though that if your client > is paranoid for intellectual property reasons > (ie: protecting his assets), then you should > be aware that even if you can decompile > a Python compiled module (or a compiled > java class), it's generally pretty useless in this > form to any would-be-thief. I beg to differ on the usefulness of the decompiled code: Python bytecode is pretty high-level stuff, and it doesn't leave that much to the imagination. It may not give you nice source code, but if you want answers to questions on how some mechanism in the code works, decompyle does a reasonable job. > Decompiling/Disassembling never gets you > the original source code back. True, but that's not always what you want, anyway. Some more opinions on the subject can be found here: http://wiki.python.org/moin/HowDoYouProtectSource Paul From sjmachin at lexicon.net Sun Oct 12 18:59:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 12 Oct 2008 15:59:47 -0700 (PDT) Subject: Pylab Fails with Runtime Error on Win XP Under Python 2.4 References: Message-ID: <8031bc6a-cc2b-49a5-8321-199b5f3cb7b4@i18g2000prf.googlegroups.com> On Oct 13, 9:07?am, "W. eWatson" wrote: > > I worked my way into the folder where the py program is, but couldn't > executed. Just entering aprog.py, run aprog.py or exec aprog.py didn't work. One wouldn't expect the "run" or the "exec" to work. Try these in this order: python aprog.py \python24\python aprog.py c:\python24\python aprog.py and instead of "didn't work", tell us what message you get. Also consider telling us where your Python 2.4 is installed, and what you see when you execute the PATH command. From castironpi at gmail.com Sat Oct 11 14:38:14 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 11 Oct 2008 11:38:14 -0700 (PDT) Subject: extracting null pointer address from PyCObject with ctypes References: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> <42a9cf1a-b5a3-428f-b547-b0bb1d9b87e2@q35g2000hsg.googlegroups.com> Message-ID: <99b20852-6e13-4046-aeef-4c1cb45636bf@j68g2000hsf.googlegroups.com> On Oct 11, 9:45?am, Gordon Allott wrote: > Aaron "Castironpi" Brady wrote: > > > My pygame install just returns an integer in get_wm_info. ?Take a > > look: > > >>>> pygame.display.get_wm_info() > > {'window': 1180066, 'hglrc': 0} > >>>> pygame.display.get_wm_info()['window'] > > 1180066 > >>>> ctypes.c_void_p( _ ) > > c_void_p(1180066) > > > You're suggesting yours looks like this: > > >>>> pygame.display.get_wm_info() > > { ... 'display': ctypes.py_object( 1180066 ), ... } > > > What does type( display ) give you? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > yes its different on windows and linux, windows only has a few items > where linux has many more. 'window' is just the window 'id' ?at any rate > which is not the data I am after (which is internally an address to an > xlib structure) > this is what pygame.display.get_wm_info() returns on linux: > {'fswindow': 31457283, 'wmwindow': 31457284, 'window': 31457294, > 'lock_func': , 'unlock_func': object at 0x89dfa88>, 'display': } > > note how the display object is a PyCObject, thats got the address I want > ?inside it. > What does print pythonapi.PyCObject_AsVoidPtr(display) give you? From duncan.booth at invalid.invalid Fri Oct 31 09:58:55 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Oct 2008 13:58:55 GMT Subject: Is there a time limit for replies? References: Message-ID: Paul Boddie wrote: > On 31 Okt, 10:38, Rafe wrote: >> I tried to post some follow-ups to some issues I posted in the hopes >> of helping others, but I only get "reply to author" and "forward", but >> no "reply" option (using GoogleGroups). Is there some kind of time >> limit to reply? > > Probably not for any of the newsgroups or mailing lists accessed via > Google Groups. The behaviour you're seeing could be temporary - Google > Groups isn't always particularly reliable - or it might be the case > that the sender is one of those people who has requested that their > messages not be archived, perhaps interpreted by Google Groups in the > way you describe, but I'm just speculating at this point. No, I believe Google Groups does impose a limit on replying. Usenet doesn't, but if the original message is so old that it has expired from most news servers then there's no benefit in replying over just posting a new message that says 'There was a thread x years ago where in message said ...' Then you'd better give plenty of context because nobody is going to remember the original message anyway. If you use the same subject line as the original then (unless google groups changed when I wasn't looking) Google will thread it together with the original messages: Google doesn't understand real threads. Real newsreaders won't thread it, but since they won't have the original anyway you haven't lost anything. -- Duncan Booth http://kupuguy.blogspot.com From timr at probo.com Sun Oct 5 01:10:40 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 05 Oct 2008 05:10:40 GMT Subject: how best to use a dictionary in this function? References: Message-ID: Terrence Brannon wrote: > >Now, I improved this function this way: > >def calc_profit(std_clicks, vip_clicks, ad_rate=200, >upline_status=None): > clicks = {} > clicks['std'] = std_clicks > clicks['vip'] = vip_clicks You can also write it this way. clicks = { 'std': std_clicks, 'vid': vip_clicks } >I know there is something like *args, or **args, but since >docs.python.org is down, I cant check. The problem with using **args is that you can no longer pass your parameters positionally. Callers of calc_profit would have to use named parameters. It also makes your default arguments a bit less natural. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From benyang22 at gmail.com Wed Oct 29 13:53:43 2008 From: benyang22 at gmail.com (Benyang) Date: Wed, 29 Oct 2008 10:53:43 -0700 (PDT) Subject: Python/Numeric users be aware! Message-ID: Maybe it has been reported somewhere, but it is a big surprise to me. # Try the following: import Numeric a = Numeric.ones(10) a[5:] = -1 print a It works correctly on 32-bit linux machines and on 32-bit Windows XP: [ 1 1 1 1 1 -1 -1 -1 -1 -1] It is totally screwed up on 64-bit linux machines: [1 1 1 1 1 1 1 1 1 1] # The following works correctly on both 32-bit and 64-bit machines (notice the comma): a[5:,] *= -1 The Python version is 2.5.1, and Numeric is the latest version 24.2. From bhawsar.vaibhav at gmail.com Tue Oct 7 03:54:32 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Tue, 7 Oct 2008 00:54:32 -0700 Subject: export opengl context to pdf Message-ID: <17d58cc40810070054j151b67fft12e93cf54615e158@mail.gmail.com> Hi, Does anyone know of a package that will allow me to output an opengl context as a PDF (or postscript)? I am using pyglet to render something on screen that i want to save as PDF. thanks! vaibhav From lie.1296 at gmail.com Sun Oct 26 13:35:31 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 26 Oct 2008 17:35:31 +0000 (UTC) Subject: Exact match with regular expression References: <8f67b6f80810260951u3fc5decem257ae60ae05586a0@mail.gmail.com> Message-ID: On Sun, 26 Oct 2008 17:51:29 +0100, Mr.SpOOn wrote: > Hi, > I'd like to use regular expressions to parse a string and accept only > valid strings. What I mean is the possibility to check if the whole > string matches the regex. > > So if I have: > >>>> p = re.compile('a*b*') > > I can match this: 'aaaaaabbb' > >>>> m = p.match('aaaaaabbb') >>>> m.group() > 'aaaaaabbb' > > But I'd like to get None with this: 'aabDDDDb' Instead it matches the > first part: > >>>> m = p.match('aabDDDDb') >>>> m.group() > 'aab' > > I know this is the expected behaviour, but I'm sure it should be > possible doing what I said. > Are there other methods I don't know about in the re module? > > Thanks. re.compile('a*b*$') $ matches the end of a string, or in MULTILINE mode, the end of a line (right before newline) Symmetrically, ^ matches the start of a string, or in MULTILINE mode, the start of a line (including the start of the string) From bearophileHUGS at lycos.com Fri Oct 10 07:36:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 10 Oct 2008 04:36:34 -0700 (PDT) Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> Message-ID: <3fe70d4b-0dfe-4c60-8b16-1bc70ce96d25@j68g2000hsf.googlegroups.com> Bruno Desthuilliers: > You mean : "to people that don't bother reading the FineManual *nor* > searching the newsgroup / ML archives ?" Are there ways to change how Python3 manages arguments and functions, to remove this antifeature of Python, avoiding this common mistake done by every newbie? I don't care if it reduces the performance of Python a little. Bye, bearophile From philip at semanchuk.com Sun Oct 12 10:28:17 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 12 Oct 2008 10:28:17 -0400 Subject: parsing javascript In-Reply-To: References: Message-ID: <47F2EF52-50E5-4F62-91AD-F5E60A0357F3@semanchuk.com> On Oct 12, 2008, at 5:25 AM, S.Selvam Siva wrote: > I have to do a parsing on webpagesand fetch urls.My problem is ,many > urls i > need to parse are dynamically loaded using javascript function > (onload()).How to fetch those links from python? Thanks in advance. Selvam, You can try to find them yourself using string parsing, but that's difficult. The closer you want to get to "perfect" at finding URLs expressed in JS, the closer you'll get to rewriting a JS interpreter. For instance, this is not so hard to understand: "http://example.com/" but this is: "http://ZZZ_DOMAIN_ZZZ/index.html".replace(/ZZZ_DOMAIN_ZZZ/, the_domain_variable) This is a long-standing problem for any program that parses Web pages. You either have to embed a JS interpreter in your application or just ignore the JavaScript. Most Web parsing robots take the latter route. Good luck Philip From prologic at shortcircuit.net.au Sun Oct 26 08:08:00 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 26 Oct 2008 22:08:00 +1000 Subject: Why can't I assign a class method to a variable? In-Reply-To: References: Message-ID: On Thu, Oct 23, 2008 at 2:34 AM, ed wrote: > I'm trying to make a shortcut by doing this: > > t = Globals.ThisClass.ThisMethod > > Calling t results in an unbound method error. > > Is it possible to do what I want? I call this method in hundreds of > locations and I'm trying to cut down on the visual clutter. I can't help but think there is a better approach to your problem. Why are you calling in hundreds of places ? What is it and what does it do ? cheers James -- -- -- "Problems are solved by method" From Michael.Coll-Barth at VerizonWireless.com Wed Oct 8 16:19:43 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 8 Oct 2008 16:19:43 -0400 Subject: Porn Addiction Solutions? In-Reply-To: References: <963ea4ac-54e6-4911-9a15-846b86de5cea@u40g2000pru.googlegroups.com><1D5F3E52E13A42AF97DB3D2D5163CCAB@office.ipglobal.net> Message-ID: <20081008203023.433A71E4002@bag.python.org> > From: Dotan Cohen > > 2008/10/8 Support Desk : > > I got a solution, cutt it off, and then Kill yourself. > > > > Cut what off? The OP is female. Are you sure about that? :) 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 bruno.42.desthuilliers at websiteburo.invalid Fri Oct 10 08:58:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 10 Oct 2008 14:58:33 +0200 Subject: a regular expression problem In-Reply-To: <06c5bc01-7ca6-4f61-b856-c1d9efff739f@u29g2000pro.googlegroups.com> References: <06c5bc01-7ca6-4f61-b856-c1d9efff739f@u29g2000pro.googlegroups.com> Message-ID: <48ef511c$0$29838$426a74cc@news.free.fr> lookon a ?crit : > I want to use django to dispatch url. > The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+ > \b)/(?P\d+)$'. > It works when the string is English(like Google), but fails when the > string is in foreign language. Care to give an exemple of url that fails ? Anyway, if you want to match just *anything* in that path segment, you can try: r'^/test/(?P.+?)/(?P\d+)$'. From castironpi at gmail.com Tue Oct 28 18:15:37 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 28 Oct 2008 15:15:37 -0700 (PDT) Subject: explanation of values, references, assignment, and method calls References: <49073e11$0$4533$426a34cc@news.free.fr> Message-ID: <8a67ea92-5728-4e93-9c56-fbe38cd9c0c7@y71g2000hsa.googlegroups.com> On Oct 28, 11:30?am, Bruno Desthuilliers wrote: > Joe Strout a ?crit : > > > I've tried to write up this topic in a clear, step-by-step manner, with > > the help of diagrams and short examples from several different OOP > > languages. ?I hope it will help clear up the confusion that seems to be > > pervading the Python community > > May I suggesthttp://effbot.org/zone/call-by-object.htm? Joe, Fredrik's is more brutal than yours. Both good, depending on what you like in leaders. Yes, some people like brutal leaders. From jarausch at skynet.be Wed Oct 15 11:59:06 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 15 Oct 2008 17:59:06 +0200 Subject: python3 - the hardest hello world ever ? In-Reply-To: <41cd8157-1cf9-41dd-8774-2e173c528c57@1g2000prd.googlegroups.com> References: <48f481af$0$2863$ba620e4c@news.skynet.be> <48f4f35e$0$25779$9b622d9e@news.freenet.de> <48F5C11C.3070807@igpm.rwth-aachen.de> <41cd8157-1cf9-41dd-8774-2e173c528c57@1g2000prd.googlegroups.com> Message-ID: <48F6134A.7040109@skynet.be> Paul Boddie wrote: > On 15 Okt, 12:08, Helmut Jarausch > wrote: >> What defines me as latin1-user? > > What does sys.stdout.encoding say? In Python 2.x, at least, that It says ansi_x3.4-1968 Where can I change this? > attribute should reflect the capabilities of your environment > (specifically, the character encoding) and help determine whether it > makes sense for Python to try and encode Unicode objects (plain > strings in Python 3.x) using a particular output encoding when > printing those objects to the display. > Thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lucaberto at libero.it Thu Oct 30 05:27:22 2008 From: lucaberto at libero.it (luca72) Date: Thu, 30 Oct 2008 02:27:22 -0700 (PDT) Subject: Ascii codec can't encode References: Message-ID: <7a61ad70-bc83-4df3-b9f7-b6b6ff741056@r66g2000hsg.googlegroups.com> Hy the code is this: Pok\xe9mon Luca From bdesth.quelquechose at free.quelquepart.fr Mon Oct 20 14:20:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 20:20:56 +0200 Subject: Python equivalent for C module In-Reply-To: <8763nndo5q.fsf@asus-190829777.TeleWell.gateway> References: <48fcdbcc$0$32727$426a74cc@news.free.fr> <8763nndo5q.fsf@asus-190829777.TeleWell.gateway> Message-ID: <48fce7e8$0$18214$426a74cc@news.free.fr> Ville M. Vainio a ?crit : > Bruno Desthuilliers writes: > >> STDOUT is for *normal* program outputs. Debug informations, >> warnings, and all verbosity should go to STDERR. > > Actually, stderr is for errors, by convention. It's rather impolite to > dump trivial debug info to stderr, which often "alerts" the user more > than stdout. If you "dump trivial debug infos" to stdout, you just break anything relying on stdout being for *normal* program outputs - IOW, you just can chain-pipe programs no more. As far as I'm concerned, it's *way* more impolite than "alerting" the user. Also and FWIW, most programs have --quiet and --verbose options that let the user specify verbosity. >> Also and FWIW, Python has a logging module in it's stdlib. Please >> use it instead of any half-backed squared-wheel homegrown solution. > > Unfortunately these square-wheeled homegrown solutions are easier to > grok than the standard logging module. It seems to target more > "serious" applications at the cost of feeling a bit too clunky for > quick hack jobs. If it's for a "quick hack job", you don't even need anything like what the OP describe. For anything more serious - anything that requires more than one .py script file with a couple functions and a main section -, the couple minutes spent setting up a default logger will very quickly pay off. But YMMV, of course... From darcy at druid.net Tue Oct 28 10:22:50 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 28 Oct 2008 10:22:50 -0400 Subject: dictionary In-Reply-To: References: Message-ID: <20081028102250.9883b4d5.darcy@druid.net> On Tue, 28 Oct 2008 10:06:31 -0400 Steve Holden wrote: > Bizarre though it may sound in this age of integrated circuits there > really was a storage device that used a cathode ray tube to store (IIRC) > a kilobit of information. It detected, by the use of a capacitance plate A kilobit? One tube would carry one bit. Imagine the size of today's computers if we were still using them. In those days you were lucky to get 4 Kbytes of core memory. In those days they would have techs walking back and forth along pathways inside the memory banks with shopping carts full of tubes replacing them as they burned out. Programs had to be prepared to deal with the fact that bits could go dead at any time and functions would run multiple times and hold an election to determine the correct answer. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From grante at visi.com Tue Oct 21 10:57:16 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 21 Oct 2008 09:57:16 -0500 Subject: search for a python compiler program whose name is jingle References: Message-ID: On 2008-10-20, oyster wrote: > I don't remember its name very clear, it may be 'jingle' or > not this program runs on windows and can compile a python > program into exe file without gcc it has no webspace but is > announced on the author's blog when I find it some times ago. > I can't find the link now. I there anybody else know it and > tell me? Thanx in advance Is "Jungle" what you're looking for? http://www.suda-chen.biz/?page_id=21 -- Grant Edwards grante Yow! Civilization is fun! at Anyway, it keeps me busy!! visi.com From mathieu.prevot at ens.fr Mon Oct 6 15:25:27 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Mon, 6 Oct 2008 21:25:27 +0200 Subject: do something in time interval In-Reply-To: References: <8aa5d90d-0647-47d4-88bb-8784a31866cf@t54g2000hsg.googlegroups.com> <4fc9afc50810061130y527f08a6o2185c80e510f9e45@mail.gmail.com> Message-ID: <3e473cc60810061225v3479a707neb0958707edda1fe@mail.gmail.com> 2008/10/6 Petr Jake? : >> I am not an expert, but why not to use time.sleep(5)? >> If you are using wxPython, you may also try wx.Timer, in which you could >> set its interval. >> > > Thanks for your reply. > During the 5s period my script has to do some stuff instead of sleeping. > Thats why it runs in the loop and once in 5s period it has to trigger some > other stuff(function, method, action) to do. > Petr Jakes You might want to use threads so you have a very simple code like this: data data0 thread1: while True: time.sleep(5) doSomething(data0) thread2: while True: time.sleep(0.01) doAnotherthing(data0) thread1 and thread2 can run in parallel; if thread2 take more time, thread1 won't be impaired. Mathieu From exiquio at gmail.com Tue Oct 7 14:02:20 2008 From: exiquio at gmail.com (exiquio) Date: Tue, 7 Oct 2008 11:02:20 -0700 (PDT) Subject: Making Non Callable Objects Callable References: Message-ID: <70378d7d-e510-4135-858b-1ee86d661cdc@v39g2000pro.googlegroups.com> On Oct 7, 1:56?pm, Christian Heimes wrote: > exiquio wrote: > > I am trying to figure out if there is a way to make an object in > > python callable, modules in particular. I wrongly assume that defining > > '__call__' in the the objects __dict__ would work. Any help would be > > appreciated. > > No, that doesn't work. Several magic methods (__*__) aren't looked up in > __dict__ or through __getattr__(). > > Christian Thanks. From no-spam at no-spam.invalid Sat Oct 18 07:24:09 2008 From: no-spam at no-spam.invalid (robert) Date: Sat, 18 Oct 2008 13:24:09 +0200 Subject: loops In-Reply-To: <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> Message-ID: Gandalf wrote: > On Oct 18, 12:39 pm, Duncan Booth > wrote: >> Gandalf wrote: >>> how can I do width python a normal for loop width tree conditions like >>> for example : >>> for x=1;x<=100;x+x: >>> print x >> What you wrote would appear to be an infinite loop so I'll assume you meant >> to assign something to x each time round the loop as well. The simple >> Python translation of what I think you meant would be: >> >> x = 1 >> while x <= 100: >> print x >> x += x >> .. > > I was hopping to describe it with only one command. most of the > languages I know use this. > It seems weird to me their is no such thing in python. it's not that I > can't fined a solution it's all about saving code You'd not save code, but only lines (and clearness). You'd also need more (non-space) characters Python saves confusion and arbitrariness => you'll usually code faster, because you don't think so much about voluptuous multimulti..possibilites, not worth the play: one-ness of mind If insistent, you could sometimes save lines like this ;-) x=1 while x<=100: print x; x+=x Robert From washakie at gmail.com Tue Oct 28 05:32:18 2008 From: washakie at gmail.com (John [H2O]) Date: Tue, 28 Oct 2008 02:32:18 -0700 (PDT) Subject: Setting up Python on a network of machines Message-ID: <20203881.post@talk.nabble.com> I have set up the Python computing environment on a machine within a network to include the following Python modules: 1) Scipy 2) Numpy 3) Matplotlib v.98 or greater 4) Matplotlib toolkit Basemap v.99 or greater 5) Scientific These are standard module products available via sourceforge.net or links directly from python.org I would like that this implementation of python be set up on all our machines in a network. Is there a way to do this without installing all the python modules individually on each machine? I have heard the problem will be that things will compile differently - for example some machines are 64 bit. Could I at least create a network instance of python for the 32 bit machines? They are mostly the same Fedora Core [5-8]. How does one create a 'common' instance of python for a network of machines? Thanks. -- View this message in context: http://www.nabble.com/Setting-up-Python-on-a-network-of-machines-tp20203881p20203881.html Sent from the Python - python-list mailing list archive at Nabble.com. From robert.kern at gmail.com Wed Oct 15 19:23:39 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 15 Oct 2008 18:23:39 -0500 Subject: problem using ctypes with MMX intrinsics In-Reply-To: <48F66E99.7080401@comcast.net> References: <48F54102.40509@comcast.net> <48F66E99.7080401@comcast.net> Message-ID: dcharno wrote: > Robert Kern wrote: >> Well, stack alignment would be a problem with how the shared library >> gets compiled, nothing to do with ctypes (I think). However, if you are > > The shared library is built with '-m32 -msse2' and works fine from a > C/C++ test harness, so I think its compiled okay. > > > passing in arrays from ctypes, *they* may also be misaligned. Try to > > check the addresses of the ctypes values you are passing in. I'm not > > entirely sure how to do that, though. > > I'm only passing filenames and some string options through the API. All > the data that gets processed with MMX/SSE is opened inside the shared > library. Hmm. Okay. Start your program under gdb, find what data it's crashing on, check the alignment on it, and if it's misaligned, figure out where that data is coming from. Is the ctypes driver doing the same exact operations as the C++ test harness? If not, it may be exposing a bug in your code. I've had a few occasions when using SSE2 intrinsics where I had a bug in my loop such that I was going off the end of the array due to a thinko. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From xxx_lord at ua.fm Wed Oct 1 04:55:21 2008 From: xxx_lord at ua.fm (ShopBody.ru) Date: Wed, 1 Oct 2008 01:55:21 -0700 (PDT) Subject: =?KOI8-R?B?6c7UxdLOxdQgzcHHwdrJziDEzNEg0M/I1cTF?= =?KOI8-R?B?zsnRIFNob3AgQm9keQ==?= Message-ID: <4694056c-31d4-4ce5-86e5-56b4c25ae78b@f36g2000hsa.googlegroups.com> ?? ???? ?????????? ?????? ???????? ?????? ??? ???????? ????? ???????????? ? ??????????? ?????? ??????? ?????????????? ????: ?????, ???????, ???????, ?????????? ??????, ??????? ??? ????????? ? ??????? ?????????, ????????? ? ??????????????, ???????? ???????????? ? ??????????, ?????? ??? ????? ?? ??????, ? ?????: ?????????? ? ??????, ????????? ????????, ????????? ??? ???? ?? ????? ? ????????, ?????????????? ? ??????? ??? ???? ? ????, ??????? ? ?????????????? ??? ?????, ???????? ????????? ? ?????????? ??????, ?????????????? ??????? ? ??????? ? ?????? ??????. From tjreedy at udel.edu Thu Oct 30 13:49:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2008 13:49:39 -0400 Subject: "xxx.has_key(a)" vs "a in xxx" In-Reply-To: <20081030111107.f00a7848.darcy@druid.net> References: <200810301537.35507.orangewarrior@gmail.com> <20081030111107.f00a7848.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > On Thu, 30 Oct 2008 09:50:57 -0500 > "Kurt Smith" wrote: >>> 2.5 docs say that: >>> "a.has_key(k) Equivalent to k in a, use that form in new code" >> Meaning: don't use 'a.has_key(k)'. >> >>> 2.6 docs say that: >>> "dict.has_key(key) is equivalent to key in d, but deprecated." >> Meaning, 'd.has_key(key)' is deprecated -- use 'key in d'. > > Wow! That is so badly written. Both those statements could easily be > read the opposite by someone reading the docs. Granted the latter is > better and it is correct but it could be clearer the the user. It > should be something like; > > """dict.has_key(key) is deprecated. Use "key in dict" instead.""" > > IOW your explanation of the sentence is better than the sentence. :-) http://bugs.python.org/issue4243 From george.sakkis at gmail.com Wed Oct 8 21:29:52 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 8 Oct 2008 18:29:52 -0700 (PDT) Subject: Safe eval of insecure strings containing Python data structures? References: Message-ID: On Oct 8, 8:34?pm, "Warren DeLano" wrote: > I would like to parse arbitrary insecure text string containing nested > Python data structures in eval-compatible form: ? > > # For example, given a "config.txt" such as: > > { > ? 'my_atom' : 1.20, > ? 'my_dict' : { 2:50 , 'hi':'mom'}, > ? 'my_list' : [ (1,2,3), [4.5,6.9], 'foo', 0 ] > > } > > # I would like to do something like this: > > empty_space = {'__builtins__' : {}} > > try: > ? ? config = eval(open("config.txt").read(), empty_space, empty_space) > except: > ? ? config = {} > > print config > > # But I know for certain that the above approach is NOT secure since > object attributes can still be accessed... > > So is there an equally convenient yet secure alternative available for > parsing strings containing Python data structure definitions? > > Thanks in advance for any pointers! This topic comes up every other month or so in this list, so if you had taken a minute to search for "python safe eval" or a variation thereof in your favorite search engine, you'd get more than enough pointers. George From mail at timgolden.me.uk Fri Oct 31 04:52:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 31 Oct 2008 08:52:59 +0000 Subject: open a new terminal window from another terminal window in linux/unix system In-Reply-To: <691e3a66-65dc-4641-9583-6096717eab0e@c36g2000prc.googlegroups.com> References: <691e3a66-65dc-4641-9583-6096717eab0e@c36g2000prc.googlegroups.com> Message-ID: <490AC76B.3020103@timgolden.me.uk> gaurav kashyap wrote: > I am using Microsoft Windows XP.Using putty.exe,I connected to LINUX > server and a terminal window gets opened.Here i logeed in as root. > > What i want to do is open another terminal window from already opened > terminal window. > Can this be achieved.If yes,please provide a tested solution If you'd posted this description of of the situation about 2 days ago, you'd have had a *much* better chance of getting a useful answer. I don't think I'd have guessed in a million years that this was what you were trying to do! In short, there's no command you can type *inside Python*, *on a remote box* which will cause Putty or Windows or anything on your local PC to open another Window. I'd be seriously worried if there were! TJG From meher4u1 at gmail.com Tue Oct 14 02:27:37 2008 From: meher4u1 at gmail.com (Aditi Meher) Date: Tue, 14 Oct 2008 11:57:37 +0530 Subject: Question In-Reply-To: <608380240810132325sf398ec8x765780937c99baf7@mail.gmail.com> References: <608380240810132325sf398ec8x765780937c99baf7@mail.gmail.com> Message-ID: <608380240810132327s4b0f941bl7f37b3b9e50aaa24@mail.gmail.com> ---------- Forwarded message ---------- From: Aditi Meher Date: Tue, Oct 14, 2008 at 11:55 AM Subject: Question To: Jonathan Gardner Hello I am using ubuntu operating system,i am using python and self app for DB storage. I hv already mentioned in my question that i want to display 10 records out of 100,how to create buffer to store remaining records which i am not displaying. I know the logic,but my language of sytax is not good so i want actual code please can u mail it to me. I have created DB using self app and after that created table using python into DB, i hv also inserted the records into it using python. please reply. From Scott.Daniels at Acm.Org Tue Oct 28 12:10:03 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 28 Oct 2008 09:10:03 -0700 Subject: Unpacking byte strings from a file of unknown size In-Reply-To: <2e14bd33-0370-4bfd-91ad-4683a2c7d05e@s9g2000prg.googlegroups.com> References: <5adcb40f-3b97-4fb7-b534-ab323bdb7636@s1g2000prg.googlegroups.com> <2e14bd33-0370-4bfd-91ad-4683a2c7d05e@s9g2000prg.googlegroups.com> Message-ID: Mark wrote: > Thanks I tested your solution and that works. > > One of the things that didn't work was > for chunk in myfile.read(10): > info1, info2, info3 = struct.unpack(' > It gets an error saying unpack requires a string of length 10, which I > thought chunk would be after the read(10). I'm still a little > confused as to why. this code python interprets as: data = myfile.read(10) for chunk in data: . --Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Thu Oct 9 17:44:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2008 17:44:56 -0400 Subject: python 3: sorting with a comparison function In-Reply-To: <6l74hpFauga7U1@mid.individual.net> References: <6l74hpFauga7U1@mid.individual.net> Message-ID: Thomas Heller wrote: > Does Python 3 have no way anymore to sort with a comparison function? > > Both [].sort() and sorted() seem to accept only 'key' and 'reverse' arguments, > the 'cmp' argument seems to be gone. Can that be? Yes. When this was discussed, no one could come up with an actual use case in which the compare function was not based on a key function. Calling the key function n times has to be faster than calling a compare function n to O(nlogn) times with 2 keys computed for each call. The main counter argument would be if there is no room in memory for the shadow array of key,index pairs. And that can be at least sometimes handled by putting the original on disk and sorting an overt key,index array. Or by using a database. From castironpi at gmail.com Fri Oct 10 13:18:53 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 10 Oct 2008 10:18:53 -0700 (PDT) Subject: inspect feature References: <4a893f80-adfd-4998-94f4-a095d62f845e@x41g2000hsb.googlegroups.com> <48edc501$0$10600$426a34cc@news.free.fr> <48ef13b8$0$11215$426a34cc@news.free.fr> Message-ID: <6efa0c25-c00e-4bf2-ac83-79594ad081cc@v30g2000hsa.googlegroups.com> On Oct 10, 3:36?am, Bruno Desthuilliers wrote: > Aaron "Castironpi" Brady a ?crit : > > > > > On Oct 9, 3:48 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > >> Aaron "Castironpi" Brady a ?crit : > > >>> Hello, > >>> The 'inspect' module has this method: > >>> inspect.getargvalues(frame) > >>> It takes a frame and returns the parameters used to call it, including > >>> the locals as defined in the frame, as shown. > >>>>>> def f( a, b, d= None, *c, **e ): > >>> ... ? ? import inspect > >>> ... ? ? return inspect.getargvalues( inspect.currentframe() ) > >>> ... > >>>>>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' ) > >>> (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1, > >>> 'e': {'h': 'g > >>> hi'}, 'd': 'abc', 'inspect': >>> \Python26\lib\in > >>> spect.pyc'>}) > >>> However, if you wanted a decorator that examines the parameters to a > >>> function, you're out of luck. ?By the time you have a frame, you're > >>> already in the function. > >> Hem... > > >> def decorator(func): > >> ? ? ?def _decorator(*args, *kw): > >> ? ? ? ? ?print "func args are ", *args, **kw > >> ? ? ? ? ?return func(*args, **kw) > >> ? ? ?return _decorator > > > It is less of a problem without tuple unpacking, but you still have > > code like: > > > if len( args )>= 2: > > ? ?b= args[ 1 ] > > else: > > ? ?try: > > ? ? ? b= (somehow check b's default val.) > > ? ?except NoDefaultVal: > > ? ? ? raise ArgumentError > > > Worse yet, you have it for each parameter. ?Unless I missed something, > > this is the only way to mimic/recreate the signature of the decoratee. > > I don't get what you're after ??? The decorator has full access to both > the actual params *and* the function's signature (via > inspect.getargspec). So your initial question "if you wanted a decorator > that examines the parameters to a function" seems fully answered. You > will indeed have to write a couple lines of code if you want the same > formating as the one you'd get with inspect.currentframe(), but what ? > > FWIW, Michele Simionato's decorator module has some trick to allow for > signature-preserving decorators, so you may want to have a look - but > I'm not sure if this would solve your problem - at least in a sane way. It's not exactly the next Millennium problem, but there are some substantial checks you have to do on a per-parameter basis to see the same thing that a function sees, when all you have is *args, **kwargs. You are wrapping a function with this signature: def f( a, b, c= None, *d, **e ): You want to find out the values of 'a', 'b', and 'c' in a decorator. You have these calls: f( 0, 1, 'abc', 'def', h= 'ghi' ) f( 0, 1 ) f( 0, 1, h= 'abc' ) f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values How do you determine 'a', 'b', and 'c'? From mmgarvey at gmx.de Tue Oct 7 12:19:33 2008 From: mmgarvey at gmx.de (mmgarvey at gmx.de) Date: Tue, 7 Oct 2008 09:19:33 -0700 (PDT) Subject: how to get the thighest bit position in big integers? References: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> Message-ID: > See also http://bugs.python.org/issue3439 > where there's a proposal to expose the _PyLong_NumBits method. ?This > would give an O(1) solution. > > In every case I can think of, I've wanted (0).numbits() to be 0. Here is surely the wrong place to respond to http://bugs.python.org/msg71384 but I want to make clear that I think that (0).numbits()==-1 is the natural solution. At least for all square-and-multiply-like algorithms needed in cryptography (modular exponentiation, point multiplication on elliptic curves, generation of lucas numbers, etc) this property of .numbits() would be needed. From castironpi at gmail.com Sat Oct 18 15:46:14 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 18 Oct 2008 19:46:14 +0000 (UTC) Subject: Help with Iteration References: <23e28a76-3ca6-4abe-8ebb-c93858977596@e17g2000hsg.googlegroups.com> <62415c53-0e07-4bbe-8a11-eff3ab536337@t42g2000hsg.googlegroups.com> Message-ID: Chris McComas wrote: > actually i'm running it online, with a mysql db. so in the db there is > a table CollegeYear with the following fields: > > name > rating > change > wp > > then another table Games > > date > year > team_1 > team_1_score > team_2 > team_2_score > > it goes through and calculates everything, then when it's time to > compute the rating i have say this code: > > http://dpaste.com/85300/ > > it goes through and computes them, then add the new rating and > absolute value of the changed rating to the db. what i need now is a > way to get the largest entry for 'change' and if it is greater than > 0.00005 then do this code again. if it is less than 0.00005 then we're > done. What about "SELECT MAX( rating ) FROM CollegeYear"? From lie.1296 at gmail.com Sun Oct 26 07:40:49 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 26 Oct 2008 11:40:49 +0000 (UTC) Subject: Why can't I assign a class method to a variable? References: Message-ID: On Wed, 22 Oct 2008 12:34:26 -0400, ed wrote: > I'm trying to make a shortcut by doing this: > > t = Globals.ThisClass.ThisMethod > > Calling t results in an unbound method error. > > Is it possible to do what I want? I call this method in hundreds of > locations and I'm trying to cut down on the visual clutter. > > Thank you! Remember that in python when you do: A_instance = A() A_instance.foo(a, b) is actually the same as A_instance = A() A.foo(A_instance, a, b) From bjourne at gmail.com Sat Oct 25 17:18:00 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 25 Oct 2008 23:18:00 +0200 Subject: arange randomly words in a list In-Reply-To: <644712.61026.qm@web38402.mail.mud.yahoo.com> References: <644712.61026.qm@web38402.mail.mud.yahoo.com> Message-ID: <740c3aec0810251418w4972eec5p184e1f266052acdd@mail.gmail.com> 2008/10/20 william paul : > I have a list that looks like: > > name = name1 name2 name3 name4 > > and I would like to be able to arrange randomly this list, like: > > name = name 2 name 1 name3 name4 > name = name4 name2 name1 name3 > .... > > I have tried with random.shuffle, but still no good result That is exactly what random.shuffle() does. Why doesn't the function work for you? -- mvh Bj?rn From metaperl at gmail.com Thu Oct 2 05:18:50 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 2 Oct 2008 02:18:50 -0700 (PDT) Subject: how best to use a dictionary in this function? Message-ID: Ok, here is some code: def calc_profit(std_clicks, vip_clicks, ad_rate=200, upline_status=None): payout = {} payout_std = std_clicks * rates['std'].per_click payout_vip = vip_clicks * rates['vip'].per_click ... now note that std_clicks and vip_clicks are passed to the function. Now, I improved this function this way: def calc_profit(std_clicks, vip_clicks, ad_rate=200, upline_status=None): clicks = {} clicks['std'] = std_clicks clicks['vip'] = vip_clicks payout = {} for member_type in rates: payout[member_type] = clicks[member_type] * rates[member_type].per_click But it seems wasteful to have to re-bind the passed-in function args to a dictionary in the function. I think there must be some way to improve this code and get the dictionary built without me manually doing it... I know there is something like *args, or **args, but since docs.python.org is down, I cant check. From ldo at geek-central.gen.new_zealand Sat Oct 18 18:48:36 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 19 Oct 2008 11:48:36 +1300 Subject: Linux.com: Python 3 makes a big break References: Message-ID: In message , Aahz wrote: > (There's a significant amount of JavaScript, much of which is generated by > Python code.) Been there, done that. Triple backslashes, anybody? :) From larry.bates at vitalEsafe.com Thu Oct 23 01:15:46 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Thu, 23 Oct 2008 00:15:46 -0500 Subject: Need some advice In-Reply-To: <4b8e0216-ad8f-4fb1-b182-ef84a44e330c@a1g2000hsb.googlegroups.com> References: <48fe207c$0$20551$426a34cc@news.free.fr> <41f37d97-d1d4-4311-8b02-b0b7896acb3d@y21g2000hsf.googlegroups.com> <48fedad6$0$2497$426a74cc@news.free.fr> <4b8e0216-ad8f-4fb1-b182-ef84a44e330c@a1g2000hsb.googlegroups.com> Message-ID: azrael wrote: > I mean shttp. (secure hyper text transfer protocol) > > > On Oct 22, 9:48 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> azrael a ?crit : >> >>> There have been some discutions with my partner about which protocol >>> to use. We agreed to use also http. But we are looking for a >>> possibility to use something to trasfer python objects like Json >>> objects. >> 'like' ??? >> >> there are a couple json implementation for Python, and for PHP too IIRC. >> >>> If my memory is me well http transfers data in plaintext. >>> Because of >>> the risk of datacapturing, is there a better soulutioon to suggest to >>> be more secure like shttp >> I suppose you mean https... >> >>> if it is implemented in python >> http://www.python.org/doc/2.5.2/lib/https-handler-objects.html > Bruno is correct, the protocol IS https, you don't type shttp into your browser get secure http connection. You don't transfer python objects with JSON, you can transfer data that was stored in Python objects via converting them to JSON (e.g. most JSON resembles a Python dictionary, but it is a text representation). PHP couldn't do anything with a Python object. You may want to pick up a copy of "RESTful Web Services", from O'Reilly. It is an excellent starting place for you. -Larry From dfnsonfsduifb at gmx.de Thu Oct 9 16:54:59 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 09 Oct 2008 22:54:59 +0200 Subject: Python HTML parser chokes on UTF-8 input Message-ID: <4m72s5xlgn.ln2@joeserver.homelan.net> Hello group, I'm trying to use a htmllib.HTMLParser derivate class to parse a website which I fetched via httplib.HTTPConnection().request().getresponse().read(). Now the problem is: As soon as I pass the htmllib.HTMLParser UTF-8 code, it chokes. The code is something like this: prs = self.parserclass(formatter.NullFormatter()) prs.init() prs.feed(website) self.__result = prs.get() prs.close() Now when I take "website" directly from the parser, everything is fine. However I want to do some modifications before I parse it, namely UTF-8 modifications in the style: website = website.replace(u"f??", u"b?r") Therefore, after fetching the web site content, I have to convert it to UTF-8 first, modify it and convert it back: website = website.decode("latin1") website = website.replace(u"f??", u"b?r") website = website.encode("latin1") This is incredibly ugly IMHO, as I would really like the parser to just accept UTF-8 input. However when I omit the reecoding to latin1: File "CachedWebParser.py", line 13, in __init__ self.__process(website) File "CachedWebParser.py", line 55, in __process prs.feed(website) File "/usr/lib64/python2.5/sgmllib.py", line 99, in feed self.goahead(0) File "/usr/lib64/python2.5/sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "/usr/lib64/python2.5/sgmllib.py", line 285, in parse_starttag self._convert_ref, attrvalue) UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 0: ordinal not in range(128) Annoying, IMHO, that the internal html Parser cannot cope with UTF-8 input - which should (again, IMHO) be the absolute standard for such a new language. Can I do something about it? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From google at mrabarnett.plus.com Fri Oct 3 17:47:34 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 3 Oct 2008 14:47:34 -0700 (PDT) Subject: Python equivalent of Perl e flag with regular expression References: Message-ID: <545df0e2-f9f6-4f84-b3ab-0d1e69c91120@k37g2000hsf.googlegroups.com> On Oct 2, 6:06?pm, "Friedman, Jason" wrote: > I have lines that look like this: > select column1, 'select' as type > from table > where column2 = 'foo' > > I want to return: > SELECT column1, 'select' AS type > FROM table > WHERE column2 = 'foo' > > This is SQL with the keywords converted to uppercase. ?Note that the > second "select" string is not a keyword and thus I do not want to > convert it to uppercase. ?Thus, I don't think the string.replace() > method will work for me. > [snip] FYI, yhe replace method can take a third argument, which is the maximum number of replacements to do: >>> query = "select column1, 'select' as type from table where column2 = 'foo'" >>> query.replace("select", "SELECT", 1) "SELECT column1, 'select' as type from table where column2 = 'foo'" From tjreedy at udel.edu Wed Oct 15 14:30:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2008 14:30:10 -0400 Subject: ANN: eGenix mxODBC - ODBC Database Interface for Python 3.0.2 In-Reply-To: <48F60F56.4020609@egenix.com> References: <48F60F56.4020609@egenix.com> Message-ID: <48F636B2.9020100@udel.edu> FYI I initially parsed the subject line as "eGenix mxODBC - ODBC Database Interface" for "Python 3.0.2" and thought, "Wow, already prepared for the future" (6 months to a year) ;-). tjr From vinay_sajip at yahoo.co.uk Wed Oct 29 09:17:52 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 29 Oct 2008 06:17:52 -0700 (PDT) Subject: how to use logging module to log an object like print() References: <6mqnjnFi9u8fU1@mid.uni-berlin.de> Message-ID: <560f5dd9-abcb-48d2-a3e9-d6e5f13b34f0@k37g2000hsf.googlegroups.com> On Oct 29, 11:24 am, Steve Holden wrote: > > One deficiency of this approach, however, is that the string formatting > is performed even when nologgingis required, thereby wasting a certain > amount of effort on unnecessary formatting. > Though you can mitigate this using the pattern: if logger.isEnabledFor(logging.DEBUG): logger.debug("Message with variable data which may be expensive: %s", expensive_call()) Which will only make the expensive_call() and formatting when the logging call will actually do something. Regards, Vinay Sajip From p at ulmcnett.com Fri Oct 24 16:24:59 2008 From: p at ulmcnett.com (Paul McNett) Date: Fri, 24 Oct 2008 13:24:59 -0700 Subject: What's the perfect (OS independent) way of storing filepaths ? In-Reply-To: <010bad59$0$20653$c3e8da3@news.astraweb.com> References: <92da89760810191049s7d0fa4e5p675ae584d7b7bfbc@mail.gmail.com> <010bad59$0$20653$c3e8da3@news.astraweb.com> Message-ID: <49022F1B.9020705@ulmcnett.com> Steven D'Aprano wrote: > On Sun, 19 Oct 2008 20:50:46 +0200, Stef Mientki wrote: > >> Duncan, in windows it's begin to become less common to store settings in >> Docs&Settings, >> because these directories are destroyed by roaming profiles The directories aren't destroyed by roaming profiles. When the user logs out, they get copied to the server. When they log in at a different machine, they get copied to the workstation. So configuration information saved in c:\Documents and Settings\pmcnett\Application Data\My Application gets conveniently migrated from machine to machine where I happen to login. A really nice feature. > Isn't *everything* destroyed by roaming profiles? *wink* I've heard such bashing of roaming profiles but I've never had anything but love for them. That is, until people go and start saving their movies and pictures in My Documents. Which is why I set their home directory to a server share and have them save their docs there. > Seriously, I don't know anyone who has anything nice to say about roaming > profiles. I loathe Windows, but roaming profiles was one thing they did (mostly) right. I couldn't be happy in a world that didn't include roaming profiles. Perhaps I'm not seeing the worst of it as I use Samba on Linux as the PDC? Anyway, on Windows user configuration information should go in the user's Application Data directory. If you don't want it to roam, you can instead put it in the (hidden) Local Settings/Application Data directory. Paul From 20080915.20.wmcclain at spamgourmet.com Fri Oct 31 14:14:40 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 31 Oct 2008 18:14:40 GMT Subject: Windows DOS box redirection References: <20253039.post@talk.nabble.com> Message-ID: On 2008-10-31, Stef Mientki wrote: > Well I don't know any Windows users that still use DOS-boxes ;-) > cheers, What do they do when they want to run a cross-platform command-line script with parameters and redirection? I suppose they could install cygwin and run bash, but that seems like overkill for what should be a simple task. -Bill -- Sattre Press The King in Yellow http://sattre-press.com/ by Robert W. Chambers info at sattre-press.com http://sattre-press.com/kiy.html From ldo at geek-central.gen.new_zealand Tue Oct 14 20:12:12 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 15 Oct 2008 13:12:12 +1300 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? References: Message-ID: In message , skip at pobox.com wrote: > If you're an Emacs user who has used both python-mode.el (the python mode > code distributed with Python and XEmacs) and python.el (the python mode > code distributed with GNU Emacs), I'd like to get your impressions on how > they compare ... I find Emacs modes just too confusing. I do all my editing in fundamental mode. From greg at cosc.canterbury.ac.nz Tue Oct 21 20:48:49 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 22 Oct 2008 13:48:49 +1300 Subject: What was that, what was it? In-Reply-To: References: <82f51155-16fe-4e5c-a83b-040cf7695ff8@u75g2000hsf.googlegroups.com> Message-ID: <6m7c1iFfg10mU1@mid.individual.net> Ross Ridge wrote: > Aaron Brady wrote: > >>If Python was a car, I think it would be a hybrid... > > Lawrence D'Oliveiro wrote: > >>I hope not. They're only good in the city, a waste of time once you get over >>50 km/h. > > Sounds a lot like Python then, a waste of time if you need to go fast, > but good for a lot of every day tasks. The neat thing about Python is that you can strap on a jet engine (C extension) when you really need a burst of speed. -- Greg From skip at pobox.com Thu Oct 9 07:20:17 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 9 Oct 2008 06:20:17 -0500 Subject: How to calculate two time? In-Reply-To: References: <3d16f21a-c131-4801-ad10-0c6b3d189f6e@s9g2000prg.googlegroups.com> Message-ID: <18669.59633.644066.180334@montanaro-dyndns-org.local> lookon> Thank you for your help.It works. However, I am using Google lookon> App Engine and cannot import dateutil and epsilon. I don't know how Google App Engine works, but are you not able to install pure Python modules? lookon> Are there any other ways? Take a look at the time.strptime function to generate a tuple, then use t = time.strptime(timestamp, format) t1 = datetime.datetime(*t[0:6]) Note that with this solution you will have to handle the timezone offset yourself. Skip From bcannon at gmail.com Tue Oct 7 15:59:20 2008 From: bcannon at gmail.com (Brett C.) Date: Tue, 7 Oct 2008 12:59:20 -0700 (PDT) Subject: Tuple parameter unpacking in 3.x References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> <87myhjcu7g.fsf@hbox.dyndns.org> Message-ID: On Oct 5, 9:13?am, Terry Reedy wrote: > Martin Geisler wrote: > > Steven D'Aprano writes: > >>> From reading the PEP-3113 I got the impression that the author > >>> thought that this feature was unused and didn't matter. > > And that there were good alternatives, and that there were technical > reasons why maintaining the feature in the face of other arguments > options would be a nuisance. > As the author of PEP 3113, I should probably say something (kudos to Python-URL bringing this thread to my attention). There are two things to realize about the tuple unpacking that acted as motivation. One is supporting them in the compiler is a pain. Granted that is a weak argument that only the core developers like myself care about. Second, tuple unpacking in parameters breaks introspection horribly. All one has to do is look at the hoops 'inspect' has to jump through in order to figure out what the heck is going on to see how messy this is. And I realize some people will say, "but if 'inspect' can handle it, then who cares about the complexity", but that doesn't work if 'inspect' is viewed purely as a simple wrapper so you don't have to remember some attribute names and not having to actually perform some major hoops. I personally prefer being able to introspect from the interpreter prompt without having to reverse-engineer how the heck code objects deal with tuple unpacking. > ?>>> With this I wish to say that it matters to me. > Well, every feature matters to someone. Question is whether it matters to enough people to warrant having a feature. I brought this up at PyCon 2006 through a partially botched lightning talk and on python- dev through the PEP, so this was not some snap decision on my part that I rammed through python-dev; there was some arguing for keeping it from some python-dev members, but Guido agreed with me in the end. If you still hate me you can find me at PyCon 2009 and tar & feather me *after* my talk. =) > >> Alas, I think it's too late. I feel your pain. > > > Thanks! And I know it's too late, I should have found out about this > > earlier :-( > > For future reference, the time to have said something would have been > during the 3 month alpha phase, which is for testing feature and api > changes. ?I suspect, from reading the pydev discussion, that the answer > still would have been to either use a def statement and add the unpack > line or to subscript the tuple arg to stick with lambda expressions. > But who knows? I have not read this whole thread thoroughly, but it sounds like using iterator unpacking at the call site (e.g., ``fxn(*args)`` when calling your lambda) is out of the question because it is from a callback? As Terry said, the alpha is one way you can give feedback if you don't want to follow python-dev or python-3000 but still have your opinion be heard. The other way is to subscribe to the PEP news feed (found off of http://www.python.org/dev/peps/) to keep on top of PEPs as practically all language changes have to result in a PEP at some point. And of course the last option is to follow python-dev. =) -Brett From steven at REMOVE.THIS.cybersource.com.au Wed Oct 1 05:02:37 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Oct 2008 09:02:37 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> <00f2b214$0$20617$c3e8da3@news.astraweb.com> Message-ID: On Tue, 30 Sep 2008 19:44:40 -0500, Grant Edwards wrote: > On 2008-09-30, Steven D'Aprano > wrote: >> On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: >> >>>>> How would the python equivalent go ? >>> >>> You would drag yourself out of the 1960s, install numpy, and then do >>> something like this: >> >> I think that was thoughtlessly rude to somebody who is asking a >> perfectly reasonable question. > > Sheesh. I guess I should have added a smiley face. > > So much for trying to be helpful. Oh the rest of your post was helpful. I think you were trying to be funny, but I think you failed. -- Steven From gh at ghaering.de Thu Oct 16 12:05:57 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 16 Oct 2008 18:05:57 +0200 Subject: like using python In-Reply-To: References: Message-ID: gdyren at gmail.com wrote: > as the subject me2 From notvalid2 at sbcglobal.net Sun Oct 12 14:24:32 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sun, 12 Oct 2008 11:24:32 -0700 Subject: Pylab Fails with Runtime Error on Win XP Under Python 2.4 Message-ID: I copied the following code from a matplotlib tutorial, and it fails. I'm using python 2.4 on Win XP. It's matplotlib-0.98.3.win32-py2.4exe. It fails in IDLE with a small window showing a runtime error. Clicking the OK on it kills IDLE and the shell. If I double-click on the py file, the console briefly appears too quickly to notice any contents. I have read raw to stop it. If I execute it from a console window, I'm told the results will be available there. I've long forgotten how to get a console window up in Win XP. I can strip it all the code way down to the from, and it will fail the same way. Bad matplotlib install? Python error? Here's the code. I added finish() to it. from pylab import * def finish(): print; print "Bye" print raw_input('Press Enter to Quit') sys.exit() t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plot(t, s, linewidth=1.0) xlabel('time (s)') ylabel('voltage (mV)') title('About as simple as it gets, folks') grid(True) show() finish() -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From carl at personnelware.com Sun Oct 26 21:24:47 2008 From: carl at personnelware.com (Carl K) Date: Sun, 26 Oct 2008 20:24:47 -0500 Subject: v4l module Message-ID: <4oudnc39tND8hZjUnZ2dnUVZ_uKdnZ2d@comcast.com> I am looking for a v4l (either version 1 or 2) module. I tried to use ctypes with ghostscript and failed. I have a feeling trying to use it with kernel modules would be even harder, so not exactly what "I" want to do. I just tried http://antonym.org/libfg and it segfaulted. (bugs reported) I found http://code.google.com/p/python-v4l2/ which is just a description, (and a post about what I want to do) but no code. I want to write unit tests to help debug v4l drivers, so I don't actually need to display any video. I expect lots of "crashed when I did this" reports. what this is for: http://chipy.org/V4l2forPyCon Carl K From martin at v.loewis.de Sun Oct 12 18:50:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Oct 2008 00:50:19 +0200 Subject: PIL on windows XP x64 (64-bit)? In-Reply-To: <9e21c282-776e-4011-a8ea-34a7f95a9537@v53g2000hsa.googlegroups.com> References: <09599912-b2b2-4cbf-a861-124ed211bc98@y29g2000hsf.googlegroups.com> <9e21c282-776e-4011-a8ea-34a7f95a9537@v53g2000hsa.googlegroups.com> Message-ID: <48f27f2b$0$25753$9b622d9e@news.freenet.de> Berco Beute wrote: > Investigated this a little more. Since I only needed to resize an > image I thought going through all the hoops of building PIL was too > much effort and took a look at PythonMagick. Turned out I had to build > that myself as well. Am I the first that wants to do image > manipulation on x64 using python? Are there alternatives? I would install the 32-bit Python interpreter. Regards, Martin From sjmachin at lexicon.net Sat Oct 18 21:53:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Oct 2008 18:53:17 -0700 (PDT) Subject: Help with Iteration References: <23e28a76-3ca6-4abe-8ebb-c93858977596@e17g2000hsg.googlegroups.com> <62415c53-0e07-4bbe-8a11-eff3ab536337@t42g2000hsg.googlegroups.com> <7c5bacbd-df3a-4e34-9108-fca17471339f@y21g2000hsf.googlegroups.com> Message-ID: <0ce5f3a5-9b3f-4ef4-a3c7-610e9c8422f4@40g2000prx.googlegroups.com> On Oct 19, 11:59?am, Chris McComas wrote: > On Oct 18, 3:46 pm, Aaron Brady wrote: > > > > > Chris McComas wrote: > > > actually i'm running it online, with a mysql db. so in the db there is > > > a table CollegeYear with the following fields: > > > > name > > > rating > > > change > > > wp > > > > then another table Games > > > > date > > > year > > > team_1 > > > team_1_score > > > team_2 > > > team_2_score > > > > it goes through and calculates everything, then when it's time to > > > compute the rating i have say this code: > > > >http://dpaste.com/85300/ What is the point of this: if games.team_1_score > games.team_2_score t1_rating = t2_rating + t1_wp - .5 t2_rating = t1_rating + t2_wp - .5 elif games.team_1_score < games.team_2_score t1_rating = t2_rating + t1_wp - .5 t2_rating = t1_rating + t2_wp - .5 elif games.team_1_score == games.team_2_score t1_rating = t2_rating + t1_wp - .5 t2_rating = t1_rating + t2_wp - .5 You have the same code for each of the three conditions. Where are the colons? Have you actually tried to execute this code? Any good reason why the second elif is not an else? > > > > it goes through and computes them, then add the new rating and > > > absolute value of the changed rating to the db. what i need now is a > > > way to get the largest entry for 'change' and if it is greater than > > > 0.00005 then do this code again. if it is less than 0.00005 then we're > > > done. > > > What about "SELECT MAX( rating ) FROM CollegeYear"? > > Aaron, > > Thnx. To clarify I can get the max, that wasn't the issue, what I'm > failing to try and visualise/figure out is how do I say, okay if MAX > > 0.00005 run this again, if MAX < 0.00005 you're done. [Aside: if MAX == 0.00005, what? Go into a catatonic trance?] Let me get this straight: Is this your first program? Are you asking how to code a while loop? From stef.mientki at gmail.com Tue Oct 14 07:04:18 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 14 Oct 2008 13:04:18 +0200 Subject: Launching scripts in Ubuntu ? In-Reply-To: <6ljb2vFcpmdoU1@mid.uni-berlin.de> References: <6ljb2vFcpmdoU1@mid.uni-berlin.de> Message-ID: <48F47CB2.5020108@gmail.com> Diez B. Roggisch wrote: > Stef Mientki wrote: > > >> hello, >> >> I'm not familiar with Linux / Ubuntu, >> still trying to get my application working under these operating systems. >> >> I've a script "file_support.py", >> now when I'm in Ubuntu, open a command window and go to the directory >> where that file is, >> I can launch the script with : >> "python file_support.py" >> and it works great >> >> Now when I want to run the script from another script, let's call it " >> test.py" >> where this is the contents of test.py: >> >> import subprocess >> subprocess.Popen ( [ 'python', 'file_support.py', ] ) >> >> The script "file_support" is executed correctly, >> but the python interpreter is not closed, >> I've to close it manual by pressing ENTER. >> > > What do you mean "it's not closed"? well the command prompt (if it is called that way in Linus) is not returned. When I run file_support, the command window looks like this >>>python file_support.py ..... all kinds of output >>> When I run test.py (which calls fie_support) , I get this >>>python test.py .... all kinds of output (the same as before) Now I've to explicitly press an enter to get the command prompt back. This might not sound important, but the problem is somewhat more complex, all these scripts are ran from another program, and although everything works fine under windows, the program hangs on Ubuntu. So I guess that this is the (first) problem to solve. thanks, Stef > Which window is taking the enter, and > how do you run test.py? > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From http Mon Oct 6 12:22:18 2008 From: http (Paul Rubin) Date: 06 Oct 2008 09:22:18 -0700 Subject: If an OS was to be written in Python, how'w it look? References: <67d3d350-42a9-429d-951c-f430bf069b29@m73g2000hsh.googlegroups.com> Message-ID: <7x7i8l1yo5.fsf@ruckus.brouhaha.com> "Eric Wertman" writes: > I'm no expert, but this would seem like a good example of something > that python wasn't good for. I have always wondered, though, what a > Linux kernel module would look like that had a python (or java, or > whatever) interpreter running low-level, so the higher level > components on the operating system could be implemented in an > interpreted language. Is there any benefit to something like that? > Or is that crap too? Again, I'm no expert. This was done 20 years ago with the Lisp machine. Really, it was a bold idea back then, but programming language and systems understanding have comea long way since then. Best to keep using Python as a scripting language; it's not the right thing for an OS. From carl at never.com Wed Oct 29 14:09:01 2008 From: carl at never.com (Carl) Date: Wed, 29 Oct 2008 14:09:01 -0400 Subject: Python/Numeric users be aware! In-Reply-To: References: Message-ID: Confirmed Benyang wrote: > Maybe it has been reported somewhere, but it is a big surprise to me. > > # Try the following: > import Numeric > a = Numeric.ones(10) > a[5:] = -1 > print a > > It works correctly on 32-bit linux machines and on 32-bit Windows XP: > [ 1 1 1 1 1 -1 -1 -1 -1 -1] > > It is totally screwed up on 64-bit linux machines: > [1 1 1 1 1 1 1 1 1 1] > > # The following works correctly on both 32-bit and 64-bit machines > (notice the comma): > a[5:,] *= -1 > > The Python version is 2.5.1, and Numeric is the latest version 24.2. From skip at pobox.com Thu Oct 2 05:15:13 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 2 Oct 2008 04:15:13 -0500 Subject: RELEASED Python 2.6 final In-Reply-To: <47c890dc0810012214ofb2c86dr4ea6dd9d0c9e93fb@mail.gmail.com> References: <47c890dc0810012214ofb2c86dr4ea6dd9d0c9e93fb@mail.gmail.com> Message-ID: <18660.37153.952539.92118@montanaro-dyndns-org.local> Chris> Also, the docs currently seem broken. Known problem. The elves are working on it. -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From lfrogerscobalt at gmail.com Wed Oct 1 18:31:36 2008 From: lfrogerscobalt at gmail.com (Albertos) Date: Wed, 1 Oct 2008 15:31:36 -0700 (PDT) Subject: megarotic - Free Message-ID: <29e1f7e9-dfdf-489a-82ea-e2f73d6c4c73@34g2000hsh.googlegroups.com> megarotic . . . *******CLICK HERE******** http://vids365.cn/megarotic ***************************** . . . . . . . . . . . . megarotic From gagsl-py2 at yahoo.com.ar Tue Oct 21 02:55:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Oct 2008 04:55:44 -0200 Subject: Python script + v4lctl References: <1224490534.48fc3e26f3708@www.inbox.lv> Message-ID: En Mon, 20 Oct 2008 06:15:34 -0200, Gatis escribi?: > I wrote script that in case of some event takes picture using usb > webcam [Creative Live! Cam Vista IM (VF0420)] and command line utility > v4lctl (from package xawtv). > Problem1: > To catch error and info messages from script I used: > sys.stdout = open('/tmp/log','a') > sys.stderr=sys.stdout > All writes to log file well, except v4lctl error messages. If script > is run from commandline, than v4lctl error messages are shown there. > How to catch these messages? Use the subprocess module to invoke the external program; see http://docs.python.org/library/subprocess.html specially the examples at the end. > Problem2: > When script is run from /etc/init.d (in runlevel 2) during boot, no > pictures are taken. I can't tell error message, because of Problem1. > If I execute now v4lctl from commandline (while my script is running > in background), picture is taken. Once you start using subprocess, you could write to some file what you get from the communicate() method - the error messages, if any, should be there. -- Gabriel Genellina From mh at pixar.com Thu Oct 9 19:09:32 2008 From: mh at pixar.com (mh at pixar.com) Date: Thu, 09 Oct 2008 23:09:32 GMT Subject: subdirectories for sys.path import? Message-ID: I'm currently sharing a directory on sys.path with another group. We don't have the option to modify sys.path. In order to reduce conflicts between the two group's code, installation procedures, etc, I'd like to make a subdirectory for each group, and have each group manage their own subdirectory. /oursharedpath/lib/python/group1 /oursharedpath/lib/python/group2 Is there a way to import a module from one of these subdirectories? Any other more pythonic ways to approach the situation? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From tjreedy at udel.edu Fri Oct 10 17:17:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Oct 2008 17:17:42 -0400 Subject: indexing arrays In-Reply-To: <19918073.post@talk.nabble.com> References: <19918073.post@talk.nabble.com> Message-ID: John [H2O] wrote: > I'm having trouble slicing arrays: If these are numpy arrays, as appears, rather that array module arrays, then the numpy list might be a better place. In any case, using 'numpy' would have gotten the attention of someone scanning for posts about numpy. > > I thought I could do the following: >>>> i = array(range(140,149)) >>>> j = array(range(5,20)) >>>> a = acc[i,j] > Traceback (most recent call last): > File "", line 1, in > ValueError: shape mismatch: objects cannot be broadcast to a single shape > > It's strange, because I can do this: > >>>> a = acc[140:148,5:19] From gagsl-py2 at yahoo.com.ar Wed Oct 22 03:03:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Oct 2008 05:03:36 -0200 Subject: IDLE home page? References: <9e2f512b0810211801x67a39556u5f132def7937ed52@mail.gmail.com> Message-ID: En Wed, 22 Oct 2008 04:49:14 -0200, Terry Reedy escribi?: > Sebastian Bassi wrote: >> If I put IDLE in the search box at python.org, the first hit is: >> http://www.python.org/idle/ >> But this page is a directory without any index file: >> If I see the "ABOUT" windows (under HELP in the IDLE menu), there is >> also a link to http://www.python.org/idle/ > > Depending on the answer you get here, you might send the same > observation and question to webmaster at python.org BTW, the README file still refers to the sourceforge tracker. -- Gabriel Genellina From python.list at tim.thechases.com Mon Oct 20 08:20:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 20 Oct 2008 07:20:24 -0500 Subject: Idenfity numbers in variables In-Reply-To: <1224501408.9143.40.camel@king.imim.es> References: <1224501408.9143.40.camel@king.imim.es> Message-ID: <48FC7788.2090002@tim.thechases.com> > atom = 'C1' > > if '1' in atom: > print 'kk' > > But, how can I do to identify in '1' all possibilities from 1-9, I > tried: > > if '[1-9]', \d,... You're reaching in the right direction (regexps), so just use Python's "re" module: import re digit = re.compile(r'\d') # or "[0-9]" for test in ["C1", "N98", "CJ", "3.141", "43+5i", ""]: print test, if digit.search(test): print "has", else: print "doesn't have", print "a digit in it" The regexp can be tightened up if you want to ensure that it has a letter in front of it, or a number of other tests but that should be a decent start. -tim From bj_666 at gmx.net Fri Oct 24 14:02:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Oct 2008 18:02:45 GMT Subject: URL as input -> "IOError: [Errno 2] The system cannot find the path specified" References: Message-ID: <6megu5Fg8n3fU1@mid.uni-berlin.de> On Fri, 24 Oct 2008 19:56:04 +0200, Gilles Ganault wrote: > I'm trying to use urllib to download web pages with the GET method, but > Python 2.5.1 on Windows turns the URL into something funny: > > ======== > url = "amazon.fr/search/index.php?url=search" This "URL" lacks the protocol! Correct would be http://amazon.fr? (I guess). > [...] > > IOError: [Errno 2] The system cannot find the path specified: > 'amazon.fr\\search\\index.php?url=search' Without protocol it seems that the 'file://' protocol is used and there is no such file on your system. Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Wed Oct 22 09:37:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2008 15:37:03 +0200 Subject: Ordering python sets References: <8f67b6f80810220522r49b0f588qf9d6001f62c080f0@mail.gmail.com> Message-ID: Tim Chase wrote: > Though for each test, in 2.3, 2.4, and 2.5 that I've got > installed on my local machine, they each printed "s" in-order, > and the iteration occurred in-order as well, even without the > added "sorted(list(s))" code. You need more tests then ;) >>> list(set([1,1000])) [1000, 1] By the way, sorted(s) is sufficient; sorted() accepts arbitrary iterables. Peter From castironpi at gmail.com Tue Oct 21 20:27:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 21 Oct 2008 17:27:46 -0700 (PDT) Subject: importing a class thru a variable? References: Message-ID: On Oct 21, 6:07?pm, john wrote: > Hi, > This is probably a question of questionable sanity, due to the fact I A question of questionable? Unacceptable. None of those, please. Yes, __import__ will do dynamics. Check your terminology. 'arguments that get passed to the class' doesn't evaluate right; classes don't have arguments. You might mean 'import a module', but modules don't take arguments either. You might mean 'import a factory function', which returns a class, which the language can do, but it didn't sound like it. From bearophileHUGS at lycos.com Thu Oct 2 21:15:59 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 2 Oct 2008 18:15:59 -0700 (PDT) Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> <6kernnF7dmkkU3@mid.uni-berlin.de> <00f2b28e$0$20617$c3e8da3@news.astraweb.com> <6kglc3F7fcvuU1@mid.uni-berlin.de> <6kh28kF7fcvuU2@mid.uni-berlin.de> <00f4d98c$0$20640$c3e8da3@news.astraweb.com> Message-ID: <4600661d-4514-4538-a39b-8c50504604db@t65g2000hsf.googlegroups.com> Steven D'Aprano: > With Python 3.0, GvR had the > opportunity to strip Python of all the features that makes Python easy to > learn, and he didn't. Python still has features that are easy for > newbies, and features that are powerful for experienced coders, and that > friendliness for newbies isn't going away. That's a good thing. I think that making range, dict.keys, dict.values, filter, map, etc, return lazy iterables GvR has made the language a little less easy to understand for newbies. What's a range(n)? A function that returns a list of n items, from 0 to n. This is easy to understand, while xrange(n) is a bit less easy to understand (a generator or generators). Python is growing toward being more fit for medium-large programs, and less fit for being small, simple and easy. Lua for example is now maybe better than Python if you need something light to script a large C++ program, so the niche partially left free by Python that has gone "up" is being partially replaced by Lua. Bye, bearophile From andy55 at gmail.com Fri Oct 24 10:40:52 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Fri, 24 Oct 2008 07:40:52 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> Message-ID: <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> On Oct 24, 2:12?am, greg wrote: > Andy wrote: > > 1) Independent interpreters (this is the easier one--and solved, in > > principle anyway, by PEP 3121, by Martin v. L?wis > > Something like that is necessary for independent interpreters, > but not sufficient. There are also all the built-in constants > and type objects to consider. Most of these are statically > allocated at the moment. > Agreed--I was just trying to speak generally. Or, put another way, there's no hope for independent interpreters without the likes of PEP 3121. Also, as Martin pointed out, there's the issue of module cleanup some guys here may underestimate (and I'm glad Martin pointed out the importance of it). Without the module cleanup, every time a dynamic library using python loads and unloads you've got leaks. This issue is a real problem for us since our software is loaded and unloaded many many times in a host app (iTunes, WMP, etc). I hadn't raised it here yet (and I don't want to turn the discussion to this), but lack of multiple load and unload support has been another painful issue that we didn't expect to encounter when we went with python. > > 2) Barriers to "free threading". ?As Jesse describes, this is simply > > just the GIL being in place, but of course it's there for a reason. > > It's there because (1) doesn't hold and there was never any specs/ > > guidance put forward about what should and shouldn't be done in multi- > > threaded apps > > No, it's there because it's necessary for acceptable performance > when multiple threads are running in one interpreter. Independent > interpreters wouldn't mean the absence of a GIL; it would only > mean each interpreter having its own GIL. > I see what you're saying, but let's note that what you're talking about at this point is an interpreter containing protection from the client level violating (supposed) direction put forth in python multithreaded guidelines. Glenn Linderman's post really gets at what's at hand here. It's really important to consider that it's not a given that python (or any framework) has to be designed against hazardous use. Again, I refer you to the diagrams and guidelines in the QuickTime API: http://developer.apple.com/technotes/tn/tn2125.html They tell you point-blank what you can and can't do, and it's that's simple. Their engineers can then simply create the implementation around those specs and not weigh any of the implementation down with sync mechanisms. I'm in the camp that simplicity and convention wins the day when it comes to an API. It's safe to say that software engineers expect and assume that a thread that doesn't have contact with other threads (except for explicit, controlled message/object passing) will run unhindered and safely, so I raise an eyebrow at the GIL (or any internal "helper" sync stuff) holding up an thread's performance when the app is designed to not need lower-level global locks. Anyway, let's talk about solutions. My company looking to support python dev community endeavor that allows the following: - an app makes N worker threads (using the OS) - each worker thread makes its own interpreter, pops scripts off a work queue, and manages exporting (and then importing) result data to other parts of the app. Generally, we're talking about CPU-bound work here. - each interpreter has the essentials (e.g. math support, string support, re support, and so on -- I realize this is open-ended, but work with me here). Let's guesstimate about what kind of work we're talking about here and if this is even in the realm of possibility. If we find that it *is* possible, let's figure out what level of work we're talking about. >From there, I can get serious about writing up a PEP/spec, paid support, and so on. Regards, Andy From pommereau at univ-paris12.fr Thu Oct 9 08:22:33 2008 From: pommereau at univ-paris12.fr (franck) Date: Thu, 9 Oct 2008 05:22:33 -0700 (PDT) Subject: Safe eval of insecure strings containing Python data structures? References: Message-ID: > I would like to parse arbitrary insecure text string containing nested > Python data structures in eval-compatible form: ? Python 2.6 has ast.literal_eval to do exactly this. It handle lists, tuples, dict, numbers, strings, bool and None, with arbitrary nesting. Cheers, Franck From patrickstinson.lists at gmail.com Wed Oct 29 03:27:01 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Tue, 28 Oct 2008 23:27:01 -0800 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <49021BD3.4020002@g.nevcal.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <49021BD3.4020002@g.nevcal.com> Message-ID: <6214d7a20810290027m3670d254v55486782c07733c4@mail.gmail.com> Wow, man. Excellent post. You want a job? The gui could use PyA threads for sure, and the audio thread could use PyC threads. It would not be a problem to limit the audio thread to only reentrant libraries. This kind of thought is what I had in mind about finding a compromise, especially in the way that PyD would not break old code assuming that it could eventually be ported. On Fri, Oct 24, 2008 at 11:02 AM, Glenn Linderman wrote: > On approximately 10/24/2008 8:42 AM, came the following characters from the > keyboard of Andy O'Meara: >> >> Glenn, great post and points! >> > > Thanks. I need to admit here that while I've got a fair bit of professional > programming experience, I'm quite new to Python -- I've not learned its > internals, nor even the full extent of its rich library. So I have some > questions that are partly about the goals of the applications being > discussed, partly about how Python is constructed, and partly about how the > library is constructed. I'm hoping to get a better understanding of all of > these; perhaps once a better understanding is achieved, limitations will be > understood, and maybe solutions be achievable. > > Let me define some speculative Python interpreters; I think the first is > today's Python: > > PyA: Has a GIL. PyA threads can run within a process; but are effectively > serialized to the places where the GIL is obtained/released. Needs the GIL > because that solves lots of problems with non-reentrant code (an example of > non-reentrant code, is code that uses global (C global, or C static) > variables ? note that I'm not talking about Python vars declared global... > they are only module global). In this model, non-reentrant code could > include pieces of the interpreter, and/or extension modules. > > PyB: No GIL. PyB threads acquire/release a lock around each reference to a > global variable (like "with" feature). Requires massive recoding of all code > that contains global variables. Reduces performance significantly by the > increased cost of obtaining and releasing locks. > > PyC: No locks. Instead, recoding is done to eliminate global variables > (interpreter requires a state structure to be passed in). Extension modules > that use globals are prohibited... this eliminates large portions of the > library, or requires massive recoding. PyC threads do not share data between > threads except by explicit interfaces. > > PyD: (A hybrid of PyA & PyC). The interpreter is recoded to eliminate global > variables, and each interpreter instance is provided a state structure. > There is still a GIL, however, because globals are potentially still used by > some modules. Code is added to detect use of global variables by a module, > or some contract is written whereby a module can be declared to be reentrant > and global-free. PyA threads will obtain the GIL as they would today. PyC > threads would be available to be created. PyC instances refuse to call > non-reentrant modules, but also need not obtain the GIL... PyC threads would > have limited module support initially, but over time, most modules can be > migrated to be reentrant and global-free, so they can be used by PyC > instances. Most 3rd-party libraries today are starting to care about > reentrancy anyway, because of the popularity of threads. > > The assumptions here are that: > > Data-1) A Python interpreter doesn't provide any mechanism to share normal > data among threads, they are independent... but message passing works. > Data-2) A Python interpreter could be extended to provide mechanisms to > share special data, and the data would come with an implicit lock. > Data-3) A Python interpreter could be extended to provide unlocked access to > special data, requiring the application to handle the synchronization > between threads. Data of type 2 could be used to control access to data of > type 3. This type of data could be large, or frequently referenced data, but > only by a single thread at a time, with major handoffs to a different thread > synchronized by the application in whatever way it chooses. > > Context-1) A Python interpreter would know about threads it spawns, and > could pass in a block of context (in addition to the state structure) as a > parameter to a new thread. That block of context would belong to the thread > as long as it exists, and return to the spawner when the thread completes. > An embedded interpreter would also be given a block of context (in addition > to the state structure). This would allow application context to be created > and passed around. Pointers to shared memory structures, might be typical > context in the embedded case. > > Context-2) Embedded Python interpreters could be spawned either as PyA > threads or PyC threads. PyC threads would be limited to modules that are > reentrant. > > > I think that PyB and PyC are the visions that people see, which argue > against implementing independent interpreters. PyB isn't truly independent, > because data are shared, recoding is required, and performance suffers. Ick. > PyC requires "recoding the whole library" potentially, if it is the only > solution. PyD allows access to the whole standard library of modules, > exactly like today, but the existing limitations still obtain for PyA > threads using that model ? very limited concurrency. But PyC threads would > execute in their own little environments, and not need locking. Pure Python > code would be immediately happy there. Properly coded (reentrant, > global-free) extensions would be happy there. Lots of work could be done > there, to use up multi-core/multi-CPU horsepower (shared-memory > architecture). > > Questions for people that know the Python internals: Is PyD possible? How > hard? Is a PyC thread an effective way of implementing a Python sandbox? If > it is, and if it would attract the attention of Brett Cannon, who at least > once wanted to do a thesis on Python sandboxes, he could be a helpful > supporter. > > Questions for Andy: is the type of work you want to do in independent > threads mostly pure Python? Or with libraries that you can control to some > extent? Are those libraries reentrant? Could they be made reentrant? How > much of the Python standard library would need to be available in reentrant > mode to provide useful functionality for those threads? I think you want PyC > > Questions for Patrick: So if you had a Python GUI using the whole standard > library -- would it likely runs fine in PyA threads, and still be able to > use PyC threads for the audio scripting language? Would it be a problem for > those threads to have limited library support (only reentrant modules)? > >> That's the rub... In our case, we're doing image and video >> manipulation--stuff not good to be messaging from address space to >> address space. The same argument holds for numerical processing with >> large data sets. The workers handing back huge data sets via >> messaging isn't very attractive. >> > > In the module multiprocessing environment could you not use shared memory, > then, for the large shared data items? > >> Our software runs in real time (so performance is paramount), >> interacts with other static libraries, depends on worker threads to >> perform real-time image manipulation, and leverages Windows and Mac OS >> API concepts and features. Python's performance hits have generally >> been a huge challenge with our animators because they often have to go >> back and massage their python code to improve execution performance. >> So, in short, there are many reasons why we use python as a part >> rather than a whole. >> >> The other area of pain that I mentioned in one of my other posts is >> that what we ship, above all, can't be flaky. The lack of module >> cleanup (intended to be addressed by PEP 3121), using a duplicate copy >> of the python dynamic lib, and namespace black magic to achieve >> independent interpreters are all examples that have made using python >> for us much more challenging and time-consuming then we ever >> anticipated. >> >> Again, if it turns out nothing can be done about our needs (which >> appears to be more and more like the case), I think it's important for >> everyone here to consider the points raised here in the last week. >> Moreover, realize that the python dev community really stands to gain >> from making python usable as a tool (rather than a monolith). This >> fact alone has caused lua to *rapidly* rise in popularity with >> software companies looking to embed a powerful, lightweight >> interpreter in their software. >> >> As a python language fan an enthusiast, don't let lua win! (I say >> this endearingly of course--I have the utmost respect for both >> communities and I only want to see CPython be an attractive pick when >> a company is looking to embed a language that won't intrude upon their >> app's design). >> > > Thanks for the further explanations. > > -- > Glenn -- http://nevcal.com/ > =========================== > A protocol is complete when there is nothing left to remove. > -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking > > -- > http://mail.python.org/mailman/listinfo/python-list > From mccarth.jack at gmail.com Wed Oct 15 14:47:44 2008 From: mccarth.jack at gmail.com (mccarth.jack at gmail.com) Date: Wed, 15 Oct 2008 11:47:44 -0700 (PDT) Subject: UICrawler Message-ID: <9638ef9f-f7cf-40e2-bb6d-8e293c483183@k30g2000hse.googlegroups.com> Hello all, I am trying to run the Universal information crawler wed spider on my mac. It seems to install without any trouble but when, in unix command line, I try to run "paster create --list-templates" it returns this Value Code error. I followed instructions provided at http://lucasmanual.com/mywiki/UICrawler. This is what comes up. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/Current/bin/ paster", line 8, in load_entry_point('PasteScript==1.6.3', 'console_scripts', 'paster') () File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/PasteScript-1.6.3-py2.6.egg/paste/script/ command.py", line 78, in run command = commands[command_name].load() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/setuptools-0.6c9-py2.6.egg/pkg_resources.py", line 1913, in load File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/PasteScript-1.6.3-py2.6.egg/paste/script/ create_distro.py", line 8, in import copydir File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/PasteScript-1.6.3-py2.6.egg/paste/script/ copydir.py", line 398, in class LaxTemplate(string.Template): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/string.py", line 119, in __init__ cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/re.py", line 188, in compile return _compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/re.py", line 236, in _compile raise ValueError('Cannot process flags argument with a compiled pattern') ValueError: Cannot process flags argument with a compiled pattern Has anyone else encountered this problem or have any suggestions as to what might be causing the problem? From clp at rebertia.com Wed Oct 8 20:50:37 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 8 Oct 2008 17:50:37 -0700 Subject: A question about funcation parameter and self defined object In-Reply-To: References: Message-ID: <47c890dc0810081750s6325251ewaaf5eaf698b9ee02@mail.gmail.com> On Wed, Oct 8, 2008 at 4:36 PM, Wei Guo wrote: > Hi, > > I defined a class called vec3 which contains x, y, z and in another > function, I tried to call a function which takes a vec3 as a parameter, but > it seems that parameter is passed as a generic object and I can not access x > , y, z in my vec3. Could anyone help me with that? Being dynamically typed, Python has no notion of variables having types, so the object isn't being "passed as a generic object", you're getting what really is a "generic object" value of type NoneType, which means the value of traV is indeed None, not vec3(). > > class vec3: > def __init__(self, x_ = 0.0, y_ = 0.0, z_ = 0.0): > self.x = x_ > self.y = y_ > self.z = z_ > class mat4: > def translation( traV = vec3() ): > tranM.rowLst[index][0] = traV.x > AttributeError: 'NoneType' object has no attribute 'x' This code is perfectly fine. See below. > > Could anyone help me how to turn the traV as type of vec3() instead of > NoneType object? That's not what's happening. It's not like traV is being cast to NoneType thus making x inaccessible, as that's not even possible to express in Python. What's happening is something is calling translation() with None as an argument, and of course None (the value the caller provided for traV) has no attribute 'x', hence the error. So, check the full exception traceback and see who's calling translation() and how the argument being passed to it got to be None. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks a lot, > > Wei > -- > http://mail.python.org/mailman/listinfo/python-list > > From prologic at shortcircuit.net.au Mon Oct 6 19:32:37 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 7 Oct 2008 09:32:37 +1000 Subject: HARD REAL TIME PYTHON In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380554720D@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380554720D@AWMAIL04.belcan.com> Message-ID: On Tue, Oct 7, 2008 at 9:25 AM, Blubaugh, David A. wrote: > close to real time constraints? For example is it possible to develop a > python program that can address an interrupt or execute an operation > within 70 Hz or less?? Are there any additional considerations that I > should investigate first regarding this matter?? Most event-driven frameworks should be capable of this kind of "real-time" performance. Indeed my own event/component framework (pymills) is capable of much more than 70Hz in terms of performance. $ python examples/event/bench.py -e 100000 Setting up Sender... Setting up Receiver... Total Events: 100005 (74663/s after 1.34s) If i'm not wrong this roughly equates to about 74 KHz I hope this helps. cheers James -- -- -- "Problems are solved by method" From sophacles at gmail.com Tue Oct 21 16:33:50 2008 From: sophacles at gmail.com (Erich) Date: Tue, 21 Oct 2008 13:33:50 -0700 (PDT) Subject: Commercial Products in Python References: Message-ID: <6d7d875a-bf78-4781-920c-0d03c0f48bb9@l64g2000hse.googlegroups.com> On Oct 21, 12:50 pm, "Paulo J. Matos" wrote: > Hi all, > > I was just wondering, if you wish to commercialize an application > developed in Python, what's the way to go? > I guess the only way is to sell the source, right? > If this application is a Windows app, and can use .Net, you may wish to look at how Resolver Systems [1] did it. Their products are written in IronPython, a python implementation for .Net. 1. http://www.resolversystems.com/products/ Regards, Erich From steve at holdenweb.com Tue Oct 28 09:56:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Oct 2008 09:56:11 -0400 Subject: [newbie] Right way to access item in array? In-Reply-To: <13qdg4l0httsobks0h26cvvdqgao39g1bq@4ax.com> References: <13qdg4l0httsobks0h26cvvdqgao39g1bq@4ax.com> Message-ID: Gilles Ganault wrote: > Hello > > I'd like to know what the right way is to access an item in a row as > returned by a database: > > ===== > import apsw > > connection=apsw.Connection("test.sqlite") > cursor=connection.cursor() > > rows=cursor.execute("SELECT isbn,price FROM books WHERE price IS > NULL") If you are dealing with a DB API-compliant module then the return value from the cursor's execute method is undefined, and you need to call one of the "fetch" methods to extract the retrieved data. So you would want something like cursor.execute("SELECT isbn,price FROM books WHERE price IS NULL") rows = cursor.fetchall() for isbn, price in rows: print isbn, ":", price Once you get that working you can do your own computations with isbn and price. Note, however, that the specific query you use guarantees that the value of "proce" will be None, since you only retrieve the rows where price is NULL! > for row in rows: > > #Is this right? > for isbn in row: > > if isbn: > print "Found price = " + price > > connection.close(True) > regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From hunterji at gmail.com Tue Oct 7 09:03:12 2008 From: hunterji at gmail.com (Hunter) Date: Tue, 7 Oct 2008 06:03:12 -0700 (PDT) Subject: SMTPlib inside function, extra tab Message-ID: <65a01382-33d2-4790-82b3-d9acdcc13b5f@w7g2000hsa.googlegroups.com> I am writing a script that needs to send some emails. And I've used smtplib in the past and it is pretty easy. But I thought, gee it would be easier if I could just call it as a function, passing the from, to, subject, and message text. So I wrote it up as a function and it sort of works, but I get a weird error. When it runs it inserts a "\t" tab character before each item during the send portion (which I can see when I turn on debug). The end result is that I don't get any body or subject in my emails. It works fine when I copy the inside of the function and run it directly. It isn't a dealbreaker, I can certainly just call it direct, but from a learning Python perspective I'm wondering if anyone knows what exactly is happening. I'm more interested in the why this is happening than a solution (though that would be great too). Oh and if you could explain it to me, with no CS background, that would be even better. I am working on Windows Vista with Python 2.5.2 (activestate). Thanks --Joshua Snip of script (more or less a copy/paste from effbot): fromaddress = 'automation at mydomain.com' tolist = ['it at mydomain.com','jhunter at mydomain.com'] msgsubj = "Hello!" messagebody = "This message was sent with Python's smtplib." def send_mail(fromaddress,tolist,msgsubj,messagebody): import smtplib SERVER = "mymailserver.mydomain.com" message = """\ From: %s To: %s Subject: %s %s """ % (fromaddress, ", ".join(tolist),msgsubj, messagebody) print message server = smtplib.SMTP(SERVER) server.set_debuglevel(1) server.sendmail(fromaddress, tolist, message) server.quit() send_mail(fromaddress, tolist, msgsubj, messagebody) Output when called from function: send: 'ehlo twaus-mycomputer.mydomain.local\r\n' reply: '250-mymailserver.mydomain.com Hello [10.10.10.119]\r\n' reply: '250-TURN\r\n' reply: '250-SIZE\r\n' reply: '250-ETRN\r\n' reply: '250-PIPELINING\r\n' reply: '250-DSN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-8bitmime\r\n' reply: '250-BINARYMIME\r\n' reply: '250-CHUNKING\r\n' reply: '250-VRFY\r\n' reply: '250-X-EXPS GSSAPI NTLM LOGIN\r\n' reply: '250-X-EXPS=LOGIN\r\n' reply: '250-AUTH GSSAPI NTLM LOGIN\r\n' reply: '250-AUTH=LOGIN\r\n' reply: '250-X-LINK2STATE\r\n' reply: '250-XEXCH50\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: mymailserver.mydomain.com Hello [10.10.10.119] TURN SIZE ETRN PIPELINING DSN ENHANCEDSTATUSCODES 8bitmime BINARYMIME CHUNKING VRFY X-EXPS GSSAPI NTLM LOGIN X-EXPS=LOGIN AUTH GSSAPI NTLM LOGIN AUTH=LOGIN X-LINK2STATE XEXCH50 OK send: 'mail FROM: size=159\r\n' reply: '250 2.1.0 automation at mydomain.com....Sender OK\r\n' reply: retcode (250); Msg: 2.1.0 automation at mydomain.com....Sender OK send: 'rcpt TO:\r\n' reply: '250 2.1.5 it at mydomain.com \r\n' reply: retcode (250); Msg: 2.1.5 it at mydomain.com send: 'rcpt TO:\r\n' reply: '250 2.1.5 jhunter at mydomain.com \r\n' reply: retcode (250); Msg: 2.1.5 jhunter at mydomain.com send: 'data\r\n' reply: '354 Start mail input; end with .\r\n' reply: retcode (354); Msg: Start mail input; end with . data: (354, 'Start mail input; end with .') send: "\tFrom: automation at mydomain.com\r\n\tTo: it at mydomain.com, j hunter at mydomain.com\r\n\tSubject: Hello!\r\n\tThis message was sent with Python's smtplib.\r\n\t\r\n.\r\n" reply: '250 2.6.0 Queued mail for delivery\r\n' reply: retcode (250); Msg: 2.6.0 Queued mail for delivery data: (250, '2.6.0 Queued mail for delivery') send: 'quit\r\n' reply: '221 2.0.0 mymailserver.mydomain.com Service closing transmission channel\r\n' reply: retcode (221); Msg: 2.0.0 mymailserver.mydomain.com Service closin g transmission channel From: automation at mydomain.com To: it at mydomain.com, jhunter at mydomain.com Subject: Hello! This message was sent with Python's smtplib. Output if you just run the internal part of the function directly: send: 'ehlo twaus-mycomputer.mydomain.local\r\n' reply: '250-mymailserver.mydomain.com Hello [10.10.10.119]\r\n' reply: '250-TURN\r\n' reply: '250-SIZE\r\n' reply: '250-ETRN\r\n' reply: '250-PIPELINING\r\n' reply: '250-DSN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-8bitmime\r\n' reply: '250-BINARYMIME\r\n' reply: '250-CHUNKING\r\n' reply: '250-VRFY\r\n' reply: '250-X-EXPS GSSAPI NTLM LOGIN\r\n' reply: '250-X-EXPS=LOGIN\r\n' reply: '250-AUTH GSSAPI NTLM LOGIN\r\n' reply: '250-AUTH=LOGIN\r\n' reply: '250-X-LINK2STATE\r\n' reply: '250-XEXCH50\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: mymailserver.mydomain.com Hello [10.10.10.119] TURN SIZE ETRN PIPELINING DSN ENHANCEDSTATUSCODES 8bitmime BINARYMIME CHUNKING VRFY X-EXPS GSSAPI NTLM LOGIN X-EXPS=LOGIN AUTH GSSAPI NTLM LOGIN AUTH=LOGIN X-LINK2STATE XEXCH50 OK send: 'mail FROM: size=154\r\n' reply: '250 2.1.0 automation at mydomain.com....Sender OK\r\n' reply: retcode (250); Msg: 2.1.0 automation at mydomain.com....Sender OK send: 'rcpt TO:\r\n' reply: '250 2.1.5 it at mydomain.com \r\n' reply: retcode (250); Msg: 2.1.5 it at mydomain.com send: 'rcpt TO:\r\n' reply: '250 2.1.5 jhunter at mydomain.com \r\n' reply: retcode (250); Msg: 2.1.5 jhunter at mydomain.com send: 'data\r\n' reply: '354 Start mail input; end with .\r\n' reply: retcode (354); Msg: Start mail input; end with . data: (354, 'Start mail input; end with .') send: "From: automation at mydomain.com\r\nTo: it at mydomain.com, jhunt er at mydomain.com\r\nSubject: Hello!\r\nThis message was sent with Python's smtplib.\r\n.\r\n" reply: '250 2.6.0 Queued mail for delivery\r\n' reply: retcode (250); Msg: 2.6.0 Queued mail for delivery data: (250, '2.6.0 Queued mail for delivery') send: 'quit\r\n' reply: '221 2.0.0 mymailserver.mydomain.com Service closing transmission channel\r\n' reply: retcode (221); Msg: 2.0.0 mymailserver.mydomain.com Service closin g transmission channel From prologic at shortcircuit.net.au Thu Oct 9 00:32:53 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 9 Oct 2008 14:32:53 +1000 Subject: Safe eval of insecure strings containing Python data structures? In-Reply-To: <896B75251BA19745A529B1B867893FA505351D@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA505351D@planet.delsci.local> Message-ID: On Thu, Oct 9, 2008 at 2:26 PM, Warren DeLano wrote: > JSON rocks! Thanks everyone. Yes it does :) > Ben wrote: > >>More generally, you should never execute (via eval, exec, or whatever) >>*any* instruction from an untrusted path; especially not arbitrary >>data from an input stream. I second this. > Wow, for the record, I completely disagree with this point of view: > Today's web apps wouldn't exist without safe forms of untrusted eval/exec > (Javascript anyone?). Such dogma is appropriate when dealing with the > CPython VM, but not as a general principle. It's far better to use Data Structures rather than Programming Constructs to represent and transmit your data. > "Rocket fuel may be dangerous, but you ain't shooting the moon without it!" Do we trust fuel from untrusted sources ? cheers James -- -- -- "Problems are solved by method" From sjmachin at lexicon.net Sun Oct 19 06:17:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 19 Oct 2008 03:17:51 -0700 (PDT) Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> <010aa307$0$20653$c3e8da3@news.astraweb.com> <7accf6cb-06b4-4db1-ba76-b3965eb3528e@i18g2000prf.googlegroups.com> <010ae139$0$20653$c3e8da3@news.astraweb.com> Message-ID: <4f1908c0-ff38-4224-a13a-901309e9025f@p10g2000prf.googlegroups.com> Steven D'Aprano wrote: > On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote: > > > On Oct 19, 2:30?pm, Steven D'Aprano > cybersource.com.au> wrote: > > [snip] > >> making your code easy to read and easy to maintain is far more > >> important. > >> > >> for x in (2**i for i in xrange(10)): > >> ? ? print x > >> > >> will also print 1, 2, 4, 8, ... up to 1000. > > > > I would say up to 512; perhaps your understanding of "up to" differs > > from mine. > > Well, mine is based on Python's half-open semantics: "up to" 1000 doesn't > include 1000, and the highest power of 2 less than 1000 is 512. We're talking about an English sentence, not a piece of Python code. When you say "I'm taking the train to X", do you get off at the station before X, as in "getting off at Redfern"? > > Perhaps you meant "up to and including 512". > From bearophileHUGS at lycos.com Thu Oct 16 05:43:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 16 Oct 2008 02:43:30 -0700 (PDT) Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <01006451$0$20646$c3e8da3@news.astraweb.com> <74643cb4-c42c-4195-8f81-ba040a2d51a7@s1g2000prg.googlegroups.com> Message-ID: <717fd279-d1c6-4790-89c7-c6119f478d91@k37g2000hsf.googlegroups.com> Chris Rebert: > Although primitive and likely somewhat flawed, you may find the > statistics in the "Compatibility Issues" section ofhttp://mail.python.org/pipermail/python-3000/2007-February/005704.html > to be of interest. I am quite glad to see that I am not the only one that cares for such topic. And I think Guido is wrong here, but I can also see there's little hope in fixing this Python wart. We'll probably have to see and use another language to see this problem/bug fixed in some way (and maybe other issues added, no language is perfect). Python is now mature, being 15+ years old, so it's also rigid. Computer languages, just like living species, resist change, and usually you need a new language/species to fix some larger warts/bugs/design problems. Python3 fixes tons of problems of Python2.x, but it's almost a new language :-) Bye, bearophile From drobinow at gmail.com Thu Oct 23 15:58:06 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Thu, 23 Oct 2008 12:58:06 -0700 (PDT) Subject: why would 'import win32com' fail? References: Message-ID: <3856362e-2ed5-499e-b50d-ce58a7756fc5@m36g2000hse.googlegroups.com> On Oct 23, 3:21?pm, bill wrote: > All, > > I am trying to access Excel from Python. Many of the examples started > with: > > ? ? ? import win32com > ? ? ? .... > ? ? ? blah, blah > > I try that from my Python shell and it fails. What am I missing here? You need to download and install the Python Extensions for Windows. http://sourceforge.net/project/showfiles.php?group_id=78018 From matt at tplus1.com Fri Oct 17 12:19:41 2008 From: matt at tplus1.com (Matthew Wilson) Date: Fri, 17 Oct 2008 16:19:41 GMT Subject: Need advice on python importing Message-ID: I started with a module with a bunch of classes that represent database tables. A lot of these classes have methods that use other classes inside, sort of like this: class C(object): @classmethod def c1(cls, a): return a class D(object): def d1(self, a): return a + C.c1(a) Notice how the d1 method on class D uses a classmethod c1 on C. C is in the same module, so it's globally available. I moved my classes C and D into different files, and then I noticed that D now needed to import C first. That worked fine until I wrote interdependent classes that couldn't import each other. So I passed in everything as parameters like this: def d1(self, C, a): That works fine, but now I've got some methods that have six parameters (or more) that are entirely just for this purpose. So, now instead of passing these in as parameters, I'm passing them into my initializer and binding them in to self. I wanted to use functools.partial to bind on these parameters like this: d1 = functools.partial(d1, C=C) But partial objects don't get the self parameter passed in, so using partial is is effectively similar to decorating methods with staticmethod. Here's a link to the documentation on partial that explains this: http://www.python.org/doc/2.5.2/lib/partial-objects.html So, partials won't work. I suspect that there's more elegant solutions for this. All thoughts are welcome. From tjreedy at udel.edu Wed Oct 8 14:18:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 08 Oct 2008 14:18:34 -0400 Subject: Upgrading an instance to a subclass In-Reply-To: References: Message-ID: Antoon Pardon wrote: > I have a subclass of socket. > > class Mysocket (socket): > ... > > But when I use the python library it will of course > just return an instance of socket, like the SocketServer > module. > > So now I was wondering if it is somehow possible to > turn this instance into a Mysocket instance, either > by somehow changing the original instance Instances of Python-coded classes can usually have __class__ changed. But not for builtin, C-coded classes, which I assume > or producing > a new instance that represents the same connection. Given that socket appears to be immutable, I believe Mysocket would need a __new__ method that called socket.__new__. But I have never worked with __new__ functions. From skip at pobox.com Mon Oct 13 13:43:13 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 13 Oct 2008 12:43:13 -0500 Subject: docpicture In-Reply-To: <010374c5$0$20641$c3e8da3@news.astraweb.com> References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> <010374c5$0$20641$c3e8da3@news.astraweb.com> Message-ID: <18675.34993.962044.115182@montanaro-dyndns-org.local> Steven> I can't imagine Python having direct syntactic support for it, Steven> but I don't see any reason why the standard library couldn't Steven> some day grow a "docpicture" module, complete with a tiny (?) Steven> Tkinter app to display the diagram when requested. Heck, if you go to the point of including a docpicture module, might as well just support the feature in IDLE... Other IDEs would probably pick up the feature as well. Skip From msh at blisses.org Fri Oct 17 18:37:07 2008 From: msh at blisses.org (Matt Herzog) Date: Fri, 17 Oct 2008 18:37:07 -0400 Subject: chomp? Message-ID: <20081017223707.GI21544@chicago.blisses.org> Hey Pythons. This script works fine except I would like it to NOT print everything on a newline. How can I tell print to chomp? Thanks. ------------------------------- snip --------------------------------------------- #!/usr/bin/python import time import sys def getload(): f = open('/proc/loadavg') data = f.readline() f.close() (load1, load2, load3, extra) = data.split(' ',3) return float(load1) done = False while not done: while getload() < 3: print getload() time.sleep(3) # we left the loop! print "Ouch! My CPUs are roasting! time.sleep(3) -- "'My country, right or wrong,' is a thing that no patriot would think of saying. It is like saying, 'My mother, drunk or sober.'" -- G.K. Chesterton From smullen.uclick at gmail.com Tue Oct 21 14:44:51 2008 From: smullen.uclick at gmail.com (smullen.uclick at gmail.com) Date: Tue, 21 Oct 2008 11:44:51 -0700 (PDT) Subject: Resizing Tif's to smaller gifs adds pixels Message-ID: <1fc506d8-2f1e-4f80-b0ee-05fc5f3bf90a@v30g2000hsa.googlegroups.com> I'm not entirely sure how this group works: if there is a page I'm supposed to follow up on or if I should expect an email in reply. Anyway, here's my question. I'm very new to Python and PIL, I know how to do this stuff in perl and ImageMagick, but I'm having issues with Python and PIL. I need to scale a TIFF image from 1925x588 px to a GIF of 600xnnn px. I've tried the following code, but it leads to a lot of extra odd colored pixels being inserted into the resulting image. img = "tmp/tmsho20080901.tif" im = Image.open("tmp/tmsho20080901.tif") w, h = im.size im.thumbnail((600, h * 600 / w), Image.ANTIALIAS) newimg = im.resize((600, int(h * (600.0 / w))), Image.ANTIALIAS) newimg.save("tmsho20080901.gif") Using ImageMagick's convert I would do this... convert -colors 256 -resize 600 -colorspace RGB -black-threshold 100 - contrast -intent Perceptual tmp/tmsho20080901.tif tmsho20080901.gif I think it may have something to do with the palette or the number of colors alotted for the resulting image, but I'm really not a graphics guy. Any help on this would be appreciated. Samuel From marco.mechi at gmail.com Tue Oct 14 06:03:52 2008 From: marco.mechi at gmail.com (MM) Date: Tue, 14 Oct 2008 03:03:52 -0700 (PDT) Subject: [NEWBIE] csv to excel format problem Message-ID: Hi to all, I'm trying to import a tab separated values file onto Excel with the following script: import csv from pyExcelerator import * w = Workbook() worksheet = w.add_sheet('sim1') def writeExcelRow(worksheet, lno, columns): style = XFStyle() style.num_format_str = '0.00E+00' cno = 0 for column in columns: worksheet.write(lno, cno, column,style) cno = cno + 1 nrow = 0 csvfile = file('res1.txt','r') csvreader = csv.reader(csvfile, delimiter='\t') for line in csvreader: writeExcelRow(worksheet,nrow,line) nrow += 1 csvfile.close() w.save('numbers.xls') All goes well and the resulting file "numbers.xls" has all the numbers in the right place.... The problem is that excel sees the numbers as text and gives the error "numbers stored as text" that I have to correct manually. The file res1.txt has the structure of a tab separated values of floating point numbers. Thank you for the help. Marco From martin at v.loewis.de Wed Oct 15 18:44:04 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Oct 2008 00:44:04 +0200 Subject: memory use with regard to large pickle files In-Reply-To: References: Message-ID: <48f67234$0$6235$9b622d9e@news.freenet.de> > The program works fine, but the memory load is huge. The size of > the pickle file on disk is about 900 Meg so I would theoretically > expect my program to consume about twice that (the dictionary > contained in the pickle file plus its repackaging into other formats), > but instead my program needs almost 5 Gig of memory to run. > Am I being unrealistic in my memory expectations? I would say so, yes. As you use 5GiB of memory, it seems you are running a 64-bit system. On such a system, each pointer takes 8 bytes. In addition, each object takes at least 16 bytes; if it's variable-sized, it takes at least 24 bytes, plus the actual data in the object. OTOH, in a pickle, a pointer takes no space, unless it's a shared pointer (i.e. backwards reference), which takes as many digits as you need to encode the "object number" in the pickle. Each primitive object takes only a single byte overhead (as opposed to 24), causing quite drastic space reductions. Of course, non-primitive objects take more, as they need to encode the class they are instances of. > Is there a way to see how much memory is being consumed > by a single data structure or variable? How can I go about > debugging this problem? In Python 2.6, there is the sys.getsizeof function. For earlier versions, the asizeof package gives similar results. Regards, Martin From ojbaconstartle at gmail.com Mon Oct 20 23:13:26 2008 From: ojbaconstartle at gmail.com (ojbaconstartle at gmail.com) Date: Mon, 20 Oct 2008 20:13:26 -0700 (PDT) Subject: preteen porn - Free Video Message-ID: <4884443b-7241-4090-b97b-0f4a4421d98a@m74g2000hsh.googlegroups.com> preteen porn . . . *******CLICK HERE******** http://vids247.cn/preteen-porn ***************************** . . . . . . . . . . . . preteen porn From sjmachin at lexicon.net Wed Oct 22 16:48:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 22 Oct 2008 13:48:33 -0700 (PDT) Subject: Using python22.dll with Python 2.5? References: <6m8ovbFfnd9nU1@mid.individual.net> Message-ID: On Oct 23, 12:43?am, Martin Schneider wrote: > Hi! > > I'd like to use the numpy library (which runs on Python 2.5) in the same > project with another (mandatory) library which needs python22.dll. When > I try to compile I get an error similar to "python22.dll not compatible > with the current Python version." > > Has anybody an idea how to solve this? > Tell us what barriers you think you face that prevent you compiling the (presumably C) source of the "another (mandatory) library which needs python22.dll" so that it will run with Python 2.x (x > 2) ... someone may be able to help you. From code at pizzashack.org Tue Oct 28 13:13:18 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 28 Oct 2008 13:13:18 -0400 Subject: Python suitable for Midi ? In-Reply-To: <8200bab70810280954l79e0f1a1icfc0308ebdc5c61@mail.gmail.com> References: <8200bab70810280954l79e0f1a1icfc0308ebdc5c61@mail.gmail.com> Message-ID: <20081028171318.GF14111@dragontoe.org> On Tue, Oct 28, 2008 at 06:54:57PM +0200, Chuckk Hubbard wrote: > The problem I've run into is that I can't set the audio to a higher > priority than the GUI (Tkinter). If I move the mouse over the app, no > matter what, I get audio dropouts. AFAICT this is the same for all > Python, regardless of what modules one uses: you can't assign system > priorities to different threads. If you're planning to pipe MIDI to > another app for playback, maybe it won't be an issue for you. FWIW... You could take your own advice, and devide your application in two: one process manages the GUI, and the second is a back-end process that plays the MIDI. Your GUI can even launch the back end, which will inherit the priority of the GUI, after which the GUI can reduce its own priority (the priority of the back end will not be affected by the change)... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gdyren at gmail.com Fri Oct 17 07:26:52 2008 From: gdyren at gmail.com (gdyren at gmail.com) Date: Fri, 17 Oct 2008 04:26:52 -0700 (PDT) Subject: no mistake but i didnt get what i want (with python module pymssql send information to the mssql) References: <4bff370e-7f72-4adc-a042-2823fdc9365e@u27g2000pro.googlegroups.com> Message-ID: <0dc98a3c-3539-4090-8520-acd9cfa8bada@a3g2000prm.googlegroups.com> On 10?17?, ??6?41?, Peter Otten <__pete... at web.de> wrote: > gdy... at gmail.com wrote: > > the code is below: > > import pymssql > > conn = pymssql.connect(host = "121.198.126.233",user = "xxxx",password > > = "xxxx",database = "test") > > print "connecting success" > > cursor = conn.cursor() > > cursor.execute("insert into bbs_test values(%s,%s,%s,%s,%s)", > > ("1","nju","9:13","ustc","test")) > > cursor.close() > > conn.close() > > in the idle: > > connecting success > > > then i get into the database :test and find that there is nothing in > > the table bbs_test. > > i don't know why > > Because you did not commit your changes with conn.commit(). > > Peter- ??????? - > > - ??????? - ???how to. From joe at strout.net Tue Oct 28 21:05:33 2008 From: joe at strout.net (Joe Strout) Date: Tue, 28 Oct 2008 19:05:33 -0600 Subject: How to get an object's name as a string? In-Reply-To: <4907B553.9010102@holdenweb.com> References: <9dc6f89d-4f85-402f-8191-21158597445d@c36g2000prc.googlegroups.com> <01178ed7$0$20630$c3e8da3@news.astraweb.com> <4907B553.9010102@holdenweb.com> Message-ID: <02182D1C-E673-48DF-99FE-39C03B23A1B2@strout.net> On Oct 28, 2008, at 6:58 PM, Steve Holden wrote: > Objects in Python *don't* have names. Period. In Python we don't > normally talk about variables anyway, except when speaking loosely, we > talk about binding names. But please don't let this start another > round > of "Python programmers don't know how to describe the language". You > have already made your opinions on that score more than clear. As have I, I suppose, and I'll try to quit engaging in that argument in the future. > l = [] > l.append(l) > del l > > What's the name of the list formerly known as "l"? Hey, that's a very nice little demonstration of an orphaned object. Thanks for sharing it! Best, - Joe From steve at REMOVE-THIS-cybersource.com.au Mon Oct 27 18:55:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Oct 2008 22:55:01 GMT Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> Message-ID: <01163fa5$0$20637$c3e8da3@news.astraweb.com> On Mon, 27 Oct 2008 13:11:04 -0600, Joe Strout wrote: > On Oct 27, 2008, at 12:19 PM, gooberts at gmail.com wrote: > >> I think this "uncontrived" example addresses the C/Python difference >> fairly directly (both were tested): > > That's correct, but of course, C is a decades-old language barely a step > above assembler. So what? It's not like C is no longer in common use. And even if C had disappeared off the landscape, there are millions of programmers, including beginning programmers, whose understanding of terms CBR and CBV are defined by the behaviour of languages like C and Pascal -- even if they haven't learned either language themselves. > For a fair comparison, pick any modern OOP language, > including the C derivatives (C++, Objective-C, Java), and compare a > Python object to an object in that language, rather than to a struct. But we already know that many such languages use the exact same calling convention as Python, so all you would be showing is that languages with the same calling convention as Python have the same calling convention as Python. By common usage and technical definition, C is call by value. Argument passing in Python does not behave like C. So why insist that Python is also call by value? [snip] >> While yes, technically, it is true that those reference values must be >> stored somewhere in memory, *that* is the implementation detail. > > Agreed. (And this was my point in response to someone arguing that no > such location exists.) Obviously any computer which is based on the Von Newman architecture of CPU plus memory is going to store the reference *somewhere*. That's a detail unimportant at the Python level. But since clockwork or Conway's "Life" cellular automata are both Turing complete, it would be possible to build a Python implementation where the reference values weren't localised to a particular place in memory, but distributed over the system. >> But is is not the *locations* of these references (i.e., the locations >> of the Python *variables*) that are copied around, it is the references >> themselves (the locations of the Python *objects*) that are copied. > > Right. The variables contain object references; these object references > are copied (not referenced!) when you pass them into a function. That's > call by value. In the case of an assignment, the reference is copied. The value of a Python name is the Python object assigned to it, not an arbitrary memory location that points to the object. Even you would consider it obfuscatory if I executed this code: x = "Norwegian Blue" and then insisted that the value of x was "3086179808L, but if I run that line of code again it could get another value, and naturally if you run it on your computer you're almost certain to get a different value". By your definition of "value=reference", the above is perfectly correct, and utterly, completely pointless, useless and unhelpful. It's rather like listing the ingredients of a cake as "Atoms". Technically true, but missing the point. [snip] > You are copying the object reference right onto the call stack. This is > pass by value, plain and simple. Who *cares* about copying the pointers? That's the WRONG LEVEL. Ultimately EVERY programming language that runs on a computer with memory is "Copy By Bit Flipping", but it would be useless and unhelpful to tell people that every programming language uses the exact same calling conventions: "bits are flipped, and that's the end of story". [snip] > No Python method can do that, because Python arguments are ALWAYS passed > by value. There is no call by reference in Python. Except that for millions of programmers who have learnt their terminology from Pascal and C, that implies that the values -- the data itself, not pointers to the data -- are copied. It implies that this can never fail: x = [1] y = function(x) assert x == [1] but of course it can fail, if function modifies x -- something which CBV implies can't happen. > Period, end of story, nothing to see here. I think that this entire argument hinges on the poverty of your mental toolbox. You have a hammer (call by value) and a screwdriver (call by reference) and refuse to accept that there could possibly be any other calling model. Hence you force any actual calling model into the framework of CBV or CBR, no matter how much violence you have to do to simple terms like "value" to make it fit. -- Steven From http Sat Oct 25 12:07:12 2008 From: http (Paul Rubin) Date: 25 Oct 2008 09:07:12 -0700 Subject: set/dict comp in Py2.6 References: <28b0fe12-9a82-4d14-b3fa-3cd203000ba0@l77g2000hse.googlegroups.com> Message-ID: <7xej24k6a7.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > {x*x for x in xrange(10)} > {x:x*x for x in xrange(10)} I've always just used: set(x*x for x in xrange(10)) dict((x,x*x) for x in xrange(10)) I didn't even realize that you could write sets with {...}. From andy55 at gmail.com Thu Oct 30 13:54:14 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Thu, 30 Oct 2008 10:54:14 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <16acff7d-e3a4-4be0-a042-e74845501cb3@k16g2000hsf.googlegroups.com> <49057647$0$26690$9b622d9e@news.freenet.de> <49078e11$0$8568$9b622d9e@news.freenet.de> <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> Message-ID: On Oct 30, 1:00?pm, "Jesse Noller" wrote: > > Multiprocessing is written in C, so as for the "less agile" - I don't > see how it's any less agile then what you've talked about. Sorry for not being more specific there, but by "less agile" I meant that an app's codebase is less agile if python is an absolute requirement. If I was told tomorrow that for some reason we had to drop python and go with something else, it's my job to have chosen a codebase path/roadmap such that my response back isn't just "well, we're screwed then." Consider modern PC games. They have huge code bases that use DirectX and OpenGL and having a roadmap of flexibility is paramount so packages they choose to use are used in a contained and hedged fashion. It's a survival tactic for a company not to entrench themselves in a package or technology if they don't have to (and that's what I keep trying to raise in the thread--that the python dev community should embrace development that makes python a leading candidate for lightweight use). Companies want to build a flexible, powerful codebases that are married to as few components as possible. > > > - Shared memory -- for the reasons listed in my other posts, IPC or a > > shared/mapped memory region doesn't work for our situation (and I > > venture to say, for many real world situations otherwise you'd see end- > > user/common apps use forking more often than threading). > > I would argue that the reason most people use threads as opposed to > processes is simply based on "ease of use and entry" (which is ironic, > given how many problems it causes). No, we're in agreement here -- I was just trying to offer a more detailed explanation of "ease of use". It's "easy" because memory is shared and no IPC, serialization, or special allocator code is required. And as we both agree, it's far from "easy" once those threads to interact with each other. But again, my goal here is to stay on the "embarrassingly easy" parallelization scenarios. > > I would argue that most of the people taking part in this discussion > are working on "real world" applications - sure, multiprocessing as it > exists today, right now - may not support your use case, but it was > evaluated to fit *many* use cases. And as I've mentioned, it's a totally great endeavor to be super proud of. That suite of functionality alone opens some *huge* doors for python and I hope folks that use it appreciate how much time and thought that undoubtably had to go into it. You get total props, for sure, and you're work is a huge and unique credit to the community. > > Please correct me if I am wrong in understanding what you want: You > are making threads in another language (not via the threading API), > embed python in those threads, but you want to be able to share > objects/state between those threads, and independent interpreters. You > want to be able to pass state from one interpreter to another via > shared memory (e.g. pointers/contexts/etc). > > Example: > > ParentAppFoo makes 10 threads (in C) > Each thread gets an itty bitty python interpreter > ParentAppFoo gets a object(video) to render > Rather then marshal that object, you pass a pointer to the object to > the children > You want to pass that pointer to an existing, or newly created itty > bitty python interpreter for mangling > Itty bitty python interpreter passes the object back to a C module via > a pointer/context > > If the above is wrong, I think possible outlining it in the above form > may help people conceptualize it - I really don't think you're talking > about python-level processes or threads. > Yeah, you have it right-on there, with added fact that the C and python execution (and data access) are highly intertwined (so getting and releasing the GIL would have to be happening all over). For example, consider and the dynamics, logic, algorithms, and data structures associated with image and video effects and image and video image recognition/analysis. Andy From Bruno at hi.t-com.hr Wed Oct 8 13:49:12 2008 From: Bruno at hi.t-com.hr (Bruno) Date: Wed, 08 Oct 2008 19:49:12 +0200 Subject: utf-8 read/write file Message-ID: Hi! I have big .txt file which i want to read, process and write to another .txt file. I have done script for that, but im having problem with croatian characters (?,?,?,?,?). How can I read/write from/to file in utf-8 encoding? I read file with fileinput.input. thanks From oliphant at enthought.com Wed Oct 1 11:10:45 2008 From: oliphant at enthought.com (Travis E. Oliphant) Date: Wed, 01 Oct 2008 10:10:45 -0500 Subject: Texas Python Regional Unconference Reminders In-Reply-To: <0107962E-D762-497B-BCEC-24CBD78B381B@enthought.com> References: <0107962E-D762-497B-BCEC-24CBD78B381B@enthought.com> Message-ID: <48E392F5.3050809@enthought.com> Travis Vaught wrote: > Greetings, > > The Texas Python Regional Unconference is coming up this weekend > (October 4-5) and I wanted to send out some more details of the > meeting. The web page for the meeting is here: > > http://www.scipy.org/TXUncon2008 > > The meeting is _absolutely free_, so please add yourself to the > Attendees page if you're able to make it. Also, if you're planning to > attend, please send me the following information (to > travis at enthought.com) so I can request wireless access for you during > the meeting: > > - Full Name > - Phone or email > - Address > - Affiliation Travis E. Oliphant 1-512-826-7480 515 Congress Ave, Suite 2100 Enthought, Inc. From enleverlesX.XmcX at XmclaveauX.com Fri Oct 17 13:13:24 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 17 Oct 2008 19:13:24 +0200 Subject: [ANN] Data Plotting Library DISLIN 9.4 In-Reply-To: References: <48f61a3f$0$925$ba4acef3@news.orange.fr> Message-ID: <48f8c996$0$885$ba4acef3@news.orange.fr> Merci beaucoup. Thanks. From steve at REMOVE-THIS-cybersource.com.au Wed Oct 29 18:58:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Oct 2008 22:58:14 GMT Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <0118e356$0$20671$c3e8da3@news.astraweb.com> On Wed, 29 Oct 2008 08:27:07 -0700, Dale Roberts wrote: > On Oct 28, 11:59?am, Joe Strout wrote: >> ... >> >> There are only the two cases, which Greg quite succinctly and >> accurately described above. ?One is by value, the other is by >> reference. ?Python quite clearly uses by value. ?Parameters are >> expressions that are evaluated, and the resulting value copied into the >> formal parameter, pure and simple. ?The continued attempts to obfuscate >> this is pointless and wrong. >> >> Best, >> - Joe > > Joe, you are being too generous and expansive here. > > [Play along with me for a minute here...] > > Don't you know? There is really only *ONE* case, and, you are right, it > is Pass By Value. There is no such thing as Pass By Reference at the > physical CPU level at all, right? If there is, show it to me. Pass By > Reference is just a silly idiom developed by high-minded CS academics to > confuse the rest of us. It has no practical use and should not be given > its own name, when we already have a good an proper name for it. [snip] But Dale, you're wrong. At the physical CPU level, there's no copying of bits at all. If we could copy bits, then we could start with 512MB of RAM and say "copy all the bits" and end up with 1GB of RAM. So-called copying is actually just bit-flipping. So anyone who talks about copying parameters is talking nonsense. There is no "pass by value". It's all pass by bit-flipping. -- Steven From mark.dufour at gmail.com Wed Oct 1 06:10:43 2008 From: mark.dufour at gmail.com (srepmub) Date: Wed, 1 Oct 2008 03:10:43 -0700 (PDT) Subject: Shed Skin (restricted) Python-to-C++ compiler 0.0.29 References: <6ccb7642-2df8-45ee-b304-74c92d520e0e@d31g2000hsg.googlegroups.com> Message-ID: > Not to sound negative, but what's with the 0.0.x version numbers ? > Maybe it's just me, but seeing a zero major/minor version give me the > impression of experimental/pre-alpha project, which (from my very > limited knowledge) doesn't do justice to shedskin's current state. I know of too many bugs to be comfortable calling it 0.1 just yet.. And I really want to improve extension module support (as mentioned) first. There's not much else holding back a 0.1 release. Thanks, Mark. From akean at paradise.net.nz Tue Oct 14 18:17:16 2008 From: akean at paradise.net.nz (Anita Kean) Date: 15 Oct 2008 11:17:16 +1300 Subject: documentation: what is "::="? References: Message-ID: On 2008-10-14, Peter Otten <__peter__ at web.de> wrote: > Anita Kean wrote: >>... >> But for example, if I import the sys module and perform the following >> three commands, >> print sys.path >> sys.path.__str__() >> str(sys.path) >> >> the first two give me the python path, and the last reports an error: >>> >>> File "", line 1, in >>> File "/usr/lib/python2.5/locale.py", line 244, in str >>> return format("%.12g", val) >>> File "/usr/lib/python2.5/locale.py", line 147, in format >... > Before these three commands you have probably executed > > from locale import * > > This has imported the locale.str() function that now shadows the builtin > str(). Had you imported locale with > > import locale > > (which is the recommended approach unless you're really know what you're > doing) you would have gained access to the functions in the module as, e. > g. > > locale.str(...) > > and still be able to access the built-ins in the usual way. That's correct. I found that line in my .pystartup file yesterday and commenting it out solved the problem. I recall when I initially started using python, scrambling to find some way to enable persistent history across sessions (something I was used to in many other apis) and copying some suggested .pystartup to enable this. It solved the problem at the time, only to create others. Thanks Peter. And thanks everyone for the pointers on ::= I'm still curious about why isn't it documented if it's used so much in the documentation and is known by another name. Obviously Wikipedia seems to think it's not totally obvious if they have an entry. It sure would have made the python docs easier to read! Anita From invalid at invalid Fri Oct 3 10:15:35 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 03 Oct 2008 09:15:35 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> <6klo5eF8ghmdU1@mid.individual.net> Message-ID: <9omdnSLTM7iatHvVnZ2dnUVZ_uudnZ2d@posted.visi> On 2008-10-03, greg wrote: > Lawrence D'Oliveiro wrote: >> In message <00f15d41$0$20617$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >> > (2) Even when the source is available, it is sometimes a legal trap to >> > read it with respect to patents and copyright. >> >> That's not how patents work. > > I don't think that's how copyrights work either. As far as > I know, whether something is deemed a derivative work is > judged on the basis of how similar it is to another work, > not whether its author had knowledge of the other work. > As long as you express an idea in an original way, it > shouldn't matter where you got the idea from. IANAL, but IIRC it does matter when it comes to establishing punative damages. If you knowingly and intentionally infringe a patent, I think you're libel for more damages than if you accidentally re-invent something. At least that's what I was told... -- Grant Edwards grante Yow! Thousands of days of at civilians ... have produced visi.com a ... feeling for the aesthetic modules -- From mensanator at aol.com Fri Oct 17 17:00:44 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 17 Oct 2008 14:00:44 -0700 (PDT) Subject: algorizm to merge nodes References: <4e08df3e-e91d-4940-8bdb-c7ff852e5de2@a19g2000pra.googlegroups.com> Message-ID: <37ea3913-b654-40ec-9210-f54bd6a77ab1@u28g2000hsc.googlegroups.com> On Oct 17, 3:20?pm, JD wrote: > Hi, > > I need help for a task looks very simple: > > I got a python list like: > > [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c', > 'u'], ['b', 'p']] > > Each item in the list need to be merged. > > For example, 'a', 'b' will be merged, 'c', 'd' will be merged. > > Also if the node in the list share the same name, all these nodes need > be merged. > > For example, ['a', 'b'], ['a', 'g'] ['b', 'p'] will be merged to ['a', > 'b', 'g', 'p'] > > The answer should be: > > [['a', 'b', 'g', 'p'], ['c', 'd', 'u'], ['e', 'f', 'k']] > > Anyone has a solution? A = [['a', 'b'], \ ['c', 'd'], \ ['e', 'f'], \ ['a', 'g'], \ ['e', 'k'], \ ['c', 'u'], \ ['b', 'p']] merged = [] for i in A: if len(merged)==0: merged.append(set(i)) else: gotit = False for k,j in enumerate(merged): u = j.intersection(set(i)) if len(u): merged[k] = j.union(set(i)) gotit = True if not gotit: merged.append(set(i)) print merged ## ## [set(['a', 'p', 'b', 'g']), set(['c', 'u', 'd']), set(['k', 'e', 'f'])] ## > > Thanks, > > JD From Pat at junk.com Sun Oct 19 14:41:04 2008 From: Pat at junk.com (Pat) Date: Sun, 19 Oct 2008 14:41:04 -0400 Subject: re.search over a list Message-ID: While I can use a for loop looking for a match on a list, I was wondering if there was a one-liner way. In particular, one of my RE's looks like this '^somestring$' so I can't just do this: re.search( '^somestring$', str( mylist ) ) I'm not smart enough (total newbie) to code up a generator expression and I was wondering if I'm missing something obvious. I love succinct but clearly understandable code. thx! From castironpi at gmail.com Sun Oct 12 19:36:37 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 12 Oct 2008 16:36:37 -0700 (PDT) Subject: Mail reader & spam Message-ID: Hello all, I'm hesitating to change news readers because I like Google's interface. In the interests of discussion, I'd make better contributions without it, if only because it's a known spam source, but its reader format beats the alternatives I've seen. I checked out the 'nntplib' module to see if some hybrid with Thunderbird and GMane, for example, would be possible. I don't think it would be that hard, but before I put in the effort, I wanted feedback. Here's what I like about it. When new messages come, the entire thread they're in is moved to the top of the list. You can click on it and browse the entire topic, and compose your reply right under the message you're replying to. You can also mark topics, to keep updated on when and what replies to your messages come too. I haven't found all these features in another reader, including Outlook, Thunderbird, and GMane. You've noticed Thunderbird isn't the best for discussing Python, due to its colored indents instead of caret marks in the interpreter prompt.. Free is a big plus too. What's my best option? Hijack Google's reader, and override 'reply' to use an SMTP account? Write my own, perhaps sorting marked and unmarked messages separately? It's of course everyone's choices whether to block Google or not, and miss out on anyone that posts them through Google. I don't think the, 'Well, if you insist' tactic is as cooperative and productive as acknowledging, 'It's a big spam source, maybe I can find a provider that isn't so beneficial to blacklist'. Is there any resolution to the dilemma? From jldunn2000 at googlemail.com Wed Oct 1 03:30:59 2008 From: jldunn2000 at googlemail.com (loial) Date: Wed, 1 Oct 2008 00:30:59 -0700 (PDT) Subject: ssh keepalive Message-ID: <34941e4c-c29c-4ae7-b062-13cd71bec86d@w32g2000hsf.googlegroups.com> I have a problem with a ssh connection in python I get the error 'NoneType' object has no attribute 'exec_command' I am thinking that maybe the ssh connection is timeing out. Since I have no control over the configuration of the ssh server(which is AIX 5.23), is there anything I can do in python to ensure that the ssh session does not timeout? From MPC8250 at gmail.com Mon Oct 20 23:05:30 2008 From: MPC8250 at gmail.com (zw) Date: Mon, 20 Oct 2008 20:05:30 -0700 (PDT) Subject: Compare Files and Cat File Difference Question Message-ID: Hi I have 2 log files, each with a timestamp on the first 2 fields. However, when I do a awk '/ / {print $1,$2}' logs/x.log on a log file, it is complicated by the fact that I also get other non timestamp column, 2008-10-20 15:00:06,113 2008-10-20 15:00:06,113 2008-10-20 14:59:48,828 javax.naming.CommunicationException: Could at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1414) at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:594) at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:587) at javax.naming.InitialContext.lookup(InitialContext.java:351) at com.cm.common.util.jndi.MultiJndiLookup.getRemoteObjectStub(MultiJndiLookup.java: 377) at com.cm.common.util.jndi.MultiJndiLookup.getRemoteObjectRef(MultiJndiLookup.java: 130) at com.cm.common.util.jndi.JndiLookup.getRemoteObjectRef(JndiLookup.java: 88) at com.cm.system.SystemInfoTopicManager.init(SystemInfoTopicManager.java: 91) at com.cm.system.SystemInfoTopicManager.reconnect(SystemInfoTopicManager.java: 181) at com.m.system.SystemInfoTopicManager.onException(SystemInfoTopicManager.java: 216) at org.jboss.mq.Connection $ExceptionListenerRunnable.run(Connection.java:1348) at java.lang.Thread.run(Thread.java:595) Caused by: at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:269) at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385) ... 11 2008-10-20 14:59:49,800 Unix diff gives extra output like 1,38c1,2 < 2008-10-20 15:00:09,890 WARN [trans2 at D-CM-TRLOAD04:***:***:***] [ExceptionListener Connection@ 323[token=ConnectionToken:ID:93/1003454235 rcvstate=STARTED]] com.cm.system.SystemInfoTopicManager - Jms server not reachable..it may be down. Deatils:Could not obtain connection to any of these urls: 172.16.70.1:1100,172.16.70.2:1100,172.16.70.3:1100,172.16.70.4:1 100,172.16.70.5:1100 I like to generate a 3rd file after comparing 2 files with format like the other 2 files but containing only the difference between 1st and 2nd files. ie suppose the file contains file1 file2 2008-10-20 15:00:06,113 ... 2008-10-20 15:00:06,113 ... 2008-10-20 15:00:06,113 ... 2008-10-20 15:00:06,113 2008-10-20 14:59:48,828 ... 2008-10-20 14:58:48,900 ... javax.naming.CommunicationException... at org.jnp.interfaces.NamingContext.ch... I'm hoping to get in file3 2008-10-20 14:59:48,828 ...plus rest of line 2008-10-20 14:58:48,900 ...plus rest of line I suppose I also need to read in the 1 field of the timestamp and convert time to unix time to compare and then convert that unix time to this timestamp format. It looks like filecmp.cmp isn't enough to cope with my requirements cuz it only gives a boolean value of 0 or 1, not the actual print out of the differences between 2 files into a new file. Can this be done with Python quickly ? Could someone be kind enough to show me steps to accomplish this ? Any help is appreciated. From carl at never.com Thu Oct 2 19:21:19 2008 From: carl at never.com (Carl) Date: Thu, 02 Oct 2008 19:21:19 -0400 Subject: help using py2app In-Reply-To: References: Message-ID: Joe Strout wrote: > I'm trying to use py2app to convert the pySketch wxPython example into a > stand-alone OS X app. I've found the documentation at > , but it wasn't terribly > enlightening for me. My setup.py looks like this: > > #!/usr/bin/env python > """ > setup.py - script for building a bundled OS X application > > Usage: > % python setup.py py2app > """ > from distutils.core import setup > import py2app > > setup( > app=['pySketch.py'], > ) > > > When I run this, it chugs along for a while and spews out lots of > output, and finally leaves me a bundle in the "dist" folder as it > should... but that app exits immediately. The only thing the console > log shows is: > > Oct 2 16:59:21 IA-J1 kernel[0]: CODE SIGNING: cs_invalid_page: > p=12336[pySketch] clearing CS_VALID > > A similar setup.py worked fine on on the "simple.py" example, but > clearly something more is needed here. Any clues? Or, is there a > better list/forum for asking about Mac-specific Python development? > (I've subscribed to the PyObjC mailing list, and sent a message to the > list, but it hasn't shown up yet... perhaps the SourceForge lists are > running slow today.) > > Thanks, > - Joe > If py2app is anything like py2exe, there is always a lot more to do. if you are importing modules, you need to explicitly include them into your build folder. From thomascribbs at gmail.com Thu Oct 2 10:51:03 2008 From: thomascribbs at gmail.com (thomascribbs at gmail.com) Date: Thu, 2 Oct 2008 07:51:03 -0700 (PDT) Subject: IDLE doesn't run on OSX 10.3.9 References: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> <48E26CB7.8060207@codebykevin.com> <48E387B0.8070908@codebykevin.com> Message-ID: <9c5b3951-11cb-4662-a16d-59022dcfe2b4@h60g2000hsg.googlegroups.com> Now I downloaded the latest Python 2.6 that came out yesterday, and also downloaded the latest ActiveTcl... I run a Terminal, cd /usr/local/bin, and type "idle2.6"...get this error message: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/Current/bin/ idle2.6", line 5, in main() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/idlelib/PyShell.py", line 1382, in main root = Tk(className="Idle") File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/lib-tk/Tkinter.py", line 1645, in __init__ self._loadtk() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/lib-tk/Tkinter.py", line 1659, in _loadtk % (_tkinter.TK_VERSION, tk_version) RuntimeError: tk.h version (8.4) doesn't match libtk.a version (8.5) Thanks for any help. -Tom On Oct 1, 9:22 am, Kevin Walzer wrote: > thomascri... at gmail.com wrote: > > Just did a new install of Tcl/tk from activestate.com and IDLE still > > not working... > > > -Tom > > Did you install Tcl/Tk 8.5? It won't work with the build of Python from > python.org (it looks for 8.4). > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com From theller at python.net Tue Oct 7 07:26:26 2008 From: theller at python.net (Thomas Heller) Date: Tue, 07 Oct 2008 13:26:26 +0200 Subject: how to get the thighest bit position in big integers? In-Reply-To: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> References: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> Message-ID: <6l0vb2Fa2621U1@mid.individual.net> Mark Dickinson schrieb: > On Oct 5, 11:40 pm, Terry Reedy wrote: >> Your point, that taking floor(log2(x)) is redundant, is a good catch. >> However, you should have added 'untested' ;-). When value has more >> significant bits than the fp mantissa can hold, this expression can be 1 >> off (but no more, I assume). The following correction should be >> sufficient: >> >> res = math.frexp(value)[1] - EXP_OF_ONE >> test = 1<> if test > r: res -= 1 >> elif 2*test < r: res += 1 >> >> For value = 2**n -1, n > 53, it is always 1 too high on my Intel >> machine, so the first correction is sometimes needed. I do not know if >> the second is or not. > > See also http://bugs.python.org/issue3439 > where there's a proposal to expose the _PyLong_NumBits method. This > would give an O(1) solution. > > Mark Here is ctypes code that works (tested with Python 2.5): from ctypes import * _PyLong_NumBits = pythonapi._PyLong_NumBits _PyLong_NumBits.argtypes = py_object, _PyLong_NumBits.restype = c_int for i in range(64): x = 1 << i print i, _PyLong_NumBits(long(x)) Thomas From steve at REMOVE-THIS-cybersource.com.au Sun Oct 5 06:12:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Oct 2008 10:12:39 GMT Subject: del and sets proposal References: <48e7b775$0$1120$426a34cc@news.free.fr> <00f80c6a$0$20633$c3e8da3@news.astraweb.com> Message-ID: <00f88c9e$0$20633$c3e8da3@news.astraweb.com> On Sun, 05 Oct 2008 22:11:38 +1300, Lawrence D'Oliveiro wrote: > In message <00f80c6a$0$20633$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> Would it really be "confusing" if sets used the same interface as dicts >> use? I don't think so. What else could "del aset[x]" mean other than >> "delete element x"? > > Yes, but "x" in what sense? The only sense possible. If I wrote aset.remove(x) would you ask "what's x, a key or a value?" No of course you wouldn't, because the question is nonsense for sets. The same goes for "x in aset", "aset.add(x)" and any other set method that takes an element as an argument. Why are you singling out del for this pretend confusion? > In dicts it's a key, in sets, shouldn't it > also be a key and not a value? That question isn't even meaningful. Sets have elements. The semantics of set elements is closer to dictionary keys than to dictionary values: x in adict # is key x in dictionary? x in aset # is element x in set? and an early implementation of Python sets used dictionaries, where the elements where stored as keys, not values. It makes no sense to treat set elements as if they were analogous to dict values. > Sets have no keys, only values. One might suggest assignment of keys, ? > la array indexes, but that means assigning an ordering to the values, > whereas sets are explicitly unordered. Why on earth should "del aset[x]" imply that sets are ordered? Dicts aren't ordered. You don't find people going "wibble wibble wibble, I don't understand del adict[x] because dicts aren't ordered, what could it mean???" -- Steven From kyosohma at gmail.com Thu Oct 30 09:50:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 30 Oct 2008 06:50:13 -0700 (PDT) Subject: Graphical object browser References: <79e10196-3943-4fc1-9161-fb6600a458a4@d36g2000prf.googlegroups.com> <96c62f3a-37f4-44b7-8906-fbdff57d4752@i18g2000prf.googlegroups.com> Message-ID: <6bdfe2c8-7db2-4d83-b042-04a989847b09@j22g2000hsf.googlegroups.com> On Oct 30, 8:33?am, Propad wrote: > On Oct 30, 2:10?am, Jason wrote: > > > Hooray! I discovered PyCrust. I made this script (for Linux - under > > Win, you could just have all but the first line as a python file and > > run it directly): > > > #!/usr/bin/python > > import wx > > import wx.py.PyCrust > > > if __name__ == '__main__' : > > ? ? app = wx.App() > > ? ? pc = wx.py.PyCrust.App(app) > > ? ? pc.MainLoop() > > > Run it from the working dir and tinker from there. > > Hello, > is it still possible to run PyCrust with Python 2.2? I see no > installer for it anywhere... > Cheers, > Propad PyCrust is part of wxPython now (I think). But I'm not sure how long it's been a part of that package. You can try downloading one of the really old wxPython versions and see if it's included: http://sourceforge.net/project/showfiles.php?group_id=10718&package_id=10559 Mike From gagsl-py2 at yahoo.com.ar Fri Oct 3 05:01:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 03 Oct 2008 06:01:28 -0300 Subject: RE module question References: <73045cca0810022359x742fc9b1nb55e25d9e9110c2@mail.gmail.com> Message-ID: En Fri, 03 Oct 2008 03:59:18 -0300, aditya shukla escribi?: > Hello folks : > > i have a string "-bin-ulockmgr_server:0.99[&&NHX:C=0.195.0]" from which i > want to delete [&&NHX:C=0.195.0] . > I wrote a regular expression for [&&NHX:C=0.195.0] as > \[&&(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\] > > now when i do > > p = re.compile('\[&&(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\]') > m =p.search("-bin-ulockmgr_server:0.99[&&NHX:C=0.195.0]") > print m > <_sre.SRE_Match object at 0x01314EE8> >>>> print m.group() > [&&NHX:C=0.195.0] > > So i guess i am able to find the substring , my question is how can i > delete > this substring from the original string? ie > -bin-ulockmgr_server:0.99 should be my output. Instead of p.search, use p.sub Or, if you need the match for other purposes, delete the characters from m.start() to m.end() See http://docs.python.org/library/re.html#regular-expression-objects -- Gabriel Genellina From martin at v.loewis.de Thu Oct 9 18:48:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 10 Oct 2008 00:48:55 +0200 Subject: Python 2.6, GUI not working on vista? In-Reply-To: <2e0ac5bd-82d9-4f8b-b7c8-9cf5998eff27@o40g2000prn.googlegroups.com> References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> <48EE7A98.5090300@v.loewis.de> <2e0ac5bd-82d9-4f8b-b7c8-9cf5998eff27@o40g2000prn.googlegroups.com> Message-ID: <48EE8A57.50508@v.loewis.de> > I posted a problem with Vista on Jul 6 concerning not being > able to run IDLE in 2.6b1. No replies. Where did you post that? On python-dev? > What am I supposed to do? File bug reports on things > I don't even know are bugs? You mean, it might have been intentional that IDLE won't run on Vista? Regards, Martin From hnassrat at gmail.com Fri Oct 10 15:22:14 2008 From: hnassrat at gmail.com (Hatem Nassrat) Date: Fri, 10 Oct 2008 16:22:14 -0300 Subject: Set Your EMAIL CLIENT dates correctly. Message-ID: <20081010192213.GA3410@torch.cs.dal.ca> I am sure this has been ranted about. People who have their dates in their client set to 2020 should be banned from using the internet, unless they have a legitimate reason like doing y3k testing on the Python Mailing list. -- Hatem Nassrat From george.sakkis at gmail.com Wed Oct 22 13:40:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 22 Oct 2008 10:40:45 -0700 (PDT) Subject: substitution of a method by a callable object References: <62359419-c908-43aa-a30e-f12715e54dec@79g2000hsk.googlegroups.com> Message-ID: <71776105-966e-4c47-9101-ea137219920d@p58g2000hsb.googlegroups.com> On Oct 22, 12:13?pm, netimen wrote: > Can I substitute a method of a class by a callable object (not a > function)? I can very easy insert my function in a class as a method, > but an object - can't. > > I have the following: > > class Foo(object): > ? ? pass > > class Obj(object): > ? ? def __call__(self, obj_self): > ? ? ? ? print 'Obj' > > def func(self): > ? ? print 'func' > > f = Foo() > Foo.meth = func > f.meth() # all goes OK > Foo.meth = Obj() > f.meth() # I get TypeError: __call__() takes exactly 2 arguments (1 > given) You have to wrap it as an (unbound) instance method explicitly: from types import MethodType Foo.meth = MethodType(Obj(), None, Foo) f.meth() For normal functions this seems to be done implicitly (of course you can do it explicitly if you want): >>> Foo.meth = func >>> print Foo.meth George From lie.1296 at gmail.com Thu Oct 9 11:22:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 9 Oct 2008 15:22:53 +0000 (UTC) Subject: Efficient Bit addressing in Python. References: <004c01c92a5f$2ed15420$0d00a8c0@hendrik> Message-ID: On Fri, 10 Oct 2008 00:30:18 +0200, Hendrik van Rooyen wrote: > Is there a canonical way to address the bits in a structure like an > array or string or struct? > > Or alternatively, is there a good way to combine eight ints that > represent bits into one of the bytes in some array or string or > whatever? > > It seems to me that there is a dilemma here : > > if you can write: > > bit3 = 1 > > Then you have to jump through hoops to get bit0 through bit7 into some > byte that you can send to an i/o routine. > > On the other hand, if you keep the bits "in" the byte, then you can > write: > > byte[3] = '\x7e' > > but you have to jump through hoops to get at the individual bits. > > Is there a "best" way? > > It would be nice to be able to write: > > if io.byte2.bit3: > do_something() > > if io.byte2 == alarm_value: > do_something_else() > > where: > > io.byte2 & 8 "is" io.byte2.bit3 > > Is this possible? > > - Hendrik You'll find that in most cases, using integer or Boolean is enough. There are some edge cases, which requires bit addressing for speed or memory optimizations, in python, the usual response to that kind of optimization requirement is to move that part of the code to C. If, for the more usual case, you require the bit addressing because the data structure is more convenient to work with that way, you could use a class that implements the __getitem__, __setitem__, and a "join" method. anyway, if you used str, it isn't hard to have both behavior (easy indexing and easy joining) the bits: >>> a = '01101010' >>> a[0], a[1] ('0', '1') >>> a '01101010' >>> int(a, 2) 106 >>> chr(int(a, 2)) 'j' >>> def bin2int(b): return int(a, 2) ... >>> def bin2chr(b): return chr(int(a, 2)) ... >>> From philip at semanchuk.com Thu Oct 23 17:13:56 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 23 Oct 2008 17:13:56 -0400 Subject: python extensions: including project local headers In-Reply-To: <87ljwf2k9i.fsf@agentultra.com> References: <87vdvjxr03.fsf@dozer.localdomain> <87ljwf2k9i.fsf@agentultra.com> Message-ID: <73B7164C-B78F-4EEE-85CC-E921DAD2003C@semanchuk.com> On Oct 23, 2008, at 3:18 PM, J Kenneth King wrote: > Philip Semanchuk writes: > >> On Oct 23, 2008, at 11:36 AM, J Kenneth King wrote: >> >>> >>> Hey everyone, >>> >>> I'm working on a python extension wrapper around Rob Hess' >>> implementation of a SIFT feature detector. I'm working on a >>> computer-vision based project that requires interfacing with >>> Python at >>> the higher layers, so I figured the best way to handle this would be >>> in >>> C (since my initial implementation in python was ungodly and slow). >>> >>> I can get distutils to compile the extension and install it in the >>> python path, but when I go to import it I get the wonderful >>> exception: >>> >>> ImportError: /usr/lib/python2.5/site-packages/pysift.so: undefined >>> symbol: _sift_features >> >> >> Kenneth, >> You're close but not interpreting the error quite correctly. This >> isn't an error from the compiler or preprocessor, it's a library >> error. Assuming this is dynamically linked, your OS is reporting >> that, >> at runtime, it can't find the library that contains _sift_features. >> Make sure that it's somewhere where your OS can find it. > > This is basically what I was looking for help with. So far the project > directory is: > > /pysift > /sift > .. > /include > .. > sift.h > /src > .. > sift.c > /src > pysift.c > setup.py > > I thought I could just #include "sift.h" in pysift.c as long as > distutils passed the right -I path to gcc. That's true, and it sounds like you've got that part working. > Maybe I should compile the sift code as a shared object and link it to > my extension? How would I get distutils to build the makefile and tell > gcc how to link it? > > Thanks for the reply. Python has spoiled me and my C is rather > rusty. :) I don't know how to get setup.py to build a shared object separately. I am in the same Python/C situation as you. I'm scrubbing the rust off of my C skills and I'm also a n00b at developing extensions. I've learned a lot from looking at other people's setup code, so maybe I can help you there. My posix_ipc module links to the realtime lib "rt" and here's the relevant snippets of setup.py: ------------------------------ import distutils.core as duc libraries = [ ] libraries.append("rt") source_files = ["posix_ipc_module.c"] ext_modules = [ duc.Extension("posix_ipc", source_files, define_macros=define_macros, libraries=libraries ) ] duc.setup(name="posix_ipc", version=VERSION, ext_modules=ext_modules) ------------------------------ You can download the whole thing here if you want to examine all the code: http://semanchuk.com/philip/posix_ipc/ HTH Philip From joe at strout.net Mon Oct 27 15:11:04 2008 From: joe at strout.net (Joe Strout) Date: Mon, 27 Oct 2008 13:11:04 -0600 Subject: Finding the instance reference of an object In-Reply-To: References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> Message-ID: On Oct 27, 2008, at 12:19 PM, gooberts at gmail.com wrote: > I think this "uncontrived" example addresses the C/Python difference > fairly directly (both were tested): That's correct, but of course, C is a decades-old language barely a step above assembler. For a fair comparison, pick any modern OOP language, including the C derivatives (C++, Objective-C, Java), and compare a Python object to an object in that language, rather than to a struct. > In Python, variables are just names/aliases for *references* to > objects, not names for the objects/values themselves. The variable > names themselves do not correspond directly to the objects' memory > locations. Exactly! In C++, this would be like a pointer variable. In Java, RB, or .NET, it's like an object reference. > While yes, technically, it is true that those reference > values must be stored somewhere in memory, *that* is the > implementation detail. Agreed. (And this was my point in response to someone arguing that no such location exists.) > But is is not the *locations* of these > references (i.e., the locations of the Python *variables*) that are > copied around, it is the references themselves (the locations of the > Python *objects*) that are copied. Right. The variables contain object references; these object references are copied (not referenced!) when you pass them into a function. That's call by value. In the case of an assignment, the reference is copied. >>> All that exists in Python is a name->object mapping. >> >> And what does that name->object mapping consist of? At some level, >> there has to be a memory location that stores the reference to the >> object, right? > > I think this is answered above, but just to drive it home, in Python > the memory locations of the variables themselves (an implementation > detail), which hold the references to the objects, are inaccessible . Right. So too in Java, RB, .NET, etc. Pointers are nasty. But lack of pointers does not change the calling semantics. > In C/C++, by contrast, variable names correspond directly to memory > locations and objects, and you can easily find the addresses of > variables. Hmm, no, the C++ equivalent of an object reference would be: SomeClass* foo; In fact, many C++ programmers prefer to typedef a pointer to each class, since it's the pointer (which is rough equivalent of a reference in newer languages) that you almost always want, rather than the class itself. So it would actually be: SomeClassPtr foo; Now, when you do: foo2 = foo; you are copying the object reference from foo to foo2, just as in Python. When you pass it into a function: void NiftyMethod(SomeClassPtr arg) {...} ... NiftyMethod(foo); You are copying the object reference right onto the call stack. This is pass by value, plain and simple. And because it is pass by value, you know that nothing NiftyMethod does can possibly change the value of foo -- that is, can make it point at something else. (It may well change the data that the object it points to contains, if SomeClass objects are mutable, but it can't change foo itself.) This is, again, just like Python and every other OOP language. Call by reference would be this: void NiftyMethod2(SomeClassPtr &arg) {...} ... NiftyMethod2(foo); Now, arg here is passed by reference (just like a ByRef parameter in RB or .NET). That means that NiftyMethod2 could very well change the value that is passed in. It could actually make foo point to something else. No Python method can do that, because Python arguments are ALWAYS passed by value. There is no call by reference in Python. Period, end of story, nothing to see here. Cheers, - Joe From werner.bruhin at free.fr Mon Oct 20 16:16:43 2008 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Mon, 20 Oct 2008 22:16:43 +0200 Subject: subprocess.Popen on Windows Message-ID: <48FCE72B.3050404@free.fr> I am trying to use subprocess - it basically works but. command = 'ping ' + '-n '+ str(count) + ' -l ' + str(size) + ' ' + str(node) print command p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) pout = p.stdout.read() This works for me but I see the Windows command window, is there a way to call subprocess without a command window showing? I am trying to replace: fdout, fdin = popen2.popen4('ping -n '+ str(count)+ ' -l '+ str(size) +' '+node) Which did not show the command window. I did quit a bit of googling bug so far did not find an answer to my problem. Appreciate any hints on how this can be accomplished. Werner From joefazee at gmail.com Fri Oct 10 23:16:12 2008 From: joefazee at gmail.com (Abah Joseph) Date: Fri, 10 Oct 2008 20:16:12 -0700 Subject: Win32 system admin Message-ID: Hi everybody... i`m not a prof in english so please read and understand me.. Thank u. Using the win32 python module can we perform every tasks like *gpedit.msc?* i will like to automate tasks like enabling or disaple some of the windows functions. with my basic experince, you can perform important adminsitrative tasks using gpedit.msc. Like today, some virus hidded my start menu/program file and i have to use gpedit.msc to enable it. point me to some article that talk about this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at cosc.canterbury.ac.nz Sat Oct 25 20:23:46 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 26 Oct 2008 13:23:46 +1300 Subject: @property decorator doesn't raise exceptions In-Reply-To: References: <7aec65b5-fd54-4417-8bec-4615afa7a5c3@w1g2000prk.googlegroups.com> Message-ID: <6mhs2pFh0ohbU1@mid.individual.net> Rafe wrote: > The docs seem to suggest this is impossible: > "Called when an attribute lookup has not found the attribute in the > usual places (i.e. it is not an instance attribute nor is it found in > the class tree for self). Getting an AttributeError is the way that the interpreter machinery tells that the attribute wasn't found. So when your property raises an AttributeError, this is indistinguishable from the case where the property wasn't there at all. To avoid this you would have to raise some exception that doesn't derive from AttributeError. -- Greg From simon at brunningonline.net Fri Oct 3 09:29:49 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 3 Oct 2008 14:29:49 +0100 Subject: Inheritance but only partly? In-Reply-To: References: Message-ID: <8c7f10c60810030629xfca0affq24f07a4e3cda2d94@mail.gmail.com> 2008/10/3 Tim Rowe : > As others have said, no. What nobody seems to have said yet is why. If > Y descends from X, you are saying that Y is an X; that a Y can be used > anywhere an X can. If Y doesn't support some methods of X then it is > *not* an X, and *can't* be used anywhere an X can. See . -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns | Facebook: http://tinyurl.com/6f47zo From alex at a13x.net Wed Oct 8 18:59:46 2008 From: alex at a13x.net (Aleksandar Radulovic) Date: Wed, 8 Oct 2008 22:59:46 +0000 Subject: utf-8 read/write file In-Reply-To: References: <6cd45025-d01b-429a-ae4c-24a08db2b9c7@b2g2000prf.googlegroups.com> Message-ID: <845b10c50810081559v3c9e199dh5adc5067b922f39c@mail.gmail.com> Hi, What is the encoding of the file1 you're reading from? I just ran tests on my machine (OS X) with both python2.5 and 2.6 and was able to read from a file containing: "?ivot je lep" The file is UTF-8 encoded. >>> data = open("test.txt").read() >>> data '\xc5\xbeivot je lep.' >>> f = open("test2.txt", "wb") >>> f.write(data) >>> f.close() mac-alex:~ alex$ file test.txt test.txt: UTF-8 Unicode text, with no line terminators mac-alex:~ alex$ file test2.txt test2.txt: UTF-8 Unicode text, with no line terminators mac-alex:~ alex$ Files test.txt and test2.txt are identical. Regards, alex. 2008/10/8 gigs : > Benjamin wrote: >> >> On Oct 8, 12:49 pm, Bruno wrote: >>> >>> Hi! >>> >>> I have big .txt file which i want to read, process and write to another >>> .txt file. >>> I have done script for that, but im having problem with croatian >>> characters >>> (?,?,?,?,?). >> >> Can you show us what you have so far? >> >>> How can I read/write from/to file in utf-8 encoding? >> >> import codecs >> data = codecs.open("my-utf8-file.txt").read() >> >>> I read file with fileinput.input. >>> >>> thanks >> > I have tried with codecs, but when i use encoding="utf-8" i get this error > on word : ?ivot > > Traceback (most recent call last): > File "C:\Users\Administrator\Desktop\getcontent.py", line 43, in > encoding="utf-8").readlines() > File "C:\Python25\Lib\codecs.py", line 626, in readlines > return self.reader.readlines(sizehint) > File "C:\Python25\Lib\codecs.py", line 535, in readlines > data = self.read() > File "C:\Python25\Lib\codecs.py", line 424, in read > newchars, decodedbytes = self.decode(data, self.errors) > UnicodeDecodeError: 'utf8' codec can't decode byte 0x9e in position 0: > unexpected code byte > > > i just need to read from file1.txt, process (its simple text processing) > some words and write them to file2.txt without loss of croatian characters. > (?????) > -- > http://mail.python.org/mailman/listinfo/python-list > -- a lex 13 x From aweraw at gmail.com Mon Oct 6 03:31:39 2008 From: aweraw at gmail.com (Aidan) Date: Mon, 06 Oct 2008 17:31:39 +1000 Subject: Pr. Euler 18, recursion problem In-Reply-To: References: <48e9ac7e@dnews.tpgi.com.au> Message-ID: <48e9beda@dnews.tpgi.com.au> process wrote: > On Oct 6, 8:13 am, Aidan wrote: >> process wrote: >>> I am trying to solve project euler problem 18 with brute force(I will >>> move on to a better solution after I have done that for problem 67). >>> http://projecteuler.net/index.php?section=problems&id=18 >>> However I can't get the recursive function right. >>> I always have to use return right? Unless I am printing? So I can?t >>> stack to diffferent recursive calls after each other like so: >>> recur_left(t, p) >>> recur_right(t,p+1) >>> Some stuff I have tried: >>> def recur(tree, pos): >>> if not tree: >>> return [] >>> else: >>> return [[tree[0][pos]] + recur(tree[1:], pos)] + \ >>> [[tree[0][pos]] + recur(tree[1:], pos+1)] >>>>>> recur([[1],[2,3],[4,5,6]],0) >>> [[1, [2, [4], [4]], [2, [5], [5]]], [1, [3, [5], [5]], [3, [6], [6]]]] >>> SO it is kind of working, just not exactly like I want. >>> A more easily parseable/readable result would be nice, I want to be >>> able to sum() over each path preferrably. >>> So the result should be: >>> [[1,2,4],[1,2,5],[1,3,5],[1,3,6]] >>> I know conceptually what has to be done. >>> Base case: empty tree, return [] >>> Else: recur to the left and to the right. >> This is just my opinion, but I felt the non-brute force solution to this >> problem was actually simpler than trying to define a brute force >> recursive solution.... I tried to implement a brute force algorithm at >> first, until I had an epiphany with regard to how simple the problem >> actually was. Then I faced palmed. > > > > But let's say you have [[1],[1,10],[1,2,300],[100000,1,1,1]]. > > you must check all solutions right? there is no pattern. if you start > from the bottom and eliminate paths that seem to be losing can you > regain that later up in the pyramid if it turns out one side gets bigg > again? It's difficult to say much here without giving the answer away... but, yes, you need to check all solutions - it's just that there's a very easy way to do that without having to recurse from the top of the tree to the bottom. Hope that gives you a clue while not fully revealing the answer. From andipink0288 at gmail.com Sun Oct 5 05:06:22 2008 From: andipink0288 at gmail.com (andi) Date: Sun, 5 Oct 2008 02:06:22 -0700 (PDT) Subject: Today s Hottest Models ! <<<<<<< Click Now >>>>>>>> Message-ID: <5ffa63db-cbd9-4611-8927-11362a4dde74@40g2000prx.googlegroups.com> Naughty Free Live Sex Web Cams & Chat Click here for free live sex web cams & chat online. Straight, Get sexy and broadcast your own cam. Chat for free. MOre...[b] http://url.co.uk/1xkbr >>> All Sexy <<< http://url.co.uk/ddxhf >>>>>>>>> NOTE:>To GET BEST Sex Advice for ALL <<<<<<<<<< {Hot} http://url.co.uk/qfq3n >>> Click Now <<< http://url.co.uk/dy9tf {Hot} From gagsl-py2 at yahoo.com.ar Tue Oct 21 01:46:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Oct 2008 03:46:37 -0200 Subject: How to transfer data structure or class from Python to C/C++? References: <7085c400-94ef-441f-b727-48ec7b66051d@p10g2000prf.googlegroups.com> <4b2c771b-7be0-47a6-8c64-346f97a3fefb@v39g2000pro.googlegroups.com> <2a81471a-b38a-4e17-8b6b-55c3a6a915cb@y21g2000hsf.googlegroups.com> Message-ID: En Fri, 17 Oct 2008 20:03:44 -0300, Aaron "Castironpi" Brady escribi?: > On Oct 16, 9:10?am, Hongtian wrote: >> Not exactly. >> >> In my C/C++ application, I have following function or flow: >> >> void func1(....) >> { >> ? ? call PyFunc(struct Tdemo, struct &Tdemo1); >> >> } >> >> I mean I want to invoke Python function 'PyFunc' and transfer a data >> structure 'Tdemo' to this function. After some process in Python, I >> want it return 'Tdemo1' back to the C/C++ application. >> >> I research boost.python and think it is not a reasonable solution >> because it make the C/C++ application too complex. >> >> Thanks. > snip > > Solution produced here. Includes dirty kludge, which will welcome > correction. > > /C file: > > #include > > typedef struct { > int a; > float b; > } TypeA; > > static PyObject * > methA(PyObject *self, PyObject *args) { > TypeA a; > TypeA b; > PyObject* fun; > PyObject* res; > > PyArg_ParseTuple( args, "O", &fun ); > a.a= 10; > a.b= 20.5; > > res= PyObject_CallFunction( fun, "II", &a, &b ); > > printf( "%i %f\n", b.a, b.b ); > Py_DECREF( res ); > > return PyInt_FromLong( 0 ); > } > > static PyMethodDef module_methods[] = { > {"methA", methA, METH_VARARGS, "No doc"}, > {NULL, NULL, 0, NULL} /* Sentinel */ > }; > > > #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ > #define PyMODINIT_FUNC void > #endif > PyMODINIT_FUNC > initng27ext(void) > { > PyObject* m; > m = Py_InitModule3("ng27ext", module_methods, > "Custom."); > if (m == NULL) > return; > } > > /Py file: > > import ng27ext > > import ctypes as c > class TypeA( c.Structure ): > _fields_= [ > ( 'a', c.c_int ), > ( 'b', c.c_float ) > ] > > from _ctypes import _cast_addr > _data_cast= c.PYFUNCTYPE( c.py_object, c.c_void_p, c.py_object, > c.py_object)( _cast_addr ) #dirty kludge > > def exposed( obj1, obj2 ): > cob1= _data_cast( obj1, None, c.POINTER( TypeA ) ) > cob2= _data_cast( obj2, None, c.POINTER( TypeA ) ) > print cob1.contents.a, cob1.contents.b > cob2.contents.a= c.c_int( 60 ) > cob2.contents.b= c.c_float( 70.5 ) > print cob2.contents.a, cob2.contents.b > > print ng27ext.methA( exposed ) > > /Compile & link: > > c:/programs/mingw/bin/gcc ng27ext.c -c -Ic:/programs/python25/include > c:/programs/mingw/bin/gcc -shared ng27ext.o -o ng27ext.pyd -Lc:/ > programs/python25/libs -lpython25 > > /Output: > > 10 20.5 > 60 70.5 > 60 70.500000 > 0 > Press any key to continue . . . > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gabriel Genellina From paul at boddie.org.uk Thu Oct 30 14:15:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 30 Oct 2008 11:15:44 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <49024ADC.4080600@g.nevcal.com> <777f7a0f-3061-4881-a5e9-b3e19422dca4@q26g2000prq.googlegroups.com> <63bcc9b2-5424-4d92-ae9d-c5a953cf431e@t41g2000hsc.googlegroups.com> Message-ID: <8ed0e9db-0b69-41c2-933b-2b799d912137@c60g2000hsf.googlegroups.com> On 30 Okt, 14:12, "Andy O'Meara" wrote: > > 3) Start a new python implementation, let's call it "CPythonES" [...] > 4) Drop python, switch to Lua. Have you looked at tinypy? I'm not sure about the concurrency aspects of the implementation, but the developers are not completely unfamiliar with game development, and there is a certain amount of influence from Lua: http://www.tinypy.org/ It might also be a more appropriate starting point than CPython for experimentation. Paul From martin at v.loewis.de Thu Oct 9 17:41:44 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 09 Oct 2008 23:41:44 +0200 Subject: Python 2.6, GUI not working on vista? In-Reply-To: References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> Message-ID: <48EE7A98.5090300@v.loewis.de> > You can believe what you want. The people who developed UAC don't have > to support it. I know for a fact that the implementation is incomplete. In Windows Installer, there is no way (that I know of) to create an MSI file that conditionally turns on UAC, only when the installation actually needs privilege elevation. There is a static bit in the installer that indicates whether the MSI file will do UAC, and there is no way to toggle this bit, e.g. after asking the user whether this is a "for me" installation or "for all users". I set this bit to "no UAC" for 2.6, in order to allow non-privileged installation at all - only to find out that (due to an unrelated problem), the "for me" installation doesn't actually work. I only found out after the release, because nobody bothered reporting this problem during the betas and release candidates. I didn't notice on my Vista machine, because that has VS 2008 installed, in which case the "for me" installation works just fine. If anybody knows how to make the "for me" installation work (i.e. how to set up the manifests that a single copy of the CRT is used both by python26.dll, and all extension modules), please let me know. IOW: HELP! HELP!! HELP!!! Meanwhile: just say no to Vista. Regards, Martin From sukhrajtakhar at hotmail.com Thu Oct 2 15:21:49 2008 From: sukhrajtakhar at hotmail.com (rajtakhar) Date: Thu, 2 Oct 2008 12:21:49 -0700 (PDT) Subject: Great New Linux Devices Message-ID: <1b819a43-12c7-4aef-bb80-f18bd99a652a@d31g2000hsg.googlegroups.com> The GP2X Wiz and Pandora units will open up the face of handheld computing The GP2X Wiz is a pure Gaming/Video/MP3 console with hundreds of emulators written for it The other, the Pandora is a UMPC, which can run openoffice/firefox and is the same shape and size as a nintendo DS Check the data here on GP2X Wiz: http://gp2x.co.uk/go.pl?A216 Check the data here on Pandora: http://openpandora.org/worldmap.html Mention you were sent by Raj Takhar and you may get an extra discount From briner at gmail.com Wed Oct 8 08:46:36 2008 From: briner at gmail.com (Sed) Date: Wed, 8 Oct 2008 05:46:36 -0700 (PDT) Subject: several version of eggs References: <61032031-edf2-41e6-be66-b3d6406fd154@j68g2000hsf.googlegroups.com> <6l1abjFa6tusU1@mid.uni-berlin.de> <4e089e6f-ba0a-407f-9fbb-5a314af736fc@m74g2000hsh.googlegroups.com> <6l1cncFa74k2U1@mid.uni-berlin.de> Message-ID: On Oct 7, 5:14?pm, "Diez B. Roggisch" wrote: > Sed wrote: > >> you need to easy_install with -m/--multi-version. All of your packages. > > Unfortunately, this is not even working :( > > It is. I see !!! thanks !!! the fact is that if you have only one egg of sqlachemy module (for example) which was not installed with easy_install -m, then you get stuck ! I was having 3 eggs for sqlalchemy:- 2 of them with -m - 1 of them without -m (that was the mistake). thanks again. cEd From lists at cheimes.de Fri Oct 17 09:54:34 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 17 Oct 2008 15:54:34 +0200 Subject: Python certification In-Reply-To: <59110.64393.qm@web7905.mail.in.yahoo.com> References: <59110.64393.qm@web7905.mail.in.yahoo.com> Message-ID: srinivasan srinivas wrote: > Hi, > I m planning to do certification in Python?? > Is therr any good certification available in Python like Sun certification for java?? The topic has been discussed on the internal Python Software Foundation list multiple times but w/o a definite answer. Christian From tjreedy at udel.edu Mon Oct 13 19:43:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Oct 2008 19:43:04 -0400 Subject: Suggestion for the PythonDevelopment for next version In-Reply-To: References: Message-ID: azrael wrote: > I know that. enumerate is a great function. Agreed. Enumerate works everywhere an iterable is wanted. Just like other functions that produce iterables. A special trick for for-loops would only work for for-loops. From jopython at gmail.com Wed Oct 8 15:51:11 2008 From: jopython at gmail.com (Joe Python) Date: Wed, 8 Oct 2008 15:51:11 -0400 Subject: Apache log munging In-Reply-To: <6a2ccd190810081115x6bf227a0i8a168f604cb751a0@mail.gmail.com> References: <6a2ccd190810081115x6bf227a0i8a168f604cb751a0@mail.gmail.com> Message-ID: I am currently using the following technic to get the info above: all = defaultdict(int) hosts = defaultdict(int) filename = defaultdict(int) for r in log: all[r['host'],r['file']] += 1 hosts[r['host']] += 1 filename[r['file']] = 1 for host in sorted(hosts,key=hosts.get, reverse=True): for file in filename: print host, all[host,file] print hosts[host] I was looking for a better option instead of building 'three' collections to improve performance. - Jo On Wed, Oct 8, 2008 at 2:15 PM, Joe Riopel wrote: > On Wed, Oct 8, 2008 at 1:55 PM, Joe Python wrote: > > I want to find the top '100' hosts (sorted in descending order of total > > requests) like follows: > > Is there a fast way to this without scanning the log file many times? > > As you encounter a new "host" add it to a dict (or another type of > collection), and if encountered again, use that "host" as the key to > retrieve the dict entry and increment it's request count. You should > only have to read the file once. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Fri Oct 17 13:11:20 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 17 Oct 2008 10:11:20 -0700 Subject: properties access by name In-Reply-To: References: Message-ID: <47c890dc0810171011s3df5c150j623f2d6ef37367e9@mail.gmail.com> Since rwproperty appears to use descriptors just like regular property(), you'd do it the same way as for any normal attribute, namely: #for reading print foo.y #is the same as print getattr(foo, "y") #for writing foo.x = 1 #is the same as setattr(foo, "x", 1) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Fri, Oct 17, 2008 at 9:36 AM, ???? wrote: > I use rwproperty (http://pypi.python.org/pypi/rwproperty/1.0) and so I > have properties in my class. Also I have a list of names of properties > wich I am to set. How can I access my properties by name in such way > that when I want to set a property, setter will be called, and and > when I want to read it - getter? > > I have something like this: > > class Film(object): > def __init__(self, title): > self.__title = title > > @getproperty > def title(self): > return self.__title > @setproperty > def title(self, value): > self.__title = value > > properties_to_set = ['title'] > f = Film('aaa') > > I d want to have sth like: > f(properties_to_set[0]) = 'bbb' > > If title was a simple variable I could write: > f.__dict__[properties_to_set[0]] = 'bbb' > > now I can write: > f.__dict__['_Film__' + properties_to_set[0]] = 'bbb' > > but I want to set my property through the provided setter. How can I > do this? > > P.S. Sorry for my english > -- > http://mail.python.org/mailman/listinfo/python-list > From metaperl at gmail.com Thu Oct 2 10:51:30 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 2 Oct 2008 07:51:30 -0700 (PDT) Subject: code critique requested - just 60 lines Message-ID: Hi, I would like some feedback on how you would improve the following program: http://www.bitbucket.org/metaperl/ptc_math/src/21979c65074f/payout.py Basically, using non-strict dictionary keys can lead to bugs, so that worried me. Also, I'm not sure that my code is as crisp and concise as it could be. I also did not like the long string representation in the Scenerio class. It is hard to read and error-prone to code. Any feedback on how you would've written this differently is welcome, either by commenting below, or by checking out the repo and checking it back in! class Rates: def __init__(self, per_click, per_ref_click): self.per_click = per_click self.per_ref_click = per_ref_click def __str__(self): return 'per_click: %.2f per_ref_click: %.2f' % (self.per_click, self.per_ref_click) ad_rate = 200 # 2 dollars for 100 clicks # http://code.activestate.com/recipes/278259/ def sumDict(d): return reduce(lambda x,y:x+y, d.values()) rates = {} rates['std'] = Rates(per_click=1, per_ref_click=0.5) rates['vip'] = Rates(per_click=1.25, per_ref_click=1.25) class Scenario: def __init__(self, std_clicks, vip_clicks, upline_status): self.clicks = {} self.payout = {} self.ad_rate = 200 self.clicks['std'] = std_clicks self.clicks['vip'] = vip_clicks self.upline_status = upline_status def calc_profit(self): for member_type in rates: self.payout[member_type] = self.clicks[member_type] * rates[member_type].per_click if self.upline_status is None: self.payout['upline'] = 0 else: self.payout['upline'] = sumDict(self.clicks) * rates[upline_status].per_ref_click #print "rates: %s self.clicks: %d upline payout: %.1f\n" % (rates[upline_status], sumDict(self.clicks), self.payout['upline']) return ad_rate - sumDict(self.payout) def __str__(self): profit = self.calc_profit() return 'upline_status: %s upline_payout: %.1f\n\tstd_clicks: %d std_payout %.1f vip_clicks: %d vip_payout: %.1f\n\t\tProfit: %.1f \n' % (self.upline_status, self.payout['upline'], self.clicks['std'], self.payout['std'], self.clicks['vip'], self.payout['vip'], profit) scenario = [] for upline_status in [None, 'std', 'vip']: for vip_clicks in [0, 25, 50, 75, 100]: std_clicks = 100 - vip_clicks scenario.append(Scenario(std_clicks, vip_clicks, upline_status)) # really, we could've printed the objects as they were made, but for debugging, I kept creation and # printing as separate steps for s in scenario: print s From theller at python.net Thu Oct 9 15:32:09 2008 From: theller at python.net (Thomas Heller) Date: Thu, 09 Oct 2008 21:32:09 +0200 Subject: python 3: sorting with a comparison function Message-ID: <6l74hpFauga7U1@mid.individual.net> Does Python 3 have no way anymore to sort with a comparison function? Both [].sort() and sorted() seem to accept only 'key' and 'reverse' arguments, the 'cmp' argument seems to be gone. Can that be? Thomas From gauravkec2005 at gmail.com Fri Oct 31 00:41:51 2008 From: gauravkec2005 at gmail.com (gaurav kashyap) Date: Thu, 30 Oct 2008 21:41:51 -0700 (PDT) Subject: How to open a shell prompt from an existing shell prompt References: <177de0b9-a5ee-40cc-9e44-1c65755553a2@l33g2000pri.googlegroups.com> <06f218e4-6282-4a3b-b23d-904edde8fecc@o40g2000prn.googlegroups.com> <712cecb7-c09b-4b04-b0d4-e077d1e8d695@r15g2000prh.googlegroups.com> Message-ID: <57f76ff9-8efa-4fee-b250-0d892c449777@b2g2000prf.googlegroups.com> Dear Tino, There is no subprocess module in python 2.3.5. My goal is: 1.Open a terminal window and login as root. 2.Issue some command in the terminal window that will open another terminal,similar to the one already opened. Am i clear now. From kerny404 at gmail.com Fri Oct 24 06:53:35 2008 From: kerny404 at gmail.com (andrea) Date: Fri, 24 Oct 2008 03:53:35 -0700 (PDT) Subject: Building truth tables References: <3c615d52-fbd4-4ab3-9efe-fbadc60bf414@x41g2000hsb.googlegroups.com> Message-ID: <8b743462-2850-437d-b7f3-d40c1200064e@k7g2000hsd.googlegroups.com> On 26 Set, 20:01, "Aaron \"Castironpi\" Brady" wrote: > > Good idea. ?If you want prefixed operators: 'and( a, b )' instead of > 'a and b', you'll have to write your own. ?('operator.and_' is bitwise > only.) ?It may be confusing to mix prefix with infix: 'impl( a and b, > c )', so you may want to keep everything prefix, but you can still use > table( f, n ) like Tim said. After a while I'm back, thanks a lot, the truth table creator works, now I just want to parse some strings to make it easier to use. Like (P \/ Q) -> S == S Must return a truth table 2^3 lines... I'm using pyparsing and this should be really simple, but it doesn't allow me to recurse and that makes mu stuck. The grammar BNF is: Var :: = [A..Z] Exp ::= Var | !Exp | Exp \/ Exp | Exp -> Exp | Exp /\ Exp | Exp == Exp I tried different ways but I don't find a smart way to get from the recursive bnf grammar to the implementation in pyparsing... Any hint? From andy55 at gmail.com Thu Oct 30 09:12:19 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Thu, 30 Oct 2008 06:12:19 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <49024ADC.4080600@g.nevcal.com> <777f7a0f-3061-4881-a5e9-b3e19422dca4@q26g2000prq.googlegroups.com> Message-ID: <63bcc9b2-5424-4d92-ae9d-c5a953cf431e@t41g2000hsc.googlegroups.com> > Okay, here's the bottom line: > * This is not about the GIL. ?This is about *completely* isolated > interpreters; most of the time when we want to remove the GIL we want > a single interpreter with lots of shared data. > * Your use case, although not common, is not extraordinarily rare > either. ?It'd be nice to support. > * If CPython had supported it all along we would continue to maintain > it. > * However, since it's not supported today, it's not worth the time > invested, API incompatibility, and general breakage it would imply. > * Although it's far more work than just solving your problem, if I > were to remove the GIL I'd go all the way and allow shared objects. > Great recap (although saying "it's not about the GIL" may cause some people lose track of the root issues here, but your following comment GIL removal shows that we're on the same page). > So there's really only two options here: > * get a short-term bodge that works, like hacking the 3rd party > library to use your shared-memory allocator. ?Should be far less work > than hacking all of CPython. The problem there is that we're not talking about a single 3rd party API/allocator--there's many, including the OS which has its own internal allocators. My video encoding example is meant to illustrate a point, but the real-world use case is where there's allocators all over the place from all kinds of APIs, and when you want your C module to reenter the interpreter often to execute python helper code. > * invest yourself in solving the *entire* problem (GIL removal with > shared python objects). Well, as I mentioned, I do represent a company willing an able to expend real resources here. However, as you pointed out, there's some serious work at hand here (sadly--it didn't have to be this way) and there seems to be some really polarized people here that don't seem as interested as I am to make python more attractive for app developers shopping for an interpreter to embed. >From our point of view, there's two other options which unfortunately seem to be the only out the more we seem to uncover with this discussion: 3) Start a new python implementation, let's call it "CPythonES", specifically targeting performance apps and uses an explicit object/ context concept to permit the free threading under discussion here. The idea would be to just implement the core language, feature set, and a handful of modules. I refer you to that list I made earlier of "essential" modules. 4) Drop python, switch to Lua. The interesting thing about (3) is that it'd be in the same spirit as how OpenGL ES came to be (except in place of the need for free threading was the fact the standard OpenGL API was too overgrown and painful for the embedded scale). We're currently our own in-house version of (3), but we unfortunately have other priorities at the moment that would otherwise slow this down. Given the direction of many-core machines these days, option (3) or (4), for us, isn't a question of *if*, it's a question of *when*. So that's basically where we're at right now. As to my earlier point about representing a company ready to spend real resources, please email me off-list if anyone here would have an interest in an open "CPythonES" project (and get full compensation). I can say for sure that we'd be able to lead with API framework design work--that's my personal strength and we have a lot of real world experience there. Andy From lie.1296 at gmail.com Mon Oct 20 12:39:54 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 20 Oct 2008 16:39:54 +0000 (UTC) Subject: Idenfity numbers in variables References: <1224501408.9143.40.camel@king.imim.es> Message-ID: On Mon, 20 Oct 2008 13:16:48 +0200, Alfons Nonell-Canals wrote: > Hello, > I have a trouble and I don't know how to solve it. I am working with > molecules and each molecule has a number of atoms. I obtain each atom > spliting the molecule. > > Ok. It is fine and I have no problem with it. > > The problem is when I have to work with these atoms. These atoms usually > are only a letter but, sometimes it can also contain one o more numbers. > If they contein a number I have to manipulate them separately. > > If the number was allways the same I know how to identify them, for > example, 1: > > atom = 'C1' > > if '1' in atom: > print 'kk' > > But, how can I do to identify in '1' all possibilities from 1-9, I > tried: > > if '[1-9]', \d,... > That's the job of regular expression: 'import re' numbered_atom = re.compile('[A-Z][a-z]?[0-9]+') if numbered_atom.match('C10'): # this is a numbered atom if numbered_atom.match('C'): # this WON'T match read more about regular expression on the web (hint: python share the same re syntax with many other languages, php, javascript, grep, etc) From prologic at shortcircuit.net.au Thu Oct 23 21:59:46 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 24 Oct 2008 11:59:46 +1000 Subject: How to examine the inheritance of a class? In-Reply-To: References: Message-ID: On Fri, Oct 24, 2008 at 11:36 AM, John Ladasky wrote: > etc. The list of subclasses is not fully defined. It is supposed to > be extensible by the user. Developer. NOT User. Consider: $ python Python 2.5.2 (r252:60911, Oct 13 2008, 15:09:03) [GCC 4.2.4 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): pass ... >>> class Spam(Foo): pass ... >>> Spam.__class__.__bases__ (,) >>> Spam.__class__ >>> Spam.__bases__ (,) >>> spam = Spam() >>> spam.__class__ >>> spam.__class__.__bases__ (,) >>> cheers James -- -- -- "Problems are solved by method" From heston.james at coldbeans.co.uk Wed Oct 15 10:00:16 2008 From: heston.james at coldbeans.co.uk (Heston James - Cold Beans) Date: Wed, 15 Oct 2008 15:00:16 +0100 Subject: ZSI: Classless complexType didn't get dictionary Message-ID: <031801c92ece$5c582130$15086390$@james@coldbeans.co.uk> Guys, I'm in need of some help. I've got an array of objects I'm trying to send to a remote server using ZSI. I've defined my class and type codes as described in the documentation, and I pass the module containing the class/typecode definition into the 'typesmodule' parameter of the ServiceProxy() method. However, when I pass an array of said objects into the method I want to call on the remote service I get an error which simply says: 'Classless complexType didn't get dictionary' What does this mean? It appears to be an error thrown by ZSI when it's trying to serialize the data in my objects, I just don't get why? If anyone can shed any light, or perhaps even just point to a decent complex types tutorial somewhere, or some examples of your own code? I would be greatly indebted to you. Cheers in advance, Heston -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Mon Oct 6 21:48:23 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 6 Oct 2008 21:48:23 -0400 Subject: HARD REAL TIME PYTHON In-Reply-To: Message-ID: <20081007014823.29191.542386757.divmod.quotient.34848@ohm> On Tue, 7 Oct 2008 09:32:37 +1000, James Mills wrote: >On Tue, Oct 7, 2008 at 9:25 AM, Blubaugh, David A. wrote: >> close to real time constraints? For example is it possible to develop a >> python program that can address an interrupt or execute an operation >> within 70 Hz or less?? Are there any additional considerations that I >> should investigate first regarding this matter?? > >Most event-driven frameworks should be capable >of this kind of "real-time" performance. Indeed my own >event/component framework (pymills) is capable of >much more than 70Hz in terms of performance. > >$ python examples/event/bench.py -e 100000 >Setting up Sender... >Setting up Receiver... > >Total Events: 100005 (74663/s after 1.34s) > >If i'm not wrong this roughly equates to about >74 KHz > Indeed, this looks wrong - or at least inconclusive. The benchmark above demonstrates throughput, not minimum (or maximum, or average, or any other statistic) response latency, which is what the OP was really asking about. Jean-Paul From steve at REMOVE-THIS-cybersource.com.au Sun Oct 19 18:26:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Oct 2008 22:26:21 GMT Subject: What's the perfect (OS independent) way of storing filepaths ? References: <010b4bb3$0$20653$c3e8da3@news.astraweb.com> Message-ID: <010bad29$0$20653$c3e8da3@news.astraweb.com> On Sun, 19 Oct 2008 15:40:32 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> In Linux, config files should go into: >> >> ~/./ or /etc// >> >> In Windows (which versions?) then should go into the Documents And >> Settings folder, where ever that is. >> >> There's no single string which can represent both of these conventions! > > The first of those should do nicely for both Linux and Windows: > >>>> os.path.normpath(os.path.expanduser('~/.appname')) > 'C:\\Documents and Settings\\Duncan\\.appname' Except Windows users will be wondering why they have a directory starting with '.' in their home directory. Dot to make files hidden is not AFAIK supported by Windows. -- Steven From gagsl-py2 at yahoo.com.ar Wed Oct 22 02:56:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Oct 2008 04:56:10 -0200 Subject: why this server can not run in python30 References: <81f2badd0810212245k11396aadr485d348dba3c7fe3@mail.gmail.com> Message-ID: En Wed, 22 Oct 2008 03:45:31 -0200, davy zhang escribi?: > import asyncore, asynchat > import os, socket, string > > PORT = 8000 > > class HTTPChannel(asynchat.async_chat): > > def __init__(self, server, sock, addr): > asynchat.async_chat.__init__(self, sock) > self.set_terminator("\r\n") self.set_terminator(b"\r\n") > self.request = None > self.data = "" self.data = b"" Same for all remaining string literals, should be bytes instead. > self.request = string.split(self.data, None, 2) The string module functions are deprecated ages ago in favor of the corresponding string (instance) methods: self.request = self.data.split(None, 2) That's enough - the example worked fine for me after doing these changes. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Oct 12 01:30:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Oct 2008 05:30:33 GMT Subject: Most compact "X if X else Y" idiom References: Message-ID: <010184ce$0$20657$c3e8da3@news.astraweb.com> On Sat, 11 Oct 2008 22:01:46 -0700, jbperez808 wrote: > I find myself having to do the following: > > x = (some complex expression) > y = x if x else "blah" > > and I was wondering if there is any built-in idiom that can remove the > need to put (some complex expression) in the temporary variable x. Use short-circuit Booleans: y = x or "blah" If x is any true value (non-zero number, non-empty string etc.) then y will be set to x; but if x is any false value (zero, empty string, None, empty list, etc.) then y will be set to "blah". However, this technique doesn't work for arbitrary tests. For example, you can't simplify the following: x = (some complex expression) y = x if 100<=x<250 else "blah" (at least I can't think of any way). -- Steven From david at abbottdavid.com Fri Oct 31 11:31:13 2008 From: david at abbottdavid.com (David) Date: Fri, 31 Oct 2008 11:31:13 -0400 Subject: open a new terminal window from another terminal window in linux/unix system In-Reply-To: <691e3a66-65dc-4641-9583-6096717eab0e@c36g2000prc.googlegroups.com> References: <691e3a66-65dc-4641-9583-6096717eab0e@c36g2000prc.googlegroups.com> Message-ID: <490B24C1.4000604@abbottdavid.com> gaurav kashyap wrote: > What i want to do is open another terminal window from already opened > terminal window. > Why? > Can this be achieved.If yes,please provide a tested solution > How about GNU Screen http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-09/msg01932.html -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From castironpi at gmail.com Wed Oct 15 15:03:12 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 15 Oct 2008 12:03:12 -0700 (PDT) Subject: File Management References: Message-ID: On Oct 15, 12:47?pm, "erict1689" wrote: > I am writing this program in which I open up a file and update that > information but to a new file. ?I already have a global variable for > it but how do I go about creating an openable file in the source code? > ?If it helps here is what I have: > > def startUp(): > ? ? # Purpose: opens files and print report headings > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > ? ? payFile=open("payroll.txt", "r") > ? ? payFile.readline() > > def readRecord(): > ? ? # Purpose: reads a record > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > ? ? employeeRec = payFile.readline() > ? ? if employeeRec == "": > ? ? ? ? eof = True > ? ? else: > ? ? ? ? # parse file line for record fields and format/convert for > final output > ? ? ? ? empName = employeeRec[0:25].strip() > ? ? ? ? previousYTD = float(employeeRec[25:40]) > ? ? ? ? payRate = float(employeeRec[40:55]) > ? ? ? ? hoursWorked = float(employeeRec[55:70]) > ? ? ? ? recordCount += 1 > ? ? ? ? eof = False > > def writeRecord(): > ? ? # Purpose: writes the updated record to the output file > ? ? #Parameter > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > def processRecords(): > ? ? # Purpose: loops through input file and processes each record > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > ? ? while not eof: > ? ? ? ? calculatePay() > ? ? ? ? printReportLine() > ? ? ? ? writeRecord() > ? ? ? ? readRecord() > > def calculatePay(): > ? ? # Purpose: calculates pay and updated YTD > ? ? # Return values: float - calculated pay, float - updated YTD amount > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > def printReportLine(): > ? ? # Purpose: prints employee pay information > ? ? # Parameters passed: float - calculated pay, float - updated YTD > amount > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > def closeUp(): > ? ? # Purpose: end of program housekeeping > ? ? global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > ? ? ? ? ? ?payFileUpdated, newYTD, currentPay > > ? ? payFile.close() > ? ? payFileUpdated.close() > ? ? print "\nNumber of records in the file was",recordCount > > Any and all help is appreciated. You can use 'open( "result.txt", "w" )' to create a file if it doesn't exist, and write to it. Use 'a' instead of 'w' to add to the end of an existing file. Later on, you might want to create an object and attributes instead of global variables. The readability is different, but if you're only using one such object, it's not necessarily better. You can always try it out and go back if you don't like it. class PayFile: def startUp( self ): self.payFile=open("payroll.txt", "r") self.payFile.readline() ... etc ... def closeUp( self ): self.payFile.close() self.payFileUpdated.close() print "\nNumber of records in the file was",self.recordCount payFile= PayFile( ) #create a new instance #or payFile= payfilemod.PayFile( ) in a separate module payFile.startUp( ) #call the startUp method Note the 'self' that precedes the variables. It acts as a container for them. It's worth changing in some cases, even if the code is merely more therapeutic to read. From prologic at shortcircuit.net.au Wed Oct 22 07:44:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 22 Oct 2008 21:44:59 +1000 Subject: Create a message In-Reply-To: <59980636-fd0f-405e-8cc0-625034932c34@17g2000hsk.googlegroups.com> References: <59980636-fd0f-405e-8cc0-625034932c34@17g2000hsk.googlegroups.com> Message-ID: On Wed, Oct 22, 2008 at 9:23 PM, Amie wrote: > for example, I wanna display a message that contains a persons age > from the database like so: "Your age is 25". kind of like a messagebox Amie, you're just picking random behavioral examples that you've seen in the software world and asking how to do them in Python. Please go through the Python tutorial, after that go through a few User Interface related tutorials such as Tkinter, or GTK, or similar. Once you have some background and a real problem to solve, we'll help you. This list is not designed to hold your hand and teach you everything about computer science / software. Have a pleasant evening, cheers James -- -- -- "Problems are solved by method" From arnodel at googlemail.com Sat Oct 11 06:42:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 11 Oct 2008 03:42:24 -0700 (PDT) Subject: type-checking support in Python? References: <1df0ae7e-d5c5-4839-9788-703cd58232c5@q9g2000hsb.googlegroups.com> <4e0e9947-5b35-43a6-abe0-5a12d4f88b91@d31g2000hsg.googlegroups.com> <418e3811-1098-4176-9d0e-c767331281bc@a3g2000prm.googlegroups.com> Message-ID: <524688a1-4e7d-4831-826b-67b81d7aef3e@e2g2000hsh.googlegroups.com> On Oct 7, 9:52?pm, Erik Max Francis wrote: > I have a unit system module (unity) in progress as well (it's working > but it's as yet unreleased), but which takes a different approach which > I think has more promise. ?Instead of having multiple united types > derived from different fundamental types, it has its own type Quantity > which takes two arguments: the amount and the units (which are further > data structures). ?That way, the amount and the units are kept > separately and the unit system doesn't know anything specific about the > amount and only deals with the unit system. ?Operations between > quantities enforce the type system (either combining the units for > operations like multiplication, or requiring that they be compatible for > operations like addition or comparison), and simply perform the > appropriate operations on the amount without enforcing any type. ?This > allows you to have united operations on integers, floating point > numbers, decimals, vectors, matrices, quaternions -- whatever values you > may want to support units. > > Mine is more of a dimensional analysis tool (as well as a general unit > converter) since it allows you to define a basis of units, then define > units within that basis and manipulate them -- thus it remembers the > definitions of all the units it has encountered. ?You can define whole > new unit systems (e.g., c.g.s. vs. SI) and have them all relate to each > other, or even define brand new unit systems (e.g., man-day-widgets for > questions like, "If it takes one man three days to make two widgets, how > many widgets can five men make in two weeks?"). > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > ? ?Those who forget the past are condemned to repeat it. > ? ? -- George Santayana It's funny how many people have had the need for this! I have written a module that seems to be very similar. It contains: * A BasicDimension class whose objects are basis vectors in the dimensions vector space. * A Dimension class which is simply a vector in the dimension vector space, which optionally can be named. E.g. distance = new_basic_dim('distance', 'metre') mass = new_basic_dim('mass', 'gram') time = new_basic_dim('time', 'second') speed = new_dim('speed', distance/time) accel = new_dim('accel', speed/time) area = new_dim('area', distance**2) volume = new_dim('volume', distance**3) density = new_dim('density', mass/volume) force = new_dim('force', mass*accel) Then: >>> volume/area >>> distance >>> speed*time >>> distance * A Units class whose objects can registered with a dimension * DObject class whose objects are just objects with a dimension. You can do arithmetic with DObjects provided that you can do arithmetic with their underlying objects. >>> s = Units(time, 1) >>> ms = Units(time, 0.001) >>> s.symbol = 's' >>> print DObject(2, s) + DObject(19, ms) 2.019 s >>> m = Units(distance, 1) >>> print DObject(3.0, m) / DObject(2.0, s) 1.5 [units distance*time**-1 1] >>> Units(distance/time, 1).symbol = 'm/s' >>> print DObject(3.0, m) / DObject(2.0, s) 1.5 m/s >>> print DObject(23.0, s).convert_to(ms) 23000 ms * You can also have separate 'Dimensions systems', e.g. you can have speed, force, time as basic dimensions instead of distance, mass, time (IOW you have a different basis for the dimensions vector space). Then you can convert DObjects between systems. Although this feature is not working to my satisfaction. I have designed this as part of a program to mark automatically online maths/science worksheets, so speed is not really a consideration in my implementation. I have always thought of this as just a tool for my program, but I suppose it can be seen as a sort of dynamic type checking system! -- Arnaud From steve at holdenweb.com Thu Oct 16 23:17:39 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Oct 2008 23:17:39 -0400 Subject: how to get the recipients addresses of an outlook mail in python... In-Reply-To: <47ccfc19-2282-4bb2-ba25-03e27240c54b@t54g2000hsg.googlegroups.com> References: <0f90b2c8-b1c2-4729-a9d0-88142e6f8f39@v53g2000hsa.googlegroups.com> <821cb1d4-9811-4ee3-8630-8b8c10f5e0e3@y21g2000hsf.googlegroups.com> <47ccfc19-2282-4bb2-ba25-03e27240c54b@t54g2000hsg.googlegroups.com> Message-ID: <48F803D3.2040504@holdenweb.com> venutaurus539 at gmail.com wrote: > On Oct 16, 5:22 pm, Miki wrote: >>> Can some one help me in obtaining the set of recipients email >>> addresses from an outlook mail? I tried various options like ... >> message["To"] >> message["Cc"] >> >> HTH, >> -- >> Mikihttp://pythonwise.blogspot.com > > Thanks for your reply... Sorry , it didn't work... > > > session = Dispatch("MAPI.session") > session.Logon('outlook') # MAPI profile name > inbox = session.Inbox > message = inbox.Messages.Item(i + 1) > rec = message["To"] > print rec > > I did some thing like the above code...it said the below error... > raise TypeError, "This object does not support enumeration" > TypeError: This object does not support enumeration > This report is impossibly vague. If you really need help then please take the trouble to provide *exactly* the code you used (pasting from the actual program) and the full traceback. Otherwise we don't even know which statement is going wrong, let alone how. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From david.lyon at preisshare.net Sun Oct 19 19:31:30 2008 From: david.lyon at preisshare.net (david.lyon at preisshare.net) Date: Sun, 19 Oct 2008 19:31:30 -0400 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: <8f167cf0-61c4-4fb0-b5ad-2dd30f2a26b4@u65g2000hsc.googlegroups.com> References: <48FAE71B.2080205@gmail.com> <880dece00810190123n1aaffabfrd5e89178f7bee0d4@mail.gmail.com> <48FAF10F.3060707@gmail.com> <880dece00810190229o300396bx9610c27ca4e218d@mail.gmail.com> <8f167cf0-61c4-4fb0-b5ad-2dd30f2a26b4@u65g2000hsc.googlegroups.com> Message-ID: <20081019193130.jx38caaen4o0wk0o@syd-srv02.ezyreg.com> Quoting bearophileHUGS at lycos.com: > Stef Mientki: >> it's just Object Pascal , which is inferior to Python. > > They are quite different languages, you can't compare them in a simple > way. > Delphi is kinda old, so today there are better languages than Delphi > (like D), but when Delphi 2-3 was out, there weren't many other > languages with IDEs at its level, especially for programs with a nice > GUIs plus interfaces with DBMSs. I have programmed Delphi for years.. and was pretty much forced to move to python for different reasons. I would go along best with the description of delphi being "old". It was great in its time... and had many advancements over others. Still has some things that I would dearly love in python... like "skinned" gui applications. As for porting... don't. Just rewrite them.... Shouldn't be so hard... David From notvalid2 at sbcglobal.net Mon Oct 13 22:07:06 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 13 Oct 2008 19:07:06 -0700 Subject: Python IDLE and Access Denied Message-ID: I had just finished working with IDLE, and tried to double-click on a py file. It produced an OK dialog with the path to the file and the msg "access denied." All my py files act that way. I rebooted and the same thing continues. I copied one py program to another computer, and accessed it there. Python 2.4. Suggestions? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From greg at cosc.canterbury.ac.nz Mon Oct 27 22:28:53 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 28 Oct 2008 15:28:53 +1300 Subject: Ordering python sets In-Reply-To: References: <2513d8ae-97ec-4b81-9ce0-f9e78bb5fa7c@r66g2000hsg.googlegroups.com> <0112ddf3$0$20624$c3e8da3@news.astraweb.com> Message-ID: <6mnc5dFhplncU1@mid.individual.net> On approximately 10/27/2008 10:27 AM, came the following characters from the keyboard of Peter Otten: > Here's a class that can negate arbitrary values > > ... def __init__(self, value): > ... self.value = value > ... def __cmp__(self, other): > ... return -cmp(self.value, other.value) Unfortunately, the __cmp__ method has been eliminated from 3.0 as well, so this won't work as-is. You would need to override __lt__, __eq__, etc. -- Greg From kakak31 at gmail.com Wed Oct 1 18:38:18 2008 From: kakak31 at gmail.com (kaka) Date: Wed, 1 Oct 2008 15:38:18 -0700 (PDT) Subject: Searching for Happiness Message-ID: Excuse me!! Would you stop for a moment?! O...man...Haven't you thought-one day- about yourself ? Who has made it? Have you seen a design which hasn't a designer ?! Have you seen a wonderful,delicate work without a worker ?! It's you and the whole universe!.. Who has made them all ?!! You know who ?.. It's "ALLAH",prise be to him. Just think for a moment. How are you going to be after death ?! Can you believe that this exact system of the universe and all of these great creation will end in in nothing...just after death! Have you thought, for a second, How to save your soul from Allah's punishment?! Haven't you thought about what is the right religion?! Read ... and think deeply before you answer.. It is religion of Islam. It is the religion that Mohammad-peace upon him- the last prophet, had been sent by. It is the religion that the right Bible- which is not distorted-has preached. Just have a look at The Bible of (Bernaba). Don't be emstional. Be rational and judge.. Just look..listen...compare..and then judge and say your word. We advise you visiting : http://www.islam-guide.com http://www.thetruereligion.org http://www.it-is-truth.org http://www.beconvinced.com http://www.plaintruth.org http://english.islamway.com http://www.todayislam.com http://www.prophetmuhammed.org http://www.islamtoday.net/english/ http://www.islamunveiled.org http://www.islamic-knowledge.com We willingly recive any inquries at the e-mail : muslim5 at hotmail.com From ldo at geek-central.gen.new_zealand Mon Oct 13 04:33:20 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 13 Oct 2008 21:33:20 +1300 Subject: PIL on windows XP x64 (64-bit)? References: <09599912-b2b2-4cbf-a861-124ed211bc98@y29g2000hsf.googlegroups.com> Message-ID: In message <09599912-b2b2-4cbf-a861-124ed211bc98 at y29g2000hsf.googlegroups.com>, Berco Beute wrote: > Has anybody here got PIL (the Image lib) working on Windows XP x64 (64- > bit)? There is no version available for that platform from > pythonware.com. Shouldn't your distro maintainers have it in their repositories? From sjmachin at lexicon.net Thu Oct 23 05:33:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 23 Oct 2008 02:33:30 -0700 (PDT) Subject: why does math.pow yields OverflowError (while python itself can calculate that large number) References: <84433286-df55-491a-a310-17b072e8b71a@e2g2000hsh.googlegroups.com> Message-ID: On Oct 23, 8:21?pm, Tzury Bar Yochay wrote: > What is the reason math.pow yields OverflowError while python itself > can > calculate these large numbers. e.g: > > >>> import math > >>> math.pow(100, 154) > 1e+308 > >>> math.pow(100, 155) > > Traceback (most recent call last): > ? File "", line 1, in > OverflowError: math range error>>> eval(('100*'* 155)[:-1]) > > 10000000000000000000000000000000000000000000000000000000000 > 00000000000000000000000000000000000000000000000000000000000 > 00000000000000000000000000000000000000000000000000000000000 > 00000000000000000000000000000000000000000000000000000000000 > 00000000000000000000000000000000000000000000000000000000000 > 0000000000000000L Because math.pow returns a float; 100 ** 155 won't fit in a float. From aspersieman at gmail.com Tue Oct 21 16:15:54 2008 From: aspersieman at gmail.com (Aspersieman) Date: Tue, 21 Oct 2008 22:15:54 +0200 Subject: pymssql stored procedures - NEW THREAD In-Reply-To: <801596.31959.qm@web110515.mail.gq1.yahoo.com> References: <801596.31959.qm@web110515.mail.gq1.yahoo.com> Message-ID: On Tue, 21 Oct 2008 20:44:24 +0200, Mike Hansen wrote: > Hi, > > I saw your posting on the python list about pymssql and you mentioned > that you call stored procedures and get back output parameters. Are you > doing this on Windows or Linux? I can't seem to get it to work on Linux. > Have you gotten it to work on Linux? > > See this discussion on stackoverflow: > > http://stackoverflow.com/questions/191644/how-do-you-get-output-parameters-from-a-stored-procedure-in-python > > Thanks > > > > Hi there I hope you don't mind - I made this a new thread on the list, so others can maybe help out. Although I use Linux quite often, I'm afraid MS SQL (with python) from Linux is something I have not tried yet. :-/ However - here are some things you might try: 1) On the pymssql site (http://pymssql.sourceforge.net/#platforms) there is some documentation on using MS SQL (specifically with pymssql) from Linux - you need to use FreeTDS (http://www.freetds.org/) [although you probably know this already so... :)] 2) (The following I have *only* tried on windows xp and server 2003 and SQL Server 2000) I have tried various suggested ways to have pymssql (and indeed a couple of other python db libraries - which didn't work) - from extensive googling etc., return an output parameter for MS SQL server. The only method that works, for me at least, is the following - using pymssql: * Assume stored procedure called : "sp_GetUserID" that has an output parameter declared as "@id". * Instead of using the "callproc" method of a cursor instead I execute the stored procedure as a normal sql statement that would return rows. import pymssql con = pymssql.connect (host='xxxxx',user='xxxx', password='xxxxx',database='xxxxx') cur = con.cursor() query = "DECLARE @id INT; EXECUTE sp_GetUserID; SELECT @id;" cur.execute(query) outputparameter = cur.fetchall() con.commit() con.close() * You should now be able to access the output parameter from the list object "outputparameter". HTH Regards Nicol Let me know if thats a bit unclear - it's a bit late here :-p -- Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo From lie.1296 at gmail.com Sun Oct 26 08:18:12 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 26 Oct 2008 12:18:12 +0000 (UTC) Subject: Ordering python sets References: <2513d8ae-97ec-4b81-9ce0-f9e78bb5fa7c@r66g2000hsg.googlegroups.com> <0112ddf3$0$20624$c3e8da3@news.astraweb.com> <0113b86c$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Sun, 26 Oct 2008 00:53:18 +0000, Steven D'Aprano wrote: [...] > And how do you find an arbitrary object's creation point without > searching the project's source code? How is it better using the current way? Asking the .implementation field isn't much harder than asking the type (), and is much more obvious that we're asking the "implementation" being used. >>> If I wanted that sort of nightmare, I can already do it by shadowing >>> the builtin: >>> >>> dict = binarytree >>> D = dict({'a': 'A'}) # make a binary tree >> >> I DON'T want THAT sort of nightmare you mentioned... And it'd be >> impossible to have two dictionary that have two different >> implementations. > > Nonsense. > There is two good arguments for using a plain string to specify the implementation used: 1) Plain-text Configuration, 2) argument passing. 1) The current way requires you have a map of the configuration text to a function (i.e. imps = {'linkedlist': linkedlist}), than assign the function to _a global name_ (i.e. lista = imps[configuration[confkey]] -- namespace pollution), then instantiate an object using that (ls = lista ([...]))). The implementation way, only requires ls = list([...], implementation = configuration[confkey]) 2) Easily said, plain text passing is safer and easier than passing function object. >>> There is no possible good that come from this suggestion. The beauty >>> of Python is that the built-in data structures (list, dict, set) are >>> powerful enough for 99% of uses[1], and for the other 1%, you can >>> easily and explicitly use something else. >> >> Oh really? As far as I know, python's list is extremely bad if you're >> inserting data at the beginning of the list > > And how often do you do that? It's not even a deque yet, a regular queue is slow using list in python, and any insertion sort requires you to insert elements into arbitrary position. This makes using array for it a O(n**2). On the other hand, using binary tree is a O(log n). > [...] >>> But *explicitly* is the point. There's never any time where you can do >>> this: >> >> Yes, true, explicitly IS the point. How more explicit can you be than: >> dict({foo: bar}, implementation = 'binarytree') >> >>> type(mydict) is dict > > > You miss the point. With your plan, you can do this: > > D1 = dict({foo: bar}, implementation = 'binarytree') D2 = dict({foo: > bar}, implementation = 'dict') type(D1) is type(D2) > > and yet D1 and D2 have UTTERLY different performance characteristics. It does not matter that it have different performance characteristic. > So > now you need to add ANOTHER test to distinguish dicts-which-are-dicts > from dicts-which-are-binary-trees: How often would you need to care about the specific implementation used? Compare with how often you want to know how to work with the object. Most of the time, you only need to know how to work with it (i.e. knowing its interface), only _sometimes_ when it DOES matter speed-wise, you'd need to know and affect its implementation. > D1.implementation != D2.implementation > > And why? So you can avoid calling a goose a goose, and call it a duck > instead. I think we have an utterly different view here. I wished that list() becomes an abstract type, instead of a data structure. (binarytreelist and arraylist is some property of a list) While you insisted that list() is a data structure, and abstract type is some obscureness somewhere unknown. >> If my memory serves right, binary tree dict and hashed table dict is >> both a dict right? (Duck Typing) >> Only their implementation differs. Implementation is... well, >> "implementation detail". > > Duck typing refers to *interface*, not implementation. Well said, you've just supported my view. > I have no problem > with you using a type with the same interface as a dict. That's what > duck typing is all about. Just don't call it a dict! why do you think binarytreedict is "less dict" than hasheddict? >>> and not know exactly what performance characteristics mydict will >>> have. >> >> Oh... why do I need to know what the performance characteristic of >> mydict is? Unless I know what I'm doing. > > http://www.joelonsoftware.com/articles/fog0000000319.html Sometimes it is good to have control of everything. Sometimes (most of the time) I know I can dump some of the details to think on more important matters. To know which parts need more thinking by doing profiling. > Because when you do this: > > mydict[key] = 1 > > it's important whether each dict lookup is O(1), O(log N) or O(N). For a > dict with one million items, that means that an implementation based on > a binary tree does O(20) times more processing than a dict, and an > implementation based on linear searching does O(1000000) times more > processing. Well, I don't need to know how the dict works if I'm only using it to store twenty items right? (I do know how python's dict/set/list/etc is implemented, but unless that particular dict is central to my program, I'm not going to create my programs around how dict is implemented, I'm going to create it on how my mind works). I don't care how print statement works, unless I'm trying to do something fancy with print. I don't care that print takes a series of electrical signal, then convert it into a series of bytes and pass it into the terminal stdout then the terminal will figure out how to draw the string using the appropriate font at the appropriate place and pass itself to a window manager which would compose the desktop into an image then pass itself to the graphic driver which would convert the image to electrical signal to be sent to the graphic card which would do some fancy tricks before sending it to the monitor, when what I need is only to show the user a simple welcome message. The reason we use high-level language is that we know we don't need to care about some details. Only when the detail matters then we take care of it. If I do care about all the details, I'd use C, no, no, lower, I'd use assembly, no, lower..., I'd design my own CPU, no even lower, I'd design my own non-von-neumann architecture. I don't think I can change the rules of physics though, but if I can... >> I don't need >> to know, they all looks and behave the same (Duck Typing)... > > Until you try a simple operation like len(mydict) and it takes three > minutes because the implementation you choose is really inefficient. ... then I know I have chosen the wrong data structure, and I know I need to change it. >>> If you want a binary tree, ask for a binary tree. >> >> Yeah, you ask for binary tree EXPLICITLY: bintreedict = dict({a:b}, >> implementation = 'binarytree') > > Or you could do it the right way: For example, if I have a certain unknown object. What is easier? >>> type(URO) # Unidentified Round Object => returns (*&%$^%* or >>> type(URO) => returns diningplate only after three thousand years of continuous and laborious researching, at last I found out that (*&%$^%* is an alien dining plate, and it does have all the features and functionality as earth dining plate, although due to it being made of CClKO32C32CH42U it is much more resistant to acidity but would melt when you put carrot on it. Only when I want to eat carrot, would I care that it is an alien dining plate. And only when I want to eat something extremely acidic, I'd chose the alien dining plate over earth dining plate. From george.sakkis at gmail.com Fri Oct 3 03:30:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 3 Oct 2008 00:30:11 -0700 (PDT) Subject: del and sets proposal References: Message-ID: <9990fa15-34fc-4e58-987f-db01d3b829a7@k30g2000hse.googlegroups.com> On Oct 2, 6:20?pm, Larry Bates wrote: > You can do the following: > > a = [1,2,3,4,5] > del a[0] > > and > > a = {1:'1', 2: '2', 3: '3', 4:'4', 5:'5'} > del a[1] > > why doesn't it work the same for sets (particularly since sets are based on a > dictionary)? > > a = set([1,2,3,4,5]) > del a[1] > > Yes I know that sets have a remove method (like lists), but since dictionaries > don't have a remove method, shouldn't sets behave like more like dictionaries > and less like lists? ?IMHO del for sets is quite intuitive. ?I guess it is too > late to change now. Funny, I would welcome a change in the opposite direction: drop completely the "del a[i]" syntax from the language and use an explicit (non-special) method name, e.g. a.delete(i) or a.remove(i). Having some functionality exposed through methods and some through function builtins (e.g. len()) is more than enough; having a third way through the del statement is unnecessarily perl-ish. George From bignose+hates-spam at benfinney.id.au Mon Oct 6 20:34:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 07 Oct 2008 11:34:53 +1100 Subject: Is PyFIT dead and abandoned? References: <9b3e48f2-9f13-49d0-98b2-0bcbe093d515@m3g2000hsc.googlegroups.com> Message-ID: <87zllhkzte.fsf@benfinney.id.au> "James Mills" writes: > On Tue, Oct 7, 2008 at 5:18 AM, wrote: > > Has PyFIT been completely abandoned? Is there a better alternative or > > other resources to help me integrate fitnesse and python? > > I for one am not interested in this kind of framework for testing - > and yet I come from a strict Software Engineering background where > this kind of User Acceptance and Requirements-based testing is > taught. How, then, do you automate functional testing of the full system? > I think you'll find most developers prefer to use unit test > frameworks and python has a great one built-in to the standard > library. In 99.9% of use cases, writing unit tests and well > documented and well designed, re-usable units of code is far better > than what any Requirements and Interactive testing framework could > ever offer. I completely disagree. Unit tests are essential for testing code *units*; e.g. functions and classes and attributes (oh my).They're a poor fit for testing the behaviour of the overall system: for that, a functional test suite is needed, and PyFIT seems to be a good . Automated unit tests and automated functional tests are complementary, and do not replace one another. Both are needed to have confidence in the code. -- \ ?Injustice is relatively easy to bear; what stings is justice.? | `\ ?Henry L. Mencken | _o__) | Ben Finney From ladasky at my-deja.com Thu Oct 23 21:41:05 2008 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 23 Oct 2008 18:41:05 -0700 (PDT) Subject: How to examine the inheritance of a class? References: Message-ID: <91511c61-8aa5-42cc-868e-9d46f3d5f257@b31g2000prb.googlegroups.com> I forgot to add -- though I suspect it should not matter -- I'm using Python 2.5.1 on Ubuntu Linux 8.04. From tjreedy at udel.edu Sat Oct 18 23:28:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Oct 2008 23:28:45 -0400 Subject: loops In-Reply-To: References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> Message-ID: MRAB wrote: > On Oct 18, 7:31 pm, Terry Reedy wrote: >> Python provide while loops for more fine-grain control, and a protocol >> so *reuseable* iterators can plug into for loops. Duncan showed you >> both. If you *need* a doubling loop variable once, you probably need >> one more than once, and the cost of the doubling generator is amortized >> over all such uses. Any Python proprammer should definitely know how to >> write such a thing without hardly thinking. We can squeeze a line out >> of this particular example: >> >> def doubling(value, limit): >> while value <= limit: >> yield value >> value += value >> > Shouldn't the upper limit be exclusive in order to be Pythonic? Yes, and perhaps I could have mentioned that, but the OP wanted a port of the C construct. From lave.wang.w at gmail.com Thu Oct 23 08:35:22 2008 From: lave.wang.w at gmail.com (Lave) Date: Thu, 23 Oct 2008 20:35:22 +0800 Subject: Question about scope In-Reply-To: References: Message-ID: <29de18070810230535x5d6d7c3hdf93c8c8ecc5ed7b@mail.gmail.com> Newbie too. I think you shoud qualify Global with the module name. On 10/23/08, Pat wrote: > I have a Globals class. > > In it, I have a variable defined something like this: > > remote_device_enabled = bool > > In one module, I assign True/False to Globals.remote_device_enabled. > Once set, this value never changes. > > In another module, at the top after the imports statements, I tried this: > > from Globals import * > from import Globals ? > RDE = Globals.remote_device_enabled > Here, RDE = .Globals.remote_device_enabled > This way, I thought that I could just use 'if RDE:' > > Within the functions, however, I get a different value. What am I > misunderstanding? > > I tried this at the top of the module (but it didn't word): > > global RDE > RDE = Globals.remote_device_enabled > > Of course, within a function, the variable using the same two lines of > code assigns the correct value to RDE. > > Thank you, > > Total Newbie > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards, Lave From bj_666 at gmx.net Sat Oct 25 19:31:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Oct 2008 23:31:41 GMT Subject: Limit between 0 and 100 References: Message-ID: <6mhoitFgjc69U4@mid.uni-berlin.de> On Sat, 25 Oct 2008 13:42:08 -0700, chemicalclothing wrote: > Hi. I'm very new to Python, and so this is probably a pretty basic > question, but I'm lost. I am looking to limit a float value to a number > between 0 and 100 (the input is a percentage). > > I currently have: > > integer = int() What's this supposed to do? I think writing it as ``integer = 0`` is a bit simpler and more clear. > running = True > > while running: > try: > per_period_interest_rate = float(raw_input("Enter per-period > interest rate, in percent: ")) > break > except ValueError: > print "Please re-enter the per-period interest rate as a number > between 0 and 100." You have to check for the range before you leave the loop. The `ValueError` handling just makes sure that the input is a valid float. The ``try``/``except`` structure can have an ``else`` branch. Maybe that can be of use here. Ciao, Marc 'BlackJack' Rintsch From mjurczuk at gmail.com Fri Oct 31 06:10:53 2008 From: mjurczuk at gmail.com (Marcin Jurczuk) Date: Fri, 31 Oct 2008 03:10:53 -0700 (PDT) Subject: python openssl x509 CA Message-ID: <381603cf-f0c1-4a51-bced-46b7c5065b3f@w1g2000prk.googlegroups.com> Hello, I'm fighting with Certificate Authority functionality with python I stuck on following problem: How to sign CSR using CA key and write resulted certificate. You can do it using following openssl cmd: openssl ca -cert CA/cert.pem -keyfile CA/private/cakey.pem -policy policy_anything -out user_cert.pem -infiles userreq.pem My try was: import OpenSSL.crypto as pki #load CA key: ca_key=pki.load_privatekey(pki.FILETYPE_PEM,open('CA/private/ cakey.pem').read(),'haselko') #load user's csr: csr=pki.load_certificate_request(pki.FILETYPE_PEM,open('userreq.pem').read()) # sign csr csr.sign(ca_key,'sha1') I don't get any erorrs however I dont' see any way to write or get result from such operation csr exports following methods: csr.add_extensions csr.get_pubkey csr.get_subject csr.set_pubkey csr.sign csr.verify I want to create pure python implementation without use of openssl wrapped with python code. Regards, From slash_dev_slash_null_2000 at yahoo.com Sun Oct 19 19:09:56 2008 From: slash_dev_slash_null_2000 at yahoo.com (Mark Sapiro) Date: Sun, 19 Oct 2008 16:09:56 -0700 (PDT) Subject: urllib2.HTTPError: HTTP Error 204: NoContent References: Message-ID: On Oct 19, 9:49?am, Philip Semanchuk wrote: > On Oct 19, 2008, at 6:13 AM, silk.odyssey wrote: > > > I am getting the following error trying to download an html page using > > urllib2. > > > urllib2.HTTPError: HTTP Error 204: NoContent > > > The url is of this type: > > >http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D... > > > I can open it in my browser without problems.Any ideas on a solution? > > Are you changing the user-agent? Some sites sniff user agents and ? > return different results to browsers than to suspected bots. I tried it. >>> import urllib2 >>> url = 'http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D183VXJS74KNQ89D0NRR2%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000KJX3A0' >>> op = urllib2.urlopen(url) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/urllib2.py", line 121, in urlopen return _opener.open(url, data) File "/usr/lib/python2.5/urllib2.py", line 380, in open response = meth(req, response) File "/usr/lib/python2.5/urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.5/urllib2.py", line 418, in error return self._call_chain(*args) File "/usr/lib/python2.5/urllib2.py", line 353, in _call_chain result = func(*args) File "/usr/lib/python2.5/urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 204: NoContent >>> headers = {} >>> headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' >>> ro = urllib2.Request(url, None, headers) >>> op = urllib2.urlopen(ro) >>> page = op.read() >>> page (lots of HTML) So the answer is as Philip suggests - amazon.com doesn't like 'Python- urllib/2.5' as a User-Agent. You have to give it something that looks like a browser. -- (for email use this address please - you can figure it out) Mark Sapiro mark at msapiro net Any clod can have the facts; San Francisco Bay Area, California having opinions is an art. - C. McCabe, The Fearless Spectator From khamenya at gmail.com Fri Oct 3 17:38:05 2008 From: khamenya at gmail.com (Valery Khamenya) Date: Fri, 3 Oct 2008 23:38:05 +0200 Subject: Problem: neither urllib2.quote nor urllib.quote encode the unicode strings arguments Message-ID: <84fecab0810031438l557930a9yfcf9e72926ea9a93@mail.gmail.com> Hi all things like urllib.quote(u"???? M?ller ") fail with error message: : u'\u043f' Similarly with urllib2. Anyone got a hint?? I need it to form the URI containing non-ascii chars. thanks in advance, best regards -- Valery -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Mon Oct 13 09:14:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 13 Oct 2008 06:14:15 -0700 (PDT) Subject: Append a new value to dict References: <115bfea1-356a-4977-8e47-e519bde57215@v53g2000hsa.googlegroups.com> Message-ID: jdd: > foo = {'bar': 'baz'} > foo.update({'quux': 'blah'}) That creates a new dict, to throw it away. Don't do that. Use the standard and more readable syntax: > foo = {...} > foo['quux'] = 'blah' Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Oct 7 17:50:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Oct 2008 18:50:50 -0300 Subject: how to start thread by group? References: Message-ID: En Tue, 07 Oct 2008 13:25:01 -0300, Terry Reedy escribi?: > Lawrence D'Oliveiro wrote: >> In message , >> Gabriel Genellina wrote: >> >>> Usually it's more efficient to create all the MAX_THREADS at once, and >>> continuously feed them with tasks to be done. >> Given that the bottleneck is most likely to be the internet >> connection, I'd >> say the "premature optimization is the root of all evil" adage applies >> here. > > There is also the bottleneck of programmer time to understand, write, > and maintain. In this case, 'more efficient' is simpler, and to me, > more efficient of programmer time. Feeding a fixed pool of worker > threads with a Queue() is a standard design that is easy to understand > and one the OP should learn. Re-using tested code is certainly > efficient of programmer time. Managing a variable pool of workers that > die and need to be replaced is more complex (two loops nested within a > loop) and error prone (though learning that alternative is probably not > a bad idea also). I'd like to add that debugging a program that continuously creates and destroys threads is a real PITA. -- Gabriel Genellina From seidymam at gmail.com Thu Oct 30 03:28:39 2008 From: seidymam at gmail.com (Seid Mohammed) Date: Thu, 30 Oct 2008 10:28:39 +0300 Subject: Unicode Problem Message-ID: <179b305e0810300028t3efa8319vf9094f166c38cfbf@mail.gmail.com> I am new to python. I want to print Amharic character using the Python IDLE. here goes somple code ============================================================== >>> abebe = '??? ?? ??' >>> abebe '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 \xe1\x89\xa0\xe1\x88\xb6 \xe1\x89\xa0\xe1\x88\x8b' >>> print abebe ??? ?? ?? >>> abeba = ['???','??','??'] >>> abeba ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', '\xe1\x89\xa0\xe1\x88\x8b'] >>> print abeba ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', '\xe1\x89\xa0\xe1\x88\x8b'] >>> len(abebe) 23 ======================== so my question is 1)why >>> abebe prints '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 \xe1\x89\xa0\xe1\x88\xb6 \xe1\x89\xa0\xe1\x88\x8b' instead of ??? ?? ?? 2) why >>> print abeba don't print the expected ??? ?? ?? string thanks a lot. Seid M. From harald.luessen at gmx.de Mon Oct 6 13:10:26 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Mon, 06 Oct 2008 19:10:26 +0200 Subject: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x] References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> <87myhjcu7g.fsf@hbox.dyndns.org> <00f89ca3$0$20633$c3e8da3@news.astraweb.com> Message-ID: On Sun, 05 Oct 2008 "Aaron \"Castironpi\" Brady" wrote: >There's the possibility that the most important words should go first in >this case: > >result_flag__t > >But, I'll admit that other people could have learned different orders of >scanning words than I, especially depending on their spoken language >backgrounds. A poll of the newsgroup isn't exactly academically >impartial sampling, but there aren't any better ways to make decisions, >are there? (I think it would be easy to make either one a habit.) > >Here's the other option in the same context: > >def function(vocab_list, result_flag__t, max_value): > result, flag = result_flag__t > pass > >To be thorough, there's also a trailing double underscore option. > >def function(vocab_list, result_flag__, max_value): > result, flag = result_flag__ > pass > >Which I don't recognize from any other usages, but I defer. If there >aren't any, conditionally, I think this is my favorite. t__result_flag and result_flag__t have the advantage that you can search for t__ or __t as start or end of a name if you want to find and change all these places in the source. You can compare it with the decision to use reinterpret_cast(...) as a cast operator in C++. It is ugly but much easier to find than (long)... A search for __ alone would have too many hits in Python. Harald From castironpi at gmail.com Thu Oct 30 23:11:44 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 30 Oct 2008 20:11:44 -0700 (PDT) Subject: Restricted Execution of untrusted code References: <6e0687fb-666b-4dad-947b-e610b8d2cf24@m32g2000hsf.googlegroups.com> Message-ID: <009939e7-23de-45ce-9326-72a15072b1de@r36g2000prf.googlegroups.com> On Oct 30, 3:50?pm, Aaron Brady wrote: > On Oct 30, 6:35?am, "Emanuele D'Arrigo" wrote: > > > > > I noticed that this issue has been discussed in this newsgroup > > periodically over the years and I seem to understand that - > > comprehensive- safe/restricted execution of untrusted code in python > > is currently quite hard to achieve. > > > What if the safety requirements are a little relaxed though? All I'd > > want to prevent is for the code opening/damaging files, formatting > > drives or similarly catastrophic exploits. I'm not particularly > > concerned if the application freeze or crashes. Nor if the > > application's objects are inspected and exploited. All I want is to > > make sure that if somebody uses my application plus a third party > > plugin for it, the worst that can happen is that they can't use my > > application with that plugin. > > > Is that feasible? > > > Thanks for your help! > > > Manu > > Hi. ?One opinion is that you could do it with a custom Python > installation, removing or restricting the import statement, removing > or restricting the os module, the file type, etc. ?Here is some > problematic code: > > >>> cust= (1).__class__.__bases__[0].__subclasses__() > >>> [ x for x in cust if x.__name__== 'file' ] > > [] > > The foreign code can get to the 'file' type. ?If you don't have it, > that's not a problem. > > Otherwise, you might be able to remove access to it by modifying > however it is the 'cust' list is obtained. ?Perhaps you can use the > technique that's used to change the value of integers. ?Keep us > posted. ?Does this give you any ideas? The hackery I was referring to makes a cut into this particular vulnerability. It empties the 'tp_subclasses' field of 'object', but who knows how else one could get to it? from _ctypes import _cast_addr _data_cast= c.PYFUNCTYPE(c.py_object, c.py_object, c.py_object, c.py_object)(_cast_addr) x= _data_cast( object, None, c.c_void_p ) y= _typeobject.from_address( x.value ) y.tp_subclasses= 0 #<--- dirty work done here (embarassed) assert (1).__class__.__bases__[0].__subclasses__()== [] #<--- (!!!) Though, oddly enough, _data_cast( object, None, _typeobject ) doesn't work. From castironpi at gmail.com Wed Oct 1 14:08:28 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 1 Oct 2008 11:08:28 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> <80ffbfcf-9fbc-458a-aaf0-ffea24db390f@34g2000hsh.googlegroups.com> Message-ID: <0241ac50-cd47-470d-991b-fc97a1405296@h2g2000hsg.googlegroups.com> On Oct 1, 5:43?am, jhermann wrote: > I didn't see this mentioned in the thread yet: the double-lambda is > unnecessary (and a hack). What you should do when you need early > binding is... early binding. ;) > > Namely: > > f = [lambda n=n: n for n in range(10)] > print f[0]() > print f[1]() > > Note the "n=n", this prints 0 and 1 instead of 9/9. Yes it was mentioned earlier. I think its similar. They both create ten new namespaces. You could do something like this (I hit a bump with eval and globals() when I tried it): def early( string ): return eval( string, current_namespace ) f = [early( 'lambda: n' ) for n for n in range(10)] print f[0]() print f[1]() Furthermore, I don't think the binding semantics of the language are completely static binding. What does that definition say about mutating a value? I think it's ambiguous and there's no obvious use case that favors either one. From ldo at geek-central.gen.new_zealand Fri Oct 17 16:26:08 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Oct 2008 09:26:08 +1300 Subject: Interface to Matlab References: <944ecfcf-635b-441f-9e8c-a68918f53e72@u40g2000pru.googlegroups.com> Message-ID: In message <944ecfcf-635b-441f-9e8c-a68918f53e72 at u40g2000pru.googlegroups.com>, Daniel wrote: > Have you looked at > http://www.scipy.org/ > and http://matplotlib.sourceforge.net/ > > They do an awful lot of what matlab does. This one I think rolls them all up into a package that does even more. > Also, I think that Matlab's perferred language is Java. It has its own built-in language (good for some things, crappy for others), though no doubt it's been making more use of Java over the years. From digitig at gmail.com Fri Oct 3 07:27:50 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 3 Oct 2008 12:27:50 +0100 Subject: Inheritance but only partly? In-Reply-To: References: Message-ID: 2008/10/2 process : > Let's say I have a class X which has 10 methods. > > I want class Y to inherit 5 of them. > > Can I do that? As others have said, no. What nobody seems to have said yet is why. If Y descends from X, you are saying that Y is an X; that a Y can be used anywhere an X can. If Y doesn't support some methods of X then it is *not* an X, and *can't* be used anywhere an X can. Rather than looking at workarounds, as others have, I think you need to go back to your design and work out what's gone wrong that you /want/ to descend Y from X. Your present design is wrong, plain and simple. Working around it won't fix that. -- Tim Rowe From rhamph at gmail.com Thu Oct 30 22:38:46 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Thu, 30 Oct 2008 19:38:46 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <63d8aa77-f863-4d8c-b135-2088d0b68760@a70g2000hsh.googlegroups.com> <6214d7a20810291545x5e7cc197u5db15063f262d8d2@mail.gmail.com> <4908FA60.5000201@g.nevcal.com> <4222a8490810300626q3275639dm774181869b86ee47@mail.gmail.com> <490A3B25.1080809@g.nevcal.com> Message-ID: <6e1aba08-fe50-48b9-95e8-3bf2a726e9ea@b31g2000prb.googlegroups.com> On Oct 30, 8:23?pm, "Patrick Stinson" wrote: > Speaking of the big picture, is this how it normally works when > someone says "Here's some code and a problem and I'm willing to pay > for a solution?" I've never really walked that path with a project of > this complexity (I guess it's the backwards-compatibility that makes > it confusing), but is this problem just too complex so we have to keep > talking and talking on forum after forum? Afraid to fork? I know I am. > How many people are qualified to tackle Andy's problem? Are all of > them busy or uninterested? Is the current code in a tight spot where > it just can't be fixed without really jabbing that FORK in so deep > that the patch will die when your project does? > > Personally I think this problem is super-awesome on the hobbyest's fun > scale. I'd totally take the time to let my patch do the talking but I > haven't read enough of the (2.5) code. So, I resort to simply reading > the newsgroups and python code to better understand the mechanics > problem :( The scale of this issue is why so little progress gets made, yes. I intend to solve it regardless of getting paid (and have been working on various aspects for quite a while now), but as you can see from this thread it's very difficult to convince anybody that my approach is the *right* approach. From greg at cosc.canterbury.ac.nz Thu Oct 30 20:58:13 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 31 Oct 2008 13:58:13 +1300 Subject: Finding the instance reference of an object In-Reply-To: References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <6mv3bnFj2qd8U1@mid.individual.net> Dale Roberts wrote: > Okay, you can have it that way, but every time you explain to someone > that Python passes "By Value", you will have to add the additional > baggage that, oh, by the way, there is a completely different meaning > for "value" in Python than what you are used to. For what it's worth, I happen to agree that telling someone that Python passes parameters "by value" without being sure they understand exactly what "by value" means, is not a good idea -- not because the term isn't well-defined, but because of the widespread confusion out there about it. But equally I wouldn't tell someone that it's *not* by value, because if they do happen to correctly understand what it means, that will confuse them just as much. So my recommendation is just to tell them that it works by assigning the result of evaluating the actual parameter to the formal parameter. If they understand how assignment works in Python, that tells them all they need to know. If they don't understand how assignment works, then they have a more fundamental knowledge gap that needs to be corrected first. -- Greg > > Then the questions and puzzled looks will start... > > And when they tell their friend that Joe The Programmer said it's Pass > By Value, your additional context may not be present any longer, and > the friend will be very confused. > > In my opinion, best just to head it off and call it something > different so as not to confuse. > > dale From arnodel at googlemail.com Wed Oct 29 15:37:13 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 29 Oct 2008 12:37:13 -0700 (PDT) Subject: Python Regex Question References: <8ba29fe7-2614-4186-952d-5a7c08d30f29@q9g2000hsb.googlegroups.com> Message-ID: <0632c105-bd66-4e9b-8918-51feff99b142@v72g2000hsv.googlegroups.com> On Oct 29, 7:01?pm, Tim Chase wrote: > > I need a regex expression which returns the start to the x=ANIMAL for > > only the x=Dog fragments so all my entries should be start ... > > (something here) ... x=Dog . ?So I am really interested in fragments 1 > > and 3 only. > > > My idea (primitive) ^start.*?x=Dog doesn't work because clearly it > > would return results > > > start > > x=Dog ?# (good) > > > and > > > start > > x=Cat > > stop > > start > > x=Dog # bad since I only want start ... x=Dog portion > > Looks like the following does the trick: > > ?>>> s = """start ? ? ?#frag 1 start > ... x=Dog # frag 1 end > ... stop > ... start ? ?# frag 2 start > ... x=Cat # frag 2 end > ... stop > ... start ? ? #frag 3 start > ... x=Dog #frag 3 end > ... stop""" > ?>>> import re > ?>>> r = re.compile(r'^start.*\nx=Dog.*\nstop.*', re.MULTILINE) > ?>>> for i, result in enumerate(r.findall(s)): > ... ? ? print i, repr(result) > ... > 0 'start ? ? ?#frag 1 start\nx=Dog # frag 1 end\nstop' > 1 'start ? ? #frag 3 start\nx=Dog #frag 3 end\nstop' > > -tkc This will only work if 'x=Dog' directly follows 'start' (which happens in the given example). If that's not necessarily the case, I would do it in two steps (in fact I wouldn't use regexps probably but...): >>> for chunk in re.split(r'\nstop', data): ... m = re.search('^start.*^x=Dog', chunk, re.DOTALL | re.MULTILINE) ... if m: print repr(m.group()) ... 'start #frag 1 start \nx=Dog' 'start #frag 3 start \nx=Dog' -- Arnaud From rafesacks at gmail.com Fri Oct 24 04:47:10 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 24 Oct 2008 01:47:10 -0700 (PDT) Subject: @property decorator doesn't raise exceptions Message-ID: Hi, I've encountered a problem which is making debugging less obvious than it should be. The @property decorator doesn't always raise exceptions. It seems like it is bound to the class but ignored when called. I can see the attribute using dir(self.__class__) on an instance, but when called, python enters __getattr__. If I correct the bug, the attribute calls work as expected and do not call __getattr__. I can't seem to make a simple repro. Can anyone offer any clues as to what might cause this so I can try to prove it? Cheers, - Rafe From nospam at spamhaters.com Wed Oct 1 04:30:42 2008 From: nospam at spamhaters.com (sc) Date: Wed, 01 Oct 2008 03:30:42 -0500 Subject: list to tuple conversion References: Message-ID: Gary M. Josack wrote: > sc wrote: >> clp: >> >> Thanx to a recent thread I am able to have a print string >> with a variable number of formatters -- what I now lack for >> the creation of an elegant print statement is a tuple -- >> following is the code, the last line of which does not work: >> >> >> #!/usr/bin/python >> import xml.sax >> import eaddyhandler >> parser = xml.sax.make_parser() >> h = eaddyhandler.EAddyHandler() >> parser.setContentHandler(h) >> parser.parse(".ea.xml") >> for i in range(1, len(h.m)): >> k = "r%06d" % i >> col = len(h.m[k]) >> if col > 2 and h.m[k][0] > " ": >> print (col * '%-30s') % h.m[k] >> >> >> What's going on is I have an oocalc spreadsheet for >> e-addresses -- column 1 has the name, and then I keep >> adding e-addresses for ppl when they get new ones, as >> successive entries on their row, meaning each row has >> a variable number of e-address columns. I have an xml >> extractor that runs before this script using >> odf.opendocument, which works famously. >> >> My class, EAddyHandler, also works, and builds its dictionary >> of rows in 'm', forgive me, no flames please, I needed a >> short name for the dictionary I have to type it so many times. >> The key to 'm' is an 'r' + row number, so I can get >> stuff out of it and it's still in the right order, fun >> with dictionaries. >> >> What I was hoping for was something that could vary the >> source for the print statement as cleanly as the 'col' >> multiplication creates the print format, but the list, >> 'h.m[k]' is not a tuple, it's a list, and I'm just not >> quite where I am trying to get with this. >> >> If there were a builtin function that took a list and >> returned a tuple, I'd be there, but if there is such a >> thing I need someone to point me at it. I can't help >> thinking I am missing some obvious construct, and I'll >> be advised to go reread the tutorial, but I'm not there, >> and if you can take pity on me and point me there, I'll >> be your friend for life. Well -- I'll be grateful... >> >> TIA, >> >> Scott >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > >>> L = [1,2,3,4,5] > >>> t = tuple(L) > >>> t > (1, 2, 3, 4, 5) fine, documented now, for the world to see, I'm an idiot, fine, but anyway, thank you both, I'll shutup now. sc From ldo at geek-central.gen.new_zealand Wed Oct 15 02:38:25 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 15 Oct 2008 19:38:25 +1300 Subject: problem using ctypes with MMX intrinsics References: Message-ID: In message , dcharno wrote: > I can load the library and access functions inside it, but > I getting a seg fault when I hit one of the intrinsics. I assume that SIGSEGV indicates some (mis)alignment issue. If the instructions were not valid, you'd get SIGILL instead. From tjreedy at udel.edu Wed Oct 29 15:04:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Oct 2008 15:04:09 -0400 Subject: parsing MS word docs -- tutorial request In-Reply-To: References: <504bbcdb-2ba1-4ac8-85e1-e86d693a214a@z6g2000pre.googlegroups.com> Message-ID: Kay Schluehr wrote: > On 28 Okt., 15:25, bp.tralfamad... at gmail.com wrote: >> All, >> >> I am trying to write a script that will parse and extract data from a >> MS Word document. Can / would anyone refer me to a tutorial on how to >> do that? (perhaps from tables). I am aware of, and have downloaded >> the pywin32 extensions, but am unsure of how to proceed -- I'm not >> familiar with the COM API for word, so help for that would also be >> welcome. >> >> Any help would be appreciated. Thanks for your attention and >> patience. >> >> ::bp:: > > One can convert MS-Word documents into some class of XML documents > called MHTML. If I remember correctly those documents had an .mht > extension. The result is a huge amount of ( nevertheless structured ) > markup gibberish together with text. If one spends time and attention > one can find pattern in the markup ( we have XML and it's human > readable ). A related solution is to use OpenOffice to convert to OpenDocumentFormat, a zipped multiple XML format, and then use ODFPY to parse the XML and access the contents as linked objects. http://opendocumentfellowship.com/development/projects/odfpy From weiguo6 at gmail.com Wed Oct 8 21:35:37 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Wed, 8 Oct 2008 18:35:37 -0700 Subject: A question about funcation parameter and self defined object In-Reply-To: <47c890dc0810081750s6325251ewaaf5eaf698b9ee02@mail.gmail.com> References: <47c890dc0810081750s6325251ewaaf5eaf698b9ee02@mail.gmail.com> Message-ID: Hi Chris, Thanks a lot for reply, you are right. I want to use this method as a static method as: translation = staticmethod( translation ) I think that here the built in function pass None. So we can not pass any self defined object for static method? Best regards, Wei On Wed, Oct 8, 2008 at 5:50 PM, Chris Rebert wrote: > On Wed, Oct 8, 2008 at 4:36 PM, Wei Guo wrote: > > Hi, > > > > I defined a class called vec3 which contains x, y, z and in another > > function, I tried to call a function which takes a vec3 as a parameter, > but > > it seems that parameter is passed as a generic object and I can not > access x > > , y, z in my vec3. Could anyone help me with that? > > Being dynamically typed, Python has no notion of variables having > types, so the object isn't being "passed as a generic object", you're > getting what really is a "generic object" value of type NoneType, > which means the value of traV is indeed None, not vec3(). > > > > > class vec3: > > def __init__(self, x_ = 0.0, y_ = 0.0, z_ = 0.0): > > self.x = x_ > > self.y = y_ > > self.z = z_ > > class mat4: > > def translation( traV = vec3() ): > > tranM.rowLst[index][0] = traV.x > > AttributeError: 'NoneType' object has no attribute 'x' > > This code is perfectly fine. See below. > > > > > Could anyone help me how to turn the traV as type of vec3() instead of > > NoneType object? > > That's not what's happening. It's not like traV is being cast to > NoneType thus making x inaccessible, as that's not even possible to > express in Python. > What's happening is something is calling translation() with None as an > argument, and of course None (the value the caller provided for traV) > has no attribute 'x', hence the error. So, check the full exception > traceback and see who's calling translation() and how the argument > being passed to it got to be None. > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > > > > > Thanks a lot, > > > > Wei > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Oct 29 15:01:17 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 29 Oct 2008 14:01:17 -0500 Subject: Python Regex Question In-Reply-To: <8ba29fe7-2614-4186-952d-5a7c08d30f29@q9g2000hsb.googlegroups.com> References: <8ba29fe7-2614-4186-952d-5a7c08d30f29@q9g2000hsb.googlegroups.com> Message-ID: <4908B2FD.30402@tim.thechases.com> > I need a regex expression which returns the start to the x=ANIMAL for > only the x=Dog fragments so all my entries should be start ... > (something here) ... x=Dog . So I am really interested in fragments 1 > and 3 only. > > My idea (primitive) ^start.*?x=Dog doesn't work because clearly it > would return results > > start > x=Dog # (good) > > and > > start > x=Cat > stop > start > x=Dog # bad since I only want start ... x=Dog portion Looks like the following does the trick: >>> s = """start #frag 1 start ... x=Dog # frag 1 end ... stop ... start # frag 2 start ... x=Cat # frag 2 end ... stop ... start #frag 3 start ... x=Dog #frag 3 end ... stop""" >>> import re >>> r = re.compile(r'^start.*\nx=Dog.*\nstop.*', re.MULTILINE) >>> for i, result in enumerate(r.findall(s)): ... print i, repr(result) ... 0 'start #frag 1 start\nx=Dog # frag 1 end\nstop' 1 'start #frag 3 start\nx=Dog #frag 3 end\nstop' -tkc From martin at v.loewis.de Wed Oct 15 04:59:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 15 Oct 2008 10:59:31 +0200 Subject: Installing Python 2.4 over 2.4? In-Reply-To: References: <48f4f262$0$25779$9b622d9e@news.freenet.de> <48f514c4$0$30052$9b622d9e@news.freenet.de> Message-ID: <48f5b0f3$0$5140$9b622d9e@news.freenet.de> > More a generic -- some applications allow one control over optional > features. "Change" would let one, uhm, change the options that were > installed; "repair" attempt to restore the installation to the > configuration that had been "last installed". In the specific case of Python, the typical choice is whether or not to install the tests, and whether or not to install Tkinter. Regards, Martin From Scott.Daniels at Acm.Org Sun Oct 19 12:25:06 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 19 Oct 2008 09:25:06 -0700 Subject: better scheduler with correct sleep times In-Reply-To: References: Message-ID: qvx wrote: > I need a scheduler which can delay execution of a > function for certain period of time. > My attempt was something like this: ... <<>> > Is there a better way or some library that does that? The trick is to use Queue's timeout argument to interrupt your sleep when new requests come in. def time_server(commands): '''Process all scheduled operations that arrive on queue commands''' pending = [] while True: now = time.time() while pending and pending[0][0] <= now: when, function, args, kwargs = heapq.heappop(pending) function(*args, **kwargs) try: command = commands.get(timeout=pending[0][0] - now if pending else None) except Queue.Empty: pass else: if command is None: break heapq.heappush(pending, command) queue = Queue.Queue() thread.thread.start_new_thread(queue) queue.put((time.time() + dt, callable, args, {})) ... --Scott David Daniels Scott.Daniels at Acm.Org From pavlovevidence at gmail.com Thu Oct 23 03:20:32 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 23 Oct 2008 00:20:32 -0700 (PDT) Subject: Possible read()/readline() bug? References: <380b01dc-eaef-425d-bb93-dbb838c20175@u28g2000hsc.googlegroups.com> Message-ID: <8649a9be-baba-4f82-838c-483c4b988c38@u75g2000hsf.googlegroups.com> On Oct 22, 2:54?pm, Mike Kent wrote: > Before I file a bug report against Python 2.5.2, I want to run this by > the newsgroup to make sure I'm not being stupid. > > I have a text file of fixed-length records I want to read in random > order. ?That file is being changed in real-time by another process, > and my process want to see the changes to the file. ?What I'm seeing > is that, once I've opened the file and read a record, all subsequent > seeks to and reads of that same record will return the same data as > the first read of the record, so long as I don't close and reopen the > file. ?This indicates some sort of buffering and caching is going on. > > Consider the following: > > $ echo "hi" >foo.txt ?# Create my test file > $ python2.5 ? ? ? ? ? ? ?# Run Python > Python 2.5.2 (r252:60911, Sep 22 2008, 16:13:07) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> f = open('foo.txt') ?# Open my test file > >>> f.seek(0) ? ? ? ? ? ? ? ?# Seek to the beginning of the file > >>> f.readline() ? ? ? ? ? ? # Read the line, I get the data I expected > 'hi\n' > >>> # At this point, in another shell I execute 'echo "bye" >foo.txt'. ?'foo.txt' now has been changed I thought this might be a case where the shell unlinks foo.txt and creates a new file... but it doesn't for me, and I still get the same behavior as you. It is indeed the buffering that's causing this. > >>> # on the disk, and now contains 'bye\n'. > >>> f.seek(0) ? ? ? ? ? ? ? ?# Seek to the beginning of the still-open file > >>> f.readline() ? ? ? ? ? ? # Read the line, I don't get 'bye\n', I get the original data, which is no longer there. > 'hi\n' > >>> f.close() ? ? ? ? ? ? ? ? # Now I close the file... > >>> f = open('foo.txt') # ... and reopen it > >>> f.seek(0) ? ? ? ? ? ? ? # Seek to the beginning of the file > >>> f.readline() ? ? ? ? ? ?# Read the line, I get the expected 'bye\n' > 'bye\n' > > It seems pretty clear to me that this is wrong. ?If there is any > caching going on, it should clearly be discarded if I do a seek. I totally disagree. If you need to discard the buffers, there's a way to do it: flush(). If you force seek() to discard perfectly good buffers you will hurt performance when not dealing with volatile data. Anyway, in Python 2.x, the behavior of the various file methods is documented as reflecting the underlying C stdio library. In fact, the documentation for fseek specifically says it sets the file's current position "like stdio's fseek()". Whatever stdio does is what Python does. So even if this behavior were a bug, it would be a bug in stdio, not in Python. >?Note > that it's not just readline() that's returning me the wrong, cached > data, as I've also tried this with read(), and I get the same > results. ?It's not acceptable that I have to close and reopen the file > before every read when I'm doing random record access. You can call f.flush() to force it to discard the cache. Or use unbuffered I/O. Better yet, get rid of file I/O altogether and use an memory mapped file. > So, is this a bug, or am I being stupid? Well, it's not a bug, so.... Seriously, I advise you not to submit a bug report. Doesn't mean you're stupid, maybe you didn't know about unbuffered I/O or the flush() method. That just means you're uneducated. :) But please leave seek() out it. Carl Banks From davidreynon at gmail.com Wed Oct 15 11:46:13 2008 From: davidreynon at gmail.com (korean_dave) Date: Wed, 15 Oct 2008 08:46:13 -0700 (PDT) Subject: Kicking off a python script using Windows Scheduled Task References: Message-ID: Hey all. i solved this problem by logging on with my network domain login (log in using...) instead of NT AUTHORITY\SYSTEM which only gave out local privleges to the process started off by Task scheduler. On Oct 15, 10:36?am, korean_dave wrote: > Does anyone know how to properly kick off a script using Windows > Scheduled Task? The script calls other python modules within itself. > HERE'S THE CATCH: > I am used to running the script directly from the command window and > the print() is very handy for us to debug and monitor. When running > the task from Windows Scheduled Task, we'd like to be able to view the > command window and keep it up after the Task has completed... > > I used the commands > > CMD /K > > cd C:\testdirectory\script_RunTests > > python AutomatedTestRun.py > > but when AutomatedTestRun.py calls other python modules, we don't see > output. From incomecash123 at gmail.com Wed Oct 22 04:42:33 2008 From: incomecash123 at gmail.com (jaggu) Date: Wed, 22 Oct 2008 01:42:33 -0700 (PDT) Subject: GOODNEWS 06 Message-ID: GOODNEWS EARN BY JUST READING SMS ON UR MOBILE- UR INCOMMING SMS PAY'S U INCOME ONE CLICK AWAY FROM EARNING THROUGH INCOMMING SMS http://www.mGinger.com/index.jsp?inviteId=623396 http://www.paisa4sms.com/Index.aspx?Inviteid=134129 http://www.youmint.com/network-jagguzwx2 http://mGinger.com/index.jsp?inviteId=1820537 http://mGinger.com/index.jsp?inviteId=1820510 { HEART SURGERY FREE OF COST FOR CHILDRENS, "SRI SATYA SAI INSTITUTE" "BANGLORE" PH: 08028411500 } PLEASE PASS THIS MESSAGE TO ALL IT MAY BE HELPFUL TO SOMEONE...... ADD YOUR NAME PLSSSS JAGADISH, IBRAHIM, DHARNIDHAR, DAYAKAR RAO, SAMIKSHYA DUGGAL RAMI REDDY, SUMALATHA, VENA, RANJIT, PETER, PASURAM, LAKSHMI, NAROTHAM RAO VENKAT, PERMASH, RAMESH, RATHI , SUSHANT SAI, DEVISREE,GOPI, DIVYASHREE, SRINIVAS,HARI BABU,PADMAJA RANI, SAVITRI, JAWHAR, From steve at holdenweb.com Wed Oct 29 06:48:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Oct 2008 06:48:13 -0400 Subject: How to get high precision timer in python? In-Reply-To: References: Message-ID: <49083F6D.9080404@holdenweb.com> ?? wrote: > ^_^ Oh! I did not read the document for time.clock before, > and supposed it was same with time.time(). > > Thank you very much. > If you are using wxPython then you should probably see whether a wxTimer would meet your needs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dbpokorny at gmail.com Mon Oct 6 18:59:06 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Mon, 6 Oct 2008 15:59:06 -0700 (PDT) Subject: PyOpenGL double-buffered hardware surface References: <1223226099.4146.1.camel@generator> <48E90498.2000609@vrplumber.com> Message-ID: On Oct 6, 11:45?am, Clay Hobbs wrote: > I'm using wxPython. ?My real problem is that everything flashes when it > moves. ?I thought the way to fix this was to make a double-buffered Have you tried looking here? If it doesn't solve your problem, then more information would be helpful (hardware, OS, what doesn't work, etc...) http://wiki.wxpython.org/DoubleBufferedDrawing David From greg.ewing at canterbury.ac.nz Sun Oct 12 05:09:06 2008 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sun, 12 Oct 2008 22:09:06 +1300 Subject: ANN: Humerus 2.0 Message-ID: Humerus 2.0 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Albow/Humerus-2.0.0.tar.gz Online documentation: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Albow/Humerus-2.0.0/doc/ This version of Humerus has been extensively revised from the previous one. Instead of a pile of code to be cut and pasted, it is now a proper library made up of reusable classes, with detailed documentation and some example code included. What is Humerus? ---------------- Humerus is a companion to the Albow widget library for PyGame. It provides a framework for games made up of a sequence of levels, including user interface and back-end logic for loading levels, saving and restoring game state and sundry other details. There is also optional support for a built-in level editor, including code for loading and saving levels to be edited, and asking whether to save modified levels. Albow can be found here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Albow/ From martin at v.loewis.de Fri Oct 3 14:43:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Oct 2008 20:43:40 +0200 Subject: "Exploding" (**myvariable) a dict with unicode keys In-Reply-To: <6e32b9f8-d785-408b-a1ae-6a86244e9643@u57g2000hsf.googlegroups.com> References: <6e32b9f8-d785-408b-a1ae-6a86244e9643@u57g2000hsf.googlegroups.com> Message-ID: <48e667dc$0$2561$9b622d9e@news.freenet.de> Devin wrote: > So Python can have unicode variable names but you can't > "explode" (**myvariable) a dict with unicode keys? WTF? That works fine for me. Regards, Martin From kay.schluehr at gmx.net Thu Oct 23 03:51:56 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 23 Oct 2008 00:51:56 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <24c98bcc-96b4-44a1-9248-3450e0797ca9@b1g2000hsg.googlegroups.com> Message-ID: <0a3ed744-2578-45e8-ad97-e095ba4ce0f9@q35g2000hsg.googlegroups.com> On 11 Okt., 09:56, lkcl wrote: > > The role of Python is somewhat arbitrary. This could change only if > > Python becomes a client side language executed by AVM,V8etc. > > pyv8 -http://advogato.org/article/985.html > pyjs.py - standalone python-to-javascript compiler, seehttp://pyjs.org. O.K. you got me all. I give up! I've already imlemented some small Flex supporting functionality in the P4D Langlet [1] and I'll also checkout pyjamas ( didn't worn them for long ) and if they are fine I work out a bridge the next days. Then only style sheets are left :) [1] http://pypi.python.org/pypi/P4D Langlet/ From bdesth.quelquechose at free.quelquepart.fr Tue Oct 21 12:34:36 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 21 Oct 2008 18:34:36 +0200 Subject: Need some advice In-Reply-To: References: Message-ID: <48fe207c$0$20551$426a34cc@news.free.fr> azrael a ?crit : > I am starting to work on a application and need some advice. > > I am planing to develop a desktop application which would have some > usage, but also it should be able to comunicate to a web server which > hosts a php web application. So I wanted to ask if someone has some > expirience with connecting PHP webapplications with Python desktop > applications. Could someone at leaset point me to the right direction > where to look for informations. Short anwser: 'http'. Longer answer: when it comes to interacting with a web application, the language used to develop both applications is irrelevant. The client app sends an HTTP request, and receive an HTTP response. From uzmanajmal at gmail.com Thu Oct 23 23:31:19 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Fri, 24 Oct 2008 08:31:19 +0500 Subject: Question about interpreter In-Reply-To: References: Message-ID: Thanks James... On Fri, Oct 24, 2008 at 8:01 AM, James Mills wrote: > On Fri, Oct 24, 2008 at 12:55 PM, Usman Ajmal > wrote: > > An interpreter which Python also uses, translates and checks for errors > in > > code, one line at a time. > > > > Question: Does interpreter also executes the translated code? > > http://en.wikipedia.org/wiki/Evaluate > > --JamesMills > > -- > -- > -- "Problems are solved by method" > -------------- next part -------------- An HTML attachment was scrubbed... URL: From derajan at gmail.com Sat Oct 18 16:53:50 2008 From: derajan at gmail.com (Rajan Arora) Date: Sat, 18 Oct 2008 13:53:50 -0700 (PDT) Subject: IO error Message-ID: Hi, I am trying to get the data out of an instrument through its GPIB port and using python code. I am able to perfectly control the operation of the instrument with my code. But I have not figured out a way as yet to get the data of the GPIB. I thin that it will go through 2 steps: 1) instrument transfers data to its output buffer 2) Read from the output buffer. When i try read() command it gives me an IO timeout error. Any suggestions? Thanx in advance. From tvrtko.sokolovski at gmail.com Tue Oct 21 04:58:16 2008 From: tvrtko.sokolovski at gmail.com (sokol) Date: Tue, 21 Oct 2008 01:58:16 -0700 (PDT) Subject: better scheduler with correct sleep times References: <658e2b0f-2551-4ec9-bcd5-ce98092a3f7b@a1g2000hsb.googlegroups.com> <5b97d8fb-aa61-4a68-aca3-d77a07cd6cbd@t18g2000prt.googlegroups.com> <8a291aa6-08c6-46c7-b792-450cebf0ce1d@i24g2000prf.googlegroups.com> <6m4lv8Feu374U1@mid.individual.net> Message-ID: <032b024d-ce05-4b8f-bbc5-e79669281c89@m73g2000hsh.googlegroups.com> On Oct 21, 2:19?am, greg wrote: > sokol wrote: > > What was a surprise to me was that python sched.py makes the same > > mistake as I did in my first version. > > The sched module is *not* designed for multithreading. It > assumes that the thread waiting for events is the only one > putting events into the queue, so it's impossible for an > event to get scheduled while in the midst of a sleep. It > also doesn't take any measures to protect its data structures > from concurrent access. > > The documentation could make this clearer, especially since > it confusingly talks about "allowing other threads to run". I find that hard to believe. Scheduler in single threaded application is useless (well, you can correct me because right now I can't come up with an example). Also, the scheduler runs inside a loop. How do you suppose to run other code while the loop is executing? Remember, all you have is a single thread. The consequence of this is that the only way to insert something new inside a queue is by doing it from scheduled function. Furthermore, if scheduler is single threaded, why does is check if the top event has changed after sleep period? What I can agree is that python sched as it is (not designed for multithreading) is quite useless. -- Tvrtko From scripteaze at gmail.com Sat Oct 25 17:33:52 2008 From: scripteaze at gmail.com (Jesse) Date: Sat, 25 Oct 2008 14:33:52 -0700 (PDT) Subject: SendKeys-0.3.win32-py2.1.exe Message-ID: <7a8a2e16-4eeb-41a2-af71-a5ebc115e9bc@v30g2000hsa.googlegroups.com> cant seem to install this, using python 2.6, any known errors that wont let me select the python installation to use, just opens a blank dialog and wont let me continue..do i need to downgrade python?? thanks in advance From wan.wuhan at gmail.com Tue Oct 14 04:23:01 2008 From: wan.wuhan at gmail.com (Jacker) Date: Tue, 14 Oct 2008 01:23:01 -0700 (PDT) Subject: IT Degrees and Computer Schools Online Message-ID: <936d35d1-a5eb-4d28-aeda-78dace8c4452@f37g2000pri.googlegroups.com> IT Schools Near You Get on the fast track to an IT degree at a school near you. Choose from many accredited schools in your area and advance your career. Get free info now. http://e.goozw.com/it.htm IT Resources at Apple.com Visit Apple's IT Pro portal to find IT related content for IT Managers and technology professionals. Find news, articles, information on the latest technologies, products and more. http://e.goozw.com/it.htm Earn an Accredited IT Degree Online US residents find an online degree in business, education, nursing, IT, computer science, health, web/graphic design and more from a directory of accredited universities. http://e.goozw.com/it.htm ITIL-based Automation for IT Firms . Total PSA solution developed by IT folks for IT folks to manage all workflow processes. Web and mobile access. Integrated with Outlook, MSP tools and accounting packages. 1000's of users. http://e.goozw.com/it.htm IBM CIO Agenda: IT Business Advantages . How to transform IT and improve business advantage. Get the report. http://e.goozw.com/it.htm IT Degrees and Computer Schools Online . Your chance to earn an IT degree or certificate valued by companies worldwide on your own time. 100% Online. You can study anytime, anywhere at your convenience. Request free info. http://e.goozw.com/it.htm IT Schools Don't waste another byte of your life. Locate a computer school near you. Many accredited institutions to choose from. Request free information today. http://e.goozw.com/it.htm IT Degree Programs at Peirce Earn a degree online. Peirce, a fully accredited college, offers accelerated business and IT programs for working adults. Courses begin each month. Learn 24/7 at Peirce. http://e.goozw.com/it.htm IT Online Degree Breyer State University offers self paced and affordable online degrees in Information Technology. http://e.goozw.com/it.htm IT Degrees and Training Programs Online directory of IT schools, degrees and training programs. Free brochures. http://e.goozw.com/it.htm IT Training Schools Find the tech education program you're looking for, near you. A comprehensive directory of training schools - get the IT career training you need. Request info to learn more. http://e.goozw.com/it.htm Lil' Flip Ringtone Get What It Do as a ringtone on your cell phone. http://e.goozw.com/it.htm Italcementi (IT): Info Go to Hoover's for in-depth, first-hand, company coverage provided by business experts. Get an overview, key executive bios, financials, news, industry trends and competitor info. http://e.goozw.com/it.htm IT Business News - CIO Insight Find free IT business articles, case studies and profiles on today's competing technology companies. http://e.goozw.com/it.htm Attend IT Computer School Request official college information and start earning your bachelors, masters or MBA today. Many campuses located throughout the U.S. http://e.goozw.com/it.htm IT Earn an information technology degree at Colorado Technical University Online. Request your free, no-risk Infopak today. http://e.goozw.com/it.htm ICC Provides IT Solutions ICC offers comprehensive IT services to clients throughout the U.S. We specialize in application development, process automation, network design, systems administration and tech. support. http://e.goozw.com/it.htm ITT Technical Institute At ITT Tech we are committed to helping men and women develop the skills and knowledge to pursue many opportunities in fields involving technology, and business. http://e.goozw.com/it.htm What Is IT - Yahoo! Shopping Search for IT books and software. Visit Yahoo! Shopping to compare products and prices from thousands of your favorite stores. Consumer reviews, store ratings and more. http://e.goozw.com/it.htm Getting It On - DeepDiscountDVD DeepDiscountDVD.com offers lower total prices on any individual, in stock, DVDs. If you find a DVD at a lower total price online, we will match the lower advertised price. http://e.goozw.com/it.htm From ldo at geek-central.gen.new_zealand Tue Oct 21 00:41:08 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 21 Oct 2008 17:41:08 +1300 Subject: indentation References: <010b3ea2$0$20653$c3e8da3@news.astraweb.com> <48fb8441$0$20787$426a74cc@news.free.fr> <010ba6be$0$20653$c3e8da3@news.astraweb.com> <48fc48df$0$12027$426a74cc@news.free.fr> <010c80c2$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <010c80c2$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Here's Jamie Zawinski: > http://www.jwz.org/doc/tabs-vs-spaces.html > > "On defaultly-configured Unix systems, and on ancient dumb terminals and > teletypes, the tradition has been for the TAB character to mean ``move to > the right until the current column is a multiple of 8.'' Actually, I think that should be "multiple of 8 plus 1". If you're in column 1, pressing tab will move the equivalent of 8 spaces, which takes you column 9, not 8. From almar.klein at gmail.com Thu Oct 9 17:36:05 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 9 Oct 2008 23:36:05 +0200 Subject: On the indexing order in (numpy) arrays In-Reply-To: References: Message-ID: > Basically, we want a[i][j] == a[i,j]. Since there is no literal syntax for > numpy arrays, we need to be able to convert from a sequence of sequences to > an array. The indexing needs to correspond between the two. > Thanks for the reply. I guess that explains the *why*... Adopt the numpy order. There are many functions in numpy which take an axis= > argument just like this. axis=0 means "y" in the terminology that you are > using. > Yes, I agree its best to use the numpy order, and I agree one gets used to it. However, it will always feel a bit unnatural to reverse the order of dimensions (at least to me it does). And I think it can in some situations lead to confusion. I for instance have a class to store sets of points in a nD space. I can index the points, so using points[99,0] selects the *first* dimension of the 99th point. I use this class to store locations of interesting points in 2D and 3D images. But when programming, it can at times be quite confusing switching between reversed and "normal" indexing. And sometimes I might have a method that does stuff with an image and a point set and I want to indicate an axis. What standard should I use then? I'm not saying numpy should change the indexing order or something. But other people must run into the same confusing situation at times. How do they handle this? In the example above, I think it'll be weird to change the pointset class such that points[99,0] selects the *last* dimension of point 99. Or is it? Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From bthayre at physics.ucsd.edu Fri Oct 17 13:07:38 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Fri, 17 Oct 2008 10:07:38 -0700 (PDT) Subject: Script can't find input file despite being in the same directory Message-ID: <8c4b42bb-a9de-45b7-b282-f8981d3245bb@u27g2000pro.googlegroups.com> I have a simple little script that reads in postscript code, appends it, then writes it to a new postscript file. Everything worked fine a month ago, but after rearranging my directory tree a bit my script fails to find the base postscript file. The line in question is: for line in fileinput.input(['base.ps']): output.write(line) I'm kind of at a loss as the script is executing in the same directory as base.ps, yet it can't find it. I'm relatively new to python scripting, so i'm expecting it's just something i haven't learned about python that is causing the problem. Any suggestions would be greatly appreciated. From duncan.booth at invalid.invalid Fri Oct 24 06:04:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Oct 2008 10:04:32 GMT Subject: substitution __str__ method of an instance References: <0110ea6b$0$20657$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > However, you can dispatch back to the instance if you really must: > > > class MyObj(object): > def __init__(self): > self.__str__ = lambda self: "I'm an object!" > def __str__(self): > return self.__str__(self) > > > But honestly, this sounds like a bad idea. If instances of the one class > have such radically different methods that they need to be treated like > this, I question whether they actually belong in the same class. > Another option would be to just change the class of the object: >>> class C(object): pass >>> c = C() >>> print c <__main__.C object at 0x01180C70> >>> def wrapstr(instance, fn=None): if fn is None: def fn(self): return "I'm an object" Wrapper = type(instance.__class__.__name__, (instance.__class__,), {'__str__':fn}) instance.__class__ = Wrapper >>> wrapstr(c) >>> print c I'm an object >>> isinstance(c, C) True >>> type(c) >>> wrapstr(c, lambda s: "object %s at %s" % (type(s).__name__, id(s))) >>> print c object C at 18353264 (I'll leave enhancing wrapstr so that it avoids multiple levels of wrapping as an exercise for anyone who actually wants to use it.) -- Duncan Booth http://kupuguy.blogspot.com From s.payandeh at gmail.com Wed Oct 22 07:27:39 2008 From: s.payandeh at gmail.com (sa6113) Date: Wed, 22 Oct 2008 04:27:39 -0700 (PDT) Subject: which program I need for sftp using pramiko?? Message-ID: <20108796.post@talk.nabble.com> which program I have to install for using paramiko for sftp between a two windows machine in local network?? I have installed freeSSHd for server machine but I got an Authentication failed erro when try to connect to server using this code : sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait() if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "Authentication failed" output: SSH negotiation successful Authentication failed May I install any program on client computer such as openssh ? please help me. Thanks -- View this message in context: http://www.nabble.com/which-program-I-need-for-sftp-using-pramiko---tp20108796p20108796.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Thu Oct 2 21:30:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 02 Oct 2008 21:30:22 -0400 Subject: docs.python.org inaccessible In-Reply-To: References: Message-ID: Lawrence D'Oliveiro wrote: > Been getting 403 errors all afternoon. > > At one time I used to assiduously download PDF files of all the > documentation I wanted to refer to. These days I've grown accustomed to > just having a bunch of Web browser windows semi-permanently open. Until a > rude shock like this happens to hit me. Seems to be working now, at least if you start at the top with http://docs.python.org/ There was a problem with links to specific pages under that subdomain not working because of page renaming. I don't know if redirects have been added yet. If not, start at the top. The Windows version installs a nice Windows Help version of the docs. The left sidebar lists all the docs, so it is much easier to jump between different docs (Language ref to lib ref and back.). At last -- a reason to be happy using Windows (other than the games). tjr From deets at nospam.web.de Mon Oct 6 10:00:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Oct 2008 16:00:11 +0200 Subject: Class properties and object properties References: <046937d2-fa31-43f9-81de-401fb7e5daeb@q9g2000hsb.googlegroups.com> <6kui6iF9kcqmU1@mid.uni-berlin.de> <14222f40-4507-4d36-9a1c-613aa6785179@c60g2000hsf.googlegroups.com> Message-ID: <6kujvaF9fnk3U1@mid.uni-berlin.de> SuperZE wrote: >> Because you declare myList to be a *class*-level variable, which means >> *all* instances of that class (a and b in your case) *share* it. Python >> does not declare *instance* variables the way you do. >> >> Instead, do this: >> >> class Foo(object): >> def __init__(self): >> self.myList = [] > > > Interesting, but that does not explain the difference in the behavior > of myList and myInt Sorry, I forgot that. The reason is simple - lists are mutable. Numbers aren't. And when you *assign* to an instance a value, it will be set on the instance, not on the class. The same happens (as you've already seen for yourself) when you do a.myList = [] as this creates a new list, stored only on a. > Both were class-level variables, as far as I can see, and therefor a > and b should also share it Nope. To change it, you need to do Test1.myInt = 5 The thing is that the lookup triggered by getattr/dotted notation goes roughly like this: 1) try to find the attribute (value *or* method! Python doesn't distinguish) in the instance itself. 2) if not found there, look at the class. 3) if not found there, look at the base-classes in the method resolution order (MRO) There are some other things involved - descriptor protocol calls on the class-level lookups - but that's not relevant for the problem at hand. OTOH, when setting with setattr/dotted notation, it will always set on the object passed. Diez From jordan.taylor2 at gmail.com Thu Oct 16 21:52:42 2008 From: jordan.taylor2 at gmail.com (Jordan) Date: Thu, 16 Oct 2008 18:52:42 -0700 (PDT) Subject: Unicode File Names References: Message-ID: On Oct 16, 9:20 pm, John Machin wrote: > On Oct 17, 11:43 am, Jordan wrote: > > > I've got a bunch of files with Japanese characters in their names and > > os.listdir() replaces those characters with ?'s. I'm trying to open > > the files several steps later, and obviously Python isn't going to > > find '01-????.jpg' (formally '01-????.jpg') because it doesn't exist. > > I'm not sure where in the process I'm able to stop that from > > happening. Thanks. > > The Fine Manual says: > """ > listdir( path) > > Return a list containing the names of the entries in the directory. > The list is in arbitrary order. It does not include the special > entries '.' and '..' even if they are present in the directory. > Availability: Macintosh, Unix, Windows. > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > Unicode object, the result will be a list of Unicode objects. > """ > > Are you unsure whether your version of Python is 2.3 or later? *** Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32. *** says my interpreter when it says "if path is a Unicode object...", does that mean the path name must have a Unicode char? From gagsl-py2 at yahoo.com.ar Thu Oct 30 18:25:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 30 Oct 2008 20:25:34 -0200 Subject: Python suitable for Midi ? References: <8200bab70810280954l79e0f1a1icfc0308ebdc5c61@mail.gmail.com> <878ws73zxt.fsf@agentultra.com> <8200bab70810301150g2f2cf59dg54cf553be355daa6@mail.gmail.com> Message-ID: En Thu, 30 Oct 2008 16:50:22 -0200, Chuckk Hubbard escribi?: > On Wed, Oct 29, 2008 at 10:32 PM, J Kenneth King > wrote: >> >> One also has access to nice-levels on unix systems. > > True enough, but it's not so much a problem for me, as I'm pretty okay > at tuning my own system, but I believe most of the people who'd be > interested in my app (if any) are not *nix users. At any rate, it's > one option for those who are, and thanks for reminding me. On Windows you can set the application global priority (SetPriorityClass) and each thread's priority related to other threads (SetThreadPriority) - either using pywin32 or the ctypes module. -- Gabriel Genellina From andre.roberge at gmail.com Wed Oct 29 21:44:10 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 29 Oct 2008 18:44:10 -0700 (PDT) Subject: math equation, svg and matplotlib References: <5e55e799-f539-4197-95e5-345501986534@u28g2000hsc.googlegroups.com> <4908d706$0$27495$426a34cc@news.free.fr> Message-ID: <1cc5591b-5693-4905-b69d-c3c8cb640514@q35g2000hsg.googlegroups.com> On Oct 29, 6:34?pm, kib2 wrote: > Andr? a ?crit : > > > Would anyone have a "quick and dirty" code sample to create an svg > > output of a sample math equation using matplotlib? > > > Andr? > > Hi Andr?, > > maybe that's not what you want be there's something like this here (a > converter from DVI to SVG in pure Python), look at the samples at the bottom > of the page: > > http://www.wmula.republika.pl/proj/pydvi2svg/index.html#samples Your project looks very interesting; however, I figured out a way to do it. It required doing a bit of playing around with one comprehensive examples on the matplotlib gallery. Thanks. Andr? From bruno.42.desthuilliers at websiteburo.invalid Thu Oct 23 08:33:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 23 Oct 2008 14:33:38 +0200 Subject: Slow comparison between two lists In-Reply-To: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> References: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> Message-ID: <49006f0f$0$19702$426a74cc@news.free.fr> Jani Tiainen a ?crit : > I have rather simple 'Address' object that contains streetname, > number, my own status and x,y coordinates for it. I have two lists > both containing approximately 30000 addresses. > > I've defined __eq__ method in my class like this: > > def __eq__(self, other): > return self.xcoord == other.xcoord and \ > self.ycoord == other.ycoord and \ > self.streetname == other.streetname and \ > self.streetno == other.streetno > > But it turns out to be very, very slow. > > Then I setup two lists: > > list_external = getexternal() > list_internal = getinternal() > > Now I need get all all addresses from 'list_external' that are not in > 'list_internal', and mark them as "new". > > I did it like this: > > for addr in list_external: > if addr not in list_internal: > addr.status = 1 # New address > > But in my case running that loop takes about 10 minutes. What I am > doing wrong? mmm... not using sets ? From vinay_sajip at yahoo.co.uk Fri Oct 17 19:33:49 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 17 Oct 2008 16:33:49 -0700 (PDT) Subject: Python logging and ThreadingTCPServer References: <4926667c-05a9-483d-8181-bbe207a129f0@w24g2000prd.googlegroups.com> Message-ID: On Oct 17, 5:48 pm, Daniel wrote: > Hello, > > I building an application that consists of several sockets > components. I would like to useloggingin them, but I've noticed > some issues with the logs getting mangled. This mangling seems to > happen when different threads attempt to access the same log file. > > For example, if a client and a server component are running on the > same box and both try to write to the same physical log file, the > first will write fine, but when the second thread (or process) writes > to the log file it mangles the first part of the log file including > deleting some of the information and adding various strange characters > and space. Sometimes it seems that the first process never is able to > write to the log file after the second process starts writing. > > Is this a known issue/bug? Are there any known workarounds? > > Thanks, > Daniel This has come up before. See for example http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fbd36c89119f27f Regards, Vinay Sajip From exiquio at gmail.com Tue Oct 7 14:02:30 2008 From: exiquio at gmail.com (exiquio) Date: Tue, 7 Oct 2008 11:02:30 -0700 (PDT) Subject: Making Non Callable Objects Callable References: Message-ID: <2d6f8357-e59c-49b0-8f18-ac84de69d8fb@s20g2000prd.googlegroups.com> On Oct 7, 1:56?pm, Christian Heimes wrote: > exiquio wrote: > > I am trying to figure out if there is a way to make an object in > > python callable, modules in particular. I wrongly assume that defining > > '__call__' in the the objects __dict__ would work. Any help would be > > appreciated. > > No, that doesn't work. Several magic methods (__*__) aren't looked up in > __dict__ or through __getattr__(). > > Christian Thanks. From pythonlarry at gmail.com Sun Oct 26 16:17:15 2008 From: pythonlarry at gmail.com (Larry Hale) Date: Sun, 26 Oct 2008 13:17:15 -0700 (PDT) Subject: Module python-magic on/for Windows - UPDATE: WORKING & HowTo!!! Message-ID: <6c2cf82d-73f8-44fe-a7e7-6c41393ac29c@m44g2000hsc.googlegroups.com> Thank you, again, Michael, for all your help many months ago. I *FINALLY* got a HowTo done up; please see http://wiki.python.org/moin/HowTo/FileMagic I've also emailed Mr. Hupp to see if he'll re-post the SWIG version; he's working on a newer binding (forget... ctypes??) and once that one's working... :) But for now... Cheers, Larry REF: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4c60ec1599056df8/3eff4049a7bfdfc0?hl=en%E3%AD%82a54360c4d26&lnk=gst&q=python-magic#3eff4049a7bfdfc0 From martin at v.loewis.de Sun Oct 26 05:57:07 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 26 Oct 2008 10:57:07 +0100 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <3fa66f6d-bb65-4aa3-9001-ca72e70c7a2f@26g2000hsk.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <3fa66f6d-bb65-4aa3-9001-ca72e70c7a2f@26g2000hsk.googlegroups.com> Message-ID: <49043ef3$0$15996$9b622d9e@news.freenet.de> >>> As far as I can tell, it seems >>> CPython's current state can't CPU bound parallelization in the same >>> address space. >> That's not true. >> > > Um... So let's say you have a opaque object ref from the OS that > represents hundreds of megs of data (e.g. memory-resident video). How > do you get that back to the parent process without serialization and > IPC? What parent process? I thought you were talking about multi-threading? > What should really happen is just use the same address space so > just a pointer changes hands. THAT's why I'm saying that a separate > address space is generally a deal breaker when you have large or > intricate data sets (ie. when performance matters). Right. So use a single address space, multiple threads, and perform the heavy computations in C code. I don't see how Python is in the way at all. Many people do that, and it works just fine. That's what Jesse (probably) meant with his remark >> A c-level module, on the other hand, can sidestep/release >> the GIL at will, and go on it's merry way and process away. Please reconsider this; it might be a solution to your problem. Regards, Martin From cournape at gmail.com Wed Oct 29 10:53:58 2008 From: cournape at gmail.com (David Cournapeau) Date: Wed, 29 Oct 2008 23:53:58 +0900 Subject: Python memory usage In-Reply-To: <007bd4b3-8ca5-4f66-a0c1-8f1f7a2f980f@y79g2000hsa.googlegroups.com> References: <48fe00a2$1@news.fhg.de> <007bd4b3-8ca5-4f66-a0c1-8f1f7a2f980f@y79g2000hsa.googlegroups.com> Message-ID: <5b8d13220810290753v25b4af56raf2195abe42e3197@mail.gmail.com> On Wed, Oct 29, 2008 at 6:56 PM, petercable at gmail.com wrote: > On Oct 21, 5:19 pm, Rolf Wester wrote: >> Hi, >> >> I have the problem that with long running Python scripts (many loops) >> memory consumption increases until the script crashes. I used the >> following small script to understand what might happen: >> > > > AFAIK, python uses malloc behind the scenes to allocate memory. From > the malloc man page... > > "The malloc() and free() functions provide a simple, general-purpose > memory allocation package. The malloc() function returns a pointer to > a block of at least size bytes suitably aligned for any use. If the > space assigned by malloc() is overrun, the results are undefined. > > The argument to free() is a pointer to a block previously allocated by > malloc(), calloc(), or realloc(). After free() is executed, this space > is made available for further allocation by the application, though > not returned to the system. Memory is returned to the system only > upon termination of the application. If ptr is a null pointer, no > action occurs. If a random number is passed to free(), the results are > undefined." Depending on your malloc implementation, that may not be true. IN particular, with glibc, bit allocations are done with mmap, and those areas are unmaped when free is called; any such area is immediatly returned to the system http://www.gnu.org/software/libtool/manual/libc/Malloc-Tunable-Parameters.html#Malloc-Tunable-Parameters David From hnassrat at gmail.com Fri Oct 10 15:10:29 2008 From: hnassrat at gmail.com (Hatem Nassrat) Date: Fri, 10 Oct 2008 16:10:29 -0300 Subject: How to create a tuple quickly with list comprehension? Message-ID: <20081010191028.GA24941@torch.cs.dal.ca> on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote: >markacy wrote: > >> On 13 Cze, 09:45, "fdu.xia... at gmail.com" > gmail.com> wrote: >>> Hi all, >>> >>> I can use list comprehension to create list quickly. So I >>> expected that I >>> can created tuple quickly with the same syntax. But I >>> found that the >>> same syntax will get a generator, not a tuple. Here is my >>> example: >>> >>> In [147]: a = (i for i in range(10)) >>> >>> In [148]: b = [i for i in range(10)] >>> >>> In [149]: type(a) >>> Out[149]: >>> >>> In [150]: type(b) >>> Out[150]: [...] >> You should do it like this: >> >>>>> a = tuple([i for i in range(10)]) >>>>> type(a) >> [...] >No need to create the intermediate list, a generator >expression works just >fine: > >a = tuple(i for i in range(10)) Well I have looked into this and it seems that using the list comprehension is faster, which is reasonable since generators require iteration and stop iteration and what not. # If you really really want a tuple, use [24] style # if you need a generator use [27] style (without the tuple keyword # off course) In [24]: %timeit tuple([x for x in range(1000)]) 10000 loops, best of 3: 185 ??s per loop In [25]: %timeit tuple([x for x in range(1000)]) 1000 loops, best of 3: 195 ??s per loop In [26]: %timeit tuple([x for x in range(1000)]) 10000 loops, best of 3: 194 ??s per loop ################################################# In [27]: %timeit tuple((x for x in range(1000))) 1000 loops, best of 3: 271 ??s per loop In [28]: %timeit tuple((x for x in range(1000))) 1000 loops, best of 3: 253 ??s per loop In [29]: %timeit tuple((x for x in range(1000))) 1000 loops, best of 3: 276 ??s per loop Thanks -- Hatem Nassrat From orestis at orestis.gr Tue Oct 7 10:30:46 2008 From: orestis at orestis.gr (Orestis Markou) Date: Tue, 7 Oct 2008 15:30:46 +0100 Subject: Getting namespaces right when parsing/executing Python ASTs In-Reply-To: <1223382410.8051.122.camel@bob> References: <1223382410.8051.122.camel@bob> Message-ID: Have you tried passing in empty dicts for globals and locals? I think that the defaults will be the *current* globals and locals, and then of course your namespace is broken... On Tue, Oct 7, 2008 at 1:26 PM, Gordon Fraser wrote: > Hi, > > I'm trying to parse Python code to an AST, apply some changes to the AST > and then compile and run the AST, but I'm running into problems when > trying to evaluate/execute the resulting code object. It seems that the > global namespace differs depending on where I call parse and eval/exec. > > The following code parses a file, compiles and then evaluates the AST. > If I call Python directly on this code, then it works: > > import sys, parser > ast = parser.suite(open(sys.argv[1]).read()) > code = ast.compile() > exec(code) > > ...and it also works this way with Python2.6: > > ast = compile(open(sys.argv[1]).read(), "", > 'exec',_ast.PyCF_ONLY_AST) > code = compile(ast, " exec(code) > > However, if I include that snippet in a different scope (some function > or class), then the namespace that the code object will have differs - > it seems the symbols defined in the AST are not included when executing > the code. For example: > > import sys,parser > > def main(): > ast = parser.suite(open(sys.argv[1]).read()) > code = ast.compile() > exec(code) > > if __name__ == "__main__": > main() > > In particular this is a problem if I'm parsing a module with several > functions - none of these functions actually ends up in the scope of the > code object (same behavior with Python2.6 and the PyCF_ONLY_AST > version). > > The function "exec" takes parameters for globals and locals, but I have > no idea where to get these dictionaries from the "parser" module. My > guess is that I am misunderstanding something about how Python treats > namespaces. Can anyone help me here? > > Thanks, > Gordon > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- orestis at orestis.gr http://orestis.gr From duncan.booth at invalid.invalid Wed Oct 29 14:49:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Oct 2008 18:49:00 GMT Subject: How to get an object's name as a string? References: <01178ed7$0$20630$c3e8da3@news.astraweb.com> Message-ID: Steve Holden wrote: >> That explanation makes no sense. Given the assignment: >> >> x = 57 >> >> if the name of x isn't 'x', then what on earth can it possibly mean to >> ask for the name of a variable? >> > He didn't ask for the name of a variable, he asked for the name of an > object. You may choose to equate them, but they aren't the same thing. When I do that assignment there seem to be 5 references to that object, two of them are dictionary keys (what's the name of a dictionary key?), and two are dictionary values. the last one is of course x. Any of these seem a reasonable answer to the question, but how the code is supposed to tell which name is the one the user wanted is another matter. >>> import varname >>> x = 57 >>> for s in varname.object_info(x): ... print s ... opcode.opmap['INPLACE_MULTIPLY'] encodings.cp850.encoding_map[57] encodings.cp850.decoding_map[57] dis.opmap['INPLACE_MULTIPLY'] __main__.x >>> When I repeat the experiment in Idle the cp850 encoding entries disappear so I only get a choice of 3 'names'. > l = [] > l.append(l) > del l > > What's the name of the list formerly known as "l"? My code thinks its name is <...>, but then that's just my code: >>> l = [] >>> l.append(l) >>> for s in varname.object_info(l): print s __main__.l <...> >>> From bj_666 at gmx.net Thu Oct 23 14:32:44 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Oct 2008 18:32:44 GMT Subject: More efficient array processing References: Message-ID: <6mbuacFfv9sgU5@mid.uni-berlin.de> On Thu, 23 Oct 2008 11:11:32 -0700, John [H2O] wrote: > I'm trying to do the following: > > datagrid = numpy.zeros(360,180,3,73,20) > > But I get an error saying that the dimensions are too large? Is there a > memory issue here? Let's see: You have: 360 * 180 * 3 * 73 * 20 * 8 bytes You want: GiB * 2.1146536 / 0.47289069 Do you have a 32 bit system? Then 2?GiB is too much for a process. Ciao, Marc 'BlackJack' Rintsch From venutaurus539 at gmail.com Wed Oct 8 02:06:45 2008 From: venutaurus539 at gmail.com (venutaurus539 at gmail.com) Date: Tue, 7 Oct 2008 23:06:45 -0700 (PDT) Subject: Problem while reading an outlook in box using python. Message-ID: <9c6e93b4-e2f1-4155-a081-2479e5596bb6@2g2000hsn.googlegroups.com> Hello, I was getting an error in Cocreate instance while trying to access "Outlook" using python script. The python script looks like: from win32com.client import Dispatch session = Dispatch("MAPI.session") session.Logon('OUTLOOK') # MAPI profile name inbox = session.Inbox When I tried to execute the script I got the error: IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) Can any one guide me in obtaining a solution for this. Thanks in advance, Venu. From jnoller at gmail.com Wed Oct 22 11:37:52 2008 From: jnoller at gmail.com (Jesse Noller) Date: Wed, 22 Oct 2008 11:37:52 -0400 Subject: Python 2.6, multiprocessing module and BSD In-Reply-To: <63663698-F40D-4E3B-9FD5-3FFC59D1D100@semanchuk.com> References: <72a04310-63d3-44fc-941f-d53e8a80ab94@p58g2000hsb.googlegroups.com> <4222a8490810220711j2b66568dwb0ffa37992e315f2@mail.gmail.com> <63663698-F40D-4E3B-9FD5-3FFC59D1D100@semanchuk.com> Message-ID: <4222a8490810220837i60c58e1an87e79a01e0df6f3b@mail.gmail.com> On Wed, Oct 22, 2008 at 11:06 AM, Philip Semanchuk wrote: >> The BSD issue was raised late in the cycle for 2.6. The problem is >> that FBSD's support is "very experimental" as Phillip points out - and >> OpenBSD doesn't even have them. >> >> Due to the lateness of the issue and a finite amount of time I have to >> work on things, I chose to disable support for this on the various >> *BSDs until I can cook up a stable patch or have one provided by >> someone more familiar with the inner workings of Free-BSD. OpenBSD >> support is a non-starter. > > Hi Jesse, > I wasn't aware of the multiprocessing module. It looks slick! Well done. > The credit goes to R. Oudkerk, the original author of the pyprocessing library - I'm simply a rabid user who managed to wrangle it into Python-Core. See: http://www.python.org/dev/peps/pep-0371/ > I don't know if you clicked on the link I gave for my posix_ipc module, but > it looks like we're duplicating effort to some degree. My module makes POSIX > semaphore & shared memory primitives available to Python programs. > Obviously, what you've done is much more sophisticated. > I actually saw your stuff cross the 'tubes - it looks darned nice as a lower-level interface. What the MP package is meant to be is obviously much more high level (and "thread like"), MP goes out of it's way to hide the gritty internals of the semaphore management/etc - posix_ipc is much more low level than that. > One oversight I noticed the multiprocessing module docs is that a > semaphore's acquire() method shouldn't have a timeout on OS X as > sem_timedwait() isn't supported on that platform. (You note OS X's lack of > support for sem_getvalue() elsewhere.) Please file a ticket or update http://bugs.python.org/issue4012 so I don't loose it, my memory is increasingly lossy. Good catch. > > A question - how do you handle the difference in error messages on various > platforms? For instance, sem_trywait() raises error 35, "Resource > temporarily unavailable" under OS X but error 11 under Ubuntu. Right now I'm > just passing these up to the (Python) caller as OSErrors. This makes it > really hard for the Python programmer to write cross-platform code. > If you look at the code, we're pretty much raising OSError - it's possible we could enhance this in later versions, but given MP is supposed to be a cross-platform as possible and protect the user from the seedy underbelly of semaphores/pipes/etc - when an OSError does occur, it's generally a bug in our code, not the users. > The only solution I can think of (which I haven't coded yet) is to compile & > run a series of small C programs during setup.py that test things like > sem_trywait() to see what errors occur, and provide those constants to my > main .c module so that it can detect those errors exactly and wrap them into > a specific, custom error for the Python caller. > > Any thoughts on this? > That's actually (while feeling hacky) a possibly sensible idea, the problem is is that you'd need to maintain documentation to tell users the exceptions for their platform. -jesse From alfons.nonell at upf.edu Mon Oct 20 07:16:48 2008 From: alfons.nonell at upf.edu (Alfons Nonell-Canals) Date: Mon, 20 Oct 2008 13:16:48 +0200 Subject: Idenfity numbers in variables Message-ID: <1224501408.9143.40.camel@king.imim.es> Hello, I have a trouble and I don't know how to solve it. I am working with molecules and each molecule has a number of atoms. I obtain each atom spliting the molecule. Ok. It is fine and I have no problem with it. The problem is when I have to work with these atoms. These atoms usually are only a letter but, sometimes it can also contain one o more numbers. If they contein a number I have to manipulate them separately. If the number was allways the same I know how to identify them, for example, 1: atom = 'C1' if '1' in atom: print 'kk' But, how can I do to identify in '1' all possibilities from 1-9, I tried: if '[1-9]', \d,... Any comments, please? Regards, Alfons. -- ------------ Alfons Nonell-Canals, PhD Chemogenomics Lab Research Group on Biomedical Informatics (GRIB) - IMIM/UPF Parc de Recerca Biom?dica de Barcelona (PRBB) C/ Doctor Aiguader, 88 - 08003 Barcelona alfons.nonell at upf.edu - http://cgl.imim.es http://alfons.elmeuportal.cat http://www.selenocisteina.info From clp at rebertia.com Tue Oct 14 01:56:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 13 Oct 2008 22:56:06 -0700 Subject: How to set cookie in client machine In-Reply-To: <300352.62583.qm@web35908.mail.mud.yahoo.com> References: <300352.62583.qm@web35908.mail.mud.yahoo.com> Message-ID: <47c890dc0810132256g692de435ga9e0f435ca58a171@mail.gmail.com> See the 'cookie' module: http://www.python.org/doc/2.5.2/lib/module-Cookie.html Also: A. In the future, Google is your friend! That page is the top hit for "python cookie" for Christ's sake; it's not hard to find. B. Please don't post your question again just because it isn't answered fast enough. You didn't even wait one whole day before reposting. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Mon, Oct 13, 2008 at 10:39 PM, Good Z wrote: > Hello, > > I want to set {name, value} cookie on client machine. > > My requirement is that when user comes to the website hosted on our server > and login into his account, we would like to set user specific information > in cookie (on his machine) that will be used later when HTTP request comes > in. Is there a generic program that may help me out in setting the cookie on > client machine? > > I will not be able to use HttpResponse and set cookie in it since within the > program i need to redirect it to different URL. > > Regards, > Mike > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From ldo at geek-central.gen.new_zealand Sun Oct 5 18:52:14 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 06 Oct 2008 11:52:14 +1300 Subject: del and sets proposal References: <48e7b775$0$1120$426a34cc@news.free.fr> <00f80c6a$0$20633$c3e8da3@news.astraweb.com> <00f88c9e$0$20633$c3e8da3@news.astraweb.com> Message-ID: In message <00f88c9e$0$20633$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Sun, 05 Oct 2008 22:11:38 +1300, Lawrence D'Oliveiro wrote: > >> In message <00f80c6a$0$20633$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> Would it really be "confusing" if sets used the same interface as dicts >>> use? I don't think so. What else could "del aset[x]" mean other than >>> "delete element x"? >> >> Yes, but "x" in what sense? > > The only sense possible. There is no precedent for using a set element as a subscript to the set. From bignose+hates-spam at benfinney.id.au Mon Oct 20 16:27:47 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 21 Oct 2008 07:27:47 +1100 Subject: a question about Chinese characters in a Python Program References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> Message-ID: <878wsj6mgs.fsf@benfinney.id.au> est writes: > IMHO it's even better to output wrong encodings rather than halt the > WHOLE damn program by an exception I can't agree with this. The correct thing to do in the face of ambiguity is for Python to refuse to guess. > When debugging encoding problems, the solution is simple. If > characters display wrong, switch to another encoding, one of them > must be right. That's debugging problems not in the program but in the *data*, which Python is helping with by making the problems apparent as soon as feasible to do so. > But it's tiring in python to deal with encodings, you have to wrap > EVERY SINGLE character expression with try ... except ... just imagine > what pain it is. That sounds like a rather poor program design. Much better to sanitise the inputs to the program at a few well-defined points, and know from that point that the program is dealing internally with Unicode. > Dealing with character encodings is really simple. Given that your solutions are baroque and complicated, I don't think even you yourself can believe that statement. > Like I said, str() should NOT throw an exception BY DESIGN, it's a > basic language standard. Any code should throw an exception if the input is both ambiguous and invalid by the documented specification. > str() is not only a convert to string function, but also a > serialization in most cases.(e.g. socket) My simple suggestion is: > If it's a unicode character, output as UTF-8; other wise just ouput > byte array, please do not encode it with really stupid range(128) > ASCII. It's not guessing, it's totally wrong. Your assumption would require that UTF-8 be a lowest *common* denominator for most output devices Python will be connected to. That's simply not the case; the lowest common denominator is still ASCII. I yearn for a future where all output devices can be assumed, in the absence of other information, to understand a common Unicode encoding (e.g. UTF-8), but we're not there yet and it would be a grave mistake for Python to falsely behave as though we were. -- \ ?I went to a fancy French restaurant called ?D?j? Vu?. The head | `\ waiter said, ?Don't I know you??? ?Steven Wright | _o__) | Ben Finney From whatpot at gmail.com Tue Oct 7 07:00:41 2008 From: whatpot at gmail.com (Vaibhav.bhawsar) Date: Tue, 7 Oct 2008 04:00:41 -0700 Subject: export opengl context to pdf In-Reply-To: <17d58cc40810070054j151b67fft12e93cf54615e158@mail.gmail.com> References: <17d58cc40810070054j151b67fft12e93cf54615e158@mail.gmail.com> Message-ID: <17d58cc40810070400l1421835andb7d8a2eae220f73@mail.gmail.com> Hi, Does anyone know of a package that will allow me to output an opengl context as a PDF (or postscript)? I am using pyglet to render something on screen that i want to save as PDF. thanks! vaibhav -- Vaibhav Bhawsar From steve at REMOVE-THIS-cybersource.com.au Sat Oct 11 05:41:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Oct 2008 09:41:17 GMT Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <3fe70d4b-0dfe-4c60-8b16-1bc70ce96d25@j68g2000hsf.googlegroups.com> <80b69331-e241-4c05-8df9-03f8bdbfe0bb@y21g2000hsf.googlegroups.com> Message-ID: <01006e17$0$20646$c3e8da3@news.astraweb.com> On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS wrote: >> I don't think simply re-executing the default argument expression on >> each call works either: that would confuse at least as many people as >> the current system. > > May I ask you why? I think I don't agree, but I am not sure. x = 100 def foo(a, b=x): return a+b first = foo(1) x = 101 second = foo(1) assert first == second I think people will be rightly surprised that this fails. >> It would be possible, but extremely annoying to limit default arguments >> to being literal constants, > > This is a possible solution, beside re-executing the default argument > expression on each call. That's no solution at all, because default arguments should not be limited to literal constants. That's unacceptable in my opinion. >> unless you invent some kind of scheme for declaring that a type is safe >> to use as a default argument. > > Well, it seems functional-style programming may become more common in > the future, and seeing languages like Scala, etc, maybe it can be useful > to add to Python some way to define immutable classes (in an explicit > way). Maybe subclasses of Immutable? You're still assuming that the behaviour is a bug. It's not, it's a feature. >> Even if you could change the behaviour of default arguments we would >> still get equivalent regular questions from the people who initialise >> class attributes with lists or dictionaries. > > I have seen professional programmers too use class attributes instead of > instance ones... That's only a mistake if you don't mean to use class attributes instead of instance attributes. -- Steven From bruno.42.desthuilliers at websiteburo.invalid Fri Oct 10 04:36:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 10 Oct 2008 10:36:35 +0200 Subject: inspect feature In-Reply-To: References: <4a893f80-adfd-4998-94f4-a095d62f845e@x41g2000hsb.googlegroups.com> <48edc501$0$10600$426a34cc@news.free.fr> Message-ID: <48ef13b8$0$11215$426a34cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > On Oct 9, 3:48 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Aaron "Castironpi" Brady a ?crit : >> >> >> >>> Hello, >>> The 'inspect' module has this method: >>> inspect.getargvalues(frame) >>> It takes a frame and returns the parameters used to call it, including >>> the locals as defined in the frame, as shown. >>>>>> def f( a, b, d= None, *c, **e ): >>> ... import inspect >>> ... return inspect.getargvalues( inspect.currentframe() ) >>> ... >>>>>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' ) >>> (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1, >>> 'e': {'h': 'g >>> hi'}, 'd': 'abc', 'inspect': >> \Python26\lib\in >>> spect.pyc'>}) >>> However, if you wanted a decorator that examines the parameters to a >>> function, you're out of luck. By the time you have a frame, you're >>> already in the function. >> Hem... >> >> def decorator(func): >> def _decorator(*args, *kw): >> print "func args are ", *args, **kw >> return func(*args, **kw) >> return _decorator > > It is less of a problem without tuple unpacking, but you still have > code like: > > if len( args )>= 2: > b= args[ 1 ] > else: > try: > b= (somehow check b's default val.) > except NoDefaultVal: > raise ArgumentError > > Worse yet, you have it for each parameter. Unless I missed something, > this is the only way to mimic/recreate the signature of the decoratee. I don't get what you're after ??? The decorator has full access to both the actual params *and* the function's signature (via inspect.getargspec). So your initial question "if you wanted a decorator that examines the parameters to a function" seems fully answered. You will indeed have to write a couple lines of code if you want the same formating as the one you'd get with inspect.currentframe(), but what ? FWIW, Michele Simionato's decorator module has some trick to allow for signature-preserving decorators, so you may want to have a look - but I'm not sure if this would solve your problem - at least in a sane way. From tsrinuvasulu491 at gmail.com Sun Oct 5 21:27:32 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Sun, 5 Oct 2008 18:27:32 -0700 (PDT) Subject: EARN 1000$ IN EVERY MONTH Message-ID: <834b115f-9959-43d1-be75-4286409c3ca4@25g2000prz.googlegroups.com> hai, i am srinu from india. i am sending a blog url for yours use. click on the blog and get more information to choose yours job. the blog url is: http://earnmonthlyincome.blogspot.com/ goodluck From greg.ewing at canterbury.ac.nz Sat Oct 25 19:29:38 2008 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sun, 26 Oct 2008 12:29:38 +1300 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <4903719E.7080908@g.nevcal.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <490278fd$0$26640$9b622d9e@news.freenet.de> <6mfscvFgpieoU1@mid.individual.net> <4903719E.7080908@g.nevcal.com> Message-ID: <4903ABE2.4010203@canterbury.ac.nz> Glenn Linderman wrote: > So your 50% number is just a scare tactic, it would seem, based on wild > guesses. Was there really any benefit to the comment? All I was really trying to say is that it would be a mistake to assume that the overhead will be negligible, as that would be just as much a wild guess as 50%. -- Greg From steve at REMOVE-THIS-cybersource.com.au Sun Oct 19 03:40:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Oct 2008 07:40:11 GMT Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> <010845d8$0$20638$c3e8da3@news.astraweb.com> <01087204$0$20638$c3e8da3@news.astraweb.com> <010a9c3f$0$20653$c3e8da3@news.astraweb.com> Message-ID: <010add7a$0$20653$c3e8da3@news.astraweb.com> On Sun, 19 Oct 2008 16:38:37 +1300, Lawrence D'Oliveiro wrote: > In message <010a9c3f$0$20653$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote: >> >>> Data can come in fractional bits. That's how compression works. >> >> If you don't believe me, try compressing a single bit and see if you >> get a "fractional bit". > > If both states of the bit are not equally likely, then you do indeed > have a fractional bit, since > > nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2 That's an arithmetic mean of the logarithms. It doesn't imply that there are fractional bits any more than an average family having 2.3 children implies that there are 0.3 of a child wandering around the streets. Using the Shannon measure of information, you can have messages which contain fractional information (technically, "surprisal"), when measured in bits. But that doesn't imply the existence of fractional bits. Look at it this way: consider a barter economy where I agree to swap 5 chickens for 2 axes. So each axe is equivalent to 2.5 chickens. But that doesn't imply that there is such a thing as 0.5 of a chicken -- at least not a *live* chicken. While I can blithely talk about bartering fractional chickens, in practice when I actually go to make good on my promise, it must be an integer number of chickens. Similarly, we can talk about messages containing fractional bits of information, but when we actually store or transmit that message in practice, we can only use integer numbers of bits. As Wikipedia puts it: It is important to differentiate between the use of "bit" in referring to a discrete storage unit and the use of "bit" in referring to a statistical unit of information. The bit, as a discrete storage unit, can by definition store only 0 or 1. A statistical bit is the amount of information that, on average[citation needed], can be stored in a discrete bit. ... If these two ideas need to be distinguished, sometimes the name bit is used when discussing data storage while shannon is used for the statistical bit. http://en.wikipedia.org/wiki/Bit -- Steven From tjreedy at udel.edu Thu Oct 9 16:49:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2008 16:49:14 -0400 Subject: Safe eval of insecure strings containing Python data structures? In-Reply-To: <7x7i8hvjur.fsf@ruckus.brouhaha.com> References: <896B75251BA19745A529B1B867893FA50677D6@planet.delsci.local> <7x7i8hvjur.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Lie Ryan writes: >> in python 2.6, ast.literal_eval may be used to replace eval() for >> literals. > > What happens on literal_eval('[1]*999999999') ? Easy to try. Since it is not a literal or display, ValueError: malformed string, just as with set({1,2,3]) >>> [1]*999999999 # or >>> eval('[1]*999999999') # give a quick MemoryError From martin at v.loewis.de Fri Oct 24 21:40:13 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 25 Oct 2008 03:40:13 +0200 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> Message-ID: <490278fd$0$26640$9b622d9e@news.freenet.de> > It seems to me that the very simplest move would be to remove global > static data so the app could provide all thread-related data, which > Andy suggests through references to the QuickTime API. This would > suggest compiling python without thread support so as to leave it up > to the application. I'm not sure whether you realize that this is not simple at all. Consider this fragment if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) { if (empty) /* want empty string */ i = j = 0; else { Py_INCREF(Py_None); return Py_None; Py_None here is a global variable. How would you replace it? It's used in thousands of places. For another example, consider PyErr_SetString(PyExc_ValueError, "Empty module name"); or dp = PyObject_New(dbmobject, &Dbmtype); There are tons of different variables denoting exceptions and other types which all somehow need to be rewritten (likely with undesirable effects on readability). So I don't think that this is a simple solution. It's the right one, but it will take five or ten years to implement. Regards, Martin From ldo at geek-central.gen.new_zealand Mon Oct 6 17:53:31 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 07 Oct 2008 10:53:31 +1300 Subject: gif creator References: <3c09d700-d1d5-4d41-bc99-088e49952f07@h2g2000hsg.googlegroups.com> Message-ID: In message <3c09d700-d1d5-4d41-bc99-088e49952f07 at h2g2000hsg.googlegroups.com>, ccdetail at gmail.com wrote: > has anyone written a gif creator program purely in python that doesn't > require PIL or tons of other claptrap? It's so much easier to just go into Synaptic (or whatever your package manager is) and check a few boxes to install all the necessary "claptrap", than it is to try to reinvent large chunks of it yourself. From robert.kern at gmail.com Wed Oct 22 10:16:28 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 22 Oct 2008 09:16:28 -0500 Subject: Using python22.dll with Python 2.5? In-Reply-To: <6m8ovbFfnd9nU1@mid.individual.net> References: <6m8ovbFfnd9nU1@mid.individual.net> Message-ID: Martin Schneider wrote: > Hi! > > I'd like to use the numpy library (which runs on Python 2.5) in the same > project with another (mandatory) library which needs python22.dll. When > I try to compile I get an error similar to "python22.dll not compatible > with the current Python version." > > Has anybody an idea how to solve this? You can't. Binary extension modules compiled for one "minor" version of Python cannot be used for another. numpy also requires Python >= 2.3 anyways, so you could not recompile it for Python 2.2 in any case. You could use numpy's predecessor, Numeric, which still should work with Python 2.2, but you will have to compile it yourself; there are no available Python 2.2 Windows binaries. http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=1351 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at microcorp.co.za Sat Oct 11 23:41:31 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 12 Oct 2008 05:41:31 +0200 Subject: Efficient Bit addressing in Python. Message-ID: <002901c92c1f$18aa6bc0$0d00a8c0@hendrik> Ross Ridge wrote: >This is the code I use to convert large bit arrays to byte strings and >back: > >import string >import binascii >import array 8<--------------- examples ---------------------- >I don't think you can do anything faster with standard modules, although >it might not be efficient if you're only working with a single byte. Thanks I was not aware of binascii module this looks powerful. - Hendrik From stef.mientki at gmail.com Mon Oct 6 14:07:23 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 06 Oct 2008 20:07:23 +0200 Subject: When Python should not be used? In-Reply-To: References: Message-ID: <48EA53DB.605@gmail.com> Andrea Francia wrote: > The right tool depends on the current problem. > > While some python users prefer to talk about when Python is the right > tool I think that it is more instructive to know when it is not. > > Please, could you let me know what do you think about that? > > Thanks I'm programming in Python now for about a year, so I'm definitely not an expert, but this friendly list will correct me I'm wrong. Here is what I can come up with - design of GUI is difficult (despite all those well meant programs, of which I couldn't get one of them working) - autoit like applications - low level drivers - licenses differ a lot, which makes it hard to combine different packages - downwards compatibility is sometimes lost - a number of libraries is quite in-mature but for the rest, it's a beautiful language, and I'm working on a large application, which should be open source replacement for MatLab + LabView. cheers, Stef From david2ansands at gmail.com Fri Oct 10 03:31:47 2008 From: david2ansands at gmail.com (davidsands) Date: Fri, 10 Oct 2008 00:31:47 -0700 (PDT) Subject: FLexible formatted text involving nested lists? References: Message-ID: On Oct 10, 4:36?am, RossRGK wrote: > I'm having trouble getting my head around a solution for a situation > where I need to flexibly format some text with a varying number of > embedded fields. > > Here's a simplified description of my challenge... > > I have a list of lists called bigList: > > bigList = [ little, small, tiny] > > The sub-lists have varying sizes. ?I won't know how many items they have > but it will be between 0 and 3 > > So perhaps little = [3, 2, 7] > small = [6,4] > tiny = [2] > > The values in those sub lists correspond to formatted print strings. The > formatting strings will change over time and they are in a list called > "fmts" where > > fmts = [fmtA, fmtB, fmtC] ? where > > fmtA = 'oats %0d kilos over %0d days with %0d workers' > fmtB = 'barley %0d lbs for %0d hours' > fmtC = 'apples %0d baskets' > > If I knew how many fields were in each 'sub-list' in bigList ahead of > time, and it never changed I could awkwardly do this: > > print fmtA %(little[0], little[1], little[2]) > print fmtB %(small[0], small[1]) > print fmtC %(tiny[0]) > > or equivalently, > > print fmts[0] %(bigList[0][0], bigList[0][1], bigList[0][2]) > print fmts[1] %(bigList[1][0], bigList[1][1]) > print fmts[2] %(bigList[2][0]) > > Both approaches would yield: > oats 3 kilos over 2 days with 7 workers > barley 6 lbs for 4 hours > apples 2 baskets > > Now my challenge: since the number of fields is unknown at design time, > my app needs to add be able to flexibly handle this. > > I though maybe I could use a loop that figures things out as it goes > along. e.g... > > i=0 > for fmtString in fmts > ? ?numbOfFields = len(fmt[i]) > ? ?print fmtString %(bigList[i][ need "for 0 to numbOffields" worth of > indices!] ) > > But I don't know how to have a number of items in the print expression > that align to the numbOfFields value!? ?Is there some other approach I > can use? > > I thought perhaps it would accomodate extra elements in the %(...) part > of the formatted print expression which would be ignored, but that > doesn't work. > > Maybe I have to break my fmts up and do a field at a time? ?Any thoughts > are appreciated ? :) > > -Ross. The tuple() type-conversion function will do what you need: print fmts[0] % tuple(bigList[0]) print fmts[1] % tuple(bigList[1]) print fmts[2] % tuple(bigList[2]) From steve077 at gmail.com Wed Oct 15 14:44:38 2008 From: steve077 at gmail.com (Steve Phillips) Date: Wed, 15 Oct 2008 14:44:38 -0400 Subject: IDE Question In-Reply-To: <76c6100e0810151019q5d829c06k9dc551c6c4b3ac23@mail.gmail.com> References: <76c6100e0810151019q5d829c06k9dc551c6c4b3ac23@mail.gmail.com> Message-ID: <76c6100e0810151144q7d1e759fx22904fbbd2d40741@mail.gmail.com> Thanks for all of your responses. I did forget to mention that I do use Notepad++ for just about everything. My larger scripts I use that and just say the hell with the auto-complete and the call-tips. I lived on that wiki page and actually still do waiting to see if something new was going to be added. It is safe to say that "my" definition of the perfect IDE would be one that has reliable call-tips and auto-completions. I have been doing Python for about 2-2.5 years now. Prior to using IDLE for modules that I am unfamiliar with I have always used NP++. Before Python was my primary language, it was straight VB, VBA, VBScript, etc... That should give you some insight to where I am coming from. Steve P On 10/15/08, Steve Phillips wrote: > > Hi All, > I am just wondering what seems to be the most popular IDE. The reason > I ask is I am currently at war with myself when it comes to IDE's. It > seems like every one I find and try out has something in it that > others don't and viceversa. I am in search for the perfect IDE and > after many months of searching, I always come back to IDLE to do what > I need to do. I want to use Komodo badly but the one issue I have with > that is sometimes the auto-complete works and other times it doesn't. > Even if I carbon copy a script. > > Thanks in advance, > Steve P > -------------- next part -------------- An HTML attachment was scrubbed... URL: From durumdara at gmail.com Tue Oct 14 04:58:35 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Tue, 14 Oct 2008 10:58:35 +0200 Subject: Reading from stdin (in windows) Message-ID: Hi! I wanna write a file processor in python (Windows XP). I wanna use pipe, and not parameters. When I write this: ... l = [] while 1: t = sys.stdin.read(1) if t == '': break l.append(t) t = "".join(l) ... and use code this: process.py References: <2c4e058e-ac16-4d98-a8b0-87cdc974607b@j22g2000hsf.googlegroups.com> Message-ID: <6mlf01FhdunaU1@mid.uni-berlin.de> jasiu85 schrieb: > Hey, > > Please take a look at the code of the two threads below: > > COMMON_DICT = {} > > def thread_1(): > global COMMON_DICT > local_dict = prepare_dict() > COMMON_DICT = local_dict > > def thread_2(): > global COMMON_DICT > local_dict = COMMON_DICT > use_dict(local_dict) > > Do I need a lock to protect the COMMON_DICT dictionary? AFAIK bytecode > operations are atomic and in each thread there's only one crucial > bytecode op: STORE_NAME in the first thread and LOAD_NAME in the > second one. So I suspect that everything will work just fine. Am I > right? Depending on what you mean by "right". The above is not enough to judge what is really happening. But depending on the execution order, thread_1 overwrites the reference in COMMON_DICT *after* thread_2 has altered it. But it won't crash or anything. If that's right for you. Diez From bj_666 at gmx.net Mon Oct 6 03:36:27 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Oct 2008 07:36:27 GMT Subject: python noob help References: Message-ID: <6kttfrF9ku1bU1@mid.uni-berlin.de> On Mon, 06 Oct 2008 00:08:58 -0700, toyko wrote: > So yeah, I have this assignment for my computer science class, > http://pages.cpsc.ucalgary.ca/~boyd/231/as1.pdf so far this is what I > have wrote, any suggestions cause I am stuck! Learn Python and actually *think* about the problem and a solution. We are not going to do your homework for you. You have to show a little effort. So far you have just tried to copy the formulas from the assignment to Python code -- and failed because there are runtime errors. So you didn't even bother to test what you have so far before crying for help. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Tue Oct 14 10:13:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 14 Oct 2008 07:13:50 -0700 (PDT) Subject: Wx.Grid and popup over cells References: Message-ID: <7529c42a-5b22-43c2-9f9a-5531e92cbd11@y79g2000hsa.googlegroups.com> On Oct 14, 5:21?am, Massi wrote: > Hi everyone, > > I'm writing a python script which uses a grid (PyGridTableBase) whose > cells can contain very large values (not only numbers, but also > strings). I've also written a custom renderer which dinamically shows > only the first n characters (according to the width of the cell) > replacing the last ones with dots. Now I would like to know if it is > possible to have a popup which shows the whole contents of a certain > cell when the mouse stops over the cell itself. Any ideas? > Thanks in advance. > > Massi First off, let me recommend the wxPython mailing list for questions of this sort. You'll probably get more relevant help quicker if you go that route. Anyway, I've done tooltips on cells in a grid before and you'll need the same concept to use a pop-up dialog too. To begin, you'll want to bind to the mouse event, EVT_MOTION, like this: self.myGrid.GetGridWindow().Bind(wx.EVT_MOTION, self.onMouseOver) Next, you'll need to do something like the following in your mouse over function: def onMouseOver(self, event): ''' Method to calculate where the mouse is pointing and then set the tooltip dynamically. ''' # Use CalcUnscrolledPosition() to get the mouse position within the # entire grid including what's offscreen x, y = self.totals_sheet.CalcUnscrolledPosition(event.GetX(),event.GetY()) coords = self.totals_sheet.XYToCell(x, y) # you only need these if you need the value in the cell row = coords[0] col = coords[1] event.GetEventObject().SetToolTipString("My amazing tooltip") Hopefully that will get you going. If not, just ask more questions (here or at the wxPython list). ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From wuwei23 at gmail.com Mon Oct 20 22:29:11 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 20 Oct 2008 19:29:11 -0700 (PDT) Subject: search for a python compiler program whose name is jingle References: Message-ID: <8419b656-07a4-4d46-80fb-4ac82df4a7c7@e2g2000hsh.googlegroups.com> On Oct 20, 3:46?pm, oyster wrote: > I don't remember its name very clear, it may be 'jingle' or not > this program runs on windows and can compile a python program into exe > file without gcc I haven't heard of 'jingle' but there are a number of tools for achieving this: http://effbot.org/pyfaq/how-can-i-create-a-stand-alone-binary-from-a-python-script.htm From ihcircekirkpatrick at gmail.com Sun Oct 5 19:15:25 2008 From: ihcircekirkpatrick at gmail.com (ihcircekirkpatrick at gmail.com) Date: Sun, 5 Oct 2008 16:15:25 -0700 (PDT) Subject: Buy fioricet online Message-ID: <2fd0b6f2-033c-4029-a92a-a87d192f0beb@17g2000hsk.googlegroups.com> buy fioricet . . . Enough to seek Fioricet! You've already found the best site where you can purchase Fioricet for lowest price! To order Fioricet without prescription visit link below! ************************************ http://med247.us/?p=fioricet ************************************ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uy fioricet by fioricet bu fioricet buy ioricet buy foricet buy firicet buy fioicet buy fiorcet buy fioriet buy fiorict buy fiorice bbuy fioricet buuy fioricet buyy fioricet buy ffioricet buy fiioricet buy fiooricet buy fiorricet buy fioriicet buy fioriccet buy fioriceet buy fioricett uby fioricet byu fioricet bu yfioricet buy iforicet buy foiricet buy firoicet buy fioircet buy fiorciet buy fioriect buy fioricte buyfioricet vuy fioricet guy fioricet huy fioricet nuy fioricet byy fioricet b7y fioricet b8y fioricet biy fioricet bky fioricet bjy fioricet bhy fioricet but fioricet bu6 fioricet bu7 fioricet buu fioricet buj fioricet buh fioricet bug fioricet buy dioricet buy rioricet buy tioricet buy gioricet buy vioricet buy cioricet buy fuoricet buy f8oricet buy f9oricet buy fooricet buy floricet buy fkoricet buy fjoricet buy fiiricet buy fi9ricet buy fi0ricet buy fipricet buy filricet buy fikricet buy fioeicet buy fio4icet buy fio5icet buy fioticet buy fiogicet buy fioficet buy fiodicet buy fiorucet buy fior8cet buy fior9cet buy fiorocet buy fiorlcet buy fiorkcet buy fiorjcet buy fiorixet buy fioridet buy fiorifet buy fiorivet buy fioricwt buy fioric3t buy fioric4t buy fioricrt buy fioricft buy fioricdt buy fioricst buy fioricer buy fiorice5 buy fiorice6 buy fioricey buy fioriceh buy fioriceg buy fioricef From glenn at nevcal.com Fri Oct 24 16:59:26 2008 From: glenn at nevcal.com (Glenn Linderman) Date: Fri, 24 Oct 2008 13:59:26 -0700 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <309f2496-ab0b-4dd1-a7b4-e5013a76f902@i18g2000prf.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <309f2496-ab0b-4dd1-a7b4-e5013a76f902@i18g2000prf.googlegroups.com> Message-ID: <4902372E.6080209@nevcal.com> On approximately 10/24/2008 1:09 PM, came the following characters from the keyboard of Rhamphoryncus: > On Oct 24, 1:02 pm, Glenn Linderman wrote: > >> On approximately 10/24/2008 8:42 AM, came the following characters from >> the keyboard of Andy O'Meara: >> >> >>> Glenn, great post and points! >>> >> Thanks. I need to admit here that while I've got a fair bit of >> professional programming experience, I'm quite new to Python -- I've not >> learned its internals, nor even the full extent of its rich library. So >> I have some questions that are partly about the goals of the >> applications being discussed, partly about how Python is constructed, >> and partly about how the library is constructed. I'm hoping to get a >> better understanding of all of these; perhaps once a better >> understanding is achieved, limitations will be understood, and maybe >> solutions be achievable. >> >> Let me define some speculative Python interpreters; I think the first is >> today's Python: >> >> PyA: Has a GIL. PyA threads can run within a process; but are >> effectively serialized to the places where the GIL is obtained/released. >> Needs the GIL because that solves lots of problems with non-reentrant >> code (an example of non-reentrant code, is code that uses global (C >> global, or C static) variables ? note that I'm not talking about Python >> vars declared global... they are only module global). In this model, >> non-reentrant code could include pieces of the interpreter, and/or >> extension modules. >> >> PyB: No GIL. PyB threads acquire/release a lock around each reference to >> a global variable (like "with" feature). Requires massive recoding of >> all code that contains global variables. Reduces performance >> significantly by the increased cost of obtaining and releasing locks. >> >> PyC: No locks. Instead, recoding is done to eliminate global variables >> (interpreter requires a state structure to be passed in). Extension >> modules that use globals are prohibited... this eliminates large >> portions of the library, or requires massive recoding. PyC threads do >> not share data between threads except by explicit interfaces. >> >> PyD: (A hybrid of PyA & PyC). The interpreter is recoded to eliminate >> global variables, and each interpreter instance is provided a state >> structure. There is still a GIL, however, because globals are >> potentially still used by some modules. Code is added to detect use of >> global variables by a module, or some contract is written whereby a >> module can be declared to be reentrant and global-free. PyA threads will >> obtain the GIL as they would today. PyC threads would be available to be >> created. PyC instances refuse to call non-reentrant modules, but also >> need not obtain the GIL... PyC threads would have limited module support >> initially, but over time, most modules can be migrated to be reentrant >> and global-free, so they can be used by PyC instances. Most 3rd-party >> libraries today are starting to care about reentrancy anyway, because of >> the popularity of threads. >> > > PyE: objects are reclassified as shareable or non-shareable, many > types are now only allowed to be shareable. A module and its classes > become shareable with the use of a __future__ import, and their > shareddict uses a read-write lock for scalability. Most other > shareable objects are immutable. Each thread is run in its own > private monitor, and thus protected from the normal threading memory > module nasties. Alas, this gives you all the semantics, but you still > need scalable garbage collection.. and CPython's refcounting needs the > GIL. > Hmm. So I think your PyE is an instance is an attempt to be more explicit about what I said above in PyC: PyC threads do not share data between threads except by explicit interfaces. I consider your definitions of shared data types somewhat orthogonal to the types of threads, in that both PyA and PyC threads could use these new shared data items. I think/hope that you meant that "many types are now only allowed to be non-shareable"? At least, I think that should be the default; they should be within the context of a single, independent interpreter instance, so other interpreters don't even know they exist, much less how to share them. If so, then I understand most of the rest of your paragraph, and it could be a way of providing shared objects, perhaps. I don't understand the comment that CPython's refcounting needs the GIL... yes, it needs the GIL if multiple threads see the object, but not for private objects... only one threads uses the private objects... so today's refcounting should suffice... with each interpreter doing its own refcounting and collecting its own garbage. Shared objects would have to do refcounting in a protected way, under some lock. One "easy" solution would be to have just two types of objects; non-shared private objects in a thread, and global shared objects; access to global shared objects would require grabbing the GIL, and then accessing the object, and releasing the GIL. An interface could allow for grabbing releasing the GIL around a block of accesses to shared objects (with GIL:) This could reduce the number of GIL acquires. Then the reference counting for those objects would also be done under the GIL, and the garbage collecting? By another PyA thread, perhaps, that grabs the GIL by default? Or a PyC one that explicitly grabs the GIL and does a step of global garbage collection? A more complex, more parallel solution would allow for independent groups of shared objects. Of course, once there is more than one lock involved, there is more potential for deadlock, but it also provides for more parallelism. So a shared object might inherit from a "concurrency group" which would have a lock that could be acquired (with conc_group:) for access to those data items. Again, the reference counting would be done under that lock for that group of objects, and garbage collecting those objects would potentially require that lock as well... The solution with multiple concurrency groups allows for such groups to contain a single shared object, or many (probably related) shared objects. So the application gets a choice of the granularity of sharing and locking, and can choose the number of locks to optimize performance and achieve correctness. This sort of shared data among threads, though, suffers in the limit from all the problems described in the Berkeley paper. More reliable programs might be achieved by using straight PyC threads, and some very limited "data ports" that can be combined using a higher-order flow control concept, as outlined in the paper. While Python might be extended with these flow control concepts, they could be added gradually over time, and in the embedded case, could be implemented in some other language. -- Glenn ------------------------------------------------------------------------ . _|_|_| _| . _| _| _|_| _|_|_| _|_|_| . _| _|_| _| _|_|_|_| _| _| _| _| . _| _| _| _| _| _| _| _| . _|_|_| _| _|_|_| _| _| _| _| ------------------------------------------------------------------------ Obstacles are those frightful things you see when you take your eyes off of the goal. --Henry Ford From gagsl-py2 at yahoo.com.ar Mon Oct 27 02:14:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Oct 2008 04:14:43 -0200 Subject: [Python 2.6] print_function and unicode_literals cannot be used at the same time? References: <96aeef2a-8705-4b6f-ba2a-85cf418c44ed@1g2000prd.googlegroups.com> Message-ID: En Sun, 26 Oct 2008 12:13:08 -0200, Christian Heimes escribi?: > ?????? wrote: >> Any ideas? >> Code 1: >> from __future__ import print_function, unicode_literals >> import sys >> print(type('HELLO, WORLD!'), file=sys.stderr) > > You have to do each future import in a separate line: > > >>> from __future__ import unicode_literals > >>> from __future__ import print_function > >>> print(type(""), file=sys.stderr) > That's a bug, isn't it? The language reference explicitely allows it: http://docs.python.org/reference/simple_stmts.html#future-statements -- Gabriel Genellina From mail at timgolden.me.uk Tue Oct 21 07:06:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 21 Oct 2008 12:06:37 +0100 Subject: pymssql - execute loads all results into memory! In-Reply-To: References: <767a6cf1-4968-4e95-8a0b-62adf871d399@s1g2000prg.googlegroups.com> <92da89760810200732p733977dfu1ac1f44ec44ee436@mail.gmail.com> Message-ID: <48FDB7BD.6040703@timgolden.me.uk> Aspersieman wrote: > However, pyODBC doesn't support return variables(parameters) in stored > procedures (at least with MS SQL). pymssql is the only db api for python > that I've found that can reliably do this. I've tried adodbapi, pyodbc > and one or two others (can't think of the names now... :-/). That's a fair point (I'm assuming you're right; I've never tried). That tends to be a shortcoming of SQL interfaces. However, pymssql is based on the defunct ntwdblib.dll interface which is becoming harder and harder to find as of SQL2005. Have you tried putting a feature request in to the pyodbc team? I've not had anything to do with them for a bit, but they did implement the .nextset method at my request a couple of years ago. (That's assuming it's even possible with ODBC in general, which I also haven't checked). TJG From notvalid2 at sbcglobal.net Fri Oct 17 19:28:06 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 17 Oct 2008 16:28:06 -0700 Subject: Convertimg a Sequence of Images to an AVI File In-Reply-To: References: Message-ID: <3c9Kk.5741$YU2.99@nlpi066.nbdc.sbc.com> W. eWatson wrote: > I have a file of images shot at a frame rate of 1/30th of a second. They > are 640 by 480 bytes followed immediately by up to 200 smaller images > 128x128 pixels. The software I'm using will convert this into a mov > file. I'd like to simply take the large images out of the file and make > an avi file from them. What in Python will help me do that? It looks like the ticket is -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From joefazee at gmail.com Fri Oct 31 02:49:33 2008 From: joefazee at gmail.com (Abah Joseph) Date: Fri, 31 Oct 2008 07:49:33 +0100 Subject: Tree or hierarchical structure Message-ID: I need tutorial or book on Tree or hierarchical structure using Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From musiccomposition at gmail.com Wed Oct 29 22:42:23 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 29 Oct 2008 19:42:23 -0700 (PDT) Subject: set/dict comp in Py2.6 References: <28b0fe12-9a82-4d14-b3fa-3cd203000ba0@l77g2000hse.googlegroups.com> <635818f8-9fdf-4f15-b2b3-76bd3aac487d@y21g2000hsf.googlegroups.com> Message-ID: <88188aac-5078-4f9d-af16-76aacae2b295@y71g2000hsa.googlegroups.com> On Oct 27, 3:38?am, "Gabriel Genellina" wrote: > En Sat, 25 Oct 2008 23:44:46 -0200, Benjamin ? > escribi?: > > > On Oct 25, 3:13?am, bearophileH... at lycos.com wrote: > >> I'd like to know why Python 2.6 doesn't have the syntax to create sets/ > >> dicts of Python 3.0, like: > > > Because nobody bothered to backport them. > > En Sat, 25 Oct 2008 23:47:32 -0200, Benjamin ? > escribi?: > > > Because nobody bothered to backport them. > > En Mon, 27 Oct 2008 00:17:20 -0200, Benjamin ? > escribi?: > > > Because nobody bothered to backport it. > > En Mon, 27 Oct 2008 00:19:29 -0200, Benjamin ? > > escribi?: > > Because nobody bothered to backport it. > > Yeah, we already know... :) Sorry about that. > > -- > Gabriel Genellina From kyosohma at gmail.com Sun Oct 26 13:46:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 26 Oct 2008 10:46:50 -0700 (PDT) Subject: Iowa Python User's Group Meeting Next Week! Message-ID: <835cd49b-8311-4fdc-9f21-1511bc4d560e@p59g2000hsd.googlegroups.com> Hi, The next Iowa Python Users Group (AKA Pyowa) is nearly upon us. We will be meeting November 3rd, from 7-9 p.m. at the following location: Marshall County Sheriff's Office 2369 Jessup Ave Marshalltown, IA 50158 At this meeting, we will be having a Crash Course of sorts for all the new programmers in our group. As anyone who has ever taken a programming course know, it is impossible to teach everything in two hours, so we'll be focusing on tools that will allow our group to help themselves. In other words, we'll be focusing on source code analysis techniques like introspection and how to use IDLE effectively. There will also be a presentation on basic GUI design and also Django. We will have 8 laptops there to use for any new people, pre-loaded with Python 2.5.2 and any additional packages we need for our presentations. You are welcome to bring your own laptop if you want. Be sure to have 2.5 on yours as well as wxPython and the PyWin32 package (if you use Windows). We will have them on USB flash drives should you forget. Free pop and bottled water will be provided. Questions and comments can be directed to mike [at] pythonlibrary [dot] org. Updates can be found at http://www.ipug.pythonlibrary.org ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From robinvaiya at gmail.com Sun Oct 12 02:18:19 2008 From: robinvaiya at gmail.com (robin) Date: Sat, 11 Oct 2008 23:18:19 -0700 (PDT) Subject: Canon mp160 drivers Message-ID: PROBLEM i lost my canon mp160 drivers for the printer and scanner. how to i download from the drivers for the printerI lost my start up disk for my canon mp180 all in one printer.How can I download another oneNeed to find the drivers to downloadmy computer has much viruses and i installed it. after finishedinstalling, i cannot print more because the software is lost visit in this sitehttp://www.usa.canon.com/consumer/controller?act=DownloadDetailAct&fcategoryid=238&modelid=13368 MP160 driver 1.01 Win98SE/ME/2000/XPhttp://www.driversdown.com/drivers/ Canon-PIXMA-MP160-driver_74508.shtmlMP160 driver 1.10 Windows Vista/ Vista-64http://www.driversdown.com/drivers/Canon-PIXMA-MP160- driver_74507.shtml From mail at timgolden.me.uk Wed Oct 1 12:52:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 01 Oct 2008 17:52:57 +0100 Subject: text file In-Reply-To: <1ac8702e-dd40-4fc7-9271-42b48ca1ec25@25g2000hsx.googlegroups.com> References: <1ac8702e-dd40-4fc7-9271-42b48ca1ec25@25g2000hsx.googlegroups.com> Message-ID: <48E3AAE9.7030506@timgolden.me.uk> yqyq22 at hotmail.com wrote: > HI all, > i have some problem with the code belove, i have a list of servers in > a textfile (elencopc.txt).... i would to retrieve informations via WMI > ( cicle for ), but i don't understand if the code is correct: Try this, using http://timgolden.me.uk/python/wmi.html : import wmi # # For the test to work # open ("elencopc.txt", "w").write ("localhost") for server in open ("elencopc.txt").read ().splitlines (): c = wmi.WMI (server) print "SERVER:", server for item in c.Win32_QuickFixEngineering (): print item # or print item.Caption, etc. print print If you get RPC Server unavailable, it usually means that the WMI service isn't running on that machine. Usually. TJG From fthiel at stny.rr.com Sat Oct 18 17:14:46 2008 From: fthiel at stny.rr.com (Frank L. Thiel) Date: Sat, 18 Oct 2008 21:14:46 GMT Subject: PythonWin --> drwatson In-Reply-To: References: Message-ID: <9lsKk.77948$sg2.23073@fe09.news.easynews.com> On 18-Oct-08 16:31, this message was sent by Dennis Lee Bieber: > On Sat, 18 Oct 2008 15:00:03 GMT, "Frank L. Thiel" > declaimed the following in comp.lang.python: > >> Thanks for your reply, Allan. I am not sure what you mean by "the >> Windows installer package" -- a *.msi file?. I cannot find a *.msi file >> at Sourceforge, which is where the came >> from. When I use the latter (I have uninstalled and reinstalled using >> this many times now!), I get no error entries in the Event Viewer. >> However, when I try to open PythonWin, the Event Viewer shows the >> following message: >> > Do you have a version of python 2.6 installed? (I'm surprised the > standalone win32 package for Python 2.6 is even available already). > Granted, win32 is maintained as a separate package, but the ActiveState > Python download (which includes it by default) is still only on Python > 2.5.2 Yes, Dennis, I have Python 2.6 installed, and it works perfectly from a cmd window and from IDLE. From tjreedy at udel.edu Sat Oct 11 19:17:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Oct 2008 19:17:21 -0400 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> Message-ID: lkcl wrote: I got the impression that there is currently no Windows binary available. Correct? If not, perhaps someone trustworthy will someday donate one. From dan.barbus at gmail.com Thu Oct 2 00:54:26 2008 From: dan.barbus at gmail.com (Dan Barbus) Date: Wed, 1 Oct 2008 21:54:26 -0700 (PDT) Subject: index all instances by id - a memory leak? Message-ID: <74db5980-0322-41aa-bd39-3f3dfe86e3da@y71g2000hsa.googlegroups.com> Hi all, I'm a python beginner, and I have a problem with no solution I can see: I want to index all instances of an object by an internal id (not the hash) and be able to retrieve them later. I created a class-level dictionary (Item._itemById) where I add every new instance. My problem is: How do I delete the instances when the class is no longer in use? ( having it in a map makes it 'in use' all the time, so my implementation results in a memory leak :( ). Here's the code: class Item(): """This is the base class for all data items""" _idBase = None _count = 0 _itemsById = {} def __init__(self, title = ''): Item._count += 1 self.id = Item._generateId(self) Item._itemsById[self.id] = self self.title = title def __del__(self): Item._count -= 1 # Should I do something here to delete the instance? # Will this ever be called if the instance is in a static dictionary? def _generateId(self): """Generates an unique id for the instance. The id will be unique for both the current run and all runs in general. """ if not Item._idBase: Item._idBase = str(hash(self)) return Item._idBase + '-' + str(Item._count).zfill(6) def getItemById(id): return _itemsById[id] From tjreedy at udel.edu Mon Oct 20 17:33:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Oct 2008 17:33:05 -0400 Subject: what's the python for this C statement? In-Reply-To: References: <48fc55bf$0$1084$4fafbaef@reader1.news.tin.it> <87wsg38sik.fsf@mulj.homelinux.net> Message-ID: Lie Ryan wrote: > (which might be the more typical case). And I think range will be an > iterator in the future, imitating the behavior of xrange. So it doesn't > really matter anyway. In 3.0, range is a class and range(arg) is a re-iterable instance of that class. >>> a = range(10,2,-3) >>> a range(10, 2, -3) >>> list(a) [10, 7, 4] >>> list(a) [10, 7, 4] Re-iterablility is handy if you want to iterate twice over the same range, especially is the range object is computed elsewhere. Map and filter, on the other hand, produce one-use iterators. Filter takes one iterable as input and map takes many iterables. Both make no presumption that the inputs are re-iterable rather than a one-time iterators. Terry Jan Reedy From notvalid2 at sbcglobal.net Tue Oct 14 07:20:28 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 14 Oct 2008 04:20:28 -0700 Subject: Installing Python 2.4 over 2.4? Message-ID: I suspect something has been corrupted in Python 2.4. Can I just re-install on top of it, and still expect to have scipy and other pkgs I've installed? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From venutaurus539 at gmail.com Thu Oct 16 09:18:16 2008 From: venutaurus539 at gmail.com (venutaurus539 at gmail.com) Date: Thu, 16 Oct 2008 06:18:16 -0700 (PDT) Subject: how to get the recipients addresses of an outlook mail in python... References: <0f90b2c8-b1c2-4729-a9d0-88142e6f8f39@v53g2000hsa.googlegroups.com> <821cb1d4-9811-4ee3-8630-8b8c10f5e0e3@y21g2000hsf.googlegroups.com> Message-ID: <47ccfc19-2282-4bb2-ba25-03e27240c54b@t54g2000hsg.googlegroups.com> On Oct 16, 5:22?pm, Miki wrote: > > ? ? ? ? Can some one help me in obtaining the set of recipients email > > addresses from an outlook mail? I tried various options like ... > > message["To"] > message["Cc"] > > HTH, > -- > Mikihttp://pythonwise.blogspot.com Thanks for your reply... Sorry , it didn't work... session = Dispatch("MAPI.session") session.Logon('outlook') # MAPI profile name inbox = session.Inbox message = inbox.Messages.Item(i + 1) rec = message["To"] print rec I did some thing like the above code...it said the below error... raise TypeError, "This object does not support enumeration" TypeError: This object does not support enumeration Thank you, Venu. From martin at v.loewis.de Mon Oct 13 01:17:29 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Oct 2008 07:17:29 +0200 Subject: unicode .replace not working - why? In-Reply-To: References: Message-ID: <48F2D9E9.4050809@v.loewis.de> > On a side note, do you really think the function call wouldn't interpret > the unichr before the function call? Dennis' main point was not that you can reuse fn (which he suggested just as performance improvement), but that you need to assign the result of .replace back to textu. Regards, Martin From bj_666 at gmx.net Fri Oct 10 03:03:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Oct 2008 07:03:08 GMT Subject: Python HTML parser chokes on UTF-8 input References: <4m72s5xlgn.ln2@joeserver.homelan.net> Message-ID: <6l8d1cFb7d49U1@mid.uni-berlin.de> On Fri, 10 Oct 2008 00:13:36 +0200, Johannes Bauer wrote: > Terry Reedy schrieb: >> I believe you are confusing unicode with unicode encoded into bytes >> with the UTF-8 encoding. Having a problem feeding a unicode string, >> not 'UFT-8 code', which in Python can only mean a UTF-8 encoded byte >> string. > > I also believe I am. Could you please elaborate further? > > Do I understand correctly when saying that type 'str' has no associated > default encoding, but type 'unicode' does? `str` doesn't know an encoding. The content could be any byte data anyway. And `unicode` doesn't know an encoding either, it is unicode characters. How they are represented internally is not the business of the programmer. If you want operate with unicode characters you have to decode a byte string (`str`) with the appropriate encoding. If you want feed `unicode` to something that expects bytes and not unicode characters you have to encode again. >>> This is incredibly ugly IMHO, as I would really like the parser to >>> just accept UTF-8 input. It accepts UTF-8 input but not `unicode` objects. > However I am sure you will agree that explicit encoding conversions are > cumbersome and error-prone. But implicit conversions are impossible because the interpreter doesn't know which encoding to use and refuses to guess. Implicit and guessed conversions are error prone too. Ciao, Marc 'BlackJack' Rintsch From andy55 at gmail.com Tue Oct 28 11:00:47 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Tue, 28 Oct 2008 08:00:47 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <16acff7d-e3a4-4be0-a042-e74845501cb3@k16g2000hsf.googlegroups.com> <49057647$0$26690$9b622d9e@news.freenet.de> Message-ID: On Oct 27, 4:05?am, "Martin v. L?wis" wrote: > Andy O'Meara wrote: > > > Well, when you're talking about large, intricate data structures > > (which include opaque OS object refs that use process-associated > > allocators), even a shared memory region between the child process and > > the parent can't do the job. ?Otherwise, please describe in detail how > > I'd get an opaque OS object (e.g. an OS ref that refers to memory- > > resident video) from the child process back to the parent process. > > WHAT PARENT PROCESS? "In the same address space", to me, means > "a single process only, not multiple processes, and no parent process > anywhere". If you have just multiple threads, the notion of passing > data from a "child process" back to the "parent process" is > meaningless. I know... I was just responding to you and others here keep beating the "fork" drum. I just trying make it clear that a shared address space is the only way to go. Ok, good, so we're in agreement that threads is the only way to deal with the "intricate and complex" data set issue in a performance-centric application. > > > Again, the big picture that I'm trying to plant here is that there > > really is a serious need for truly independent interpreters/contexts > > in a shared address space. > > I understand that this is your mission in this thread. However, why > is that your problem? Why can't you just use the existing (limited) > multiple-interpreters machinery, and solve your problems with that? Because then we're back into the GIL not permitting threads efficient core use on CPU bound scripts running on other threads (when they otherwise could). Just so we're on the same page, "when they otherwise could" is relevant here because that's the important given: that each interpreter ("context") truly never has any context with others. An example would be python scripts that generate video programatically using an initial set of params and use an in-house C module to construct frame (which in turn make and modify python C objects that wrap to intricate codec related data structures). Suppose you wanted to render 3 of these at the same time, one on each thread (3 threads). With the GIL in place, these threads can't anywhere close to their potential. Your response thus far is that the C module should release the GIL before it commences its heavy lifting. Well, the problem is that if during its heavy lifting it needs to call back into its interpreter. It's turns out that this isn't an exotic case at all: there's a *ton* of utility gained by making calls back into the interpreter. The best example is that since code more easily maintained in python than in C, a lot of the module "utility" code is likely to be in python. Unsurprisingly, this is the situation myself and many others are in: where we want to subsequently use the interpreter within the C module (so, as I understand it, the proposal to have the C module release the GIL unfortunately doesn't work as a general solution). > > > For most > > industry-caliber packages, the expectation and convention (unless > > documented otherwise) is that the app can make as many contexts as its > > wants in whatever threads it wants because the convention is that the > > app is must (a) never use one context's objects in another context, > > and (b) never use a context at the same time from more than one > > thread. ?That's all I'm really trying to look at here. > > And that's indeed the case for Python, too. The app can make as many > subinterpreters as it wants to, and it must not pass objects from one > subinterpreter to another one, nor should it use a single interpreter > from more than one thread (although that is actually supported by > Python - but it surely won't hurt if you restrict yourself to a single > thread per interpreter). > I'm not following you there... I thought we're all in agreement that the existing C modules are FAR from being reentrant, regularly making use of static/global objects. The point I had made before is that other industry-caliber packages specifically don't have restrictions in *any* way. I appreciate your arguments these a PyC concept is a lot of work with some careful design work, but let's not kill the discussion just because of that. The fact remains that the video encoding scenario described above is a pretty reasonable situation, and as more people are commenting in this thread, there's an increasing need to offer apps more flexibility when it comes to multi-threaded use. Andy From mensanator at aol.com Thu Oct 9 18:28:58 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 9 Oct 2008 15:28:58 -0700 (PDT) Subject: Python 2.6, GUI not working on vista? References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> <48EE7A98.5090300@v.loewis.de> Message-ID: <2e0ac5bd-82d9-4f8b-b7c8-9cf5998eff27@o40g2000prn.googlegroups.com> On Oct 9, 4:41?pm, "Martin v. L?wis" wrote: > > You can believe what you want. The people who developed UAC don't have > > to support it. > > I know for a fact that the implementation is incomplete. In Windows > Installer, there is no way (that I know of) to create an MSI file > that conditionally turns on UAC, only when the installation actually > needs privilege elevation. > > There is a static bit in the installer that indicates whether the MSI > file will do UAC, and there is no way to toggle this bit, e.g. after > asking the user whether this is a "for me" installation or "for all users". > > I set this bit to "no UAC" for 2.6, in order to allow non-privileged > installation at all - only to find out that (due to an unrelated > problem), the "for me" installation doesn't actually work. I only found > out after the release, because nobody bothered reporting this problem > during the betas and release candidates. I posted a problem with Vista on Jul 6 concerning not being able to run IDLE in 2.6b1. No replies. I also noted the successful use and need to use the Administrator account on Sep 12 for 2.6rc1. Again, no replies. What am I supposed to do? File bug reports on things I don't even know are bugs? > I didn't notice on my Vista > machine, because that has VS 2008 installed, in which case the "for me" > installation works just fine. > > If anybody knows how to make the "for me" installation work > (i.e. how to set up the manifests that a single copy of the CRT > is used both by python26.dll, and all extension modules), please > let me know. > > IOW: HELP! HELP!! HELP!!! > Meanwhile: just say no to Vista. > > Regards, > Martin From rridge at csclub.uwaterloo.ca Wed Oct 1 19:21:23 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 01 Oct 2008 19:21:23 -0400 Subject: How to emit UTF-8 from console mode? References: <48E3CB98.8000705@v.loewis.de> Message-ID: > I need UTF-8 because I need to experiment with some OS function calls that > give me UTF-16 and I need to emit UTF-16 or UTF-8. wrote: >Try setting the code page to 65001, and emit the UTF-8 explicitly. Hmm... apparently that's not allowed on Windows XP: C:\> chcp 65001 Active code page: 65001 C:\> python -c "for i in range(0x410, 0x430): print unichr(i).encode('utf-8')" Traceback (most recent call last): File "", line 1, in IOError: [Errno 13] Permission denied This works though: C:\> python -c "for i in range(0x410, 0x430): print unichr(i).encode('utf-8')" > x C:\> type x [a bunch of Cyrillic letters] Hmm... "more x" doesn't work, while "copy x con" works but gives an error. Looks like Windows XP support UTF-8 console output is a bit half-assed. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From bdesth.quelquechose at free.quelquepart.fr Fri Oct 3 14:38:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 03 Oct 2008 20:38:11 +0200 Subject: javascript to python In-Reply-To: <4a62c214-6755-46ee-963b-2daea5268480@r66g2000hsg.googlegroups.com> References: <48e54014$0$15732$426a74cc@news.free.fr> <48e5f3cd$0$21826$426a74cc@news.free.fr> <4a62c214-6755-46ee-963b-2daea5268480@r66g2000hsg.googlegroups.com> Message-ID: <48e6827c$0$19710$426a74cc@news.free.fr> lkcl a ?crit : > On Oct 3, 10:29 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> lkcl a ?crit :> On Oct 2, 7:42 pm, Bruno Desthuilliers >>> wrote: >>>> lkcl a ?crit : > >> And as far as I'm concerned, the point is >> exactly here : it's doing "a little bit more" than the original code. > > yeah, i know. and that "bit more" gets you a proper representation > of the python "class" concept. Except that in most cases - at least when it comes to browser scripting[1] - this concept is just useless. IOW, that's quite a lot of code for something you just don't need. [1] but ask yourself how many times you end up having only one single instance of a given class in a python utility script... > i was merely pointing out that if you want to _really_ translate the > original code into python - _really_ strictly - it's not actually > possible. "really strictly", nope. But mainly because there's nothing in Python that behave like the 'this' javascript object (and it doesn't matter in the OP snippet). But you can have something quite close, using the class as an object (which it is anyway). > because python doesn't have the concept of non-prototyping > (but... see below: i believe i may stand corrected on that) !-) >> Indeed. But the point is that Python - while close to a prototype-based >> language in many aspects - is still class-based. The closer Python >> translation of the OP's javascript snippet is probably the one I gave >> using a 'class singleton' - that is, using the class itself as an >> object. > > oh is _that_ how you do it. thanks. i always wondered how you did > class singletons in python. Note that this not really idiomatic Python - partly for cultural reasons, and mostly because use case and constraint differs (class singleton would surely become idiomatic if Python was used as browser-scripting language the way js is, because you then have to avoid any useless code to keep the site responsive). Anyway, that's still IMHO the pythonic way to translate a litteral javascript object - I fail to see anything closer in Python (if there's some guru around ?) >> python-source-to-javascript-source tool like pyjamas won't give you back >> the original javascript snippet (which is by no mean a criticism of >> pyjamas - it would just be way too complicated to automatize such a >> translation). > > well... you _say_ that... but... actually, if that's the real way to > represent class singletons, and it's an accurate representation of the > OP's javascript, and a good example, then _yes_, pyjs should > definitely have that added as a feature - to understand that a class > singleton _can_ get mapped to the much more efficient javascript > example you gave. I'm afraid it's going to be quite complicated. You'd have to make sure the class only has classmethods - including inherited methods (and exception made of methods inherited from object). And FWIW, even such a class may be a base class for 'normal' python classes, so there's just no reliable semantic way to make sure the class is really a class singleton that should map to a litteral js object. See, the problem here is that we have two high level, highly dynamic languages, that are quite close on quite a lot of things but are based on two really different object models. So quite often, the best translation is obvious for a programmer with a decent knowledge of both languages, but almost impossible for a program because there are way too much imply stuff (like, for the python class singleton, the fact that the class is not meant to be instanciated is totally implicit). > not that many people would _want_ to do that, Err... Do you have much experience in browser scripting ??? That's a *very* common js idiom. > so it goes onto the > "diminishing returns TODO list", but... > >> Nope. You defined functions outside the object's scope, and you still >> have to instanciate dataListener. Also, this above code just won't work >> - unless you explicitely pass the dataListener instance to the >> functions, ie: >> >> d = dataListener() >> d.onDataAvailable(d, ...) > > yeah - i didn't realise what the python class singleton thing was. In this case, the problem I pointed out was that Python's functions needs to be class instances to yield instancemethods when looked up on an instance or class. If you set a function as an instance attribute, the descriptor protocol is not invoked, and you just have a plain function (note that this is by design). >> It seem you didn't read my other translation proprosal, so I repost it here: > >> class dataListener(object): >> data = '' > > i did - i just didn't understand its significance. > > so - to get this straight: when you do class clsname(object), and you > have the indentation and declaration of variables (e.g. data, above) > at the same level as the functions, it means that there's only one of > them? (i.e. a singleton)? Nope. Whatever is declared within the class statement becomes a class attribute - that is, an attribute of the class object, shared by all instances. But that doesn't prevent you from instanciating the class and set an instance attribute by that name, in which case it will shadow the class attribute. > so, if i do this: > > d = dataListener() > e = dataListener() > > d.data = "fred" > > print f.data > > will return "fred"? > Nope. The lookup rules for "reading" are: - first check if the class (or it's bases, following mro) has a __getattribute__ method. If yes, call it, and stop here whatever the result. - else check if there's a descriptor by that name in the class (including bases etc) - if not, check if the instance has a non-descriptor attribute by that name in it's dict - else check if the class (and it's bases etc) has a non-descriptor by that name - else lookup if the class (etc...) have a callable __getattr__ attribute and if yes call it with the looked up name - else (if nothing matched so far) raise an attribute error When it comes to 'writing', it's much more simple: - first check if the class (and it's bases...) have a __setattr__ method. If yes, call it with the name and value and stop here whatever happens. - else check if the class (and it's bases etc...) have a descriptor by that name _with binding behaviour_ (IOW : with a __set__ method). If yes, call the descriptor's __set__ method with instance, name and value. - else just set the instance's __dict__ with the name and value. NB : I didn't mention slots, but they are rarely used. I leave it up to you to read the relevant doc for more detailed informations. To make a long story short, in your above snippet, the d.data = "fred" statement ends up being a shortcut for d.__dict__['data'] = "fred". To have the class singleton working as an object, you must not instanciate it - just use the class object directly, ie: class dataListener(object): data = "" dataListener.data = "fred" print dataListener.data If you really want to prevent dataListener from being instanciated, you'd have to provide a __new__ method preventing instanciation, ie: class dataListener(object): def __new__(cls): raise TypeError("class %s is a class singleton" % cls) HTH From gordallott at gmail.com Sat Oct 11 14:59:23 2008 From: gordallott at gmail.com (Gordon Allott) Date: Sat, 11 Oct 2008 19:59:23 +0100 Subject: extracting null pointer address from PyCObject with ctypes In-Reply-To: <99b20852-6e13-4046-aeef-4c1cb45636bf@j68g2000hsf.googlegroups.com> References: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> <42a9cf1a-b5a3-428f-b547-b0bb1d9b87e2@q35g2000hsg.googlegroups.com> <99b20852-6e13-4046-aeef-4c1cb45636bf@j68g2000hsf.googlegroups.com> Message-ID: <48F0F78B.1010309@gmail.com> Aaron "Castironpi" Brady wrote: > > What does print pythonapi.PyCObject_AsVoidPtr(display) give you? > -- > http://mail.python.org/mailman/listinfo/python-list Traceback (most recent call last): File "pygametest.py", line 125, in app = PyGameOGREApp() File "pygametest.py", line 33, in __init__ self._createWindow(width, height, fullscreen) File "pygametest.py", line 65, in _createWindow print pythonapi.PyCObject_AsVoidPtr(display) ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1 -- Gord Allott (gordallott at gmail.com) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fernandena at gmail.com Fri Oct 10 09:05:52 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Fri, 10 Oct 2008 06:05:52 -0700 (PDT) Subject: Enormous amount webcams womans showing groupsex. Free Message-ID: Enormous amount webcams womans showing groupsex. http://sexystory.psend.com/groupsex.htm From vizualbod at vizualbod.com Thu Oct 9 12:36:13 2008 From: vizualbod at vizualbod.com (Frank Malina @ vizualbod.com) Date: Thu, 9 Oct 2008 09:36:13 -0700 (PDT) Subject: How to do regular BASH work in Python? References: <95c0fa2d-2eb0-45e5-b6bf-9950e948af68@u65g2000hsc.googlegroups.com> <14ca62d5-f9eb-4369-952c-032a0a10ddf2@x41g2000hsb.googlegroups.com> Message-ID: <9978593a-4f99-4d35-a8b7-a953406a8571@q35g2000hsg.googlegroups.com> On Oct 9, 3:22?pm, jdd wrote: > On Oct 9, 10:13?am, Frantisek Malina wrote: > > > Hey, > > I found it. Python rocks:http://www.python.org/doc/2.5.2/lib/os-file-dir.html > > > If you have any further links that provide some lively code examples > > and recipes, please pass them on. > > > Thank you > > > Frank Malinahttp://vizualbod.com > > http://examples.oreilly.com/python3/has some good examples, although > they may be a little tough to read through if you don't have a copy of > "programming python", the book they're from. Coming form PHP, I find Python is pleasure to read no matter what. From notvalid2 at sbcglobal.net Sun Oct 12 19:25:00 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sun, 12 Oct 2008 16:25:00 -0700 Subject: Pylab Fails with Runtime Error on Win XP Under Python 2.4 In-Reply-To: <8031bc6a-cc2b-49a5-8321-199b5f3cb7b4@i18g2000prf.googlegroups.com> References: <8031bc6a-cc2b-49a5-8321-199b5f3cb7b4@i18g2000prf.googlegroups.com> Message-ID: <6HvIk.2358$W06.722@flpi148.ffdc.sbc.com> John Machin wrote: > On Oct 13, 9:07 am, "W. eWatson" wrote: > >> I worked my way into the folder where the py program is, but couldn't >> executed. Just entering aprog.py, run aprog.py or exec aprog.py didn't work. > > One wouldn't expect the "run" or the "exec" to work. > > Try these in this order: > python aprog.py > \python24\python aprog.py > c:\python24\python aprog.py > > and instead of "didn't work", tell us what message you get. Also > consider telling us where your Python 2.4 is installed, and what you > see when you execute the PATH command. The first one requires a compile program. The second required a path, probably back to my c-drive The third one is too ghastly to think about, unless I move aprog.py to the python folder. I think I'll compile it and try. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From prologic at shortcircuit.net.au Fri Oct 24 01:00:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 24 Oct 2008 15:00:20 +1000 Subject: How to get the actual address of a object In-Reply-To: <39964422-a965-4dc0-8018-81e1c2e373a0@a29g2000pra.googlegroups.com> References: <39964422-a965-4dc0-8018-81e1c2e373a0@a29g2000pra.googlegroups.com> Message-ID: On Fri, Oct 24, 2008 at 2:51 PM, wrote: > Hi,I have a strange idea:is there any way to get memory address of a > object. id(obj) Example: >>> x = 10 >>> id(x) 134536908 But this probably (most likely) isn't it's address in memory but more it's unique identifier that separates it from every other object in memory. > j = cast(addr,) You can't do this in Python afaik nor would you want to. If you simply want to copy an object, do this: >>> x = 10 >>> y = x >>> id(x) 134536908 >>> id(y) 134536908 >>> cheers James -- -- -- "Problems are solved by method" From netimen at gmail.com Thu Oct 23 04:49:52 2008 From: netimen at gmail.com (netimen) Date: Thu, 23 Oct 2008 01:49:52 -0700 (PDT) Subject: substitution __str__ method of an instance Message-ID: I couldn't substitute __str__ method of an instance. Though I managed to substitute ordinary method of an instance: from types import MethodType class Foo(object): pass class Printer(object): def __call__(self, obj_self): return 'printed' f = Foo() f.printer = MethodType(Printer(), f, Foo) print f.printer() # works fine - I get: 'printed' print f # get: <__main__.Foo object at 0x00D69C10> f.__str__ = MethodType(Printer(), f, Foo) print f # still get: <__main__.Foo object at 0x00D69C10>. Why? Foo.__str__ = MethodType(Printer(), None, Foo) print f # works fine - I get: 'printed' How can I substitute __str__ method of an instance? From gagsl-py2 at yahoo.com.ar Tue Oct 14 17:54:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 14 Oct 2008 18:54:50 -0300 Subject: splitting a string into an array using a time value References: Message-ID: En Tue, 14 Oct 2008 18:08:53 -0300, Joe Python escribi?: > I want to find a way to split a string into an array using a time value. > s = r""" > 8/25/2008 11:10:08 AM Lorem ipsum dolor sit amet, consectetuer > adipiscing elit. Sed imperdiet luctus nisl. > ipsum vel arcu gravida mattis. In mattis dolor id sem. Praesent > dictum > tortor non lacus. 0/3/2008 5:10:23 PM > ras quis ante id lacus sodales accumsan. Morbi bibendum iaculis > purus > 10/6/2008 4:39:55 PM Maecenas lectus libero, > tincidunt sed > """ > > I tried to use the pattern but its not working: > pattern = r'(\d+/\d+/\d+ \d+:\d+:\d+ .+)' > pat = re.compile(pattern) > result = re.split(pat,s) The pattern must match the *separator* only. Try with: pattern = r'\d+/\d+/\d+ \d+:\d+:\d+ (AM|PM)' -- Gabriel Genellina From mrwarw at gmail.com Fri Oct 3 20:13:01 2008 From: mrwarw at gmail.com (Marius) Date: Fri, 3 Oct 2008 17:13:01 -0700 (PDT) Subject: Wing IDE 101 (new freeware version) works with Python 2.6 Message-ID: <5d298b57-4f09-4c07-b401-372ad5e4741e@x16g2000prn.googlegroups.com> Wing IDE 101 Version: 3.1.4-1 (rev 18789) Release Date: September 18, 2008 from http://www.wingware.com/wingide-101 "Wing IDE 101 is a free basic edition of Wing IDE that was designed with the University of Toronto Computer Science Department for teaching entry level computer science courses with Python. It omits much of the feature set of Wing IDE Professional and introduces some simplifications appropriate for beginners" From skip at pobox.com Sat Oct 11 22:30:30 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 11 Oct 2008 21:30:30 -0500 Subject: Define a 2d Array? In-Reply-To: References: Message-ID: <18673.24902.46552.665421@montanaro-dyndns-org.local> Jill> How do I define a 2d list? Python doesn't truly have 2d lists in the way you might think of 2d arrays in C or Fortran. It has 1d lists which can contain any Python object, including other lists. If you wanted to create a 4x5 list you'd do something like this: N = 4 M = 5 mylist = [] for i in range(N): mylist.append([0.0] * M) If you are looking to do numeric work with such multidimensional lists you should consider the builtin array object or the numpy package: http://docs.python.org/dev/library/array.html#module-array http://numpy.scipy.org/ Skip From goodz158 at yahoo.com Mon Oct 13 09:59:54 2008 From: goodz158 at yahoo.com (Good Z) Date: Mon, 13 Oct 2008 06:59:54 -0700 (PDT) Subject: How to set cookie in client machine Message-ID: <410791.54903.qm@web35908.mail.mud.yahoo.com> Hello, I want to set {name, value} cookie on client machine. My requirement is that when user comes to the website hosted on our server and login into his account, we would like to set user specific information in cookie that will be used later. Is there a generic program that may help me out in setting the cookie on client machine? Regards, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Wed Oct 8 01:19:30 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 8 Oct 2008 15:19:30 +1000 Subject: If an OS was to be written in Python, how'w it look? In-Reply-To: References: Message-ID: On Wed, Oct 8, 2008 at 10:40 AM, Gabriel Genellina wrote: > web.archive.org contains the site history: > http://web.archive.org/web/*re_/http://www.unununium.org > Going back to Jan 2007 is enough to discover that their repository was at > http://www.unununium.org/darcs/ - and it's still there. Thanks :) Is anyone still interested in continuing Uuu's efforts ? I've just checked out the darcs repository and converted it to Mercurial. I'm going to have a bit of a play wiht it... Anyone interested in this ? cheers James -- -- -- "Problems are solved by method" From gauravkec2005 at gmail.com Tue Oct 21 02:14:20 2008 From: gauravkec2005 at gmail.com (gaurav kashyap) Date: Mon, 20 Oct 2008 23:14:20 -0700 (PDT) Subject: How to execute a makefile from LINUX system. References: Message-ID: <7d3d45f9-f45f-43ad-b2eb-55e37ffe20e4@o40g2000prn.googlegroups.com> Thanks From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 20 07:50:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 13:50:02 +0200 Subject: indentation In-Reply-To: References: <48fb8441$0$20787$426a74cc@news.free.fr> <010ba6be$0$20653$c3e8da3@news.astraweb.com> <48fc48df$0$12027$426a74cc@news.free.fr> Message-ID: <48fc7069$0$20770$426a74cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> I can't remember having seen any other "standard" so far. > > I've seen various indentation styles used in examples on this newsgroup. I meant: in a real-life project. From clp at rebertia.com Mon Oct 20 15:35:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 20 Oct 2008 12:35:30 -0700 Subject: hiding modules in __init__.py In-Reply-To: <1hzudrgmuhdrl$.9ofug6rn0u5u.dlg@40tude.net> References: <1hzudrgmuhdrl$.9ofug6rn0u5u.dlg@40tude.net> Message-ID: <47c890dc0810201235o1a1b1f5cka5a9b50938449188@mail.gmail.com> On Sat, Oct 18, 2008 at 12:03 PM, Brendan Miller wrote: > How would I implement something equivalent to java's package private in > python? > > Say if I have > > package/__init__.py > package/utility_module.py > > and utility_module.py is an implementation detail subject to change. > > Is there some way to use __init__.py to hide modules that I don't want > clients to see? Or is the best practice just to name the module you don't > want clients to use _utility_module and have it private by convention? Generally the latter on account of Python's "we are all consenting adults here" philosophy. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Brendan > -- > http://mail.python.org/mailman/listinfo/python-list > From mccredie at gmail.com Fri Oct 31 17:36:57 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 31 Oct 2008 14:36:57 -0700 (PDT) Subject: brackets content regular expression References: <405e1745-2b3e-4ab7-812d-f9dbba2dad45@o40g2000prn.googlegroups.com> <461dc81d-e71f-4c72-ac5f-74afab74af28@o40g2000prn.googlegroups.com> Message-ID: <98f676be-437b-4c32-bca7-ecb32cb6852b@n33g2000pri.googlegroups.com> On Oct 31, 11:57?am, netimen wrote: > Thank's but if i have several top-level groups and want them match one > by one: > > text = "a < b < ? > d > here starts a new group: ?< e < f ?> g >" > > I want to match first " b < ? > d " and then " e < f ?> g " but not " > b < ? > d > here starts a new group: ?< e < f ?> g " > On 31 ???, 20:53, Matimus wrote: > > > On Oct 31, 10:25?am, netimen wrote: > > > > I have a text containing brackets (or what is the correct term for > > > '>'?). I'd like to match text in the uppermost level of brackets. > > > > So, I have sth like: 'aaaa 123 < 1 aaa < t bbb < a ff > > 2 > > > > bbbbb'. How to match text between the uppermost brackets ( 1 aaa < t > > > bbb < a ff > > 2 )? > > > > P.S. sorry for my english. > > > I think most people call them "angle brackets". Anyway it should be > > easy to just match the outer most brackets: > > > >>> import re > > >>> text = "aaaa 123 < 1 aaa < t bbb < a ff > > 2 >" > > >>> r = re.compile("<(.+)>") > > >>> m = r.search(text) > > >>> m.group(1) > > > ' 1 aaa < t bbb < a ff > > 2 ' > > > In this case the regular expression is automatically greedy, matching > > the largest area possible. Note however that it won't work if you have > > something like this: " ". > > > Matt > > As far as I know, you can't do that with a regular expressions (by definition regular expressions aren't recursive). You can use a regular expression to aid you, but there is no magic expression that will give it to you for free. In this case it is actually pretty easy to do it without regular expressions at all: >>> text = "a < b < O > d > here starts a new group: < e < f > g >" >>> def get_nested_strings(text, depth=0): ... stack = [] ... for i, c in enumerate(text): ... if c == '<': ... stack.append(i) ... elif c == '>': ... start = stack.pop() + 1 ... if len(stack) == depth: ... yield text[start:i] ... >>> for seg in get_nested_strings(text): ... print seg ... b < O > d e < f > g Matt From skip at pobox.com Thu Oct 2 16:12:34 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 2 Oct 2008 15:12:34 -0500 Subject: Regular expressions and Unicode In-Reply-To: References: Message-ID: <18661.11058.168793.733770@montanaro-dyndns-org.local> Jeffrey> However, when I apply it to this Unicode string, I get only the Jeffrey> first 3 letters of the surname: Jeffrey> name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' Maybe name = unicode('Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k', "utf-8") ? Yup, that works: >>> name = unicode('Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k', "utf-8") >>> name u'Anton\xedn Dvo\u0159\xe1k' >>> surname = r'(?u).+ (\w+)' >>> import re >>> surname_re = re.compile(surname) >>> m = surname_re.search(name) >>> m.groups() (u'Dvo\u0159\xe1k',) From steve at REMOVE-THIS-cybersource.com.au Mon Oct 13 12:46:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Oct 2008 16:46:51 GMT Subject: docpicture References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> Message-ID: <010374c5$0$20641$c3e8da3@news.astraweb.com> On Mon, 13 Oct 2008 08:34:03 -0700, bearophileHUGS wrote: > So in this situation I have sometimes created a quite small image (1 > bit/pixel) that encoded in png image format may require just few hundred > bytes. With Python I encode is binary data string in base64, and I paste > that as a string into the Python souce code. It probably takes only 4-7 > lines or so. [...] > Have you ever done this? Do you think such "documentation picture" > (analogous to a docstring) is an acceptable practice? I've never done it, but I've often wished to be able to store diagrams in my code. > I don't need to do > that often enough, so I think it doesn't deserve to become supported by > Python itself. I can't imagine Python having direct syntactic support for it, but I don't see any reason why the standard library couldn't some day grow a "docpicture" module, complete with a tiny (?) Tkinter app to display the diagram when requested. I think this would be useful. If you choose to share your code under an appropriate licence, I would like to experiment with it. -- Steven From sulyokpeti at gmail.com Wed Oct 15 02:10:27 2008 From: sulyokpeti at gmail.com (sulyokpeti at gmail.com) Date: Tue, 14 Oct 2008 23:10:27 -0700 (PDT) Subject: Deviation from object-relational mapping (pySQLFace) References: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> <27eae129-78d5-40e8-b15b-2f1c8c145e05@64g2000hsm.googlegroups.com> <28d12195-7ce3-4e07-91de-8ab3518082cb@j22g2000hsf.googlegroups.com> Message-ID: <01822c9b-d929-4334-8601-e559df8eb87f@s9g2000prg.googlegroups.com> On okt. 14, 13:26, Paul Boddie wrote: > On 14 Okt, 00:43, sulyokp... at gmail.com wrote: > > > > > It is not convincing to look at an XML file alone. Let me give you an > > example. Glade is a GTK+ application for creating GTK+ GUI. It > > generates an XML file, that can be loaded in every programming > > language that has libglade binding. Similarly, there could be a > > database design tool to create a database, and save SQL/DML > > expressions into an XML config file. Then you create the RDB command > > objects by loading the XML in your favourite language. > > I'd agree that XML makes a good interchange representation which saves > everyone from having to parse various things, but having worked a bit > with relational databases and having had to actively manage their > schemas, I have to say that my primary representation for a schema is > SQL/DDL, and that my primary representation for queries is also SQL. > Now, there's a lot to be said for making that SQL more consumable, and > I've done a little work on converting SQL to XML (as have many others) > in order to make life easier for, say, tool authors, and I'd even go > as far as saying that it should be possible to convert XML back to > SQL, but in doing so there would potentially remain a need for the XML > dialect to be as expressive as SQL, which then means that you have to > replicate SQL in XML. > > > I think programming languages are intended for describing neither relational > > databases nor GUIs. > > The above discussion is somewhat tangential to what you've done, > though, and I certainly didn't mean to say that the use of XML was in > any way "wrong", especially in the way you've been using it. I suppose > that when you state the above about programming languages, you > actually mean languages other than SQL. Even so, I'd much rather use > SQL to describe a database table than one of the many different Python- > based, class-plus-attributes representations so beloved of the various > object-relational mappers. > > I look forward to seeing where you take your project in future, > however. > > Paul I agree more than you thought. I do not want to replace SQL with XML either. I only use XML to interchange data (SQL/DML) between the database designer (tool) and the application interface in order to create a specific database interface for a certain database. It is the focus of database design using different RDBMS-s and different programming languages. There is an other reason for XML. At this point my XML structure contains the SQL/DML expressions as you use it in sql clients, and some metadata to generate documentation using XSL transformation. That's why I provided that sqlface.xsl in the src directory. Yes I have to relocate DTD and XSL from the python source directory. Relational stuff stays in the relational language SQL. Data processing, and business logic goes into a programming language like python. Otherwise I plan to support other languages with such an SQL interface. Peti From george.sakkis at gmail.com Tue Oct 21 13:26:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 21 Oct 2008 10:26:23 -0700 (PDT) Subject: csv.reader problem tab-delimiter - newbie References: Message-ID: <9ba8e57b-97d0-4b66-8f35-6c07d54b1f46@2g2000hsn.googlegroups.com> On Oct 21, 12:26?pm, hidd... at uni-duesseldorf.de wrote: > Hi all, > > I use python 2.5 and want to read in a simple 5-columned, tab- > delimited ascii file "dummy.txt" such as as > > 1 ?2 ? ?3.0 ? ?4 ? ? 5.6 > 4 ?6 ? ?77 ? ? 8.2 ?19 > > I do > > import csv > asciireader = csv.reader(open('dummy.txt'), delimiter='\t') > > array1 = [] > for entry in asciireader: > ?array1.append( entry ) > > however when I then > > print array1 > > then the array does only have two elements [1 ?2 ? ?3.0 ? ?4 ? ? 5.6] > and [4 ?6 ? ?77 ? ? 8.2 ?19]. The tab-delimiter seems to have been > totally ignored! This is bad because I want to do some maths with the > numbers from the file later (after converting them into floats). > > Can someone help? > > Best regards, > > Bernhard Most likely the file is not tab delimited. If you used an editor to produce dummy.txt, check whether it uses soft tabs and disable it temporarily. HTH, George From george.sakkis at gmail.com Sat Oct 4 09:12:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 4 Oct 2008 06:12:49 -0700 (PDT) Subject: lint for Python? References: Message-ID: On Oct 3, 5:38?pm, Pat wrote: > I've been searching for a good multi-module lint checker for Python and > I haven't found one yet. > > Pylint does a decent job at checking for errors only within a single module. > > Here's one of my problems. ?I have two modules. > > In module one, I have a function: > > def foo( host, userid, password ): > ? ? ?pass > > In module two, I call that function: > > foo( userid, password) > > lint doesn't find that error and it won't be caught until it's called > while the program is running. ?I don't want that error found at 3AM. > > I've never used a language that didn't catch that type of error. ?I'm > quite surprised that Python is being used by a number of major > companies. ?How you catch these types of errors? With a decent testing suite of course. Even if this specific issue might be handled more or less by a lint-like tool (which is not trivial in a dynamic language since the f() used in module2 might not even be the function you think it is), there are dozens more potential errors that can't be checked, e.g. changing the order and/or the expected type of the arguments. There is no substitute of testing, and while this is true in statically typed languages too, it's even more critical in dynamic languages. George From torriem at gmail.com Sun Oct 26 22:24:46 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 26 Oct 2008 20:24:46 -0600 Subject: Module python-magic on/for Windows - UPDATE: WORKING & HowTo!!! In-Reply-To: References: Message-ID: <4905266E.70808@gmail.com> Carl K wrote: > I need to convert pdf to png, which imagemagic convert does, I think by using > ghostscript. a little over a year ago I tried with some imagemagic (there are > at least 2 i think) and neither seemed close to working (for pdf that is.) any > idea if pdf conversion is working? python-magic isn't about image conversion. libmagic has nothing to do with ImageMagick. It's a library for identifying what type of file something is based in it's signature (magic number). This is the same library that drives the unix "file" command. From martin at v.loewis.de Tue Oct 21 16:39:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 21 Oct 2008 22:39:52 +0200 Subject: Unicode (UTF8) in dbhas on 2.5 In-Reply-To: <86f028f4-9cd7-4df1-9050-ae8c42841e5b@k37g2000hsf.googlegroups.com> References: <6m3hfpFepea4U1@mid.uni-berlin.de> <86f028f4-9cd7-4df1-9050-ae8c42841e5b@k37g2000hsf.googlegroups.com> Message-ID: <48fe3e19$0$26657$9b622d9e@news.freenet.de> Paul Boddie wrote: > On 20 Okt, 16:04, "Diez B. Roggisch" wrote: >> What is the difference? The dbhash module can only work with *bytestrings*. >> Bytestrings are just that - a sequence of 8-bit-values. > > Sounds like a prime candidate for some improvement work. Patches, > anyone? ;-) It's not possible to "fix" this - it isn't even broken. The *db modules, by design, support storing of arbitrary bytes, not just character data. You can put images into them, or sound files, java byte code files, etc. So if Python would assume they have to be UTF-8 encoded character strings, it would severely limit the usability of these modules. For keys, things are slightly different from values - there is a higher chance that the keys are indeed intended to be character strings. However, in the bsddb btree format, any byte sequence that has a good lexical order can be used as a key, and people do use the interface that way (e.g. by putting an md-5 hash as the key, and the original data as the value). It would be possible to put a layer on top of them which assumes that either keys, values, or both are characters, and that they are further UTF-8 encoded. However, such a package doesn't need to be part of the standard library. Regards, Martin From hep.sebastien.binet at gmail.com Tue Oct 7 15:04:56 2008 From: hep.sebastien.binet at gmail.com (Sebastien Binet) Date: Tue, 7 Oct 2008 12:04:56 -0700 (PDT) Subject: type-checking support in Python? References: <1df0ae7e-d5c5-4839-9788-703cd58232c5@q9g2000hsb.googlegroups.com> Message-ID: <4e0e9947-5b35-43a6-abe0-5a12d4f88b91@d31g2000hsg.googlegroups.com> hi, On Oct 7, 3:24?am, Bas wrote: > I have heard about some python package which overloads numbers and > calculations to include units (quick google found unum, not sure if > that is the only one). I guess that unless you are dealing with life- > critical equipment or are using extreme programming, this is overkill > (but I guess python is not really the right language for that anyway, > imagine a garbage collection just when you want to launch your > shuttle). FWIW, the python papers volume 3 issue 1 is mentionning another package, 'scalar': http://archive.pythonpapers.org/ThePythonPapersVolume3Issue1.pdf http://russp.us/scalar.htm cheers, sebastien. From cheapaf at sina.com Tue Oct 21 04:03:04 2008 From: cheapaf at sina.com (wyy) Date: Tue, 21 Oct 2008 01:03:04 -0700 (PDT) Subject: Nike air force one, air force 1, air force one low cut, air force one Message-ID: <0cf82267-53ca-41b8-ad28-50a48b1139b3@40g2000prx.googlegroups.com> shoes on AIR Jordan 1 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 2 AIR Jordan 3 AIR Jordan 4 AIR Jordan 5 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 6 Rings AIR Jordan 6 AIR Jordan 7 AIR Jordan 8 AIR Jordan 9 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 10 AIR Jordan 11 AIR Jordan 12 AIR Jordan 13 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 14 AIR Jordan 15 AIR Jordan 16 AIR Jordan 17 AIR Jordan 18 AIR Jordan 19 AIR Jordan 20 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 21 AIR Jordan 22 AIR Jordan 23 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 3.5 AIR AIR Jordan 4.5 AIR Jordan 7.5 AIR Jordan 9.5 AIR Jordan 12.5 (paypal payment)(www.yourbestshoes.cn ) AIR Jordan 15.5 AIR Jordan 19.5 AIR Jordan 21.5 AIR Jordan Large Size Jordan AIR Jordan Size 14 Jordan AIR Jordan Size 15 shoes AIR Jordan DMP Nike air force one, air force 1, air force one low cut, air force one high cut, air force one release date Air force one, air foce one 25TH, af 1, af 1 25TH, Nike air force one new releases, limited version Air Force One (paypal payment)(www.yourbestshoes.cn ) Air Force one 25TH AF 1 AF 1 25TH (paypal payment)(www.yourbestshoes.cn ) Dunk sb nike sb dunk nike dunk sb dunk sb high dunk sb low dunk sb woman Nike sb dunk Nike Dunk High SB nike dunk low premuim sb Nike SB Dunk High Shimizu Nike SB Dunk Pro Nike SB Dunk Dunk SB Nike Dunk shoes Dunk shoes for woman (paypal payment)(www.yourbestshoes.cn ) Dunk low cut Dunk high cut AIR Jordans Fusion 1 Jordan 2 Fusion AIR Jordan 3 Nike Jordan Fusion 4 Jordan 5 shoes Nike Air Jordan 6 VI Force 1 Jordan Fusion AJF 6 AJF6 AJ6F Jordan 6 Rings Jordan 6 fusion (paypal payment) (www.yourbestshoes.cn ) AIR Jordan Fusions 13 NIKE Jordan Fusion 14 AIR Jordans 15Nike Jordan 16 Fusion Jordan 17 shoes Nike Air Jordans 18 XVIII Force 1 Jordan Fusion AJF18 AJF18 AJ18F Jordan 18 fusions (paypal payment)(www.yourbestshoes.cn ) AIR Jordan Fusions 7 NIKE Jordan Fusion 8 AIR Jordans 9 Nikes Jordan Fusion 10 Jordan 11 shoes Nike Air Jordan 12 XII Force 1 Jordan Fusion AJF 12 AJF12 AJ12F Jordans 12 fusions (paypal payment)(www.yourbestshoes.cn ) NIKE AIR JORDAN FORCE FUSION SHOES AJF 5 V JORDANs 5 FUSION NIKE JORDAN 5 FUSION SHOES AJF5 Nike Air Jordan XXIII 23 Force 1 Jordan Fusion AJF 23 AJF23 AJ23F (paypal payment)(www.yourbestshoes.cn ) Nike Jordans Fusion 23 AIR Jordan 22 Jordan Fusions 21 AIR Jordans Fusion 20 Jordan 19 shoes Air Jordan Force Fusion VIII (8), AJF 8 Nike (paypal payment)(www.yourbestshoes.cn ) Air Jordan 17 XVII Force 1 Jordan Fusions AJF 17 AJF17 AJ17F Jordan our website : www.yourbestshoes.cn From alan.isaac at gmail.com Fri Oct 17 17:18:32 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 17 Oct 2008 21:18:32 GMT Subject: bibtex parsing Message-ID: Can anyone recommend a pure Python parser of BibTeX files? Ideally MIT or BSD licensed? Online search some possibilities: http://svn.plone.org/svn/collective/bibliograph.parsing/trunk/bibliograph/parsing/parsers/bibtex.py http://www.geocities.com/fiolj/bibtexparse.html http://www.cis.udel.edu/~sprenkle/bibtex2html/bibtex2xml.py Despite the current licenses, I'd appreciate info on these too. Also, there was a rumor that PyParsing was to become part of the standard library, but I do not see it at http://docs.python.org/modindex.html False rumor? Has anyone tried parsing BibTeX with PyParsing? Thanks, Alan Isaac From martin at v.loewis.de Wed Oct 8 16:14:36 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 08 Oct 2008 22:14:36 +0200 Subject: Compiler, ast and forwards/backwards compatibility In-Reply-To: References: Message-ID: <48ed14ac$0$14322$9b622d9e@news.freenet.de> > The documentation for the ast module states that it "helps to find out > programmatically what the current grammar looks like". I can't find > any reference (even when reading the code) on how you should go about > this, other than checking the sys.version number and reading up on the > changes. Not sure what "this" is, but if you mean what you quoted - what does that have to do with version numbers? To find out what the grammar looks like, just inspect the classes in the _ast module, e.g. py> _ast.For._fields ('target', 'iter', 'body', 'orelse') py> _ast.For._attributes ['lineno', 'col_offset'] In any case, you shouldn't look at sys.version, but at _ast.__version__ To see the source code version of that, look at Python/Parser.asdl. > My understanding is that there is no way to write, say, an ast visitor > that runs under Python 3.0 that targets 2.4 because the ast has > changed, and there's no way to indicate that you want to parse another > version. I wouldn't say that. The writer might not be trivial, but should be fairly simple. It can't be 1:1, because, as you say, the AST has changed. > I guess that Python 2.6 can target Python 2.3-6, and with specific > compiler flags it can also target 3.0, so it seems that the correct > thing to do is to use that. Depends on what you want to do. To transform source code so that people can still read and understand it, the _ast module might be inappropriate, as it drops all comments. For code-rewriting applications, look at lib2to3 instead. > Am I correct? Am I seriously confused? Please help! I think you are a little confused. Regards, Martin From wbdismalgoldstein at gmail.com Sun Oct 5 20:03:31 2008 From: wbdismalgoldstein at gmail.com (wbdismalgoldstein at gmail.com) Date: Sun, 5 Oct 2008 17:03:31 -0700 (PDT) Subject: Best free casino games Message-ID: <74b7fddc-f6ab-4071-922a-1af8d7648bef@d1g2000hsg.googlegroups.com> . . . Welcome to the Golden Palace online casino! We are one of the most trusted internet casinos online today, making winners since 1997! We offer a huge selection of free online casino games to download and play for free or for real money. Visit our website - ************************************ http://med247.us/?p=adventure+palace+online+casino ************************************ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ogo slots cheat pgo slots cheat poo slots cheat pog slots cheat pogo lots cheat pogo sots cheat pogo slts cheat pogo slos cheat pogo slot cheat pogo slots heat pogo slots ceat pogo slots chat pogo slots chet pogo slots chea ppogo slots cheat poogo slots cheat poggo slots cheat pogoo slots cheat pogo sslots cheat pogo sllots cheat pogo sloots cheat pogo slotts cheat pogo slotss cheat pogo slots ccheat pogo slots chheat pogo slots cheeat pogo slots cheaat pogo slots cheatt opgo slots cheat pgoo slots cheat poog slots cheat pog oslots cheat pogo lsots cheat pogo solts cheat pogo sltos cheat pogo slost cheat pogo slot scheat pogo slots hceat pogo slots cehat pogo slots chaet pogo slots cheta pogoslots cheat pogo slotscheat oogo slots cheat 0ogo slots cheat logo slots cheat pigo slots cheat p9go slots cheat p0go slots cheat ppgo slots cheat plgo slots cheat pkgo slots cheat pofo slots cheat poto slots cheat poyo slots cheat poho slots cheat pobo slots cheat povo slots cheat pogi slots cheat pog9 slots cheat pog0 slots cheat pogp slots cheat pogl slots cheat pogk slots cheat pogo alots cheat pogo wlots cheat pogo elots cheat pogo dlots cheat pogo xlots cheat pogo zlots cheat pogo skots cheat pogo soots cheat pogo spots cheat pogo slits cheat pogo sl9ts cheat pogo sl0ts cheat pogo slpts cheat pogo sllts cheat pogo slkts cheat pogo slors cheat pogo slo5s cheat pogo slo6s cheat pogo sloys cheat pogo slohs cheat pogo slogs cheat pogo slofs cheat pogo slota cheat pogo slotw cheat pogo slote cheat pogo slotd cheat pogo slotx cheat pogo slotz cheat pogo slots xheat pogo slots dheat pogo slots fheat pogo slots vheat pogo slots cgeat pogo slots cyeat pogo slots cueat pogo slots cjeat pogo slots cneat pogo slots cbeat pogo slots chwat pogo slots ch3at pogo slots ch4at pogo slots chrat pogo slots chfat pogo slots chdat pogo slots chsat pogo slots cheqt pogo slots chewt pogo slots chest pogo slots chext pogo slots chezt pogo slots chear pogo slots chea5 pogo slots chea6 pogo slots cheay pogo slots cheah pogo slots cheag pogo slots cheaf From dg.google.groups at thesamovar.net Tue Oct 7 15:48:04 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Tue, 7 Oct 2008 12:48:04 -0700 (PDT) Subject: type-checking support in Python? References: <1df0ae7e-d5c5-4839-9788-703cd58232c5@q9g2000hsb.googlegroups.com> <4e0e9947-5b35-43a6-abe0-5a12d4f88b91@d31g2000hsg.googlegroups.com> Message-ID: <418e3811-1098-4176-9d0e-c767331281bc@a3g2000prm.googlegroups.com> I also wrote a units package which I'm using for a project of my own (a spiking neural network simulator package called 'Brian'), released separately as a package called Piquant which you can get at sourceforge: http://sourceforge.net/projects/piquant I'm also looking for people to help improve it (get in touch!). The way the package works is to have a Quantity class derived from float, with extra operations. One thing that is different from the other packages out there (and the reason I went to the effort of writing my own package rather than using unum or scalar) is that we also have a QuantityArray or qarray class that derives from numpy.ndarray. There are at the moment two supported types of qarray, with homogeneous units (one unit for the whole array), and heterogeneous units (different unit for each item in the array). At the moment the heterogeneous units implementation is horrible and very slow, but I have a plan for a nicer version at some point (based on numpy's broadcasting rules, so allowing you to have one unit for each row or each column in a matrix for example). Actually I think it would be a really good idea for someone at some point to make a standardised system for units and add it to numpy/ scipy. I'd love to do it myself, but at the moment I have grant applications, papers to finish, etc... :-( Dan Sebastien Binet wrote: > hi, > > On Oct 7, 3:24?am, Bas wrote: > > I have heard about some python package which overloads numbers and > > calculations to include units (quick google found unum, not sure if > > that is the only one). I guess that unless you are dealing with life- > > critical equipment or are using extreme programming, this is overkill > > (but I guess python is not really the right language for that anyway, > > imagine a garbage collection just when you want to launch your > > shuttle). > > FWIW, the python papers volume 3 issue 1 is mentionning another > package, 'scalar': > http://archive.pythonpapers.org/ThePythonPapersVolume3Issue1.pdf > http://russp.us/scalar.htm > > cheers, > sebastien. From drobinow at gmail.com Sat Oct 11 08:18:56 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sat, 11 Oct 2008 05:18:56 -0700 (PDT) Subject: how to set the time of a directory? References: <6a4f17690810102216h69367381oc9058521f6585e06@mail.gmail.com> Message-ID: On Oct 11, 1:27?am, "Timothy Grant" wrote: > On Fri, Oct 10, 2008 at 10:16 PM, oyster wrote: > > os.utime works only against files. so what to do for a directory? > > thanx > > Not sure why you'd say that. I am. He's running Windows. > > drwxr-xr-x ?2 tjg ?tjg ? ? ? 68 Oct 10 22:23 test > (tjg at bastard%) python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> import os > >>> help(os.utime) > > Help on built-in function utime in module posix: > > utime(...) > ? ? utime(path, (atime, mtime)) > ? ? utime(path, None) > > ? ? Set the access and modified time of the file to the given values. ?If the > ? ? second form is used, set the access and modified times to the current time. > > >>> os.utime('test', None) > >>> ^D > > (tjg at bastard%) ls -ltr > drwxr-xr-x ?2 tjg ?tjg ? ? ? 68 Oct 10 22:24 test > > -- > Stand Fast, > tjg. ?[Timothy Grant] >>> os.utime('WinDir', None) Traceback (most recent call last): File "(stdin)", line 1, in WindowsError: [Error 5] Access is denied: 'WinDir' >>> I consider this a bug. (Note that os.utime works for directories under cygwin) From exarkun at divmod.com Sat Oct 18 16:01:13 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 18 Oct 2008 16:01:13 -0400 Subject: Linux.com: Python 3 makes a big break In-Reply-To: Message-ID: <20081018200113.29191.199960083.divmod.quotient.41448@ohm> On Sat, 18 Oct 2008 15:30:23 -0400, Terry Reedy wrote: >http://www.linux.com/feature/150399 >Interesting article with one minor incompleteness. >"For instance, the print statement got turned into a print function; you >must now put parentheses around what you want to print to the screen. The >change allows developers to work with print in a more flexible and uniform >way. If someone needs to replace the print function with some other action, >it can be done with a universal search and replace, rather than rewriting >each print statement by hand." > >Even easier, print as a function can be replaced simply by defining a new >version with the same name. No search/replace is needed. And reversion to >the built-in only requires commenting out the replacement. Perhaps it also omitted the fact that nothing prevents you from defining a function to write things to stdout (or elsewhere) in Python 2.5, making the Python 3.x change largely a non-feature. ;) Jean-Paul From steve at REMOVE-THIS-cybersource.com.au Tue Oct 28 18:31:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Oct 2008 22:31:53 GMT Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <01178bb1$0$20630$c3e8da3@news.astraweb.com> On Tue, 28 Oct 2008 09:59:57 -0600, Joe Strout wrote: > There are only the two cases, which Greg quite succinctly and accurately > described above. One is by value, the other is by reference. Python > quite clearly uses by value. That is absolute nonsense, based on the idiotic assumption that programmers should care more about an arbitrary reference to a value than to the value itself. I'm sure I've quoted the excellent effbot before, but he deserves repeating: [quote] well, I guess you can, in theory, value an artificial number assigned to an object as much as the object itself. "Joe, I think our son might be lost in the woods" "Don't worry, I have his social security number" [end quote] As I wrote yesterday: The value of a Python name is the Python object assigned to it, not an arbitrary memory location that points to the object. Even you would consider it obfuscatory if I executed this code: x = "Norwegian Blue" and then insisted that the value of x was "3086179808L, but if I run that line of code again it could get another value, and naturally if you run it on your computer you're almost certain to get a different value". By your definition of "value=reference", the above is perfectly correct, and utterly, completely pointless, useless and unhelpful. It's rather like listing the ingredients of a cake as "Atoms". Technically true, but missing the point. Once we discard the unhelpful assumption that value=reference, your entire argument falls apart. -- Steven From tjreedy at udel.edu Mon Oct 13 17:12:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Oct 2008 17:12:28 -0400 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> Message-ID: lkcl wrote: > On Oct 11, 11:17 pm, Terry Reedy wrote: >> lkcl wrote: >> >> I got the impression that there is currently no Windows binary >> available. Correct? If not, perhaps someone trustworthy will someday >> donate one. > > sorry, terry, you deleted a bit too much context :) I was referring to this at pyjd.org: Pre-built amd64 .debs are available for download, providing pywebkitgtk-1.0, libwebkit-1.0-2 and libwebkit-dev, here: * Download libwebkit-dev, libwebkit-1.0-2 and pywebkitgtk-1.0 and this >> If not, perhaps someone trustworthy will someday donate one. was my acknowledgement that a Windows binary is not trivial and that I don't expect one from you after all the nice work you have done. [compiling with mingw32] > why the python developers didn't include the patches, and keep them up- > to-date, isn't clear. Mostly likely because no one who uses mingw32 has volunteered to become the mingw32 Python developer who would update such patches to current Python (now 2.6/3.0) and support them by responding to bug reports and by upgrading them to 2.7/3.1 in the next few years. Any system supported in core Python code with a set of #includes needs *someone* who will support that set. If the supporter disappears and no one else volunteers, the #includes become obsolete and get deleted. Terry Jan Reedy From rhamph at gmail.com Fri Oct 24 17:16:50 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 24 Oct 2008 14:16:50 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: <3919088a-9d8c-40b8-87fd-6ef39ed69f76@d10g2000pra.googlegroups.com> On Oct 24, 3:02?pm, Glenn Linderman wrote: > On approximately 10/23/2008 2:24 PM, came the following characters from the > keyboard of Rhamphoryncus: >> >> On Oct 23, 11:30 am, Glenn Linderman wrote: >> >>> >>> On approximately 10/23/2008 12:24 AM, came the following characters from >>> the keyboard of Christian Heimes >>>> >>>> Andy wrote: >>>> I'm very - not absolute, but very - sure that Guido and the initial >>>> designers of Python would have added the GIL anyway. The GIL makes >>>> Python faster on single core machines and more stable on multi core >>>> machines. > > Actually, the GIL doesn't make Python faster; it is a design decision that > reduces the overhead of lock acquisition, while still allowing use of global > variables. > > Using finer-grained locks has higher run-time cost; eliminating the use of > global variables has a higher programmer-time cost, but would actually run > faster and more concurrently than using a GIL. Especially on a > multi-core/multi-CPU machine. Those "globals" include classes, modules, and functions. You can't have *any* objects shared. Your interpreters are entirely isolated, much like processes (and we all start wondering why you don't use processes in the first place.) Or use safethread. It imposes safe semantics on shared objects, so you can keep your global classes, modules, and functions. Still need garbage collection though, and on CPython that means refcounting and the GIL. >> Another peeve I have is his characterization of the observer pattern. >> The generalized form of the problem exists in both single-threaded >> sequential programs, in the form of unexpected reentrancy, and message >> passing, with infinite CPU usage or infinite number of pending >> messages. >> > > So how do you get reentrancy is a single-threaded sequential program? I > think only via recursion? Which isn't a serious issue for the observer > pattern. If you add interrupts, then your program is no longer sequential. Sorry, I meant recursion. Why isn't it a serious issue for single-threaded programs? Just the fact that it's much easier to handle when it does happen? >> Try looking at it on another level: when your CPU wants to read from a >> bit of memory controlled by another CPU it sends them a message >> requesting they get it for us. They send back a message containing >> that memory. They also note we have it, in case they want to modify >> it later. We also note where we got it, in case we want to modify it >> (and not wait for them to do modifications for us). >> > > I understand that level... one of my degrees is in EE, and I started college > wanting to design computers (at about the time the first microprocessor chip > came along, and they, of course, have now taken over). But I was side-lined > by the malleability of software, and have mostly practiced software during > my career. > > Anyway, that is the level that Herb Sutter was describing in the Dr Dobbs > articles I mentioned. And the overhead of doing that at the level of a cache > line is high, if there is lots of contention for particular memory locations > between threads running on different cores/CPUs. So to achieve concurrency, > you must not only limit explicit software locks, but must also avoid memory > layouts where data needed by different cores/CPUs are in the same cache > line. I suspect they'll end up redesigning the caching to use a size and alignment of 64 bits (or smaller). Same cache line size, but with masking. You still need to minimize contention of course, but that should at least be more predictable. Having two unrelated mallocs contend could suck. >> Message passing vs shared memory isn't really a yes/no question. It's >> about ratios, usage patterns, and tradeoffs. *All* programs will >> share data, but in what way? If it's just the code itself you can >> move the cache validation into software and simplify the CPU, making >> it faster. If the shared data is a lot more than that, and you use it >> to coordinate accesses, then it'll be faster to have it in hardware. >> > > I agree there are tradeoffs... unfortunately, the hardware architectures > vary, and the languages don't generally understand the hardware. So then it > becomes an OS API, which adds the overhead of an OS API call to the cost of > the synchronization... It could instead be (and in clever applications is) a > non-portable assembly level function that wraps on OS locking or waiting > API. In practice I highly doubt we'll see anything that doesn't extend traditional threading (posix threads, whatever MS has, etc). > Nonetheless, while putting the shared data accesses in hardware might be > more efficient per unit operation, there are still tradeoffs: A software > solution can group multiple accesses under a single lock acquisition; the > hardware probably doesn't have enough smarts to do that. So it may well > require many more hardware unit operations for the same overall concurrently > executed function, and the resulting performance may not be any better. Speculative ll/sc? ;) > Sidestepping the whole issue, by minimizing shared data in the application > design, avoiding not only software lock calls, and hardware cache > contention, is going to provide the best performance... it isn't the things > you do efficiently that make software fast ? it is the things you don't do > at all. Minimizing contention, certainly. Minimizing the shared data itself is iffier though. From evelien_amco at hotmail.com Wed Oct 22 12:46:40 2008 From: evelien_amco at hotmail.com (Evelien) Date: Wed, 22 Oct 2008 09:46:40 -0700 (PDT) Subject: error estimation in a non-linear least squares fitting References: <230e4c66-0ed3-4acc-98c5-e88ad36c4650@y21g2000hsf.googlegroups.com> Message-ID: Thanks Robert for your reply. I must say I am kind of disappointed if that is the only solution. I thought that such a standard problem as least squares fitting, would always give you an estimation of the error bars, without having to look up how you can convert a covariance matrix into error bars... But thanks anyway. Evelien From prologic at shortcircuit.net.au Tue Oct 7 18:30:24 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 8 Oct 2008 08:30:24 +1000 Subject: If an OS was to be written in Python, how'w it look? In-Reply-To: References: Message-ID: On Tue, Oct 7, 2008 at 4:02 PM, Gabriel Genellina wrote: > There was an experiment ("Unununium"), now abandoned: http://unununium.org/ Yeah does anyone have or know where one can get the source code and any other materials relating to Unununium ? It not only seems to be abandoned, but it's content also lost :/ cheers James -- -- -- "Problems are solved by method" From tsrinuvasulu491 at gmail.com Wed Oct 22 21:24:02 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Wed, 22 Oct 2008 18:24:02 -0700 (PDT) Subject: YOU WANT TO EARN $$$ see my blog. Message-ID: <145a2dec-6357-4c28-9745-62b28f4c4a55@a29g2000pra.googlegroups.com> hai, i am srinu from india. i am sending a blog url for yours use. Right side Of The Blog Awsurvey Banner will appear. click on the banner and get a free signup with 6$ bonus and you will get more surveys. once you have completed one survey you will get minimem 4$ and more left side of the blog home based jobs will appear click on the ads you will get more details about to choose your job. you willnot satisfy to choose your job you will type jobs or sports or jewelery etc on search box field .and click on search. then you will find what resuilts are you want. click on the blog and get more information to choose yours job. the blog url is: http://wealthinonline.blogspot.com/ goodluck From santiortega2000 at gmail.com Thu Oct 23 11:58:20 2008 From: santiortega2000 at gmail.com (Santix) Date: Thu, 23 Oct 2008 08:58:20 -0700 (PDT) Subject: Do a Gnuplot of a file in python Message-ID: <20134007.post@talk.nabble.com> I am doing a python program that save the data in a text file in columns and I want to do a gnuplot to plot the results. But I want the program in python to show the result with gnuplot. I have tried this: g.load(power.p) but it gives me this error: Traceback (most recent call last): File "./spectrum_output.py", line 310, in main_loop(tb) File "./spectrum_output.py", line 289, in main_loop g.load(power.p) AttributeError: 'file' object has no attribute 'p' On power.p I have this: set autoscale unset logscale unset label set xtic auto set ytic auto set title "Spectrum Analyzer" set xlabel "Frecuency" set ylabel "Power (dB)" plot "power.dat" using 1:2 title 'm.data[0]' with linespoints And in power.dat: 2231500000.0 18.2582263947 2234500000.0 17.0396003723 ... ... with more data It goes ok when I load it in gnuplot, but not when I execute the python program in the Terminal. Thanks in advance! Regards, Santiago Ortega. -- View this message in context: http://www.nabble.com/Do-a-Gnuplot-of-a-file-in-python-tp20134007p20134007.html Sent from the Python - python-list mailing list archive at Nabble.com. From wouter.dewilde at gmail.com Fri Oct 17 04:00:50 2008 From: wouter.dewilde at gmail.com (Wouter DW) Date: Fri, 17 Oct 2008 01:00:50 -0700 (PDT) Subject: __metaclass__ and deepcopy issue Message-ID: I read the article on http://www.python.org/download/releases/2.2/descrintro/#metaclasses and started using autoprop. But now I have a problem I can't seem to solve myself. class autoprop(type): def __init__(cls, name, bases, dict): super(autoprop, cls).__init__(name, bases, dict) props = {} for name in dict.keys(): if name.startswith("_get_") or name.startswith("_set_"): props[name[5:]] = 1 for name in props.keys(): fget = getattr(cls, "_get_%s" % name, None) fset = getattr(cls, "_set_%s" % name, None) setattr(cls, name, property(fget, fset)) class InvertedX: __metaclass__ = autoprop def _get_x(self): return -self.__x def _set_x(self, x): self.__x = -x a = InvertedX() from copy import deepcopy b = deepcopy(a) The deepcopy gives an error inside copy.py of the python lib. TypeError: descriptor '__reduce__' of 'object' object needs an argument Does anybody know how to solve this issue? From ladasky at my-deja.com Thu Oct 23 23:53:03 2008 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 23 Oct 2008 20:53:03 -0700 (PDT) Subject: How to examine the inheritance of a class? References: Message-ID: On Oct 23, 6:59 pm, "James Mills" wrote: > Developer. NOT User. For the foreseeable future, this program is for my use only. So the developer and the user are one and the same. And, thank you, __bases__ is what I was looking for. Though Chris Mills also pointed out that isinstance() handles the type checking nicely. From tino at wildenhain.de Sun Oct 19 02:43:55 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 19 Oct 2008 08:43:55 +0200 Subject: Creating single .exe file without py2exe and pyinstaller In-Reply-To: References: Message-ID: <48FAD72B.3030606@wildenhain.de> Hi, Abah Joseph wrote: > I have written a small application of about 40-45 lines which is about > 4KB, so I want to create a single .exe file from it, using py2exe it > created unnecessary files, that just increase the size of the program > and also less portable to me. What else can I use? the "unneccessary files" you say, are what your 40-45 lines bring to life. 1) just distribute the 40-45 lines - but this requires python installation on users end 2) use a python to C(++) compiler and compile the result to .exe, works pretty well for simple applications: http://shed-skin.blogspot.com/ Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From afriere at yahoo.co.uk Wed Oct 15 21:35:46 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 15 Oct 2008 18:35:46 -0700 (PDT) Subject: OOP books? References: <4b0f5$48f63024$4553@news.teranews.com> <48f66a98$0$1137$426a74cc@news.free.fr> Message-ID: <40258915-d8a1-4c91-870a-e7d572bc2bdd@f40g2000pri.googlegroups.com> On Oct 16, 7:12 am, Bruno Desthuilliers wrote: [snip] > Not a word about Python in it, but:http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-... > > A must-read if you want to understand OO (MHO of course). Yes, if only to see how many of the design patterns in C++ are not applicable to Python ;) But seriously, the Gang of Four book is the classic book for design patterns. I agree that it is required reading, but it probably requires a working knowledge of basic OO design to get much out of it. At a more basic level a good UML primer (such as Page-Jones' 'Fundamentals of OO Design in UML') will get you thinking about OO Design and is worth a look. If only to see how many of the Java-like concepts are not applicable to Python. Has anyone looked at, and have any opinions about, this rather expensive tome? Goldwasser & Letcher 'Object-Oriented Programming in Python' http://www.amazon.com/Object-Oriented-Programming-Python-Michael-Goldwasser/dp/0136150314/ From castironpi at gmail.com Thu Oct 9 00:07:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 8 Oct 2008 21:07:41 -0700 (PDT) Subject: Safe eval of insecure strings containing Python data structures? References: Message-ID: <0424d1ac-7f47-4be2-92ea-e538c123f9e9@u28g2000hsc.googlegroups.com> On Oct 8, 7:34?pm, "Warren DeLano" wrote: > I would like to parse arbitrary insecure text string containing nested > Python data structures in eval-compatible form: ? > ... > # But I know for certain that the above approach is NOT secure since > object attributes can still be accessed... > > So is there an equally convenient yet secure alternative available for > parsing strings containing Python data structure definitions? > > Thanks in advance for any pointers! > > Cheers, > Warren As mentioned, I don't know if everything has been tried or how secure what attempts have been. I haven't seen this one: Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> del __builtins__ >>> a= [ x for x in (1).__class__.__bases__[0].__subclasses__() if x.__name__== 'file' ][ 0 ] >>> a >>> a('abc.txt','w') Traceback (most recent call last): File "", line 1, in IOError: file() constructor not accessible in restricted mode >>> import os Traceback (most recent call last): File "", line 1, in ImportError: __import__ not found So, at least one of the newsgroup favorites is gone. Take a shot though! Maybe a variant would be sufficient. No warranty. From kyosohma at gmail.com Wed Oct 8 11:53:38 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 8 Oct 2008 08:53:38 -0700 (PDT) Subject: Accessing the message of Outlook inbox References: <72ffe2f3-3c08-4888-99ae-30899615de3b@1g2000prd.googlegroups.com> Message-ID: On Oct 8, 9:24?am, venutaurus... at gmail.com wrote: > Hi all, > ? ? ? ? How can I access the body of a mail in Outlook Inbox? I tried > various options like message.Body or message.Mesg etc. but didn't > work. I could get the subject of the mail using message.Subject > though. > > Any help is appreciated. > > Thanks in advance, > Venu Can you connect via POP3? If so, the email module should be able to get it. Otherwise, you'll probably have to use the PyWin32 package's win32com module. Google is your friend. The following links should give you a general idea of how to access Outlook with Python: http://cephas.net/blog/2004/09/17/sending-your-outlook-calendar-using-python/ http://www.boddie.org.uk/python/COM.html http://www.goldb.org/goldblog/CommentView,guid,dcd1d9cd-eb1b-4590-a14b-1480bdf1db69.aspx http://mail.python.org/pipermail/python-win32/2007-November/006446.html Mike From jarausch at igpm.rwth-aachen.de Thu Oct 16 05:28:13 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 16 Oct 2008 11:28:13 +0200 Subject: python3 - the hardest hello world ever ? In-Reply-To: <48f6f990$0$2492$9b622d9e@news.freenet.de> References: <48f481af$0$2863$ba620e4c@news.skynet.be> <48f4f35e$0$25779$9b622d9e@news.freenet.de> <48F5C11C.3070807@igpm.rwth-aachen.de> <48f6438d$0$19075$9b622d9e@news.freenet.de> <48F6F6EE.9000704@igpm.rwth-aachen.de> <48f6f990$0$2492$9b622d9e@news.freenet.de> Message-ID: <48F7092D.2050806@igpm.rwth-aachen.de> Martin v. L?wis wrote: >> Still, I wished it were possible call sys.setdefaultencoding >> at the very beginning of a script. >> >> Why isn't that possible? > > The default encoding was used when combining byte-oriented > text and unicode-oriented text. Such combination is no longer > supported, hence the notion of a default encoding > has disappeared. You have to perform conversion between bytes > and strings now explicitly. > I meant setting the default encoding which is used by print (e.g.) when outputting the internal unicode string to a file. As far as I understood, currently I am fixed to setting either the 'locale' or to switch settings for each output file (by settting the _encoding property. I wished I could override the locale settings within a Python script. Thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From fuzzyman at gmail.com Sun Oct 5 17:48:13 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 5 Oct 2008 14:48:13 -0700 (PDT) Subject: Python 2.6: Determining if a method is inherited References: <0b330a07-75bb-41a8-8ded-98a2f6ea76b1@v53g2000hsa.googlegroups.com> <1ioc74i.oj0w5116i5a6jN%dialUAZ###UZ#$AAtone@gWARAmail.com> Message-ID: <9eb88361-b8c6-47b9-926c-54192fbd6bc3@i76g2000hsf.googlegroups.com> On Oct 5, 8:15?pm, dialUAZ###UZ#$AAt... at gWARAmail.com (Valentino Volonghi aka Dialtone) wrote: > Fuzzyman wrote: > > So how do I tell if the X.__lt__ is inherited from object? I can look > > I don't have python 2.6 installed so I can't try but what I think could > work is: > > >>> class Foo(object): > > ... ? ? def hello(self): > ... ? ? ? ? pass > ...>>> class Bla(Foo): > > ... ? ? def hello(self): > ... ? ? ? ? pass > ...>>> class Baz(Foo): > > ... ? ? pass > ...>>> Baz.hello.im_func > > >>> Bla.hello.im_func > > >>> Foo.hello.im_func > > >>> Foo.hello.im_func is Baz.hello.im_func > True > >>> Foo.hello.im_func is Bla.hello.im_func > > False > Nope: Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class X(object): pass ... >>> X.__lt__.im_func Traceback (most recent call last): File "", line 1, in AttributeError: 'method-wrapper' object has no attribute 'im_func' >>> What I went with in the end: import sys as _sys if _sys.version_info[0] == 3: def _has_method(cls, name): for B in cls.__mro__: if B is object: continue if name in B.__dict__: return True return False else: def _has_method(cls, name): for B in cls.mro(): if B is object: continue if name in B.__dict__: return True return False See this page for why I needed it: http://www.voidspace.org.uk/python/weblog/arch_d7_2008_10_04.shtml#e1018 Michael > Which to me also makes sense. If it's inherited I expect it to be the > very same function object of one of the bases (which you can get with > inspect.getmro(Clazz)). On the other end if you override it it's not the > same function object so it won't return True when applied to 'is'. > > HTH > > -- > Valentino Volonghi aka Dialtonehttp://stacktrace.it-- Aperiodico di resistenza informatica > Blog:http://www.twisted.it/ > Public Beta:http://www.adroll.com/ From ldo at geek-central.gen.new_zealand Sun Oct 19 19:38:14 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 20 Oct 2008 12:38:14 +1300 Subject: keyword in package name. References: <6m0bk2Fe8qbdU1@mid.uni-berlin.de> Message-ID: In message , Steve Holden wrote: > Though I do think it's an inappropriate choice for Python. I'd characterize it as a Javaism. It exemplifies the difference between the corporate, management-driven Java development model, versus the more freewheeling, informal Python one. Like the difference between strict subclassing and duck-typing. From malteseunderdog at gmail.com Wed Oct 29 14:29:08 2008 From: malteseunderdog at gmail.com (MalteseUnderdog) Date: Wed, 29 Oct 2008 11:29:08 -0700 (PDT) Subject: Python Regex Question Message-ID: <8ba29fe7-2614-4186-952d-5a7c08d30f29@q9g2000hsb.googlegroups.com> Hi there I just started python (but this question isn't that trivial since I couldn't find it in google :) ) I have the following text file entries (simplified) start #frag 1 start x=Dog # frag 1 end stop start # frag 2 start x=Cat # frag 2 end stop start #frag 3 start x=Dog #frag 3 end stop .... I need a regex expression which returns the start to the x=ANIMAL for only the x=Dog fragments so all my entries should be start ... (something here) ... x=Dog . So I am really interested in fragments 1 and 3 only. My idea (primitive) ^start.*?x=Dog doesn't work because clearly it would return results start x=Dog # (good) and start x=Cat stop start x=Dog # bad since I only want start ... x=Dog portion Can you help me ? Thanks JP, Malta. From user at asus-190829777.TeleWell.gateway Tue Oct 21 14:39:53 2008 From: user at asus-190829777.TeleWell.gateway (Ville M. Vainio) Date: Tue, 21 Oct 2008 18:39:53 GMT Subject: Developing for Python (2.x or 3)? References: Message-ID: <87y70hsseu.fsf@asus-190829777.TeleWell.gateway> "Paulo J. Matos" writes: > I am in the process of choosing which Python version for a brand new > application. Van Rossum in an interview recently advised all new > applications to use Python3 but I am afraid, most libraries (PyGtk, I don't think he meant "all new" applications, bit rather when you are about to embark on a new "thing" that will take a while to build (new django? ;-). > PyQt, Networking Libs, etc) won't follow suit to 3.0 and I will end > up using a version of the language which can't connect to libraries > because they haven't been ported yet. I'd expect the libs to catch up quite quickly, bit I'd still not do an end-user app in 3.0 yet. 2.6, using 3.0 comatibility features is your best bet. From kib2 at free.fr Fri Oct 3 11:05:11 2008 From: kib2 at free.fr (kib2) Date: Fri, 03 Oct 2008 17:05:11 +0200 Subject: tkinter textwidget problem In-Reply-To: References: <48e5278e$0$6543$426a74cc@news.free.fr> Message-ID: <48e634a9$0$17742$426a74cc@news.free.fr> > Tk/Tkinter apparently considers the position 1.13 to be after the last > word in the text. You get the same problem if you set the insertion > point just after the word 'two' for example: text.index('insert') > returns 1.7 and text.index('insert wordstart') returns 1.7 too... > Exactly. > My solution would simply be to go back one character before asking the > word start: text.index('insert - 1 chars wordstart') Don't know if > that'll do what you want if there are spaces at the end of the text. And > BTW, if you actually want the *last* word in the text, you may want to > use text.index('end - 2 chars wordstart'). Here, you have to use '- 2 > chars' because end points to the first non-existent index (2.0 in your > case...). > > HTH Good idea, it seems to work fine now. See you. Kib?. From paul at boddie.org.uk Mon Oct 20 10:45:22 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 20 Oct 2008 07:45:22 -0700 (PDT) Subject: a question about Chinese characters in a Python Program References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> Message-ID: <1736d4c0-8a8f-4587-a4a7-fe499a141162@e38g2000prn.googlegroups.com> On 20 Okt, 15:30, est wrote: > > Thanks for the long comment Paul, but it didn't help massive errors in > Python encoding. > > IMHO it's even better to output wrong encodings rather than halt the > WHOLE damn program by an exception I disagree. Maybe I'll now get round to uploading an amusing pictorial example of this strategy just to illustrate where it can lead. CJK characters may be more demanding to deal with than various European characters, but I've seen public advertisements (admittedly aimed at IT course applicants) which made jokes about stuff like "??" and "??" appearing in documents instead of the intended European characters, so it's fairly safe to say that people do care what gets written out from computer programs. > When debugging encoding problems, the solution is simple. If > characters display wrong, switch to another encoding, one of them must > be right. > > But it's tiring in python to deal with encodings, you have to wrap > EVERY SINGLE character expression with try ... except ... just imagine > what pain it is. If everything is in Unicode then you don't have to think about encodings. I recommend using things like codecs.open to ensure that input and output even produce and consume Unicode objects when dealing with files. > Just like the example I gave in Google Groups, u'\ue863' can NEVER be > encoded into '\xfe\x9f'. Not a chance, because python REFUSE to handle > a byte that is greater than range(128). Aside from the matter of which encoding you'd need to use to convert u'\ue863' into '\xfe\x9f', it has nothing to do with any implicit byte value range. To get from a Unicode object to a sequence of bytes (since that is the external representation of the text for other programs), Python has to perform a conversion. As a safe (but obviously conservative) default, Python only attempts to convert each Unicode character to a byte value using the ASCII character value table which is only defined for characters 0 to 127 - there's no such thing as "8-bit ASCII". Python doesn't attempt to automatically convert using other character tables (encodings, in other words), since there is quite a large possibility that the result, if not produced for the correct encoding, will not produce the desired visual effect. If I start with, say, character "?" and encode it using UTF-8, I get a sequence of bytes which, if interpreted by a program expecting ISO-8859-15 will appear as "??". If I encode the character using ISO-8859-15 and then feed the resulting byte sequence to a program expecting UTF-8, it will probably either complain or produce an incorrect visual effect. The reason why ASCII is safer (although not entirely safe) is because many encodings support ASCII as a subset of themselves. > Strangely the 'mbcs' encoding system can. Does 'mbcs' have magic or > something? But it's Windows-specific I thought Microsoft used some UTF-16 variant. That would explain how it can handle more or less everything. > Dealing with character encodings is really simple. AFAIK early > encoding before Unicode, although they have many names, are all based > on hacks. Take Chinese characters as an example. They are called > GB2312 encoding, in fact it is totally compatible with range(256) > ANSI. (There are minor issues like display half of a wide-character in > a question mark ? but at least it's readable) If you just output > serials of byte array, it IS GB2312. The same is true with BIG5, JIS, > etc. >From the Wikipedia page, it appears that you need to convert GB2312 values to EUC-CN by a relatively straightforward process, and can then output the resulting byte sequence in an ASCII compatible way, provided that you filter out all the byte values greater than 127: these filtered bytes would produce nonsense for anyone using a program not expecting EUC-CN. UTF-8 has some similar properties, but as I noted above, you wouldn't want to read most of the output if your program wasn't expecting UTF-8. > Like I said, str() should NOT throw an exception BY DESIGN, it's a > basic language standard. str() is not only a convert to string > function, but also a serialization in most cases.(e.g. socket) My > simple suggestion is: If it's a unicode character, output as UTF-8; > other wise just ouput byte array, please do not encode it with really > stupid range(128) ASCII. It's not guessing, it's totally wrong. I think it's unfortunate that "str" is now potentially unreliable for certain uses, but to just output an arbitrary byte sequence (unless by byte array you mean a representation of the numeric values) is the wrong thing to do unless you don't care about the output; in which case, you could just as well use "repr" instead. I think the output of "str" vs. "unicode" especially with regard to Unicode objects was discussed extensively on the python-dev mailing list at one point. I don't disagree that people sometimes miss a way of having Python or some library "do the right thing" when writing stuff out. I could imagine a wrapper for Python accepting UTF-8 whose purpose is to "blank out" characters which the console cannot handle, and people might use this wrapper explicitly because that is the "right thing" for them. Indeed, such a program may already exist for a more general audience since I imagine that it could be fairly useful. Paul From dan.eloff at gmail.com Sat Oct 11 13:57:36 2008 From: dan.eloff at gmail.com (Eloff) Date: Sat, 11 Oct 2008 10:57:36 -0700 (PDT) Subject: What do _ast Load | Store | Del | AugLoad | AugStore | Param mean? Message-ID: <355071a5-6969-4f81-808e-4af29d40d050@t65g2000hsf.googlegroups.com> In the _ast module Attribute, Subscript, Name, List, Tuple all have an expr_context associated with them which is defined as: expr_context = Load | Store | Del | AugLoad | AugStore | Param I have no idea what they mean, and what's the difference between them. I'm porting _ast to IronPython and this is the only part I've had difficulty understanding. The only clue I've found is that all these expressions are unique in that they can occur in assignment context. Any insights at all? Thanks, -Dan From jasiu85 at gmail.com Tue Oct 28 16:29:07 2008 From: jasiu85 at gmail.com (jasiu85) Date: Tue, 28 Oct 2008 13:29:07 -0700 (PDT) Subject: Do I need a lock here? References: <2c4e058e-ac16-4d98-a8b0-87cdc974607b@j22g2000hsf.googlegroups.com> <6mlf01FhdunaU1@mid.uni-berlin.de> Message-ID: <5dbbf67d-4e18-4ece-8e09-774c7e2fd5c7@40g2000prx.googlegroups.com> On Oct 27, 10:12?am, "Diez B. Roggisch" wrote: > jasiu85 schrieb: > > > > > Hey, > > > Please take a look at the code of the two threads below: > > > COMMON_DICT = {} > > > def thread_1(): > > ? ? global COMMON_DICT > > ? ? local_dict = prepare_dict() > > ? ? COMMON_DICT = local_dict > > > def thread_2(): > > ? ? global COMMON_DICT > > ? ? local_dict = COMMON_DICT > > ? ? use_dict(local_dict) > > > Do I need a lock to protect the COMMON_DICT dictionary? AFAIK bytecode > > operations are atomic and in each thread there's only one crucial > > bytecode op: STORE_NAME in the first thread and LOAD_NAME in the > > second one. So I suspect that everything will work just fine. Am I > > right? > > Depending on what you mean by "right". > > The above is not enough to judge what is really happening. But depending > on the execution order, thread_1 overwrites the reference in COMMON_DICT > *after* thread_2 has altered it. > > But it won't crash or anything. If that's right for you. > > Diez The second thread doesn't alter the dictionary, it only reads it. Even if the first thread puts a reference to a new dictionary into the COMMON_DICT variable while the second thread is reading the old dictionary, such sematics is fine for me. I'm seeking for a kind of Producer/Consumer pattern. So the first thread produces some data in a form of a dictionary. The second thread reads it from time to time. It's sufficient for me if a dictionary is "lost" because the first thread overwrites the COMMON_DICT variable before the second thread tries to read it. It's also sufficient for me if the first thread updates COMMON_DICT variable while the second thread is reading the previous copy of the dictionary. So from my point of view the most critical parts are these two lines: COMMON_DICT = local_dict # in the first thread local_dict = COMMON_DICT # in the second thread Can these two instructions by any chance interfere with each other in a way that will crash either of the threads? I hope I made myself a little bit more clear :). Thanks!! Mike From rtw at freenet.co.uk Fri Oct 3 17:10:21 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 03 Oct 2008 16:10:21 -0500 Subject: processing email with Python on Windows? References: Message-ID: Beliavsky wrote in news:d579f554-be4b-4066-acec-49a7bafb1046 @t41g2000hsc.googlegroups.com in comp.lang.python: > I work for a financial company where we run Windows XP and read email > using Microsoft Outlook 2003. I get daily files that come as email > attachments from various counterparties. I save them as h:\firm_name > \yyyymmdd.csv . Would Python be a good tool to automate the process of > saving reports, or would it be more convenient to use a Microsoft > proprietary language such as VB or C#? Of course one factor is one's > relative competence with the various languages. > Assuming your Outlook is using Exchange (or at least a IMAP server), you can use imaplib in the standard library. This example should list the messages and attachments in you InBox fot today. EXCHANGE = '' #<-- YOUR EXCHANGE SERVER HERE EXCHANGE_PORT = 143 # default USER = '' #<-- YOUR USERNAME PWD ='' #<-- YOUR PASSWORD import imaplib, email from datetime import date today = date.today().strftime( '"%d-%b-%Y"' ) imap = imaplib.IMAP4( EXCHANGE, EXCHANGE_PORT ) imap.login( USER, PWD ) imap.select( 'InBox' ) typ, data = imap.search( None, 'SINCE', today ) for num in data[0].split(): typ, data = imap.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) print ( "%s, %s\n" % ( num, msg['subject'] ) ) for part in msg.walk(): if part.get_filename() is not None: print ( " %s\n" % part.get_filename() ) imap.close() imap.logout() Rob. -- http://www.victim-prime.dsl.pipex.com/ From prologic at shortcircuit.net.au Thu Oct 23 20:37:02 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 24 Oct 2008 10:37:02 +1000 Subject: Style questions In-Reply-To: References: Message-ID: David, Here's a "good" example (NB: subjective): http://hg.softcircuit.com.au/index.wsgi/circuits/file/251bce4b92fd/circuits/core.py On Fri, Oct 24, 2008 at 10:04 AM, David Di Biase wrote: > I have a few simple questions regarding python style standards. I have a > class contained in a module...I'm wondering if I should perform any imports > that are relevant to the class within the constructor of the class or at the > top of the module page. Normally imports are conventionally done at the top of the module. Within the module's scope. Some people import the entire module while others import only bits that they need. > Also if I'm creating a docstring for the class I should list all my public > methods, should I just list them or should I just summarise what they do? > ie: > > """Displays a graphical game of variant of Connect4. > Supports two players on a 6x7 game board. > > Public methods: > __init__() > clear_screen() > draw_header() > draw_board() > play() > prompt_for_move() > > """ Don't write what can be easily dispalyed with pydoc or some other documentation tool. The methods are already clearly there. See my core.py above. > Last question, sometimes I have a simple function with no keyword arguments > and returns none. According to the styleguide we are to include return None > at the end of the function regardless, so should I also explicitly state > that the function returns this in the one line description? ie: Not generally. Most python developers know that functions that do not have a return statement, actually implicitly returns None. You're documenting for developers (python developers) not users. cheers James -- -- -- "Problems are solved by method" From eyeprotocol at gmail.com Tue Oct 28 05:26:12 2008 From: eyeprotocol at gmail.com (Protocol) Date: Tue, 28 Oct 2008 02:26:12 -0700 (PDT) Subject: Python suitable for Midi ? Message-ID: Hello all Is Python suitable for building a multi-track midi sequencer (with a gui), that would run on windows / mac ? I fail to find sufficient information on this, being a newbie and all. Furthermore, i found references on Python not being really able of multi-threading, that further adds to the confusion. Please assist. Panos From jopython at gmail.com Wed Oct 8 13:55:42 2008 From: jopython at gmail.com (Joe Python) Date: Wed, 8 Oct 2008 13:55:42 -0400 Subject: Apache log munging Message-ID: I have a written a generator for an apache log which returns two types of information, hostname and the filename requested. The 'log' generator can be 'consumed' like this: for r in log: print r['host'], r['filename'] I want to find the top '100' hosts (sorted in descending order of total requests) like follows: host filename1 filename2 filename3 .... Total hostA 6 9 45 110 hostC 4 43 43 98 hostB 34 4 45 83 and so on. Is there a fast way to this without scanning the log file many times? Thanks in advance. - Jo -------------- next part -------------- An HTML attachment was scrubbed... URL: From gooberts at gmail.com Tue Oct 28 15:44:37 2008 From: gooberts at gmail.com (Dale Roberts) Date: Tue, 28 Oct 2008 12:44:37 -0700 (PDT) Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: On Oct 28, 11:59?am, Joe Strout wrote: > ... > > There are only the two cases, which Greg quite succinctly and ? > accurately described above. ?One is by value, the other is by ? > reference. ?Python quite clearly uses by value. ?Parameters are ? > expressions that are evaluated, and the resulting value copied into ? > the formal parameter, pure and simple. ?The continued attempts to ? > obfuscate this is pointless and wrong. > > Best, > - Joe 5 + 3 What is the "value" of that expression in Python? Can you tell me? 99.99% of programmers (who do not have this thread as context) will say that the value is 8. But you say the value is the memory address of the resulting object created when the + operator is applied to the 5 object and the 3 object. That is the "value" that is copied. Okay, you can have it that way, but every time you explain to someone that Python passes "By Value", you will have to add the additional baggage that, oh, by the way, there is a completely different meaning for "value" in Python than what you are used to. Then the questions and puzzled looks will start... And when they tell their friend that Joe The Programmer said it's Pass By Value, your additional context may not be present any longer, and the friend will be very confused. In my opinion, best just to head it off and call it something different so as not to confuse. dale From bdesth.quelquechose at free.quelquepart.fr Sat Oct 11 09:21:04 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 11 Oct 2008 15:21:04 +0200 Subject: python debugger tips? In-Reply-To: <76b16170-4e69-431c-8651-ba26b43c81d3@y21g2000hsf.googlegroups.com> References: <76b16170-4e69-431c-8651-ba26b43c81d3@y21g2000hsf.googlegroups.com> Message-ID: <48f0c426$0$13005$426a74cc@news.free.fr> just.another.random.user at gmail.com a ?crit : > Hi All, > > I'm switching to python from perl, and like the language a ton, but I > find pdb and pydb to be vastly inferior debuggers to the perl version. > > In particular, I've grown very used to stepping into arbitrary > functions interactively. For instance, in perl you can do this: > > casqa1:~> perl -de 42 > > Loading DB routines from perl5db.pl version 1.28 > Editor support available. > > Enter h or `h h' for help, or `man perldebug' for more help. > > main::(-e:1): 42 > DB<1> sub foo {return 42} > > > > DB<2> s foo() > main::((eval 7)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3): > 3: foo(); > > > DB<<3>> s > main::foo((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:2): > 2: sub foo {return 42}; > DB<<3>> > > > > Which is quite awesome; I don't have to restart the program if I want > to step through a given function call with a different set of values. In your python shell: import somelib import pdb pdb.runcall(somelib.somefunc, 42, foo='bar') Also and IIRC, ipython (an alternative and more featurefull python shell) has some interesting stuff wrt/ pdb integration. From bdesth.quelquechose at free.quelquepart.fr Mon Oct 6 17:24:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Oct 2008 23:24:42 +0200 Subject: When Python should not be used? In-Reply-To: References: Message-ID: <48ea822c$0$1793$426a34cc@news.free.fr> Andrea Francia a ?crit : > The right tool depends on the current problem. > > While some python users prefer to talk about when Python is the right > tool I think that it is more instructive to know when it is not. > > Please, could you let me know what do you think about that? Last time I had to change a flat tire, it happened that Python was definitively not the right tool - even calling on super-bicycle-repair-man !-) HTH From wgrigg at draper.com Thu Oct 23 16:05:35 2008 From: wgrigg at draper.com (bill) Date: Thu, 23 Oct 2008 13:05:35 -0700 (PDT) Subject: why would 'import win32com' fail? References: Message-ID: <5930e971-840a-4be2-8b87-8d22a98d2f0e@26g2000hsk.googlegroups.com> On Oct 23, 3:21?pm, bill wrote: > All, > > I am trying to access Excel from Python. Many of the examples started > with: > > ? ? ? import win32com > ? ? ? .... > ? ? ? blah, blah > > I try that from my Python shell and it fails. What am I missing here? > > TIA, > > Bill Thanks for the responses. I did not realize it had to be downloaded. Bill From bjourne at gmail.com Sun Oct 26 13:45:28 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 26 Oct 2008 18:45:28 +0100 Subject: Improving interpreter startup speed In-Reply-To: References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> Message-ID: <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> 2008/10/26 James Mills : > On Sun, Oct 26, 2008 at 11:23 AM, BJ?rn Lindqvist wrote: >> How are you getting those numbers? 330 ?s is still pretty fast, isn't >> it? :) Most disks have a seek time of 10-20 ms so it seem implausible >> to me that Ruby would be able to cold start in 47 ms. > > $ time python -c "pass" > > real 0m0.051s > user 0m0.036s > sys 0m0.008s Pedro was talking about cold startup time: $ sudo sh -c "echo 3 > /proc/sys/vm/drop_caches" $ time python -c "pass" real 0m0.627s user 0m0.016s sys 0m0.008s That is quite a lot and for short scripts the startup time can easily dominate the total time. > And yes I agree. the CPython interpreter startup times is > a stupid thing to be worrying about, especially since that > is never the bottleneck. I disagree. The extra time Python takes to start makes it unsuitable for many uses. For example, if you write a simple text editor then Pythons longer startup time might be to much. -- mvh Bj?rn From sbassi at clubdelarazon.org Tue Oct 21 13:59:13 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Tue, 21 Oct 2008 14:59:13 -0300 Subject: Commercial Products in Python In-Reply-To: <48FE1665.8070709@gmail.com> References: <48FE1665.8070709@gmail.com> Message-ID: <9e2f512b0810211059v6324fe0aqff23200d5e699f6f@mail.gmail.com> On Tue, Oct 21, 2008 at 2:50 PM, Paulo J. Matos wrote: > I was just wondering, if you wish to commercialize an application > developed in Python, what's the way to go? You choose the conditions. Nothing in Python license prevents you of selling your work. > I guess the only way is to sell the source, right? No > This is because (and tell me if I am wrong): > 1) You can't sell an executable because Python doesn't compile to native > code (the usual approach, afaik); There are py2exe utilities to compile Python applications. > 2) You can't sell the bytecode, otherwise you get the client stuck with > a specific python version (given bytecode might vary between versions) > (the alternative); Never heard of people selling bytecode, but I guess yes, it is tied to the same version where is was produced. -- Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 From jura.grozni at gmail.com Tue Oct 21 17:56:32 2008 From: jura.grozni at gmail.com (azrael) Date: Tue, 21 Oct 2008 14:56:32 -0700 (PDT) Subject: Need some advice References: <48fe207c$0$20551$426a34cc@news.free.fr> Message-ID: <41f37d97-d1d4-4311-8b02-b0b7896acb3d@y21g2000hsf.googlegroups.com> There have been some discutions with my partner about which protocol to use. We agreed to use also http. But we are looking for a possibility to use something to trasfer python objects like Json objects. If my memory is me well http transfers data in plaintext. Because of the risk of datacapturing, is there a better soulutioon to suggest to be more secure like shttp if it is implemented in python On Oct 21, 6:34?pm, Bruno Desthuilliers wrote: > azrael a ?crit : > > > I am starting to work on a application and need some advice. > > > I am planing to develop a desktop application which would have some > > usage, but also it should be able to comunicate to a web server which > > hosts a php web application. So I wanted to ask if someone has some > > expirience with connecting PHP webapplications with Python desktop > > applications. Could someone at leaset point me to the right direction > > where to look for informations. > > Short anwser: 'http'. > > Longer answer: when it comes to interacting with a web application, the > language used to develop both applications is irrelevant. The client app > sends an HTTP request, and receive an HTTP response. From prologic at shortcircuit.net.au Sun Oct 26 20:33:47 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 27 Oct 2008 10:33:47 +1000 Subject: Improving interpreter startup speed In-Reply-To: <8BD1F7BF-96B1-4B08-8383-2C1E498D6F38@gmail.com> References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <8BD1F7BF-96B1-4B08-8383-2C1E498D6F38@gmail.com> Message-ID: On Sun, Oct 26, 2008 at 11:19 PM, Pedro Borges wrote: > The scripts i need to run but be executed with no apparent delay specially > when the text transforms are simple. That makes no sense whatsoever! If you are performing data conversion with Python, interpreter startup times are going to be so insignificant. --JamesMills -- -- -- "Problems are solved by method" From stodge at gmail.com Thu Oct 9 09:54:58 2008 From: stodge at gmail.com (Stodge) Date: Thu, 9 Oct 2008 06:54:58 -0700 (PDT) Subject: Twisted Matrix and multicast broadcast References: Message-ID: <54f824d3-c92c-423d-a9ce-0ac5764f1406@42g2000pry.googlegroups.com> On Oct 9, 9:33?am, Jean-Paul Calderone wrote: > On Thu, 9 Oct 2008 06:03:44 -0700 (PDT), Stodge wrote: > > [snip] > >class MulticastServerUDP(DatagramProtocol): > > ? ?def startProtocol(self): > > ? ? ? ?print 'Started Listening' > > ? ? ? ?# Join a specific multicast group, which is the IP we will > >respond to > > ? ? ? ?self.transport.joinGroup('224.0.0.1') > > > [snip] > > >class MulticastClientUDP(DatagramProtocol): > > ? ?def startProtocol(self): > > ? ? ? ?print 'Started Listening' > > ? ? ? ?# Join a specific multicast group, which is the IP we will > >respond to > > ? ? ? ?self.transport.joinGroup('224.0.0.1') > > > [snip] > > >No surprises there! But how do I get the server to send to all clients > >using multicast? transport.write requires an address. Any suggestions > >appreciated. > > Your server and client are both listening on the multicast address > 224.0.0.1. ?Traffic sent to that address will be delivered to both > of them. ?If you want to send something to all clients listening on > that address, then that's the address to pass to transport.write. > > Jean-Paul Thanks. So the server write should be: self.transport.write("data", ('224.0.0.1', 8005)) I guess I can't run multiple peers on the same PC as they'll all be listening on port 8005. From exarkun at divmod.com Sat Oct 25 12:45:20 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 25 Oct 2008 12:45:20 -0400 Subject: how to pass a dictionary (including chinese characters) through Queue as is? In-Reply-To: <38a0d87e-4a6e-41b9-ae3a-0529422b82a9@s1g2000prg.googlegroups.com> Message-ID: <20081025164520.29191.1018832111.divmod.quotient.44686@ohm> On Sat, 25 Oct 2008 08:36:22 -0700 (PDT), ouyang wrote: >Hi everyone, > As indicated in the following python script, the dictionary b has >Chinese characters: "??". But a.get() returns the dictionary with a >little bit different format for the "???: '\xd6\xd0\xce\xc4' . How >can I get the dictionary through the Queue as is? > >>>> import Queue >>>> a = Queue.Queue(0) >>>> b = {'a':'??','b':1232,'c':'abc'} >>>> a.put(b) >>>> c = a.get() >>>> c >{'a': '\xd6\xd0\xce\xc4', 'c': 'abc', 'b': 1232} > Try printing b before you put it into the Queue. The Queue isn't doing anything to the objects you pass through it, you're just surprised at how repr() is presenting the un-altered data. Jean-Paul From mnordhoff at mattnordhoff.com Mon Oct 13 19:20:34 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 13 Oct 2008 23:20:34 +0000 Subject: Implementing my own Python interpreter In-Reply-To: <48F3C407.8020800@mailshack.com> References: <48F3C407.8020800@mailshack.com> Message-ID: <48F3D7C2.6000000@mattnordhoff.com> Ognjen Bezanov wrote: > Hello All, > > I am a third year computer science student and I'm the process of > selection for my final year project. > > One option that was thought up was the idea of implement my own version > of the python interpreter (I'm referring to CPython here). Either as a > process running on another OS or as a process running directly on the CPU. > > Now, I can't seem to find a decent source of information on the python > interpreter. I have made the assumption that Python works very much like > Java, you have code that is compiled into bytecode, which is then > executed in a virtual machine. IS this correct? Is there a good source > to give me an overview of Python internals? (I can look at the code, but > I would find it easier to understand if I can see the "big picture" as > well) > > Also, any pro's out there willing to chime on the feasibility of > implementing python to run directly on the hardware (without an > underlying OS)? I don't expect 100% compatibility, but would the basics > (branching, looping, arithmatic) be feasible? > > Thank you, > > > Ognjen FWIW... There are several other implementations of Python: IronPython (.Net) Jython (Java) PyPy (Python) You might find working on one of them interesting, or maybe even CPython itself. -- From __peter__ at web.de Mon Oct 13 09:07:08 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 13 Oct 2008 15:07:08 +0200 Subject: strip module bug References: Message-ID: Poppy wrote: > > I'm using versions 2.5.2 and 2.5.1 of python and have encountered a > potential bug. Not sure if I'm misunderstanding the usage of the strip > function but here's my example. > > var = "detail.xml" > print var.strip(".xml") ### expect to see 'detail', but get 'detai' > var = "overview.xml" > print var.strip(".xml") ### expect and get 'overview' > > I have a work around using the replace function which happens to be the > better choice for my script anyhow. But am curious about the strip module. > Any thoughts? Is it removing the 'l' in detail because the strip function > text ends in 'l'? The behaviour you intend, stripping a suffix, is achieved by >>> var = "detail.xml" >>> suffix = ".xml" >>> if var.endswith(suffix): ... var = var[:-len(suffix)] ... The var.strip(chars) /method/ does something different. It treats chars as a set of characters and removes any of these characters from the end and the beginning of the var string, i. e. "detail.xml" d is not in ".xml" -> remove no further chars from the beginning "detail.xml" l is in ".xml", remove it "detail.xm" m is in ".xml", remove it "detail.x" x is in ".xml", remove it "detail." . is in ".xml", remove it "detail" l is in ".xml", remove it "detai" i is not in ".xml", we're done Peter From luke.leighton at googlemail.com Tue Oct 14 09:26:18 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 14 Oct 2008 06:26:18 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> <9ff85307-5b74-4789-b572-3bca2f18940b@f77g2000hsf.googlegroups.com> Message-ID: <29e38fc0-0def-4a27-865e-7d37e081b2d7@l76g2000hse.googlegroups.com> > if there's a way to enforce the displaying of text - for the _text_ > to say "i need to be a total area of X in order to display my words. > if you make my width too small, i will _force_ my height to be larger > as i wrap the text". > > just like an HTML

does. ... of course, i'm well aware of the reasons _why_ this isn't supported - in either of Qt4 or Gtk2. it's because automatic- resizing, and correct (i.e. exact) size-hinting, is a complete lairy nightmare to implement. browsers get it right, because they have to, and the trade-off is a rather awkward judder-judder-displaying of content (which, for example, gives the use of HTML tables such a bad name). all of which of course makes the desktop-app developers' job just that little bit more awkward... From carsten.haese at gmail.com Mon Oct 6 19:33:24 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Mon, 06 Oct 2008 19:33:24 -0400 Subject: Pure Python interface to MySQL? In-Reply-To: References: Message-ID: Roy Smith wrote: > Does there exist a pure Python version of a MySQL module? A quick google search turns up this: http://github.com/mopemope/pure-python-mysql/tree/master/pymysql I've never used it, though, so I have no idea whether it works or how well it works. HTH, -- Carsten Haese http://informixdb.sourceforge.net From mal at egenix.com Thu Oct 23 11:02:42 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 23 Oct 2008 17:02:42 +0200 Subject: Possible read()/readline() bug? In-Reply-To: <4eab88c6-097e-4671-8d13-2c0cf9fd0f8d@d70g2000hsc.googlegroups.com> References: <380b01dc-eaef-425d-bb93-dbb838c20175@u28g2000hsc.googlegroups.com> <4eab88c6-097e-4671-8d13-2c0cf9fd0f8d@d70g2000hsc.googlegroups.com> Message-ID: <49009212.5030804@egenix.com> On 2008-10-22 23:00, kdwyer wrote: > On 22 Oct, 19:54, Mike Kent wrote: >> Before I file a bug report against Python 2.5.2, I want to run this by >> the newsgroup to make sure I'm not being stupid. >> >> I have a text file of fixed-length records I want to read in random >> order. That file is being changed in real-time by another process, >> and my process want to see the changes to the file. What I'm seeing >> is that, once I've opened the file and read a record, all subsequent >> seeks to and reads of that same record will return the same data as >> the first read of the record, so long as I don't close and reopen the >> file. This indicates some sort of buffering and caching is going on. The C lib uses a buffer for reading files and you are seeing the affects of this. Try using f = open('foo.txt', 'r', 0) http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-54 >> Consider the following: >> >> $ echo "hi" >foo.txt # Create my test file >> $ python2.5 # Run Python >> Python 2.5.2 (r252:60911, Sep 22 2008, 16:13:07) >> [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>> f = open('foo.txt') # Open my test file >>>>> f.seek(0) # Seek to the beginning of the file >>>>> f.readline() # Read the line, I get the data I expected >> 'hi\n' >>>>> # At this point, in another shell I execute 'echo "bye" >foo.txt'. 'foo.txt' now has been changed >>>>> # on the disk, and now contains 'bye\n'. >>>>> f.seek(0) # Seek to the beginning of the still-open file >>>>> f.readline() # Read the line, I don't get 'bye\n', I get the original data, which is no longer there. >> 'hi\n' >>>>> f.close() # Now I close the file... >>>>> f = open('foo.txt') # ... and reopen it >>>>> f.seek(0) # Seek to the beginning of the file >>>>> f.readline() # Read the line, I get the expected 'bye\n' >> 'bye\n' >> >> It seems pretty clear to me that this is wrong. If there is any >> caching going on, it should clearly be discarded if I do a seek. Note >> that it's not just readline() that's returning me the wrong, cached >> data, as I've also tried this with read(), and I get the same >> results. It's not acceptable that I have to close and reopen the file >> before every read when I'm doing random record access. >> >> So, is this a bug, or am I being stupid? > > Hello Mike, > > I'm guessing that this is not a bug. I'm no expert, but I'd guess > that the open(file, mode) function simply loads the file into memory, > and that further operations (such as seek or read) are performed on > the in-memory data rather than the data on disk. Thus changes to the > file are only observed after a fresh open operation. > > This behaviour is probably enforced by the C library on the machine > that you are using. If you want to be able to pick up data changes > like this then you're better off using a database package that has > support for concurrent access, locking and transactions. > > Cheers, > > Kev > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 23 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From netimen at gmail.com Tue Oct 21 08:31:58 2008 From: netimen at gmail.com (=?KOI8-R?B?7cnU0Q==?=) Date: Tue, 21 Oct 2008 05:31:58 -0700 (PDT) Subject: dumping in destructor References: <1fec9da2-4ef6-4e8b-9015-8eb6c43cc397@m36g2000hse.googlegroups.com> <618c9b29-0bbf-4a95-aa4f-e41c6b8c581f@j68g2000hsf.googlegroups.com> <6f03bf3f-e86c-43b5-9157-fd139a249280@m73g2000hsh.googlegroups.com> Message-ID: <20e7a1db-d294-482a-a7f7-93cd963daf7f@k7g2000hsd.googlegroups.com> Thank you! I have already implemented custom load/save operations without pickle. And they work fine on atexit. Just for information: pickle.dump worked OK when called manually, but being called by atexit it produeced the above described error. I don't know why. On Oct 21, 7:54 am, "Gabriel Genellina" wrote: > En Mon, 20 Oct 2008 10:01:07 -0200, ???? escribi?: > > > Thank you for your answers! > > > my g_register is a global object, and it lives all the program's > > lifetime, so 'with' is not appliable. Am I right? > > Why not? You could use a with statement (or try/finally) around your main > entry point. > > > > > > > I tried to use atexit and wrote following: > > > class _Register(object): > > def dump(self): > > .... > > > class Registerable(object): > > .... > > > g_register = _Register() > > atexit.register(g_register.dump) > > ... > > ... > > g_register.add(Registerable('aa')) > > > But now I get: > > > cPickle.PicklingError: Can't pickle : > > attribute lookup __main__.Registerable failed > > > Does that mean that by the time of atexit execution my Registerable > > class is already dead? > > No, at least not due to using atexit. When atexit functions are executed, > the interpreter is still in a fully working state. From pythonrun.c, > function Py_Finalize: > > /* The interpreter is still entirely intact at this point, and the > * exit funcs may be relying on that. In particular, if some thread > * or exit func is still waiting to do an import, the import machinery > * expects Py_IsInitialized() to return true. So don't say the > * interpreter is uninitialized until after the exit funcs have run. > * Note that Threading.py uses an exit func to do a join on all the > * threads created thru it, so this also protects pending imports in > * the threads created via Threading. > */ > > Probably you have another problem in your code; try to use pickle alone > (not within atexit) and see what happens. > > -- > Gabriel Genellina From timr at probo.com Thu Oct 2 03:11:33 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 02 Oct 2008 07:11:33 GMT Subject: How to read a jpg bytearray from a Flash AS3 file References: <3641130e-43d3-4996-a123-0254a47a19d7@o40g2000prn.googlegroups.com> Message-ID: <1vs8e49l6lv6mcfaerl9c9jv6fslirj3tk@4ax.com> rsgalloway at gmail.com wrote: > >Thanks! I'm using form = cgi.FieldStorage(). When I print out the >contents of form, I get this: > > FieldStorage(None, None, '\xff\xd8\xff\xe0\x00\x10JFIF >\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb >\x00\x84\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c >\x08\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f >\x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d >\x1f\x1f\x1f\x13\x17"$"\x1e$\x1c\x1e\x1f\x1e >\x01\x05\x05\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\..... > >Which is obviously the binary data of the image I want. How do I >access this data? I'm used to getting it like this: > > name = form['name'].value > >But I don't think this will work in this case. TIA. What led you to ask that here, instead of taking 60 seconds to load cgi.py in an editor and search for the FieldStorage class? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From skip at pobox.com Tue Oct 14 19:25:16 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 14 Oct 2008 18:25:16 -0500 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? In-Reply-To: <7xvdvug7pn.fsf@ruckus.brouhaha.com> References: <7xvdvug7pn.fsf@ruckus.brouhaha.com> Message-ID: <18677.10844.451057.885188@montanaro-dyndns-org.local> Paul> Main thing I know is that C-c ! used to make a new Python Paul> subwindow and now it doesn't, which is bad. That's probably the newer FSF version, python.el. Someone else complained that it didn't do Python interpreters. Skip From a_hebso_10 at hotmail.co.uk Tue Oct 14 16:18:02 2008 From: a_hebso_10 at hotmail.co.uk (Ally) Date: Tue, 14 Oct 2008 13:18:02 -0700 (PDT) Subject: Excel 2007 Charts with PyWin32 References: Message-ID: Solved. See http://bytes.com/forum/thread482449.html application = Dispatch("Excel.Application") should be application = win32com.client.gencache.EnsureDispatch('Excel.Application') From tjreedy at udel.edu Tue Oct 7 12:39:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 07 Oct 2008 12:39:21 -0400 Subject: Compiler, ast and forwards/backwards compatibility In-Reply-To: References: Message-ID: Orestis Markou wrote: > Hello, > > I'm the developer of PySmell ( http://github.com/orestis/pysmell ), a > static analysis/intellisense provider for Python. I am targeting > Python 2.4 code so I'm using the compiler package. > > I've been toying around yesterday with the ast module in Python 2.6 > and it seems much more cleaner. One thing I don't understand is how > should one handle backwards and forwards compatibility. My impression is that the 2.6 ast package is quite different from the 2.4 compiler package, but I have not looked at it (in its 3.0 version) yet. If the 2.4 code you are analyzing is syntactically and sematically valid as 2.6 code, which I believe is usual, then of course there is no problem. If it is not, then I would not be sure. > I guess that Python 2.6 can target Python 2.3-6, and with specific > compiler flags it can also target 3.0, so it seems that the correct > thing to do is to use that. If you want to target 2.3 to 3.0, 2.6 is the only option as far as I know. I expect you will want to run your code through 2to3 (still being improved) and run under 3.0 to properly handle 3.0 code. Maybe someone else can give a better answer. tjr From bdesth.quelquechose at free.quelquepart.fr Wed Oct 15 15:51:14 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 15 Oct 2008 21:51:14 +0200 Subject: File Management In-Reply-To: References: Message-ID: <48f66596$0$8018$426a74cc@news.free.fr> erict1689 a ?crit : > I am writing this program in which I open up a file and update that > information but to a new file. I already have a global variable for > it A global variable ??? WHY ??? > but how do I go about creating an openable file in the source code? It's in the FineManual(tm) > If it helps here is what I have: > > def startUp(): > # Purpose: opens files and print report headings > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > payFile=open("payroll.txt", "r") > payFile.readline() > > > def readRecord(): > # Purpose: reads a record > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > employeeRec = payFile.readline() > if employeeRec == "": > eof = True > else: > # parse file line for record fields and format/convert for > final output > empName = employeeRec[0:25].strip() > previousYTD = float(employeeRec[25:40]) > payRate = float(employeeRec[40:55]) > hoursWorked = float(employeeRec[55:70]) > recordCount += 1 > eof = False > > def writeRecord(): > # Purpose: writes the updated record to the output file > #Parameter > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > def processRecords(): > # Purpose: loops through input file and processes each record > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > while not eof: > calculatePay() > printReportLine() > writeRecord() > readRecord() > > def calculatePay(): > # Purpose: calculates pay and updated YTD > # Return values: float - calculated pay, float - updated YTD amount > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > def printReportLine(): > # Purpose: prints employee pay information > # Parameters passed: float - calculated pay, float - updated YTD > amount > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > def closeUp(): > # Purpose: end of program housekeeping > global empName, previousYTD, payRate, hoursWorked, recordCount, > eof, payFile, \ > payFileUpdated, newYTD, currentPay > > payFile.close() > payFileUpdated.close() > print "\nNumber of records in the file was",recordCount OMG ! Good Ole Almighty Procedural Programming (With Lots Of Useless Gobals(tm)) is back ! Where have you been these 20 last years ??? > Any and all help is appreciated. Err... Python is not BASIC ?-) Not tested, but you may be interested in another approach (which *also* contains the answer to your question)... import sys def parse_field(slice, transform, line): return transform(line[slice].strip()) # key => processing function mapping INFIELDS = dict( emp_name=partial(parse_field, slice(0,25), lambda x : x), previous_ytd=partial(parse_field, slice(25,40), float), payrate=partial(parse_field, slice(40,55), float), hoursworked=partial(parse_field, slice(55,70), float) ) def parse_line(line): """ parse a line and return a record (key=>value mapping) from it """ return dict( (fname, parse(line)) for fname, parse in INFIELDS.items() ) def calculate_pay(record): """ calculate pay etc and returns updated record with additional fields """ # dummy code record['yadda'] = "yadda" return record def format_record(record): """ returns a formatted string for output """ # dummy code, assuming output is csv like format return "%(emp_name)s;%(payrate)s;%(yadda)s" % record def print_report_line(record): """ print tracing / debugging info on stderr """ print >> sys.stderr, record def process_line(lineno, line): """ parse a line, compute pay, and return a nicely formatted output """ source = parse_line(line) source['num_record'] = lineno dest = calculate_pay(source) print_report_line(dest) return format_record(dest) def main(infile, outfile): """ process lines from infile and write the result to outfile """ for lineno, line in enumerate(infile): line = line.strip() if line: print >> outfile, process_line(lineno, line) if __name__ == '__main__': # # the boring part... would better be done using optparse... # # we expect two optional params: # 1/ the path to an input file - default to stdin # 2/ the path to an output file - default to stdout # try: infile = open(args[0]) except IndexError: infile = sys.stdin except IOError, e: sys.exit( "could not open file %s for reading : %s" \ % (args[0], e) ) try: outfile = open(args[1], 'w') except IndexError: outfile = sys.stdout except IOError, e: if infile is not sys.stdin: infile.close() sys.exit( "could not open file %s for writing : %s" \ % (args[1], e) ) try: # processing main(infile, outfile) finally: # housekeeping... if infile is not sys.stdin: infile.close() if outfile is not sys.stdout: outfile.close() HTH From lyaqys at gmail.com Tue Oct 14 07:33:54 2008 From: lyaqys at gmail.com (=?GB2312?B?xL7X0w==?=) Date: Tue, 14 Oct 2008 19:33:54 +0800 Subject: Python-list Digest, Vol 61, Issue 191 In-Reply-To: References: Message-ID: 2008/10/14 ?? > maybe you r test.py should be this: > > import subprocess > subprocess.Popen ( [ 'python', 'file_support.py', ] ) > sys.exit() > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From metaperl at gmail.com Fri Oct 3 05:24:46 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Fri, 3 Oct 2008 02:24:46 -0700 (PDT) Subject: code critique requested - just 60 lines References: <00f4ddb3$0$20640$c3e8da3@news.astraweb.com> Message-ID: <54581f9d-f5c4-4733-95ed-fa55694b7b3c@8g2000hse.googlegroups.com> On Oct 2, 11:09?am, Steven D'Aprano wrote: > On Thu, 02 Oct 2008 07:51:30 -0700, Terrence Brannon wrote: > > > Basically, using non-strict dictionary keys can lead to bugs, so that > > worried me. > > What's a "non-strict dictionary key"? > In Perl, you can pre-define what keys are allowed in a dictionary. That way, mis-spelling the dict key doesnt lead to accessing something didnt mean to. From tjreedy at udel.edu Sat Oct 18 15:30:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Oct 2008 15:30:23 -0400 Subject: Linux.com: Python 3 makes a big break Message-ID: http://www.linux.com/feature/150399 Interesting article with one minor incompleteness. "For instance, the print statement got turned into a print function; you must now put parentheses around what you want to print to the screen. The change allows developers to work with print in a more flexible and uniform way. If someone needs to replace the print function with some other action, it can be done with a universal search and replace, rather than rewriting each print statement by hand." Even easier, print as a function can be replaced simply by defining a new version with the same name. No search/replace is needed. And reversion to the built-in only requires commenting out the replacement. From gherron at islandtraining.com Thu Oct 2 16:46:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 02 Oct 2008 13:46:56 -0700 Subject: Inheritance but only partly? In-Reply-To: <48E530C0.9090504@islandtraining.com> References: <48E530C0.9090504@islandtraining.com> Message-ID: <48E53340.4050201@islandtraining.com> Gary Herron wrote: > process wrote: > >> Let's say I have a class X which has 10 methods. >> >> I want class Y to inherit 5 of them. >> >> Can I do that? Can I do something along the lines of super(Y, exclude >> method 3 4 7 9 10) ? >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > No. > > But why do yo care? You can just ignore the 5 you don't want -- their > existence costs you nothing in either memory or execution speed. > > You can also redefine the ones you don't want inherited: > > class A: > def DontInheritMe(self, ...): > ... > > Class B(A): > def DontInheritMe(self, ...): > raise NotImplementedError // Or some such > > > Gary Herron > > -- > http://mail.python.org/mailman/listinfo/python-list > Here's another (very Python) possibility class Base: class m1(self, ...): ... class m2(self, ...): ... class NotInheritable: class m3(self, ...): ... class A(Base, NotInheritable); ... class B(Base): ... From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 20 04:06:21 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 10:06:21 +0200 Subject: regexp in Python (from Perl) In-Reply-To: <927089ec-9a9c-4b5b-b0c5-429022c698fa@d70g2000hsc.googlegroups.com> References: <48fb8083$0$6976$426a74cc@news.free.fr> <927089ec-9a9c-4b5b-b0c5-429022c698fa@d70g2000hsc.googlegroups.com> Message-ID: <48fc3bfd$0$22811$426a74cc@news.free.fr> MRAB a ?crit : > On Oct 19, 5:47 pm, Bruno Desthuilliers > wrote: >> Pat a ?crit : (snip) >>> ip = ip[ :-1 ] >>> ip =+ '9' >> or: >> >> ip = ip[:-1]+"9" >> (snip) >> >>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.1") >> '192.168.1.9' >> >>>>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.100") >> '192.168.1.9' > > The regular expression changes the last sequence of digits to > "9" ("192.168.1.100" => "192.168.1.9") but the other code replaces the > last digit ("192.168.1.100" => "192.168.1.109"). Mmm - yes, true. ip = ".".join(ip.split('.')[0:3] + ['9']) From david at boddie.org.uk Sat Oct 11 18:45:34 2008 From: david at boddie.org.uk (David Boddie) Date: Sun, 12 Oct 2008 00:45:34 +0200 Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> Message-ID: On Saturday 11 October 2008 21:40, lkcl wrote: > On Oct 11, 3:31 pm, David Boddie wrote: >> You can remove layouts from layouts with the QLayout.removeItem() method. > > yes... it didn't work. a layout within a layout - i think it was a > QHorizontalLayout within a QGridLayout - didn't want to be removed. > it's probably a bug. Was it detached from the layout, but still visible? [...] > in order to pull in flash plugins and other material, the accepted > method in pygtk2 is to use python-gtk-mozplugger. that's crazy. > embed an _entire_ web browser, just to pull in a flash component. > likewise, for doing a single bit of HTML, in pyqt4 and/or pygtk2, pull > in a 17mb binary dependency using python-webkit-qt4 and/or > pywebkitgtk, _just_ to display _one_ bit of HTML text?? _that's_ > crazy. Sure, if all you want to do is display one bit of HTML text. It always helps if you choose the most appropriate libraries for each task. David From lepto.python at gmail.com Mon Oct 20 01:46:50 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 20 Oct 2008 13:46:50 +0800 Subject: search for a python compiler program whose name is jingle Message-ID: <6a4f17690810192246y1edbaa36vc90546167fc07a89@mail.gmail.com> I don't remember its name very clear, it may be 'jingle' or not this program runs on windows and can compile a python program into exe file without gcc it has no webspace but is announced on the author's blog when I find it some times ago. I can't find the link now. I there anybody else know it and tell me? Thanx in advance From luca.ciciriello at email.it Thu Oct 2 09:33:47 2008 From: luca.ciciriello at email.it (luca.ciciriello at email.it) Date: Thu, 2 Oct 2008 15:33:47 +0200 Subject: python-2.6 Message-ID: <4033d7d91293743c79818d464cefbd98@85.18.140.153> Hi all. I've installed on may MacOS X 10.4.11 (PPC) Python-2.5.2, numpy and scipy. Now I'm interested to insall Python-2.6. My question is: What will happen to may scientific modules if now I jump fro 2.5.2 to 2.6? I've to reinstall numpy and scipy? Thanks in advance for any answer. Luca -- Email.it, the professional e-mail, gratis per te: http://www.email.it/f Sponsor: Scopri i games pi? scaricati su cellulare! Gioca la tua partita! Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=8272&d=20081002 From chemicalclothing at temple.edu Sat Oct 25 16:42:08 2008 From: chemicalclothing at temple.edu (chemicalclothing at temple.edu) Date: Sat, 25 Oct 2008 13:42:08 -0700 (PDT) Subject: Limit between 0 and 100 Message-ID: Hi. I'm very new to Python, and so this is probably a pretty basic question, but I'm lost. I am looking to limit a float value to a number between 0 and 100 (the input is a percentage). I currently have: integer = int() running = True while running: try: per_period_interest_rate = float(raw_input("Enter per-period interest rate, in percent: ")) break except ValueError: print "Please re-enter the per-period interest rate as a number between 0 and 100." I also have to make sure it is a number and not letters or anything. Thanks for the help. James P.S. I don't understand a lot of what I have there, I got most of it from the beginning tutorials and help sections. I have never programmed before, but this is for a school assignment. From tino at wildenhain.de Fri Oct 31 06:51:17 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 31 Oct 2008 11:51:17 +0100 Subject: modifying locals In-Reply-To: <490ADB41.9090306@egenix.com> References: <20255725.post@talk.nabble.com> <011a2c95$0$20617$c3e8da3@news.astraweb.com> <20257394.post@talk.nabble.com> <011ab22b$0$20643$c3e8da3@news.astraweb.com> <490ABCF0.8060100@wildenhain.de> <490ADB41.9090306@egenix.com> Message-ID: <490AE325.80901@wildenhain.de> M.-A. Lemburg wrote: > On 2008-10-31 09:08, Tino Wildenhain wrote: ... >> Ah thats interesting. I would not know because I usually avoid >> such ugly hacks :-) > > It doesn't even work for already defined local variables: > >>>> def foo(): > ... x = 1 > ... locals()['x'] = 2 > ... print x > ... >>>> foo() > 1 > > The reason is that locals are copied in to a C array > when entering a function. Manipulations are then > done using the LOAD_FAST, STORE_FAST VM opcodes. > > The locals() dictionary only shadows these locals: it copies > the current values from the C array into the frame's > f_locals dictionary and then returns the dictionary. > > This also works the other way around, but only in very > cases: > > * when running "from xyz import *" > * when running code using "exec" > > globals() on the other hand usually refers to a module > namespace dictionary, for which there are no such > optimizations.. > > I don't know of any way to insert locals modified in > a calling stack frame... but then again: why would you > want to do this anyway ? Yes, thats what I'm saying. Unless you are writing a debugger or something you better don't mess with the internals. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mrmakent at cox.net Wed Oct 22 14:54:23 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 22 Oct 2008 11:54:23 -0700 (PDT) Subject: Possible read()/readline() bug? Message-ID: <380b01dc-eaef-425d-bb93-dbb838c20175@u28g2000hsc.googlegroups.com> Before I file a bug report against Python 2.5.2, I want to run this by the newsgroup to make sure I'm not being stupid. I have a text file of fixed-length records I want to read in random order. That file is being changed in real-time by another process, and my process want to see the changes to the file. What I'm seeing is that, once I've opened the file and read a record, all subsequent seeks to and reads of that same record will return the same data as the first read of the record, so long as I don't close and reopen the file. This indicates some sort of buffering and caching is going on. Consider the following: $ echo "hi" >foo.txt # Create my test file $ python2.5 # Run Python Python 2.5.2 (r252:60911, Sep 22 2008, 16:13:07) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('foo.txt') # Open my test file >>> f.seek(0) # Seek to the beginning of the file >>> f.readline() # Read the line, I get the data I expected 'hi\n' >>> # At this point, in another shell I execute 'echo "bye" >foo.txt'. 'foo.txt' now has been changed >>> # on the disk, and now contains 'bye\n'. >>> f.seek(0) # Seek to the beginning of the still-open file >>> f.readline() # Read the line, I don't get 'bye\n', I get the original data, which is no longer there. 'hi\n' >>> f.close() # Now I close the file... >>> f = open('foo.txt') # ... and reopen it >>> f.seek(0) # Seek to the beginning of the file >>> f.readline() # Read the line, I get the expected 'bye\n' 'bye\n' >>> It seems pretty clear to me that this is wrong. If there is any caching going on, it should clearly be discarded if I do a seek. Note that it's not just readline() that's returning me the wrong, cached data, as I've also tried this with read(), and I get the same results. It's not acceptable that I have to close and reopen the file before every read when I'm doing random record access. So, is this a bug, or am I being stupid? From thomascribbs at gmail.com Wed Oct 1 09:43:18 2008 From: thomascribbs at gmail.com (thomascribbs at gmail.com) Date: Wed, 1 Oct 2008 06:43:18 -0700 (PDT) Subject: IDLE doesn't run on OSX 10.3.9 References: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> <48E26CB7.8060207@codebykevin.com> Message-ID: Just did a new install of Tcl/tk from activestate.com and IDLE still not working... -Tom On Sep 30, 1:15 pm, Kevin Walzer wrote: > thomascri... at gmail.com wrote: > > Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and > > when clicking on the IDLE icon in the MacPython 2.5 folder nothing > > happens, program doesn't execute... > > > I've uninstalled, reinstalled over again... > > > I friend of mine just installed the same 2.5.2 download from the > > Python.org website on OSX 10.4.11 and all went fine...but shouldn't it > > install on 10.3.9 as well? > > > Anyone have any ideas? Thanks. > > -Tom > > Do you have Tcl/Tk installed? It doesn't come on 10.3.9 by default. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com From ldo at geek-central.gen.new_zealand Sat Oct 18 01:43:14 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Oct 2008 18:43:14 +1300 Subject: Convertimg a Sequence of Images to an AVI File References: Message-ID: In message , W. eWatson wrote: > I'd like to simply take the large images out of the file and make an avi > file from them. What in Python will help me do that? Probably easier to just use FFmpeg from the command line. From bj_666 at gmx.net Wed Oct 8 14:05:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Oct 2008 18:05:20 GMT Subject: distributing apps without the Python source? References: <6l41pbFaj22eU1@mid.uni-berlin.de> Message-ID: <6l4b30Fakp4rU1@mid.uni-berlin.de> On Wed, 08 Oct 2008 10:59:44 -0500, skip wrote: > Marc> On Wed, 08 Oct 2008 09:18:47 -0600, Joe Strout wrote: > >> We have a client who's paranoid about distributing the Python > >> source to his commercial app. Is there some way I can distribute > >> and use just the .pyc files, so as to not give away the source? > > Marc> Yes. Just use the *.pyc files. > > Though of course there is decompyle to consider, assuming Joe's client > is truly paranoid. Simply don't tell the client. All he has to know is that it's basically the same as Java *.class files. Most paranoid clients are fine with that. Unless you tell them there are decompilers for *.class files. :-) Ciao, Marc 'BlackJack' Rintsch From peke at iki.fi Mon Oct 6 19:50:26 2008 From: peke at iki.fi (Pekka Laukkanen) Date: Tue, 7 Oct 2008 02:50:26 +0300 Subject: Python 2.6 / 3.0: Determining if a method is inherited In-Reply-To: References: <0862144a-bc06-40ef-ad1a-019bf08a6768@y71g2000hsa.googlegroups.com> Message-ID: 2008/10/7 Pekka Laukkanen : > 2008/10/5 Fuzzyman : >> I may well be being dumb (it has happened before), but I'm struggling >> to fix some code breakage with Python 2.6. >> >> I have some code that looks for the '__lt__' method on a class: >> >> if hasattr(clr, '__lt__'): >> >> However - in Python 2.6 object has grown a default implementation of >> '__lt__', so this test always returns True. >> >>>>> class X(object): pass >> ... >>>>> X.__lt__ >> >>>>> X.__lt__ == object.__lt__ >> False >> >> So how do I tell if the X.__lt__ is inherited from object? I can look >> in the '__dict__' of the class - but that doesn't tell me if X >> inherits '__lt__' from a base class other than object. (Looking inside >> the method wrapper repr with a regex is not an acceptable answer...) > > I don't have Python 2.6 available, but if __lt__ on it works similarly > as __str__ on Python 2.5, you might be able to achieve this either > with inspect.ismethod or by checking methods' im_class attribute > directly: > >>>> class C(object): > ... pass > ... >>>> class D(object): > ... def __str__(self): > ... return '' > ... >>>> class E(D): > ... pass > ... >>>> import inspect >>>> inspect.ismethod(C().__str__) > False >>>> inspect.ismethod(D().__str__) > True >>>> inspect.ismethod(E().__str__) > True >>>> >>>> C().__str__.im_class > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'method-wrapper' object has no attribute 'im_class' >>>> D().__str__.im_class > >>>> E().__str__.im_class > Ooops, didn't notice this was suggested already. One more attempt, hopefully this is unique. =) >>> C().__str__.__objclass__ >>> D().__str__.__objclass__ Traceback (most recent call last): File "", line 1, in AttributeError: 'function' object has no attribute '__objclass__' >>> 'spam'.__str__.__objclass__ Someone who actually knows what __objclas__ does can probably comment does this make any sense in your case. Cheers, .peke From andy55 at gmail.com Sun Oct 26 22:03:31 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Sun, 26 Oct 2008 19:03:31 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <63d8aa77-f863-4d8c-b135-2088d0b68760@a70g2000hsh.googlegroups.com> Message-ID: <0b92de73-de5a-4c1b-862a-7d52d3747def@m74g2000hsh.googlegroups.com> > > And in the case of hundreds of megs of data > > ... and I would be surprised at someone that would embed hundreds of > megs of data into an object such that it had to be serialized... seems > like the proper design is to point at the data, or a subset of it, in a > big buffer. ?Then data transfers would just transfer the offset/length > and the reference to the buffer. > > > and/or thousands of data structure instances, > > ... and this is another surprise! ?You have thousands of objects (data > structure instances) to move from one thread to another? > I think we miscommunicated there--I'm actually agreeing with you. I was trying to make the same point you were: that intricate and/or large structures are meant to be passed around by a top-level pointer, not using and serialization/messaging. This is what I've been trying to explain to others here; that IPC and shared memory unfortunately aren't viable options, leaving app threads (rather than child processes) as the solution. > Of course, I know that data get large, but typical multimedia streams > are large, binary blobs. ?I was under the impression that processing > them usually proceeds along the lines of keeping offsets into the blobs, > and interpreting, etc. ?Editing is usually done by making a copy of a > blob, transforming it or a subset in some manner during the copy > process, resulting in a new, possibly different-sized blob. Your instincts are right. I'd only add on that when you're talking about data structures associated with an intricate video format, the complexity and depth of the data structures is insane -- the LAST thing you want to burn cycles on is serializing and unserializing that stuff (so IPC is out)--again, we're already on the same page here. I think at one point you made the comment that shared memory is a solution to handle large data sets between a child process and the parent. Although this is certainty true in principle, it doesn't hold up in practice since complex data structures often contain 3rd party and OS API objects that have their own allocators. For example, in video encoding, there's TONS of objects that comprise memory-resident video from all kinds of APIs, so the idea of having them allocated from shared/mapped memory block isn't even possible. Again, I only raise this to offer evidence that doing real-world work in a child process is a deal breaker--a shared address space is just way too much to give up. Andy From andre.roberge at gmail.com Tue Oct 14 12:23:31 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 14 Oct 2008 09:23:31 -0700 (PDT) Subject: docpicture References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> <010374c5$0$20641$c3e8da3@news.astraweb.com> <18675.34993.962044.115182@montanaro-dyndns-org.local> <0103c2da$0$20671$c3e8da3@news.astraweb.com> <01049eb4$0$20671$c3e8da3@news.astraweb.com> Message-ID: <0f00167d-96d2-4592-a3c2-fcf4812616df@31g2000prz.googlegroups.com> On Oct 14, 10:58?am, Steven D'Aprano wrote: > On Tue, 14 Oct 2008 06:12:59 -0700, Scott David Daniels wrote: > > Steven D'Aprano wrote: > >> And if not, it's no big deal. Your help string has a clearly labeled > >> few lines of hex: > > >> Help on function spam: > > >> spam(...) > >> ? ? spam spam spam spam spam spam > >> ? ? spam spam spam spam with a fried egg on top > > >> ? ? === begin docpicture === > >> ? ? 1234567890ABCDEF... > >> ? ? === end docpicture === > >> Or similar. I'm sure people will cope, especially since it should be > >> relatively rare. > > > or you could even use: > > ? ? ? ?''' > > ? ? ? ?1234567890ABCDEF... > > ? ? ? ?''' > > A comment _not_ a docstring (only found by scanning the source). which > > is easy enough to hunt for. > > +1 for docpictures > > -1 for them being comments instead of docstrings. The whole point of > having them is to allow Python tools to operate on them. I should be able > to do this: > > >>> import docpicture > >>> docpicture.gui(myfunction) > > and get a nice Tk window showing the picture. There's all sorts of > functionality that you lose by making them comments and therefore > unavailable to Python tools. (Okay, technically this hypothetical > docpicture module could scan the source file -- assuming the source code > is even available, which isn't always true.) > > But anyway, we're getting well ahead of ourselves here. Unless bearophile > is willing to share his code, or somebody reverse engineers it, this is > nothing more than vapourware. > > -- > Steven Ok, the following is my first attempt at implementing this idea. Of course, it could be improved by using reStructuredText in the docstring and docutils to format it... '''Experimental function allowing to view docstrings with embedded images. The images are encoded in base 64. (c) Andre Roberge License: Adapt as you please, but preferably give credit to original author (and any subsequent contributor). ''' import base64 import os import re import sys import webbrowser html_template = "%s" def docpicture_view(function): """ This is a test. docpicture = reeborg_img.png Some more explanation. """ source_module = sys.modules[function.__module__] # extract image information from docstring, retrieve encoded data, # decode, and write to file image_name_pattern = re.compile("\s*docpicture\s*=\s*(.+?)\s") image_filename = image_name_pattern.search(function.__doc__).groups()[0] base_name, ext = image_filename.split('.') image = base64.b64decode(getattr(source_module, base_name)) image_file = open(image_filename, "wb") image_file.write(image) image_file.close() # replace image information in docstring by link to image file, # insert in an html template, create a new file that will be displayed # in a browser. docpicture_pattern = re.compile("\s*(docpicture\s*=\s*.+?)\s") text = docpicture_pattern.sub("

" % image_filename, function.__doc__) html_file = open("test.html", 'w') html_file.write(html_template % text) html_file.close() url = os.path.join(os.getcwd(), "test.html") webbrowser.open(url) reeborg_img = """\ iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAMAAAAfOR5kAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAD AFBMVEUAAAAzMzNbW1v/AACAgICkpKTAwMD/// 8AAAAS8uhyd1MAAAABD3UAADYAAAAAAFAAABkA AAGFBJ4AAAkAADYAAAAAAFAAABkAAAAAAAAAABQAABcAAAkAAAQAAAQAAAQAAATxogDxoeQBD3UA ADkAAAMAABMAABMBDusAAAAAACYFDpQAAAAAACaqAAD/// 8V5iAV5hgS9XC1WqAS85wBDwG2L+RF NyAAABMAABMBDutPyjgS9CC1WqC1VShP0RYAAABPyji1WqAS9CC1RBxP7jMAAAIBD3UAADkAAAMA ABMAABMV5iAS9BhBx0G1DExCx4VCx43LD8i1DGxFM5sS9BhFM7JFM7oS9LRFM8QS9BgS9JjLD8jL D8i1WqAS9DBCWLYABAEAAAC6Z1AAAAES9FzUhzRTBRAABAEAAAC6Z1DLD8i6q80AAAAS9JgS9HTU tqPUhPzUhaQDBRoAAAEWIagWIcgABAAWX8gAAADUtik94ZFTBRAS9SwAAAAWX8g94ZwAAAAAAAAA BAAAABMS9RAS9TjXBGfUiDD////UiCrUuJsAAADLD8hTBRAABAEAAAC6Z1B +cqwAAAEAAAAAAAAA AAAAAACKACEABADV8+N+cph +8XAAAAAAAAQAAaYAAAIABAAAABMWIcgBCJ4AAAAAAAAAAAAAAAAA AAAAAAAAAAAS8HSAFjwAAAUAAAVI2FSAGByAGKxI2GAAb1oS9fw97BsWX8gAAAAWIUgAAAQAAAAS 9mQ95ZgAAADXIloAAAAS9bzUtqPUhPzUhaQDBRoAAAEAAAAWX8gWIUgDBQES9dDUwr8S9gA90ZMD BRo95ZgWX8jUiKYAAAAAAAIAAMgAABMWIVAS9ijUhzRTBRAAAA8AAAAAAAA95Zi6q80AAAAS9mQ9 5ZgS9pDUi9n90AAS9pDUiFoS9lDUiCoAAA895ZgS +WgAABQAAAEAAAAAAAAAABAAAAAAAFAAAAEA AAAAAAAS9kTxbGQS+TjXBGfUiDD////UiCoAAAAAAADKTwNHAAAACHRSTlP///////// AN6DvVkA AAB6SURBVHjardCLCsAgCAXQO7P8/z +eyVxWEgzmKNghfEEES5CoqV5E7FFbIzKOao5SjJknj0yo Gbt2fnKfOCQJHEt+43Lkdcp8J8bbBmEb7Jemh35cq/07axJjzhjIuJ+dsb/ 2iZaSc3fO3qO88T+P mpF5TB+YMp4bvwEGcAqR53QgIgAAAABJRU5ErkJggg== """ if __name__ == '__main__': docpicture_view(docpicture_view) From tjreedy at udel.edu Wed Oct 29 18:59:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Oct 2008 18:59:37 -0400 Subject: how to get the thighest bit position in big integers? In-Reply-To: <9189df2f-90d3-459a-a973-f9905573408e@d70g2000hsc.googlegroups.com> References: <3c25c2cd-0357-47b0-b51d-fb38a55bd54e@t18g2000prt.googlegroups.com> <5ad76973-e776-4654-bc6f-6913eb4f99f0@c60g2000hsf.googlegroups.com> <9189df2f-90d3-459a-a973-f9905573408e@d70g2000hsc.googlegroups.com> Message-ID: Mensanator wrote: > You would think when you add a new function, you would > also add it's documentation, but maybe that was an > oversight. I don't have 3.0, but maybe it can be found > in that set of docs. 3.0c1 >>> help(bin) Help on built-in function bin in module builtins: bin(...) bin(number) -> string Return the binary representation of an integer or long integer. Manual bin(x) Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. You can file a doc bug for whatever is missing in 2.6. You might check other 3.0 builtins that were backported. tjr From anton.shishkov at gmail.com Fri Oct 24 03:28:50 2008 From: anton.shishkov at gmail.com (ASh) Date: Fri, 24 Oct 2008 00:28:50 -0700 (PDT) Subject: Logger / I get all messages 2 times References: <6mbetlFftblkU1@mid.uni-berlin.de> Message-ID: <6081332e-4be8-46a2-bc7d-02c870d407f3@q35g2000hsg.googlegroups.com> On Oct 23, 5:10?pm, "Diez B. Roggisch" wrote: > ASh wrote: > > Hi, > > > I have this source: > > > import logging > > import logging.config > > > logging.config.fileConfig("logging.properties") > > log = logging.getLogger("qname") > > log.debug("message") > > > ------------------- OUTPUT > > DEBUG logger_test:8: ?message > > DEBUG logger_test:8: ?message > > > ------- FILE CONFIG > > [formatters] > > keys: detailed > > > [handlers] > > keys: console > > > [loggers] > > keys: root, engine > > > [formatter_detailed] > > format: %(levelname)s %(module)s:%(lineno)d: ?%(message)s > > > [handler_console] > > class: StreamHandler > > args: [] > > formatter: detailed > > > [logger_root] > > level: ERROR > > handlers: console > > > [logger_engine] > > level: DEBUG > > qualname: qname > > handlers: console > > > --------------- > > > Why do I get the log 2 times? > > Because you add the handler "console" two times, to logger_engine and > logger_root. You should only add it to root, or set propagate to false. > > Diez What if I want to output only the specific logger to console and ignore every other? From tony.meyer at gmail.com Sun Oct 5 00:58:52 2008 From: tony.meyer at gmail.com (Tony Meyer) Date: Sun, 5 Oct 2008 17:58:52 +1300 Subject: One class per file? In-Reply-To: References: Message-ID: [HCB] >> The book "Code Complete" recommends that you put only one class in a >> source file, which seems a bit extreme for me. IMO this is a misunderstanding (by the author). In Python, a file is not equivalent to a class, it is equivalent to a module. A module might contain a single class or many, just as a class might contain a single method or many. You can tell that files are not classes, because you have have variables, methods, etc at the module level, outside of class definitions. If all of the module's functionality is in a single class, then of course the file only contains one class. If the module's functionality is split over many classes (or no classes at all), then the file will not contain exactly one class. Rigidly putting every class in a separate file would mean that the next level higher than classes wouldn't be modules, it would be packages. [Roy Smith] > Consider this. You're slogging through some code in a large project > trying > to debug a problem when you come upon the line (in pseudo-code): > > foo = SomeClass::SomeFunction(bar) > > You want to go look at the source for SomeClass. What file do you > open to > find it? If you follow the "one class per file" rule, the answer is > easy; > it's in SomeClass.xxx! Alternatively, most IDEs will let you go to the source very simply. If you don't have that facility available, then you just do "import X;print X.__file__". Cheers, Tony From joe at strout.net Thu Oct 9 10:24:21 2008 From: joe at strout.net (Joe Strout) Date: Thu, 9 Oct 2008 08:24:21 -0600 Subject: template strings for matching? In-Reply-To: <18670.382.955904.251930@montanaro-dyndns-org.local> References: <63F6CC9F-9BAF-4447-BCC4-FB40781295E6@strout.net> <48EDFE88.7040202@wildenhain.de> <18670.382.955904.251930@montanaro-dyndns-org.local> Message-ID: On Oct 9, 2008, at 7:05 AM, skip at pobox.com wrote: > Tino> http://docs.python.org/library/stdtypes.html#string-formatting-operations > > That shows how to use the template formatting as it currently > exists. To my > knowledge there is no support for the inverse operation, which is > what Joe > asked about. Given a string and a format string assign the elements > of the > string which correspond to the template elements to key/value pairs > in a > dictionary. Right. Well, what do y'all think? It wouldn't be too hard to write this for myself, but it seems like the sort of thing Python ought to have built in. Right on the Template class, so it doesn't add anything new to the global namespace; it just makes this class more useful. I took a look at PEP 3101, which is more of a high-powered string formatter (as the title says, Advanced String Formatting), and will be considerably more intimidating for a beginner than Template. So, even if that goes through, perhaps Template will stick around, and being able to use it in both directions could be quite handy. Oh boy! Could this be my very first PEP? :) Thanks for any opinions, - Joe From aizenman at gmail.com Fri Oct 10 18:41:12 2008 From: aizenman at gmail.com (aizenman at gmail.com) Date: Fri, 10 Oct 2008 15:41:12 -0700 (PDT) Subject: python debugger tips? References: <76b16170-4e69-431c-8651-ba26b43c81d3@y21g2000hsf.googlegroups.com> Message-ID: <86b09978-5231-4036-b94e-8f8f6578809a@u65g2000hsc.googlegroups.com> On Oct 10, 5:58 pm, Stef Mientki wrote: > take a look at winpdb (which has no relation with Windows-OS !! > > cheers, > Stef Looks pretty cool; sadly, our sysadmin refuses to install wxwindows, and the commandline version is fairly cryptic... Thanks! Y From steve at holdenweb.com Mon Oct 13 16:38:05 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Oct 2008 16:38:05 -0400 Subject: Quality control in open source development In-Reply-To: <85a586f5-154a-4cce-a002-68d5c7e56de3@u40g2000pru.googlegroups.com> References: <85a586f5-154a-4cce-a002-68d5c7e56de3@u40g2000pru.googlegroups.com> Message-ID: Dave wrote: > With the open source licenses that allow redistribution of modified > code, how do you keep someone unaffiliated with the Python community > from creating his or her own version of python, and declaring it to be > Python 2.6, or maybe Python 2.7 without any approval of anyone at the > PSF? Maybe their code is terrible, and not even compatible with the > rest of Python! How can the PSF, for example, maintain the quality and > coheren of new code contributed to be part of Python, or derivative > works that claim to be some future version of Python? If licensees can > redisribute as they like, isn't this a huge problem? Is this dealt > with be restricting use of the Python trademarks? Just curious.. The PSF relies on the Python core developers to maintain quality. As far as redistribution is concerned there are requirements to describe the changes made to the basic Python distribution in derived works. As far as calling it "Python" is concerned, the PSF maintains a trademark on the word "Python" used to describe computer software. An informal description of PSF policy on uses of the trademark can be found at http://www.python.org/psf/trademarks/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mal at egenix.com Fri Oct 31 05:34:50 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 31 Oct 2008 10:34:50 +0100 Subject: Python 2.5: wrong number of arguments given in TypeError for function argument aggregation (dictionary input vs the norm) In-Reply-To: <1225408700.27458.37.camel@jmk> References: <28efa6970810301549u5d01d4e3t5feacf775f7a6075@mail.gmail.com> <1225408700.27458.37.camel@jmk> Message-ID: <490AD13A.6090106@egenix.com> On 2008-10-31 00:18, John Krukoff wrote: > On Fri, 2008-10-31 at 08:55 +1000, James Mills wrote: >> What you have discovered is not a bug :) >> >> cheers >> James >> > > Are you sure? It looks like his complaint isn't that it doesn't work, > but that the error message is misleading. > > With the setup: > > Python 2.5.2 (r252:60911, Sep 22 2008, 12:08:38) > [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> def foo( a, b, c ): > ... pass > ... > > Compare the error messages from: > >>>> foo( **{ 'a' : 1, 'c' : 3 } ) > Traceback (most recent call last): > File "", line 1, in > TypeError: foo() takes exactly 3 non-keyword arguments (1 given) > > to the error message here: > >>>> foo( **{ 'a' : 1, 'b' : 3 } ) > Traceback (most recent call last): > File "", line 1, in > TypeError: foo() takes exactly 3 non-keyword arguments (2 given) The (n given) notice refers to the number of keyword parameters you specified in the call that could be associated with a non-keyword arguments of the function. I agree that this is a bit misleading. Please open a bug report on python.org. > Is it even possible to get an error message in terms of required keyword > arguments? I seem to remember seeing a note about keyword only arguments > recently... You probably saw PEP 3102: http://www.python.org/dev/peps/pep-3102/ That has a somewhat different focus though: it allows defining keyword-only arguments, ie. ones that cannot be used as both non-keyword parameter and keyword parameter (like we have in Python 2.x). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 31 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From patrickstinson.lists at gmail.com Fri Oct 24 12:08:37 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Fri, 24 Oct 2008 08:08:37 -0800 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: <6214d7a20810240908y442be535v3db1ada19c08cbe0@mail.gmail.com> As a side note to the performance question, we are executing python code in an audio thread that is used in all of the top-end music production environments. We have found the language to perform extremely well when executed at control-rate frequency, meaning we aren't doing DSP computations, just responding to less-frequent events like user input and MIDI messages. So we are sitting this music platform with unimaginable possibilities in the music world (of which python does not play a role), but those little CPU spikes caused by the GIL at low latencies won't let us have it. AFAIK, there is no music scripting language out there that would come close, and yet we are sooooo close! This is a big deal. On Fri, Oct 24, 2008 at 7:42 AM, Andy O'Meara wrote: > > Glenn, great post and points! > >> >> Andy seems to want an implementation of independent Python processes >> implemented as threads within a single address space, that can be >> coordinated by an outer application. This actually corresponds to the >> model promulgated in the paper as being most likely to succeed. > > Yeah, that's the idea--let the highest levels run and coordinate the > show. > >> >> It does seem simpler and more efficient to simply "copy" >> data from one memory location to another, rather than send it in a >> message, especially if the data are large. > > That's the rub... In our case, we're doing image and video > manipulation--stuff not good to be messaging from address space to > address space. The same argument holds for numerical processing with > large data sets. The workers handing back huge data sets via > messaging isn't very attractive. > >> One thing Andy hasn't yet explained (or I missed) is why any of his >> application is coded in a language other than Python. > > Our software runs in real time (so performance is paramount), > interacts with other static libraries, depends on worker threads to > perform real-time image manipulation, and leverages Windows and Mac OS > API concepts and features. Python's performance hits have generally > been a huge challenge with our animators because they often have to go > back and massage their python code to improve execution performance. > So, in short, there are many reasons why we use python as a part > rather than a whole. > > The other area of pain that I mentioned in one of my other posts is > that what we ship, above all, can't be flaky. The lack of module > cleanup (intended to be addressed by PEP 3121), using a duplicate copy > of the python dynamic lib, and namespace black magic to achieve > independent interpreters are all examples that have made using python > for us much more challenging and time-consuming then we ever > anticipated. > > Again, if it turns out nothing can be done about our needs (which > appears to be more and more like the case), I think it's important for > everyone here to consider the points raised here in the last week. > Moreover, realize that the python dev community really stands to gain > from making python usable as a tool (rather than a monolith). This > fact alone has caused lua to *rapidly* rise in popularity with > software companies looking to embed a powerful, lightweight > interpreter in their software. > > As a python language fan an enthusiast, don't let lua win! (I say > this endearingly of course--I have the utmost respect for both > communities and I only want to see CPython be an attractive pick when > a company is looking to embed a language that won't intrude upon their > app's design). > > > Andy > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Sun Oct 5 21:57:33 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 5 Oct 2008 18:57:33 -0700 (PDT) Subject: Python 2.6 / 3.0: Determining if a method is inherited References: <0862144a-bc06-40ef-ad1a-019bf08a6768@y71g2000hsa.googlegroups.com> <2d9d0fb1-9526-49d4-aeb5-95818d7b2451@8g2000hse.googlegroups.com> Message-ID: <2cf894cb-1088-47cc-aa9e-93560bb4c4aa@t65g2000hsf.googlegroups.com> On Oct 5, 7:13?pm, MRAB wrote: > Fuzzyman wrote: > > Hello all, > > > I may well be being dumb (it has happened before), but I'm struggling > > to fix some code breakage with Python 2.6. > > > I have some code that looks for the '__lt__' method on a class: > > > if hasattr(clr, '__lt__'): > > > However - in Python 2.6 object has grown a default implementation of > > '__lt__', so this test always returns True. > > > Hmmm... I can get this working with Python 2.6 with: > > Methods are objects. How do you know if two references refer to the > same object? You use "is": > > X.__lt__ is object.__lt__ That doesn't work for me. >>> class A( object ): ... pass ... >>> class B( A ): ... def __lt__( self, other ): ... return self ... >>> a= A() >>> b= B() >>> B.__lt__ is object.__lt__ False >>> A.__lt__ is object.__lt__ False >>> Further, it's been noted before that A().meth is not A().meth From gagsl-py2 at yahoo.com.ar Fri Oct 3 15:23:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 03 Oct 2008 16:23:28 -0300 Subject: execute a function before and after any method of a parent class References: Message-ID: En Fri, 03 Oct 2008 11:03:22 -0300, TP escribi?: > I would like to be able to specialize an existing class A, so as to > obtain a > class B(A), with all methods of B being the methods of A preceded by a > special method of B called _before_any_method_of_A( self ), and followed > by > a special method of B called _after_any_method_of_A( self ). > > The goal is to avoid to redefine explicitly in B all methods of A. > > Is this possible in Python? Sure. After reading this (excelent!) article by M. Simionato http://www.phyast.pitt.edu/~micheles/python/documentation.html you should be able to write a decorator to make any method into a "sandwich" (probably based on his "trace" example). Your code would look like this: @decorator def sandwich(f, self, *args, **kw): self.before() f(self, *args, **kw) self.after() class A: @sandwich def foo(self): ... @sandwich def bar(self, x): ... Ok, but then you have to explicitely decorate every method. To avoid this, you may use a metaclass; this article by Michael Foord explains how: http://www.voidspace.org.uk/python/articles/metaclasses.shtml#a-method-decorating-metaclass That's all! -- Gabriel Genellina From lpyeagertutu at googlemail.com Sun Oct 5 18:50:49 2008 From: lpyeagertutu at googlemail.com (lpyeagertutu at googlemail.com) Date: Sun, 5 Oct 2008 15:50:49 -0700 (PDT) Subject: Buy cheap levitra Message-ID: <90eaa1b9-eda9-4fa9-83ff-5b67519a92d4@k13g2000hse.googlegroups.com> buy cheap levitra . . . Enough to seek Levitra! You've already found the best site where you can purchase Levitra for lowest price! To order Levitra without prescription visit link below! ************************************ http://med247.us/?p=levitra ************************************ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uy cheap levitra by cheap levitra bu cheap levitra buy heap levitra buy ceap levitra buy chap levitra buy chep levitra buy chea levitra buy cheap evitra buy cheap lvitra buy cheap leitra buy cheap levtra buy cheap levira buy cheap levita buy cheap levitr bbuy cheap levitra buuy cheap levitra buyy cheap levitra buy ccheap levitra buy chheap levitra buy cheeap levitra buy cheaap levitra buy cheapp levitra buy cheap llevitra buy cheap leevitra buy cheap levvitra buy cheap leviitra buy cheap levittra buy cheap levitrra buy cheap levitraa uby cheap levitra byu cheap levitra bu ycheap levitra buy hceap levitra buy cehap levitra buy chaep levitra buy chepa levitra buy chea plevitra buy cheap elvitra buy cheap lveitra buy cheap leivtra buy cheap levtira buy cheap levirta buy cheap levitar buycheap levitra buy cheaplevitra vuy cheap levitra guy cheap levitra huy cheap levitra nuy cheap levitra byy cheap levitra b7y cheap levitra b8y cheap levitra biy cheap levitra bky cheap levitra bjy cheap levitra bhy cheap levitra but cheap levitra bu6 cheap levitra bu7 cheap levitra buu cheap levitra buj cheap levitra buh cheap levitra bug cheap levitra buy xheap levitra buy dheap levitra buy fheap levitra buy vheap levitra buy cgeap levitra buy cyeap levitra buy cueap levitra buy cjeap levitra buy cneap levitra buy cbeap levitra buy chwap levitra buy ch3ap levitra buy ch4ap levitra buy chrap levitra buy chfap levitra buy chdap levitra buy chsap levitra buy cheqp levitra buy chewp levitra buy chesp levitra buy chexp levitra buy chezp levitra buy cheao levitra buy chea0 levitra buy cheal levitra buy cheap kevitra buy cheap oevitra buy cheap pevitra buy cheap lwvitra buy cheap l3vitra buy cheap l4vitra buy cheap lrvitra buy cheap lfvitra buy cheap ldvitra buy cheap lsvitra buy cheap lecitra buy cheap lefitra buy cheap legitra buy cheap lebitra buy cheap levutra buy cheap lev8tra buy cheap lev9tra buy cheap levotra buy cheap levltra buy cheap levktra buy cheap levjtra buy cheap levirra buy cheap levi5ra buy cheap levi6ra buy cheap leviyra buy cheap levihra buy cheap levigra buy cheap levifra buy cheap levitea buy cheap levit4a buy cheap levit5a buy cheap levitta buy cheap levitga buy cheap levitfa buy cheap levitda buy cheap levitrq buy cheap levitrw buy cheap levitrs buy cheap levitrx buy cheap levitrz From george.sakkis at gmail.com Tue Oct 7 19:48:30 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 7 Oct 2008 16:48:30 -0700 (PDT) Subject: Array of dict or lists or ....? References: Message-ID: <810b61fd-ac4a-4223-9e7d-b7201f1682a1@v39g2000pro.googlegroups.com> On Oct 7, 10:15 pm, Pat wrote: > Dennis Lee Bieber wrote: > > On Mon, 06 Oct 2008 19:45:07 -0400, Pat declaimed the > > following in comp.lang.python: > > >> I can't figure out how to set up a Python data structure to read in data > >> that looks something like this (albeit somewhat simplified and contrived): > > >> States > >> Counties > >> Schools > >> Classes > >> Max Allowed Students > >> Current enrolled Students > > >> Nebraska, Wabash, Newville, Math, 20, 0 > >> Nebraska, Wabash, Newville, Gym, 400, 0 > >> Nebraska, Tingo, Newfille, Gym, 400, 0 > >> Ohio, Dinger, OldSchool, English, 10, 0 > > > > > > The structure looks more suited to a database -- maybe SQLite since > > the interface is supplied with the newer versions of Python (and > > available for older versions). Seconded. > I don't understand why I need a database when it should just be > a matter of defining the data structure. Picking an appropriate data structure depends on the kind of functionality you want to provide. So far you basically described just one requirement: keep a tally of how many students are in each class and compare it to the max allowed (and zero). If that's the only kind of query you want to run against your data, there's no reason to index separately each state, county, or school; all you care about are classes. A simple data structure that satisfies perfectly the requirement could then be: # mapping of {class-info : (max,enrolled)} data = { ('Nebraska', 'Wabash', 'Newville', 'Math') : (20, 0), ('Nebraska', 'Wabash', 'Newville', 'Gym') : (400, 0), ('Nebraska', 'Tingo', 'Newville', 'Gym') : (400, 0), ('Ohio', 'Dinger', 'OldSchool', 'English') : (10, 0), } Of course this data structure is pretty bad at answering a query like "how many classes are there in Nebraska" or "what's the average number of enrolled students in Newville". The more general information you might want to get from the data, the more obvious it becomes that you need a real database. HTH, George From s.payandeh at gmail.com Sun Oct 5 06:10:34 2008 From: s.payandeh at gmail.com (sa6113) Date: Sun, 5 Oct 2008 03:10:34 -0700 (PDT) Subject: paramiko.SSHException : No existing session ??? Message-ID: <19823051.post@talk.nabble.com> I use this code : hostname = "192.168.1.4" username = "test" port = 22 password = '123456' # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect_ex((hostname, port)) except Exception, e: print 'Connect failed: ' + str(e) traceback.print_exc() sys.exit(1) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) print "started client" event.wait(15) if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" print "doing authentication" t.auth_password(username, password, event) event.clear() event.wait(20) ----------------- the result is : started client ssh negotiation sucessful donig authentication .... paramiko.SSHException : No existing session ------------------- I am sure that the username and password exists properly. what is the problem?? -- View this message in context: http://www.nabble.com/paramiko.SSHException-%3A-No-existing-session-----tp19823051p19823051.html Sent from the Python - python-list mailing list archive at Nabble.com. From duncan.booth at invalid.invalid Sun Oct 5 12:48:29 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Oct 2008 16:48:29 GMT Subject: how to get the thighest bit position in big integers? References: Message-ID: mmgarvey at gmx.de wrote: > My question to the group: Does anyone know of a non-hackish way to > determine the required bit position in python? I know that my two > ideas > can be combined to get something working. But is there a *better* way, > that isn't that hackish? > How about using the hex representation of the value? OFFSET = dict(("%x"%i, int(c)) for i,c in enumerate("5433222211111111")) def get_highest_bit_num(r): s = "%x"%r return len(s) * 4 - OFFSET[s[0]] From guuwwe at hotmail.com Tue Oct 7 16:10:02 2008 From: guuwwe at hotmail.com (Micky) Date: Tue, 7 Oct 2008 13:10:02 -0700 (PDT) Subject: Demand that Obama release his college records! Where is the media? Message-ID: Why is it important to see Obama's college records? Because the media has created fantasies around Obama on every issue. You should start dispelling them with the easiest one, i.e. the fantasy of Obama's "academic degrees and honors". Obama has been fighting desperately to block all access to his college records. Even his "academic paper" at Columbia mysteriously disappeared. The media just swallowed the official Obama's "academic degrees and honors" without checking his actual grades, his scores on standardized tests, his academic writings if any, etc. All the decisions to admit Obama to colleges, to give him "academic degrees and honors" were made by a few unknown individuals. Read about the racial turmoil at one college where he got his "academic honors". The race tensions seem to follow Obama wherever he goes. If Obama's college records fail to meet the requirements for legitimate academic degrees and honors then Obama will be declared an academic fraud. Maybe then the media will start vetting Obama on other issues. Then we will be able to address the biggest fantasies like Obama's "ability to solve" the financial crisis which requires making executive decisions. Obama never made a single real executive decision in his life! How will Obama be able to attract quality people if he has a long history of attracting and being attracted to the worst kind? Any Hollywood actor can read a teleprompter and memorize talking points written by secret handlers. If Obama gets elected and turns the United States into a war-torn country like Kenya then his college records will mysteriously leak, but then it could be too late. I am asking everybody to request at least one major news network to make it an election issue. Ask others to do the same. Since Obama has built his political career around his "academic degrees and honors", all his college records (complete set of grades, scores on standardized tests, etc) must be released. Keep in mind that Obama's supporters have saturated media outlets and internet bandwidth for the last two years with stories of Obama's "academic degrees and honors". Now they viciously attack those who want to see Obama's grades and scores on standardized tests. Obama's "academic degrees and honors" without checking his grades and his scores on standardized tests are like "good standing" of Enron or Fannie Mae before they collapsed. You would be surprised what racial accusations, threats, boycotts can do to academic integrity at US colleges! Some websites to submit your requests: http://my.barackobama.com/page/s/contact2 http://abcnews.go.com/Site/page?id=3068843 http://www.msnbc.msn.com/id/6872152/ http://www.cnn.com/feedback/ http://www.foxnews.com/story/0,2933,77538,00.html http://www.cbsnews.com/ Some websites to read about Obama's "academic career": http://atlasshrugs2000.typepad.com/atlas_shrugs/2008/05/obama-mythical.html http://www.investors.com/editorial/editorialcontent.asp?secid=1501&status=article&id=307579834298611 http://www.nysun.com/new-york/obamas-years-at-columbia-are-a-mystery/85015/ http://www.jpost.com/servlet/Satellite?cid=1218710381368&pagename=JPost%2FJPArticle%2FShowFull http://worldnetdaily.com/index.php?fa=PAGE.view&pageId=74877 http://reason.com/news/show/128461.html From dialUAZ###UZ#$AAtone at gWARAmail.com Sun Oct 5 15:15:36 2008 From: dialUAZ###UZ#$AAtone at gWARAmail.com (Valentino Volonghi aka Dialtone) Date: Sun, 5 Oct 2008 12:15:36 -0700 Subject: Python 2.6: Determining if a method is inherited References: <0b330a07-75bb-41a8-8ded-98a2f6ea76b1@v53g2000hsa.googlegroups.com> Message-ID: <1ioc74i.oj0w5116i5a6jN%dialUAZ###UZ#$AAtone@gWARAmail.com> Fuzzyman wrote: > So how do I tell if the X.__lt__ is inherited from object? I can look I don't have python 2.6 installed so I can't try but what I think could work is: >>> class Foo(object): ... def hello(self): ... pass ... >>> class Bla(Foo): ... def hello(self): ... pass ... >>> class Baz(Foo): ... pass ... >>> Baz.hello.im_func >>> Bla.hello.im_func >>> Foo.hello.im_func >>> Foo.hello.im_func is Baz.hello.im_func True >>> Foo.hello.im_func is Bla.hello.im_func False Which to me also makes sense. If it's inherited I expect it to be the very same function object of one of the bases (which you can get with inspect.getmro(Clazz)). On the other end if you override it it's not the same function object so it won't return True when applied to 'is'. HTH -- Valentino Volonghi aka Dialtone http://stacktrace.it -- Aperiodico di resistenza informatica Blog: http://www.twisted.it/ Public Beta: http://www.adroll.com/ From bieffe62 at gmail.com Wed Oct 8 05:08:41 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Wed, 8 Oct 2008 02:08:41 -0700 (PDT) Subject: how to start thread by group? References: Message-ID: <8ab1eac6-e802-4496-a34f-1726614264f4@r15g2000prh.googlegroups.com> On 7 Ott, 06:37, "Gabriel Genellina" wrote: > En Mon, 06 Oct 2008 11:24:51 -0300, escribi?: > > > On 6 Ott, 15:24, oyster wrote: > >> my code is not right, can sb give me a hand? thanx > > >> for example, I have 1000 urls to be downloaded, but only 5 thread at ? > >> one time > > I would restructure my code with someting like this ( WARNING: the > > following code is > > ABSOLUTELY UNTESTED and shall be considered only as pseudo-code to > > express my idea of > > the algorithm (which, also, could be wrong:-) ): > > Your code creates one thread per url (but never more than MAX_THREADS ? > alive at the same time). Usually it's more efficient to create all the ? > MAX_THREADS at once, and continuously feed them with tasks to be done. A ? > Queue object is the way to synchronize them; from the documentation: > > > ?from Queue import Queue > ?from threading import Thread > > num_worker_threads = 3 > list_of_urls = ["http://foo.com", "http://bar.com", > ? ? ? ? ? ? ? ? ?"http://baz.com", "http://spam.com", > ? ? ? ? ? ? ? ? ?"http://egg.com", > ? ? ? ? ? ? ? ? ] > > def do_work(url): > ? ? ?from time import sleep > ? ? ?from random import randrange > ? ? ?from threading import currentThread > ? ? ?print "%s downloading %s" % (currentThread().getName(), url) > ? ? ?sleep(randrange(5)) > ? ? ?print "%s done" % currentThread().getName() > > # from this point on, copied almost verbatim from the Queue example > # at the end ofhttp://docs.python.org/library/queue.html > > def worker(): > ? ? ?while True: > ? ? ? ? ?item = q.get() > ? ? ? ? ?do_work(item) > ? ? ? ? ?q.task_done() > > q = Queue() > for i in range(num_worker_threads): > ? ? ? t = Thread(target=worker) > ? ? ? t.setDaemon(True) > ? ? ? t.start() > > for item in list_of_urls: > ? ? ?q.put(item) > > q.join() ? ? ? # block until all tasks are done > print "Finished" > > > -- > Gabriel Genellina Agreed. I was trying to do what the OP was trying to do, but in a way that works. But keeping the thread alive and feeding them the URL is a better design, definitly. And no, I don't think its 'premature optimization': it is just cleaner. Ciao ------ FB From joe at strout.net Fri Oct 17 17:39:33 2008 From: joe at strout.net (Joe Strout) Date: Fri, 17 Oct 2008 15:39:33 -0600 Subject: Finding the instance reference of an object In-Reply-To: References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> Message-ID: <7A77404C-E34F-4CD8-90E4-844DB9921D8C@strout.net> On Oct 17, 2008, at 3:19 PM, Grant Edwards wrote: >> And my real point is that this is exactly the same as in every >> other modern language. > > No, it isn't. In many other languages (C, Pascal, etc.), a > "variable" is commonly thought of as a fixed location in memory > into which one can put values. Those values may be references > to objects. Right, though not in languages like C and Pascal that don't HAVE the notion of objects. We really ought to stop bringing up those dinosaurs and instead compare Python to any modern OOP language. > In Python, that's not how it works. There is no > "location in memory" that corresponds to a variable with a > particular name the way there is in C or Pascal or Fortran or > many other languages. No? Is there any way to prove that, without delving into the Python source itself? If not, then I think you're talking about an internal implementation detail. > All that exists in Python is a name->object mapping. And what does that name->object mapping consist of? At some level, there has to be a memory location that stores the reference to the object, right? >> Nothing unusual here at all (except that some of us here seem >> to want to make up new terminology for standard behavior, >> perhaps in order to make Python seem more exotic). > > That's because it is fundamentally different from what happens > in languages like C. What happens in a modern OOP language is just as fundamentally different (which is to say, not really very much) from what happens in C or FORTRAN or COBOL, too. But if there's any demonstrable difference between Python and any other modern OOP language, I'd love to hear about it. >>> a = a + [something] >>> >>> rebinds a >> >> In standard terminology, it assigns a new value to a. > > The problem is that listeners from a C or FORTRAN background > will infer that there is a fixed region of memory named "a" and > "assigning a value to a" means writing that new value into the > region of memory named "a". And they'd be correct. The value being written, in this case, as a reference to some data that lives somewhere on the heap. Point that out, and now their understanding is correct. But if you instead say something like "all parameters are passed by reference in Python," then the user gets the wrong idea. That statement has a specific meaning which is, quite demonstrably, not true. If you make up new terms like "rebinds," well, I guess at least that avoids giving the listener the wrong idea. Instead it gives them no idea at all, which may be better, but not as good as giving them the right idea. It still leaves them to investigate what actually happens, and ultimately they will find that the parameters are always passed by value in Python. May as well save them the trouble and point that out up front. And how many recovering FORTRAN or C programmers do we get around here, anyway? Java is what they've been teaching in school for the last several years, and it was C++ for a good decade before that. The semantics of Python (insofar as objects, assignments, and parameters are concerned) are exactly the same as Java, and Java is just a cleaned-up and streamlined C++. Even old-timers (like me) who learned FORTRAN and COBOL way back in the day have long since moved on. Best, - Joe From robert.kern at gmail.com Sat Oct 25 16:19:41 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 25 Oct 2008 15:19:41 -0500 Subject: big objects and avoiding deepcopy? In-Reply-To: <5e5bfdda-9f90-44c5-a558-f089538f6831@q30g2000prq.googlegroups.com> References: <5e5bfdda-9f90-44c5-a558-f089538f6831@q30g2000prq.googlegroups.com> Message-ID: Reckoner wrote: > I am writing an algorithm that takes objects (i.e. graphs with > thousands of nodes) into a "hypothetical" state. I need to keep a > history of these hypothetical objects depending on what happens to > them later. Note that these hypothetical objects are intimately > operated on, changed, and made otherwise significantly different from > the objects they were copied from. > > I've been using deepcopy to push the objects into the hypothetical > state where I operate on them heavily. This is pretty slow since the > objects are very large. > > Is there another way to do this without resorting to deepcopy? > > by the way, the algorithm works fine. It's just this part of it that I > am trying to change. This is similar to implementing "Undo" functionality in applications. One solution is to define every operation you can do on the data structure as a pair of functions, one which does the "forward" operation on the data structure and one which does the "backward" operation which will return the modified data structure back to its original state. Each time you do a forward operation, append the pair of functions to a list (along with any auxiliary data that you need). Once you have finished with the hypothetical operations, you can work your way backwards through the list and using the "backwards" operations. This works fairly well if you have a single data structure that you are managing this way and a limited set of operations to track. If you have multiple interacting objects and a large set of operations, things can become cumbersome. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sandricionut at yahoo.com Wed Oct 1 08:07:14 2008 From: sandricionut at yahoo.com (sandric ionut) Date: Wed, 1 Oct 2008 05:07:14 -0700 (PDT) Subject: change line with columns when print Message-ID: <471365.66562.qm@web51308.mail.re2.yahoo.com> Thank you Almar It worked :), I now have to format it nicely Ionut ----- Original Message ---- From: Almar Klein To: python-list at python.org Sent: Wednesday, October 1, 2008 2:57:00 PM Subject: Re: change line with columns when print Hi, probably not the best solution, but this should work: L1 = [] L2 = [] for i in file: ??? tmp = i.split(" ") ??? L1.append(tmp[0]) ??? L2.append(tmp[1]) ??? for i in L1: ??? print i, print # new line for i in L2: ??? print i, print # new line Almar 2008/10/1 sandric ionut Hello: I have a text file that looks like: 0 23 1 342 3 31 and I want to read the file and print it out like: 0 1 3 23 342 31 How can I do this? Thnak you in advance, Ionut -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Fri Oct 17 16:16:11 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Oct 2008 09:16:11 +1300 Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> <010845d8$0$20638$c3e8da3@news.astraweb.com> <01087204$0$20638$c3e8da3@news.astraweb.com> Message-ID: In message , Sion Arrowsmith wrote: > Maybe it should be "fewer random data". Except these days we tend to think of "data" being, say, more like "flour" than "bees", so it's "less data", like "less flour", rather than like "fewer bees". :) > After all, each byte in the block is discrete. Data can come in fractional bits. That's how compression works. From ivan at datasyncorp.com Fri Oct 24 10:32:30 2008 From: ivan at datasyncorp.com (ivandatasync) Date: Fri, 24 Oct 2008 07:32:30 -0700 (PDT) Subject: Python equivalent to SharePoint? In-Reply-To: <3D7759C1-8358-4986-AD1A-756370974912@strout.net> References: <3D7759C1-8358-4986-AD1A-756370974912@strout.net> Message-ID: <20151313.post@talk.nabble.com> I have read about both Plone and Alfresco being considered as alternatives to Sharepoint and unfortunately they may not be enough if you require everything Sharepoint has too offer. Plone and Alfresco are both great applications but out of the box they are too focused to be complete replacements. Sharepoint is quite the Monolithic beast when it comes to both features and complexity. I have done some Sharepoint development and customization work in a former life err.... job and although I would not wish it on my worst competitor, it is very 'feature' rich. Either way, IMHO, these all-in-one, frameworks are not the way to go. They just get too large and encourage companies to keep their eggs all in one basket. Although I admit, I am very biased as I work on the Datasync Suite, which is a Sharepoint competitor. Our approach is to not re-invent the wheel but rather integrate open source applications that are very good for select business units under a single web based portal. The applications we integrate are written in various languages but our Suite that ties them all together is written entirely in Python. Which has served as a marvelous glue language and base for application extensions. I'll stop there because I don't want to turn my post into more of an advertisement then it has already become but if your interested, the link is in my sig. Good Luck, Ivan Ven Osdel http://www.datasyncsuite.com/ Joe Strout-2 wrote: > > We've got a client who has been planning to use SharePoint for > managing their organization documents, but has recently dropped that > idea and is looking for an alternative. Is there any Python package > with similar functionality? > > I confess that I've never used SharePoint myself, and what I know > about is mainly from these sources: > > http://en.wikipedia.org/wiki/SharePoint > http://discuss.joelonsoftware.com/default.asp?joel.3.66103.7 > > I found a reference to CPS, but its developers have dropped the Python > source to rewrite it in Java. That's disturbing, and I don't want to > recommend an abandoned platform. Anything else I should consider? > > Thanks, > - Joe > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Python-equivalent-to-SharePoint--tp19995715p20151313.html Sent from the Python - python-list mailing list archive at Nabble.com. From robin at reportlab.com Thu Oct 9 09:29:52 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 09 Oct 2008 14:29:52 +0100 Subject: template strings for matching? In-Reply-To: <63F6CC9F-9BAF-4447-BCC4-FB40781295E6@strout.net> References: <63F6CC9F-9BAF-4447-BCC4-FB40781295E6@strout.net> Message-ID: <48EE0750.9080409@chamonix.reportlab.co.uk> Joe Strout wrote: > Catching up on what's new in Python since I last used it a decade ago, > I've just been reading up on template strings. These are pretty cool! > However, just as a template string has some advantages over % > substitution for building a string, it seems like it would have > advantages over manually constructing a regex for string matching. > > So... is there any way to use a template string for matching? I > expected something like: ....... you could use something like this to record the lookups >>> class XDict(dict): ... def __new__(cls,*args,**kwds): ... self = dict.__new__(cls,*args,**kwds) ... self.__record = set() ... return self ... def _record_clear(self): ... self.__record.clear() ... def __getitem__(self,k): ... v = dict.__getitem__(self,k) ... self.__record.add(k) ... return v ... def _record(self): ... return self.__record ... >>> x=XDict() >>> x._record() set([]) >>> x=XDict(a=1,b=2,c=3) >>> x {'a': 1, 'c': 3, 'b': 2} >>> '%(a)s %(c)s' % x '1 3' >>> x._record() set(['a', 'c']) >>> a slight modification would allow your template match function to work even when some keys were missing in the dict. That would allow you to see which lookups failed as well. -- Robin Becker From pmezard at gmail.com Tue Oct 28 19:13:57 2008 From: pmezard at gmail.com (=?UTF-8?B?UGF0cmljayBNw6l6YXJk?=) Date: Wed, 29 Oct 2008 00:13:57 +0100 Subject: urlsplit() and windows paths Message-ID: <49079cb6$0$6000$426a74cc@news.free.fr> Hello, Why does urlparse.urlsplit() succeed here ? """ Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import urlparse >>> urlparse.urlsplit('c:\\foo\\bar') ('c', '', '\\foo\\bar', '', '') """ Documentations (of urlparse(), referenced by urlsplit()) states: """ Parse a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL: scheme://netloc/path;parameters?query#fragment. """ What kind of URLs does it parse not containing "://" ? -- Patrick M?zard From c.bertsche at tecplot.com Tue Oct 28 14:06:31 2008 From: c.bertsche at tecplot.com (Callie Bertsche) Date: Tue, 28 Oct 2008 11:06:31 -0700 Subject: zipping a directory Message-ID: Hey Python-ers, I apologize if this is covered in the archives; I think I saw one instance of it but I couldn't get the solution to work out. I'm working on zipping an entire directory to one zip file. I can zip a flat group of files, but when my code encounters a hierarchy of folders, for some reason it starts to zip everything on my desktop (instead of everything inside one folder directory on desktop). Then it goes into an infinite loop and barfs. Here's what I have so far: import zipfile import glob, os def main(): directory = "test\*" (success,filename)=createZipFile(directory); if success == 1: print "Operation completed. All files written to zip." else: print "Operation failed." def createZipFile(directory): zippedHelp = zipfile.ZipFile("help.zip", "w" ) for entity in directory: if os.path.isfile(entity): zippedHelp.write(entity,os.path.basename(entity),zipfile.ZIP_DEFLATED) else: addFolderToZip(zippedHelp,entity) zippedHelp.close() return (1,zippedHelp) def addFolderToZip(zippedHelp,folder): for file in folder: if os.path.isfile(file): zippedHelp.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(zippedHelp,file) main() Thanks for any help!! :) Callie -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Thu Oct 9 09:00:26 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 9 Oct 2008 08:00:26 -0500 Subject: How to calculate two time? In-Reply-To: References: <3d16f21a-c131-4801-ad10-0c6b3d189f6e@s9g2000prg.googlegroups.com> Message-ID: <18670.106.661271.593594@montanaro-dyndns-org.local> lookon> but can you tell me what format is it? Read the strftime man page on your computer or Google for strftime or read the Python docs about the time.strftime function. (strftime and strptime strive to have the same set of format characters.) Skip From gcmartijn at gmail.com Tue Oct 7 14:50:51 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Tue, 7 Oct 2008 11:50:51 -0700 (PDT) Subject: print command don't work (subscripted) word[2:4] Message-ID: <4c3e5cd3-182d-4539-b211-b30739c30603@n38g2000prl.googlegroups.com> Why is this not working ? bla = 'hondenriem' print bla[0:4] # correct ! (= hond) print bla[3:2] # nothing ! (= en) print bla[6:3] # nothing ! (= riem) Why don't bla[3:2] and bla[6:3] won't work ? I use this version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 http://docs.python.org/tutorial/introduction.html#strings word = 'HelpA' >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' From support.desk.ipg at gmail.com Wed Oct 15 11:09:06 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 15 Oct 2008 10:09:06 -0500 Subject: account balance checker In-Reply-To: References: Message-ID: <3DC3719BC2F94B18A57B5A041BC36A95@office.ipglobal.net> Hello all, I was wondering if it would be possible to make a script to grab my balance account balance a few times a day without having to login every time. I know I can use the urlib2 library, but not sure how to go about filling in the forms and submitting them. BOA has a mobile site that is pretty simple. Anyone else use Bank of America and would be interested in this. This is not for anything illegal, just for me to prevent overdrafting my account https://sitekey.bankofamerica.com/sas/signonScreen.do?isMobileDevice=true y = urllib.urlopen('https://sitekey.bankofamerica.com/sas/signonScreen.do?isMobl eDevice=true',urllib.urlencode({'onlineID':'MYONLLINEID'})).readlines() From kay.schluehr at gmx.net Fri Oct 10 08:35:18 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 10 Oct 2008 05:35:18 -0700 (PDT) Subject: python 3: sorting with a comparison function References: <6l74hpFauga7U1@mid.individual.net> Message-ID: On 9 Okt., 22:36, bearophileH... at lycos.com wrote: > Yes, that's a wonderful thing, because from the code I see around > 99.9% of people see the cmp and just use it, totally ignoring the > presence of the 'key' argument, that allows better and shorter > solutions of the sorting problem. Me too because I don't get this: "key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None." Kay From philip at semanchuk.com Thu Oct 16 09:55:45 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 16 Oct 2008 09:55:45 -0400 Subject: urllib accept-language doesn't have any effect In-Reply-To: <48F71C74.5050704@rwth-aachen.de> References: <48F5F530.9010805@rwth-aachen.de> <5E4DC4DF-DFB0-4FD8-92B4-549D4B01251D@semanchuk.com> <48F71C74.5050704@rwth-aachen.de> Message-ID: <039F1A07-6ED0-4185-8848-A791EEE04FF7@semanchuk.com> On Oct 16, 2008, at 6:50 AM, Martin Bachwerk wrote: > Hmm, thanks for the ideas, > > I've checked the requests in Firefox one more time after deleting > all the cookies and both google.com and gizmodo.com do indeed > forward me to the German site without caring about the browser > settings. > > wget shows me that the server does a 302 redirect straight away.. > soo.. I'm not sure what you mean by this. In my experiment with wget, Google respects the Accept-Language header. On other words, this returns a Swedish page even though I'm executing it from a U.S. IP address: wget "--header=Accept-Language: sv" http://www.google.com/ I see the same behavior from urllib2, although my code is slightly different from yours. Here's my code. If I use "sv" in the header I get Swedish, "pl" gives me Polish, etc. I get the same result when I add your Mozilla user-agent string. ---------------------------------------- import urllib2 headers = { "Accept-Language" : "sv" } req = urllib2.Request("http://www.google.com/", None, headers) f = urllib2.urlopen(req) content = f.read() f.close() print content ---------------------------------------- Do you get different results with this same code in Germany? Cheers Philip > >> >> On Oct 15, 2008, at 9:50 AM, Martin Bachwerk wrote: >> >>> Hello, >>> >>> I'm trying to load a couple of pages using the urllib2 module. The >>> problem is that I live in Germany and some sites seem to look at >>> the IP of the client and forward him to a localized page.. Here's >>> an example of the code, how I want to access google.com main >>> english page, but get German instead. (For those of you who live >>> in US, you will probably get correct results.. try emulating with >>> 'fr' in accepted languages or something) >>> >>> opener = urllib2.build_opener() >>> opener.addheaders = [('Host', 'www.google.com'), ('Accept- >>> Language','en-gb,en;q=0.5'), ('User-agent', 'Mozilla/5.0 (Windows; >>> U; Windows NT 5.1; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/ >>> 3.0.1')] >>> webfile = opener.open(url) >> >> Martin, >> It looks to me like what you're sending is correct. Debugging >> suggestions -- >> >> - Set up a Web server on 127.0.0.1 and see what that server >> receives when your Python code connects to it. Maybe you're not >> sending quite what you think. >> - Try emulating your Python code with wget or a similar command >> line tool that lets you set headers. >> - Sniff the conversation you're having with google using Wireshark. >> Maybe you're getting redirected by the remote server. >> >> Good luck >> Philip >> > From dotancohen at gmail.com Tue Oct 14 10:23:27 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 14 Oct 2008 16:23:27 +0200 Subject: Can Python fix vcard files? In-Reply-To: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> References: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> Message-ID: <880dece00810140723q7635a236ke4e7003454fc7d52@mail.gmail.com> 2008/10/14 Paul Boddie : >> Can Python go through a directory of files and replace each instance >> of "newline-space" with nothing? The system is Ubuntu 8.04 with KDE if >> it matters. Thanks. > > You should file a bug against Kontact: the KDE developers love fixing > bugs, especially in their old work. ;-) > I had to reopen an old bug on this: https://bugs.kde.org/show_bug.cgi?id=68350 I would really appreciate it if the knowledgeable folks here would chime in on that bug. Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From Tribulations at Paralleles.invalid Mon Oct 27 18:50:08 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 27 Oct 2008 23:50:08 +0100 Subject: question about the textwrap module Message-ID: <06tht5-dhf.ln1@rama.nodalpoint> Hi everybody, Recently, I have tried to improve the look of the printed text in command line. For this, I was compelled to remove redundant spaces in strings, because in my scripts, often the strings are spreading on several lines. For example, "aaa bbb" had to be transformed in "aaa bbb". I have coded some simple functions to do that. Today, by examining Python documentation, I have found an interesting module: http://www.python.org/doc/2.5.2/lib/module-textwrap.html But, I haven't found any way to do my redundant space deletion with this module? Am I right? Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z (55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From sjmachin at lexicon.net Thu Oct 23 06:46:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 23 Oct 2008 03:46:54 -0700 (PDT) Subject: why does math.pow yields OverflowError (while python itself can calculate that large number) References: <84433286-df55-491a-a310-17b072e8b71a@e2g2000hsh.googlegroups.com> Message-ID: <9a8e1534-1101-4eb5-9bd3-52e94940a775@o4g2000pra.googlegroups.com> On Oct 23, 9:24?pm, Tzury Bar Yochay wrote: > > Because math.pow returns a float; 100 ** 155 won't fit in a float. > > Sure that is the reason. > May I rephrase, my question: > Why not returning another type as long as we can calculate it? > After all, math module is likely to be used on large numbers as well. The math module is intended to replicate the functionality found in math.h in the C Standard Library; that's it, no more, no less. There are other libraries if you want more-than-float precision. From orestis at orestis.gr Tue Oct 21 05:18:34 2008 From: orestis at orestis.gr (Orestis Markou) Date: Tue, 21 Oct 2008 10:18:34 +0100 Subject: Triple-quoted strings hath not the Python-nature In-Reply-To: References: Message-ID: from textwrap import dedent dedent("""\ this is a multi-line string.""") will do what you want On Tue, Oct 21, 2008 at 9:58 AM, Lawrence D'Oliveiro wrote: > If triple-quoted strings had the Python-nature, then they would take > indentation into account. Thus: > > """this > is a > multi-line > string.""" > > would be equivalent to > > "this\n is a\n multi-line\nstring." > > and not > > "this\n is a\n multi-line\n string." > > The rule would be: the exact same whitespace characters at the beginning of > the line on which the triple-quoted string starts must also occur at the > start of the lines on which the string continues; these are stripped off > and not included in the string contents. Any additional whitespace is of > course part of the string. > -- > http://mail.python.org/mailman/listinfo/python-list > -- orestis at orestis.gr http://orestis.gr From tjreedy at udel.edu Fri Oct 10 17:32:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Oct 2008 17:32:15 -0400 Subject: Python 2.5.3: call for patches In-Reply-To: References: Message-ID: troelswh at gmail.com wrote: > On Oct 7, 9:27 am, "Martin v. L?wis" wrote: >> In principle, the release will include all changes that are already on >> the release25-maint branch in subversion [1]. If you think that specific >> changes should be considered, please create an issue in the bug tracker >> [2], and label it with the 2.5.3 version. Backports of changes that >> are already released in Python 2.6 but may apply to 2.5 are of >> particular interest. > > There is a number of Python 2.5.2 security vulnerabilities registered > with CVE. It would be great if the 2.5.3 release included fixes for > all of these! > > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3144 This references http://bugs.python.org/issue2588 http://bugs.python.org/issue2589 both of which report fixes backported to 2.5.3 I will let you investigate whether the name is true of the rest, or whether someone should be nudged to either report or submit a patch or help review a patch. > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-3142 > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2316 > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2315 > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1887 > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1721 > http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1679 > > For some reason none of these have made it into Python security > advisories (http://www.python.org/news/security/), but many vendors > who ship Python have released patched versions already. Presumably, none were considered really critical, or the volunteer core developers were busy doing something else. Also, release schedules differ. From chaim at chaim.com Fri Oct 31 14:53:30 2008 From: chaim at chaim.com (Chaim Krause) Date: Fri, 31 Oct 2008 11:53:30 -0700 (PDT) Subject: split() and string.whitespace Message-ID: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> I am unable to figure out why the first two statements work as I expect them to and the next two do not. Namely, the first two spit the sentence into its component words, while the latter two return the whole sentence entact. import string from string import whitespace mytext = "The quick brown fox jumped over the lazy dog.\n" print mytext.split() print mytext.split(' ') print mytext.split(whitespace) print string.split(mytext, sep=whitespace) From bignose+hates-spam at benfinney.id.au Tue Oct 21 09:02:58 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 22 Oct 2008 00:02:58 +1100 Subject: IRC References: <5e6f515f-e4a5-4e06-a2a2-b8977b019ceb@p59g2000hsd.googlegroups.com> Message-ID: <87prlu3xtp.fsf@benfinney.id.au> Amie writes: > Please can you perhaps provide me with links or good places where I > can learn what IRC is [?] A rather strange request on a forum dedicated to the Python programming language. Nevertheless, you will likely find useful. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but this time *you* put the trousers on the chimp.? | _o__) ?_Pinky and The Brain_ | Ben Finney From luke.leighton at googlemail.com Sat Oct 11 15:40:34 2008 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 11 Oct 2008 12:40:34 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> Message-ID: <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> On Oct 11, 3:31 pm, David Boddie wrote: > On Saturday 11 October 2008 11:19, lkcl wrote: > > > pyqt4 has the concept of layouts. a layout can be a horizontal > > layout, vertical, grid, and you can even specify the percentage or > > ratio of the width (or height) that individual cells can use. you > > attach a layout to a widget; you can attach layouts to layouts. you > > can remove layouts from widgets. what you _can't_ do is _remove_ > > layouts from layouts. > > You can remove layouts from layouts with the QLayout.removeItem() method. yes... it didn't work. a layout within a layout - i think it was a QHorizontalLayout within a QGridLayout - didn't want to be removed. it's probably a bug. > These days, you'd probably use PyQt4's WebKit integration for HTML > rendering, anyway, though I imagine that it doesn't help you much if > you're already using WebKit directly. [see below...] > You can write your own layouts as well, but maybe that's more work than > you're prepared to do, definitely. > especially now that you seem to have settled on > WebKit as your toolkit. well, it just made vast amounts of sense - cut out all the middle men. if you're going to pull in a 17mb binary dependency, why do it in a clumsy way? in order to pull in flash plugins and other material, the accepted method in pygtk2 is to use python-gtk-mozplugger. that's crazy. embed an _entire_ web browser, just to pull in a flash component. likewise, for doing a single bit of HTML, in pyqt4 and/or pygtk2, pull in a 17mb binary dependency using python-webkit-qt4 and/or pywebkitgtk, _just_ to display _one_ bit of HTML text?? _that's_ crazy. especially as webkit actually has far better rendering capability, features and flexibility than any of the standard desktop widget sets which had been designed for the job! wonderfully ironic... oh - for completeness, if anyone's reading this and goes "no chance i will _ever_ convert to the pyjamas API because i've spent so much time writing pygtk2 apps" - there is a project by luis pamirez, where he has _reimplemented_ gtk.py, gobject.py and gdk.py to sit _on top_ of the pyjamas DOM model. at present, it's only available in the subversion repository of http://code.google.com, and you'll need to check out a revision some time around sep 2007 of the llpamies branch. basically, what that will give you is a means to run your pygtk2 applications... in a web browser! very cool. i'll do a port to pyjamas-desktop at some time, if i have a need for it, and will be happy to help guide anyone who wants to spend the time on it themselves. > especially now that you seem to have settled on WebKit as your toolkit. well, it's not _my_ toolkit - i just use it. but you're right inasmuch as i won't be initiating any new applications using pyqt4 or pygtk2, not out of personal choice, anyway. l. From antroy at gmail.com Wed Oct 22 08:07:53 2008 From: antroy at gmail.com (Ant) Date: Wed, 22 Oct 2008 05:07:53 -0700 (PDT) Subject: Python search path (on Windows) References: Message-ID: On Oct 22, 10:03?am, "wooly booly" wrote: > I would like to execute a Python script from Windows command line: > > Python myscript.py > > This works if myscript.py resides in the current folder. My question is: > Is it possible to execute the command above from another folder? > > I put the script's folder in the PYTHONPATH environment variable but this > didn't help. > > Thanks for your help! You can put the script directory in the PATH environment variable, and call it with just: myscript.py From nono.231 at gmail.com Sat Oct 25 18:07:53 2008 From: nono.231 at gmail.com (I. Soumpasis) Date: Sat, 25 Oct 2008 23:07:53 +0100 Subject: [Numpy-discussion] [SciPy-user] ANN: Python programs for epidemic modelling In-Reply-To: <490393B1.7030904@american.edu> References: <3ff92a550810251314m18d0596fxffb0a09658a21260@mail.gmail.com> <490393B1.7030904@american.edu> Message-ID: <3ff92a550810251507q3696aa15x46f5b96684ff7f3c@mail.gmail.com> 2008/10/25 Alan G Isaac > On 10/25/2008 4:14 PM I. Soumpasis apparently wrote: > > http://blog.deductivethinking.com/?p=29 > > This is cool. > But I do not see a license. > May I hope this is released under the new BSD license, > like the packages it depends on? > > The programs are GPL licensed. More info on the section of copyrights http://wiki.deductivethinking.com/wiki/Deductive_Thinking:Copyrights. I hope it is ok, Ilias -------------- next part -------------- An HTML attachment was scrubbed... URL: From redetin at gmail.com Thu Oct 23 08:46:05 2008 From: redetin at gmail.com (Jani Tiainen) Date: Thu, 23 Oct 2008 05:46:05 -0700 (PDT) Subject: Slow comparison between two lists References: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> Message-ID: On 23 loka, 15:24, Peter Otten <__pete... at web.de> wrote: > Jani Tiainen wrote: > > I have rather simple 'Address' object that contains streetname, > > number, my own status and x,y coordinates for it. I have two lists > > both containing approximately 30000 addresses. > > > I've defined __eq__ method in my class like this: > > > ? ? def __eq__(self, other): > > ? ? ? ? return self.xcoord == other.xcoord and \ > > ? ? ? ? ? ? self.ycoord == other.ycoord and \ > > ? ? ? ? ? ? self.streetname == other.streetname and \ > > ? ? ? ? ? ? self.streetno == other.streetno > > > But it turns out to be very, very slow. > > > Then I setup two lists: > > > list_external = getexternal() > > list_internal = getinternal() > > > Now I need get all all addresses from 'list_external' that are not in > > 'list_internal', and mark them as "new". > > > I did it like this: > > > for addr in list_external: > > ? ? if addr not in list_internal: > > ? ? ? ? addr.status = 1 # New address > > > But in my case running that loop takes about 10 minutes. What I am > > doing wrong? > > Even if list_external and list_internal contain the same items you need > about len(list_external)*(len(list_internal)/2), or 45 million comparisons. > You can bring that down to 30000*some_small_factor if you make your > addresses hashable and put the internal ones into a dict or set > > def __hash__(self): > ? ?return hash((self.xcoord, self.yccord, self.streetname, self.streetno)) > def __eq__(self, other): > ? ?# as above > > Then > > set_internal = set(list_internal) > for addr in list_external: > ? ? if addr not in set_internal: > ? ? ? ? addr.status = 1 > > Note that the attributes relevant for hash and equality must not change > during this process. Very complete answer, thank you very much. I tried that hash approach and sets but it seemed to get wrong results first time and it was all due my hash method. Now it takes like 2-3 seconds to do all that stuff and result seem to be correct. Apparently I have lot to learn about Python... :) -- Jani Tiainen From tjreedy at udel.edu Mon Oct 6 21:29:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 06 Oct 2008 21:29:27 -0400 Subject: Python 2.6: Determining if a method is inherited In-Reply-To: References: <0b330a07-75bb-41a8-8ded-98a2f6ea76b1@v53g2000hsa.googlegroups.com> Message-ID: Fuzzyman wrote: > On Oct 6, 7:02 pm, Terry Reedy wrote: >> fuzzyman wrote: >>> Doesn't sound like a particularly *good* solution to me. :-) >> From what you posted, 'type object at' should work. > > It's still a hack... I am sorry if I offended you by pointing out to you a quick and dirty solution that would solve your problem immediately. From miki.tebeka at gmail.com Tue Oct 14 17:04:05 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 14 Oct 2008 14:04:05 -0700 (PDT) Subject: C API with *args and **kw References: Message-ID: <6b18a23a-c945-49ef-8ebd-50e9b37003c4@f37g2000pri.googlegroups.com> > > I'm try to write the C equivalent of: > > Use PyArg_ParseTupleAndKeywords() to parse the args and kwargs objects. Couldn't figure out how to get *args with ParseTupleAndKeywords. Thanks, Miki From bearophileHUGS at lycos.com Thu Oct 2 18:11:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 2 Oct 2008 15:11:12 -0700 (PDT) Subject: Inheritance but only partly? References: Message-ID: Gary Herron: > You can also redefine the ones you don't want inherited: > class A: > def DontInheritMe(self, ...): > ... > Class B(A): > def DontInheritMe(self, ...): > raise NotImplementedError // Or some such I have never used something like this, but the OP may use a masking class too: class A(object): def m1(self): pass def m2(self): pass def m3(self): pass def m4(self): pass class Mask(object): def m3(self): raise NotImplementedError def m4(self): raise NotImplementedError class B(Mask, A): pass a = A() a.m1() a.m2() a.m3() a.m4() b = B() b.m1() b.m2() b.m3() # raises b.m4() # raises In a language without multiple inheritance you need a different trick, I presume. What's the name of this python design pattern? :-) Bye, bearophile From gagsl-py2 at yahoo.com.ar Fri Oct 3 04:33:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 03 Oct 2008 05:33:32 -0300 Subject: code critique requested - just 60 lines References: Message-ID: En Fri, 03 Oct 2008 05:07:41 -0300, Terrence Brannon escribi?: > On Oct 2, 11:56?am, bearophileH... at lycos.com wrote: >> Terrence Brannon, I suggest you to shorten a lot some of those very >> long lines. > > yes, I wanted to, but was not sure how to continue a line on the next > line in Python. Having ANY open () or [] or {} is enough to implicitely continue a line (being it a function call, a list definition, a generator expression, whatever...) tags = { 'S': 'Small', 'M': 'Medium', 'L': 'Large', 'XL': 'Extra large', } Also, you may use \ as the LAST character (immediately preceding the newline) to continue the logical line on the next physical line: result = coef[0] * sum_deliverd + \ coef[1] * max_income + \ coef[2] * min_delay -- Gabriel Genellina From bruno.42.desthuilliers at websiteburo.invalid Wed Oct 1 05:50:11 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 01 Oct 2008 11:50:11 +0200 Subject: One class per file? In-Reply-To: References: Message-ID: <48e347af$0$19545$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > , HCB > wrote: > >> The book "Code Complete" recommends that you put only one class in a >> source file ... > > That would only apply to languages like C with no namespace control. classes in C ?-) OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++ (which both have namespaces one way or another) From castironpi at gmail.com Sat Oct 11 14:34:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 11 Oct 2008 11:34:00 -0700 (PDT) Subject: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x] References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> <87myhjcu7g.fsf@hbox.dyndns.org> <00f89ca3$0$20633$c3e8da3@news.astraweb.com> <01004dd8$0$20646$c3e8da3@news.astraweb.com> Message-ID: <2bd3d3ce-ef37-4439-aa00-6e0fdc6826dc@v28g2000hsv.googlegroups.com> On Oct 11, 2:23?am, Steven D'Aprano wrote: snip > I am talking about a clash between *conventions*, where there could be > many argument names of the form a_b which are not intended to be two item > tuples. > > In Python 2.x, when you see the function signature > > def spam(x, (a, b)) > > it is clear and obvious that you have to pass a two-item tuple as the > second argument. But after rewriting it to spam(x, a_b) there is no such > help. There is no convention in Python that says "when you see a function > argument of the form a_b, you need to pass two items" (nor should there > be). > > But given the deafening silence on this question, clearly other people > don't care much about misleading argument names. No, we just document them. (ducks) And ambiguous is different from misleading anyway. If the docs say pass a 2-tuple as the 2nd parameter...? From kay.schluehr at gmx.net Thu Oct 30 02:39:08 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 29 Oct 2008 23:39:08 -0700 (PDT) Subject: beutifulsoup References: <7d11954e-5e8b-4ed1-8c12-432c8ffef95b@k37g2000hsf.googlegroups.com> Message-ID: On 29 Okt., 17:45, luca72 wrote: > Hello > I try to use beautifulsoup > i have this: > sito = urllib.urlopen('http://www.prova.com/') > esamino = BeautifulSoup(sito) > luca = esamino.findAll('tr', align='center') > > print luca[0] > > >>#144.4MB Pc-prova.rar > > I need to get the following information: > 1)Only|G|BoT|05 > 2)#1 > 3)44.4MB > 4)Pc-prova.rar > with: print luca[0].a.string i get #1 > with print luca[0].td.string i get 44.4MB > can you explain me how to get the others two value > Thanks > Luca The same way you got `luca` 1,2) luca.find("a")["onclick"].split("'") and search through the result list 3) luca.find("td").string 4) luca.find("font").string From opsbat at infomed.sld.cu Thu Oct 30 00:22:29 2008 From: opsbat at infomed.sld.cu (Michel Perez) Date: Wed, 29 Oct 2008 23:22:29 -0500 Subject: about recursive load Message-ID: <1225340549.8863.43.camel@cerebellum> Hi, am very newbie in Python, but as part of a project i need to load configuration -a settings.py file in the package dir- of my apps recursively, something like this: settings.load_config("project.test.app") ?settings.load_config("project.test.*") ?settings.load_config("project.test") ?settings.load_config("*") this allows me to load them as: settings.project.CONFIG_PARAMETER_1 # project configuration settings.project.test.CONFIG_PARAMETER_1 # sub project and so on. This it's what i've done, class Settings: def __getattr__( self, attr): return self.__dict__['flags'][attr] def __setattr__(self, attr, value): self.__dict__['flags'][attr]=value def __init__(self, package = None, parent = None): self.__package = package self.__parent = None self.__dict__['flags']={} def get_parent ( self): return self.__parent def create_config_structure( self, pkg, parent = None ): # ... assuming no error and all that if pkg.count(".") > 0: if parent is None: if not self.__dict__['flags'].has_key(pkg[:pkg.find(".")]): father=self.__dict__['flags'][pkg]=Settings( \ pkg[:pkg.find(".")],self) else: father = parent else: if not parent.__dict__['flags'].has_key(pkg[:pkg.find(".")]): father=parent.__dict__['flags'][pkg[:pkg.find(".")]]= \ Settings(pkg[:pkg.find(".")], parent) else: father = parent self.create_config_structure( pkg [pkg.find(".")+1:],father) else: if not parent.__dict__['flags'].has_key: parent.__dict__['flags'][pkg]=Settings(pkg,parent) return parent.__dict__['flags'][pkg] def load_config ( self, pkg= None ): config_module_object = self.create_config_structure( pkg ) # the loading configuration part try: if pkg is not None: mod = __import__( pkg + ".settings", {},{},['']) else: mod = __import__( "settings", {},{},['']) except: raise ImportError("Settings not found") data={} for setting in dir(mod): if setting == setting.upper(): data[setting]=getattr(mod, setting) for key in data: if pkg is not None: setattr( config_module_object.__dict__['flags'], key, data[key]) else: setattr(self.__dict__['flags'], key, data[key]) Any idea it's welcome --------------------------------------- Red Telematica de Salud - Cuba CNICM - Infomed From rt8396 at gmail.com Fri Oct 31 13:28:43 2008 From: rt8396 at gmail.com (r) Date: Fri, 31 Oct 2008 10:28:43 -0700 (PDT) Subject: how to run python file from the python IDLE editor References: Message-ID: On Oct 31, 1:33?am, "Seid Mohammed" wrote: > Greetins all > 1. I can easily run python file from a comand prompt just typing > "python filname.py". > How can I do this from the python IDLE shell > 2. How to create EXE in python. > thanks all for making me to be more copnfortable with python > Seid M > > -- > "RABI ZIDNI ILMA" normally you open the file in IDLE and "RUN" it. not call it like from CMD -or- use execfile() funtion: >>> execfile(filename, globals, locals) From david at boddie.org.uk Sat Oct 11 11:31:58 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 11 Oct 2008 17:31:58 +0200 Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> Message-ID: On Saturday 11 October 2008 11:19, lkcl wrote: > pyqt4 has the concept of layouts. a layout can be a horizontal > layout, vertical, grid, and you can even specify the percentage or > ratio of the width (or height) that individual cells can use. you > attach a layout to a widget; you can attach layouts to layouts. you > can remove layouts from widgets. what you _can't_ do is _remove_ > layouts from layouts. You can remove layouts from layouts with the QLayout.removeItem() method. > disappointingly, this was the killer, for me. it was just getting... > too complicated. i had already encountered advice that, in order to > implement the means to move widgets around, i should remove > *everything* and redo the layout. it just... wasn't happening. You'll need to delete the contents of those layouts yourself - maybe that's the real problem. You shouldn't need to redo the whole layout structure, though. > plus, i think also that there are problems, again, with the HTML > layout: you can't _entirely_ stop text-squashing. so, although pyqt4 > was _better_, it still wasn't _enough_. These days, you'd probably use PyQt4's WebKit integration for HTML rendering, anyway, though I imagine that it doesn't help you much if you're already using WebKit directly. [...] > QT4 lacks crucial layout management (layouts not being deletable from > layouts), flow-layout, and variable-sized rich text. they _do_ have > proportional subdivision of layouts (allowing you to specify a fixed > width on one cell and a percentage width on others) but it is very > clumsy. You can write your own layouts as well, but maybe that's more work than you're prepared to do, especially now that you seem to have settled on WebKit as your toolkit. David From james at agentultra.com Thu Oct 16 17:39:12 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 16 Oct 2008 17:39:12 -0400 Subject: PYTHON WORKING WITH PERL ?? References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> Message-ID: <87abd46wzj.fsf@agentultra.com> Joshua Kugler writes: > Pat wrote: >>> Rewrite everything in python. Save yourself now...while you still >>> can. >>> >>> ~Sean >> >> Trust me. Sean is absolutely correct. I'm currently in the process of >> converting a large Perl project to Python (and learning Python at the >> same time) and the improvement in code is incredible. After you learn >> Python, you'll come to despise Perl. > > I'm not a Python fan-boy, but I'm going to have to agree with Sean too. I > had been using Perl on-and-off for some 10 years, when I finally had to > write a 500-ish line script in Perl for some data processing. It got messy > in a hurry. Is this a hash? Is it a reference to a hash? Is it a reference > to a hash of array references? Gaaah! I rewrote it in Python, and it was > so much easier to keep all my data structures straight. > > j Perl just gives you a lot of rope. You can do a lot of neat things with rope. ;) From prologic at shortcircuit.net.au Tue Oct 28 22:00:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 29 Oct 2008 12:00:12 +1000 Subject: gl Multiple versions of python In-Reply-To: <4907C183.2040206@g.nevcal.com> References: <4907B26F.4050807@g.nevcal.com> <4907C183.2040206@g.nevcal.com> Message-ID: On Wed, Oct 29, 2008 at 11:50 AM, Glenn Linderman wrote: >>> When using multiple versions of Python co-installed on the same system, >>> what happens with local .pyc files? If the .py is loaded with a >>> different version of Python, is the .pyc rebuilt (even if the .py hasn't >>> changed)? Worth having a look at virtualenv > Also for test code, is there a way to test the version of python which is > executing the code? Something like > > if __name__ == "__main__" #!/usr/bin/env python import sys def main(): print sys.version print sys.subversion print sys.hexversion print sys.api_version print sys.version_info if __name__ == "__main__": main() 2.5.2 (r252:60911, Oct 27 2008, 14:12:15) [GCC 4.2.4 (CRUX)] ('CPython', 'tags/r252', '60911') 33882864 1013 (2, 5, 2, 'final', 0) Read the sys documentation for the meaning of the attributes used aboave. cheers James -- -- -- "Problems are solved by method" From brianlong at cox.net Fri Oct 10 17:22:28 2008 From: brianlong at cox.net (brianrpsgt1) Date: Fri, 10 Oct 2008 14:22:28 -0700 (PDT) Subject: Read data from Serial Command References: <6PednQiTyPLyW3LVnZ2dnUVZ_uednZ2d@posted.visi> Message-ID: Thanks for the message What exactly is happening is that the return is "None" for the command that I am sending. If I connect through Hyperterminal and execute the 'sh nw enc' command, it returns 'WEP' I have confirmed that the serial port is correct and open with the s.isOpen() function. Also able to successfully connect in Hypterterminal with the same configuration settings. Grant Edwards wrote: > On 2008-10-10, brianrpsgt1 wrote: > > I am new to scripting. I am trying to read the settings from a serial > > device using Python. I have been able to successfully connect to the > > device and change baud rate settings, ect... with PySerial. I am > > trying to send a command to the serial device and capture the returned > > info, however, it is not working. > > It works fine for me. > > I'm afraid you're going to have to be a bit more detailed than > "it is not working". Are we supposed to guess what it's doing > and how that differs from what you want it to do? > > Do you have the serial cable plugged in? > > Is the device to which you're talking powered on? > > > Code is below: > > > > import serial > > import time > > > > s = serial.Serial(port=1, timeout=None, baudrate=9600) > > print s > > time.sleep(5) > > print "Enter CFG" > > s.write('CFG') > > print "Change baud" > > s.baudrate=115200 > > print s > > time.sleep(5) > > print "New line" > > s.write('\n') > > > > > > time.sleep(2) > > print "Show Encryption Setting" > > nw = s.write('sh nw enc') > > > > time.sleep(1) > > > > print nw > > s.close() > > -- > Grant Edwards grante Yow! Well, I'm INVISIBLE > at AGAIN ... I might as well > visi.com pay a visit to the LADIES > ROOM ... From martin at v.loewis.de Wed Oct 8 16:20:06 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 08 Oct 2008 22:20:06 +0200 Subject: Compiler, ast and forwards/backwards compatibility In-Reply-To: References: Message-ID: <48ed15f6$0$21887$9b622d9e@news.freenet.de> > My confusion starts with the fact that I'm not sure if all Python 2.4 > code is going to be syntactically valid 2.6 code. That's not so much a matter of confusion, but of careful research. I *think* all code that is syntactically correct in 2.4 is also syntactically correct in 2.6 - but only because raise "Hello" is still syntactically correct in 2.6 - it's a TypeError, not a SyntaxError. The other case would be assignment to None, but that was banned in 2.4 already. > I guess 2.3 is valid > 2.4 is valid 2.5 I think not so: assignment to None got disallowed, syntactically (can't test 2.3, at the moment). Regards, Martin From clp at rebertia.com Wed Oct 8 15:57:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 8 Oct 2008 12:57:12 -0700 Subject: Job Posting In-Reply-To: References: Message-ID: <47c890dc0810081257v5a8b9fa2r2c9b67a99397f2b8@mail.gmail.com> On Wed, Oct 8, 2008 at 9:20 AM, Capuano, Rebecca wrote: > HI, > > Would you be able to post this on your site? I don't know if you post jobs. > Thanks! This is a general-interest mailinglist about the Python programming language, not a way of directly contacting just the Python.org admins. Based on the Community --> Jobs page from the python.org website, you can find instructions on submitting a job posting on http://www.python.org/community/jobs/howto/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Our client in Princeton, NJ is looking for a Python Developer to join its > team. > > Description > A small to medium Python project needs a motivated developer to work with > the team lead. The position entails designing, implementing, and testing a > flexible schema definition and data cataloging front end for an image and > metadata management system. The project may include building a distributed > image repository system as well as the cataloging tool. The entire project > will eventually be released as open source software. > > 6-month+ project. > > Requirements > > 3+ years of Python experience preferably in a professional capacity. > Familiarity with JQuery, PIL, SQLAlchemy, PyProcessing, Pylons, Django. > Knowledge of functional programming is a plus. > Knowledge of image processing is a plus. > Excellent verbal and written communication skills. > > You will be required to write some python code as part of the interview > proces > > To apply please contact: > Rebecca Capuano > Sr. Recruiter > Information Technology and Engineering > TECHNISOURCE > 100 Wood Ave. South, Suite 208, Iselin, New Jersey 08830 > Direct 732.635.0700 x 227 | fax 800.258.9775 > rebeccacapuano at technisource.com | www.technisource.com > > -- > http://mail.python.org/mailman/listinfo/python-list > > From Kevin.Smith at sas.com Fri Oct 24 15:51:07 2008 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Fri, 24 Oct 2008 14:51:07 -0500 Subject: PIL: Getting a two color difference between images Message-ID: I'm trying to get the difference of two images using PIL. The ImageChops.difference function does almost what I want, but it takes the absolute value of the pixel difference. What I want is a two color output image: black where the image wasn't different, and white where it was different. Right now I get black where it wasn't different, and abs(image1-image2) where it was different. It would be nice if I could specify the colors for difference and no difference. This sounds like it should be easy, but I just don't see how to do it. -- Kevin D. Smith From robert.kern at gmail.com Thu Oct 23 18:26:12 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 23 Oct 2008 17:26:12 -0500 Subject: python extensions: including project local headers In-Reply-To: <87ljwf2k9i.fsf@agentultra.com> References: <87vdvjxr03.fsf@dozer.localdomain> <87ljwf2k9i.fsf@agentultra.com> Message-ID: J Kenneth King wrote: > Philip Semanchuk writes: > >> On Oct 23, 2008, at 11:36 AM, J Kenneth King wrote: >> >>> Hey everyone, >>> >>> I'm working on a python extension wrapper around Rob Hess' >>> implementation of a SIFT feature detector. I'm working on a >>> computer-vision based project that requires interfacing with Python at >>> the higher layers, so I figured the best way to handle this would be >>> in >>> C (since my initial implementation in python was ungodly and slow). >>> >>> I can get distutils to compile the extension and install it in the >>> python path, but when I go to import it I get the wonderful exception: >>> >>> ImportError: /usr/lib/python2.5/site-packages/pysift.so: undefined >>> symbol: _sift_features >> >> Kenneth, >> You're close but not interpreting the error quite correctly. This >> isn't an error from the compiler or preprocessor, it's a library >> error. Assuming this is dynamically linked, your OS is reporting that, >> at runtime, it can't find the library that contains _sift_features. >> Make sure that it's somewhere where your OS can find it. > > This is basically what I was looking for help with. So far the project > directory is: > > /pysift > /sift > .. > /include > .. > sift.h > /src > .. > sift.c > /src > pysift.c > setup.py > > I thought I could just #include "sift.h" in pysift.c as long as > distutils passed the right -I path to gcc. > > Maybe I should compile the sift code as a shared object and link it to > my extension? How would I get distutils to build the makefile and tell > gcc how to link it? I don't recommend doing that, if you can avoid it. distutils does not really support that. If you can get the sift files to compile under distutils as part of the Extension, that is by far the best option. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From washakie at gmail.com Thu Oct 23 10:08:22 2008 From: washakie at gmail.com (John [H2O]) Date: Thu, 23 Oct 2008 07:08:22 -0700 (PDT) Subject: f2py Error - module crashes after several iterations... In-Reply-To: References: <20128015.post@talk.nabble.com> Message-ID: <20131768.post@talk.nabble.com> I can try, would you mind giving very brief instructions on how to 'run it under gdb'... thanks! I'll post results over at numpy-discussions. Robert Kern-2 wrote: > > John [H2O] wrote: >> Hello, >> >> I have a module created from a Fortran file to read in unformatted binary >> fortran output. It works fine for some datasets, but crashes with others. >> The strange thing is it will loop through several files before it >> crashes, >> then suddently giving me this output: > > Can you run it under gdb to get a more complete backtrace? Please join us > on > numpy-discussion. > > http://www.scipy.org/Mailing_Lists > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though > it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/f2py-Error---module-crashes-after-several-iterations...-tp20128015p20131768.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Mon Oct 20 18:13:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Oct 2008 18:13:31 -0400 Subject: Don't understand syntax error: unqualified exec is not allowed .. In-Reply-To: <48FCEC76.6080202@gmail.com> References: <48FCEC76.6080202@gmail.com> Message-ID: Stef Mientki wrote: > hello, > > I've syntax error which I totally don't understand: > > ########## mainfile : > import test_upframe2 > > if __name__ == '__main__': > var1 = 33 > code = 'print var1 + 3 \n' > test_upframe2.Do_Something_In_Parent_NameSpace ( code ) > > ########### file = test_upframe2 : > class Do_Something_In_Parent_NameSpace ( object ) : > def __init__ ( self, code ) : > def do_more ( ) : > nonvar = [3,4] > while len ( nonvar ) > 0 : # <<<=== > nonvar.pop() # <<<=== Indendation is screwed. Is the above all do_more body? > import sys > p_locals = sys._getframe(1).f_locals Which locals does this get you? __init__'s? (locals()?) > p_globals = sys._getframe(1).f_globals Isn't this just the same as globals()? > try : > exec ( code, p_globals, p_locals ) This is 3.0 exec function syntax. Postings should specify which interpreter you are running, especially when mucking with internals. > except : > print 'ERROR' > > > gives me: > SyntaxError: unqualified exec is not allowed in function '__init__' it > contains a nested function with free variables (gui_support.py, line > 408) > "unqualified exec" : I thought that meant there is some ambiguity in the > namespace, but I explictly definied the namespace > > The function "do_more" is never called, so what does it matter what's > in there ? > > If I remove the while-loop (which of course I can't) the syntax error > disappears. > > I can place the function either as a class method or as a normal > function outside the class, > which both works well. > But I want the method / function not to be hidden. Since you are hiding it, I presume you mean to be, not not to be. > > Why does the above syntax error appear ? > Are there other ways to hide the function ? Either use module level __all__ or name the function _do_more and anyone will know it is private to the module. From steve at REMOVE-THIS-cybersource.com.au Fri Oct 31 20:23:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Nov 2008 00:23:47 GMT Subject: split() and string.whitespace References: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> <911c4fe3-0c89-4c58-ae44-6cad5206f7fb@s9g2000prm.googlegroups.com> Message-ID: <011b9a55$0$20643$c3e8da3@news.astraweb.com> On Fri, 31 Oct 2008 12:18:32 -0700, Chaim Krause wrote: > I have arrived here while attempting to break down a larger problem. I > got to this question when attempting to split a line on any whitespace > character so that I could then add several other characters like ';' and > ':'. Ultimately splitting a line on any char in a union of > string.whitespace and some pre-designated chars. > > I am now beginning to think that I have outgrown split() and must move > up to regular expressions. If that is the case, I will go off and RTFM > on RegEx. Or just do this: s = "the quick brown\tdog\njumps over\r\n\t the lazy dog" s = s.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') s.split(' ') or even simpler: s.split() -- Steven From bdesth.quelquechose at free.quelquepart.fr Wed Oct 22 12:35:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 22 Oct 2008 18:35:35 +0200 Subject: [APSW] SELECT COUNT(*) not succesfull? In-Reply-To: References: Message-ID: <48ff7236$0$13233$426a34cc@news.free.fr> Gilles Ganault a ?crit : > Hello > > I'm trying to use the APSW package to access a SQLite database, but > can't find how to check if a row exists. I just to read a > tab-separated file, extract a key/value from each line, run "SELECT > COUNT(*)" to check whether this tuple exists in the SQLite database, > and if not, run an INSERT. > > The problem is that "if not row" isn't run: It is - the problem is that cursor.execute doesn't return what you think... Truth is that according to the db-api specification, the return value of cursor.execute is not defined (IOW : can be absolutely anything). FWIW, sqlite3 returns the cursor object itself and mysqldb returns (IIRC) the numbor of rows affected (selected, updated, whatever). Now I don't know what apsw is, but it's common for libraries to provide their own wrapping of the db-api. Anyway: it doesn't return a 'row' in any case. > ========== > import apsw > > connection=apsw.Connection("test.sqlite") > cursor=connection.cursor() > > data = {} > > f = open("data.tsv", "r") > textlines = f.readlines() > f.close() files are their own iterators, so you could just keep the file opened and iterate over it - might save you some memory if the file is huge. > p = re.compile('^(\d+)\t(\d+)$') > for line in textlines: > m = p.search(line) > if m: > data[m.group(1)] = m.group(2) You do understand that if m.group(1) appears more than one time in data.tsv, only the last value will be kept, do you ? > for (key,value) in data.items(): You don't need the parens around key, value here. > sql = "SELECT COUNT(*) FROM mytable WHERE key='%s'" % key > row=cursor.execute(sql) The recommended way is to pass the arguments to cursor.execute, ie: sql = "SELECT COUNT(*) FROM mytable WHERE key=%s" # cf below cursor.execute(sql, (key,)) NB : checks that for your implementation of the db-api, the placeholder is %s (this is implementation-specific). This will do all appropriate preparation of the arguments (quoting etc) and will protect you from sql injection. Also, you can now extract the sql= from the loop. Also, you may want to rewrite your query as "SELECT COUNT(key) FROM mytable (etc...)", which (depending on the database engine, the schema and a couple other considerations) might be a bit faster > #Why not run? > if not row: you want: row = cursor.fetchone() count = row[0] if not count: > print "Row doesn't exist : %s" % key > sql = "INSERT INTO mytable (key,value) VALUES ('%s',%u)" % > key,value same remark as above. > cursor.execute(sql) > > connection.close(True) > sys.exit() If it's the end of your script, this last statement is useless. HTH From jcd at sdf.lonestar.org Wed Oct 29 08:14:16 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 29 Oct 2008 08:14:16 -0400 Subject: Improving interpreter startup speed In-Reply-To: <8BD1F7BF-96B1-4B08-8383-2C1E498D6F38@gmail.com> References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <8BD1F7BF-96B1-4B08-8383-2C1E498D6F38@gmail.com> Message-ID: <1225282456.6950.0.camel@jcd-desktop> Maybe Ruby is the right language for your need. Just sayin'. On Sun, 2008-10-26 at 13:19 +0000, Pedro Borges wrote: > The scripts i need to run but be executed with no apparent delay > specially when the text transforms are simple. > > > On Oct 26, 2008, at 11:13 AM, James Mills wrote: > > > On Sun, Oct 26, 2008 at 11:23 AM, BJ?rn Lindqvist > > wrote: > >> How are you getting those numbers? 330 ?s is still pretty fast, > >> isn't > >> it? :) Most disks have a seek time of 10-20 ms so it seem implausible > >> to me that Ruby would be able to cold start in 47 ms. > > > > $ time python -c "pass" > > > > real 0m0.051s > > user 0m0.036s > > sys 0m0.008s > > > > $ time python3.0 -c "pass" > > > > real 0m0.063s > > user 0m0.048s > > sys 0m0.004s > > > > And yes I agree. the CPython interpreter startup times is > > a stupid thing to be worrying about, especially since that > > is never the bottleneck. > > > > Python loads plenty fast enough! > > > > --JamesMills > > > > -- > > -- > > -- "Problems are solved by method" > > -- > http://mail.python.org/mailman/listinfo/python-list From greg at cosc.canterbury.ac.nz Fri Oct 31 03:47:44 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 31 Oct 2008 20:47:44 +1300 Subject: Finding the instance reference of an object In-Reply-To: <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> References: <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <6mv3bnFj2qd8U1@mid.individual.net> <011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> Message-ID: <6mvrbiFj3eh4U1@mid.individual.net> Aaron Brady wrote: > Maybe I missed this part. What does the phrase, "value of variable x" > mean in Python? I didn't use the phrase "value of variable x" anywhere in my definitions, so it doesn't matter what it means, or even whether it means anything at all. > If "value of 'x'" is not defined, we should agree on a definition > that's really clear and useful, favoring useful. After that's > established, we can proceed to evaluating what 'call by value' would > behave like, which would then determine if Python behaves like it. There you go, getting distracted by that annoying word "value". Forget about it, we don't need it! -- Greg From leahspider4 at gmail.com Thu Oct 23 13:39:48 2008 From: leahspider4 at gmail.com (www.maidi2008.com) Date: Thu, 23 Oct 2008 10:39:48 -0700 (PDT) Subject: http://www.maidi2008.com/views.asp?big_id=131&sort_id=389&nsort_id=1273&hw_id=43533 Message-ID: <53ea8800-4ffb-4bab-971c-6727bf5547f9@v22g2000pro.googlegroups.com> Reply to: leahspider1 at gmail.com MSN:spiderleah01 at hotmail.com From christos.jonathan.hayward at gmail.com Fri Oct 3 16:21:22 2008 From: christos.jonathan.hayward at gmail.com (Jonathan Hayward) Date: Fri, 3 Oct 2008 13:21:22 -0700 (PDT) Subject: Tkinter setting alpha Message-ID: I'm trying to make a Tkinter/Python port of the demo at http://wiki.tcl.tk/10515 , which has adjustable alpha under Windows and (I think) MacOS. I'm not quite sure how to port: wm attributes . -alpha [expr {$alphaLevel + 0.05} ] set AlphaLevel [wm attributes . -alpha] The goal is to have a screen pop that fades in and out at least on Windows, and it would be nice if it could fade on other platforms (including my preferred Linux). Two questions: 1: Is Tkinter a good choice, or are there other libraries that are easier and/or will allow cross-platform GUI work with (ideally) fading in and out? 2: If I go with Tkinter, how can I port lines like those quoted above to be able to get and set a Frame's alpha value? -- -- Jonathan Hayward, christos.jonathan.hayward at gmail.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com ++ Would you like to curl up with one of my hardcover books? ++ You can now get my books from http://CJSHayward.com From lists at cheimes.de Wed Oct 8 16:11:49 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 08 Oct 2008 22:11:49 +0200 Subject: no unbound methods in py3k In-Reply-To: <6l4hiuFan1lpU1@mid.individual.net> References: <6l4hiuFan1lpU1@mid.individual.net> Message-ID: Thomas Heller wrote: > but this is very ugly, imo. Is there another way? > The raw_func instances that I have are not descriptors (they > do not implement a __get__() method...) I've written PyInstanceMethod_Type for this use case. It's not (yet) available for Python code. Barry hasn't decided whether he should expose the type so late in the release cycle or not. See http://bugs.python.org/issue3787 and http://docs.python.org/dev/3.0/c-api/method.html?highlight=pyinstancemethod#PyInstanceMethod_Type Christian From rtw at freenet.co.uk Sat Oct 4 14:57:49 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 04 Oct 2008 13:57:49 -0500 Subject: csv files for download References: Message-ID: Bobby Roberts wrote in news:cdc29298-d005-4804-b407-81ecaf6bb1b4@ 2g2000hsn.googlegroups.com in comp.lang.python: > I need to be able to offer a client "click to download" functionality > on their website. Generating the data to provide to them is not an > issue but I want them to be able to click a button and have the > response be sent to a csv file which they are prompted to download. > Can someone point me in the right direction how to do this in python. > Thanks in advance. Assuming your using WSGI (you don't say) it would be something like this: def wsgi( environ, start_response ): start_response( '200 OK', [ ('Content-Type','text/csv'), ('Content-Disposition', 'attachment; filename=whatever.csv') ]) ... If your using cgi it will be something like: print "Content-Type: text/csv" print 'Content-Disposition: attachment; filename=whatever.csv' print ... http://search.yahoo.com/search?p=Content-Disposition http://www.python.org/doc/2.5.2/lib/cgi-intro.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From pheeh.zero at gmail.com Fri Oct 10 06:55:17 2008 From: pheeh.zero at gmail.com (pheeh.zero at gmail.com) Date: Fri, 10 Oct 2008 03:55:17 -0700 (PDT) Subject: Porn Addiction Solutions? References: <8cdd5941-16cd-493a-bb8f-2e8dd4ac3eb0@g17g2000prg.googlegroups.com> Message-ID: <2f0dc683-4f1c-40d5-b669-c0eacd40a313@26g2000hsk.googlegroups.com> On Oct 10, 4:37?am, paul... at gmail.com wrote: > On Oct 9, 12:07?am, pavement... at yahoo.com wrote: > > > Help, I'm addicted to porn. I've been spending a lot of time > > downloading hardcore porn and masturbating to it. It's ruining my > > life. I just found out that one of these sites somehow hacked my card > > and rang up $5K in charges which they won't even refund me. Even with > > that I haven't stopped my habit and it's only getting worse. How can I > > end this addiction? > > > Any suggestions? > > It's very simple. You need to know the world is much more than the > imaginery life you are looking. Spend some time in the feet of the > Lord Jesus who would help you to come out of this trouble. Dear friend > remember Jesus came down to Earth died for you and me just for we to > be relieved from these bondages. I would also support you in prayers > that you are out of these troubles. > > Paul I have to compliment you guys with your suggestions and support. Most other groups would have a field day and not be helpful. Compassion is rarely present on usenet. From dotancohen at gmail.com Wed Oct 15 17:17:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 15 Oct 2008 23:17:06 +0200 Subject: Can Python fix vcard files? In-Reply-To: References: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> <1ddce4a8-e11c-4b06-9859-32d69407e1ac@r66g2000hsg.googlegroups.com> Message-ID: <880dece00810151417h7cc91abdv47b4cade9d67c6c6@mail.gmail.com> 2008/10/15 Lawrence D'Oliveiro : Thanks. The RFC pages for vcard (http://www.ietf.org/rfc/rfc2426.txt and http://www.ietf.org/rfc/rfc2425.txt) are very difficult for me to read. I'm using the test file to learn, and I will work out the kinks on other files that I come across. This is for personal use, not production, so I can be sloppy :) -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From grahn+nntp at snipabacken.se Sat Oct 18 13:54:47 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 18 Oct 2008 17:54:47 GMT Subject: Loosely-coupled development environment (was: IDE Question) References: <874p3dbn6f.fsf@benfinney.id.au> Message-ID: On Thu, 16 Oct 2008 07:47:36 +1100, Ben Finney wrote: > "Steve Phillips" writes: > >> I am just wondering what seems to be the most popular IDE. The >> reason I ask is I am currently at war with myself when it comes to >> IDE's. It seems like every one I find and try out has something in >> it that others don't and viceversa. > > This speaks to the twin facts that people want different things, and > that Python is flexible enough to accommodate these differing desires. > >> I am in search for the perfect IDE > > Perfect for whom, exactly? Perfect for what, exactly? > > These are not facetious questions: they cut to the core of your quest. > I am convinced that your quest for a development environment that is > ?integrated? (or ?tightly-coupled?, in programming terminology) is > incompatible with any useful criterion of ?perfect?. > > Instead, I find the greater gain comes from a working environment of > *loosely-coupled* tools, with standard well-defined interfaces, that > one can flexibly mold and reconnect to meet whatever task is at hand. > The deeper this extends into the operating system, the more the system > as a whole will be able to support this flexibility, and the more > likely the tools will have been designed to do so. > > Because of the inescapable central role in our craft of manipulating > text files, essential in this development environment is a > highly-customisable text editor with a broad *and* deep library of > existing customisations, to maximise the amount of work already done > for you when embarking on work in an area that is, to you, new. > > It happens that the text editors which meet these criteria are limited > to Emacs and Vim, with a sharp decline in suitability (by these > criteria) beyond those two. Both have powerful user-customisable > capabilities and a mammoth availability of existing extensions for a > staggering variety of tasks. Learn one of these editors well, > familiarise yourself with how to access the rich library of available > extensions, and make the text editor the core of your loosely-coupled > development environment. You think like I think, but I think your standards are too high. I like claiming "my IDE is Emacs and Unix", but in fact I know very little about how to customize Emacs using elisp -- I have added a few keyboard shortcuts, made it use a readable font, and disabled a few silly features, but that's about it. I use a Unix shell on the side to do the non-editing tasks which I guess you train your editor to do. So, my requirements on the editor boils down to: - free and universally available - will still be around when I'm dead - capable as a pure text editor - support for colorizing Python code (at least strings and comments) - helps me indenting Python code - support for other languages I hope many editors fulfill those criteria, except maybe the first two. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From dave.hirschfeld at gmail.com Tue Oct 14 08:45:07 2008 From: dave.hirschfeld at gmail.com (Dave) Date: Tue, 14 Oct 2008 12:45:07 +0000 (UTC) Subject: Reg: Installation problems in psycopg2 References: <4720aa3b-bdf9-4f8b-b134-45508c2811cd@t39g2000prh.googlegroups.com> Message-ID: gmail.com> writes: > I am trying to install psycopg2 in my windows machine for > connecting with the PostgreSQL server. > Since there is no binary executable*, I am trying to build my own > - and I am facing this issue. > > C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: > cannot find -lpq > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > After a little bit of googling, I found that this can be solved > by -L while linking - but I am not specifically > linking the code. Rather, I am installing by doing the following - I don't think the lpq library comes (in the correct format) with the latest versions of PostgreSQL hence I had the same problem which I never resolved. You can get windows binaries from http://www.stickpeople.com/projects/python/win-psycopg/ though. HTH, Dave From lie.1296 at gmail.com Sat Oct 25 04:36:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 25 Oct 2008 08:36:32 +0000 (UTC) Subject: How can I handle the char immediately after its input, without waiting an endline? References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> <29de18070810220417p331e17c1rbd9db9cb1fd9d578@mail.gmail.com> Message-ID: >>> I want to write something that handle every char immediately after its >>> input. Then tehe user don't need to type [RETURN] each time. How can I >>> do this? >>> >>> Thanks in advance. Don't you think that getting a one-character from console is something that many people do very often? Do you think that all these platform independent code should be moved to the interpreter level instead (and raises the appropriate error when the platform somehow cannot do unbuffered input)? So python developer could do something like this: raw_input(bufferring = 0) From nosklo at gmail.com Tue Oct 21 13:50:02 2008 From: nosklo at gmail.com (Clovis Fabricio) Date: Tue, 21 Oct 2008 15:50:02 -0200 Subject: csv.reader problem tab-delimiter - newbie In-Reply-To: <5397f383-fbbc-4b61-a327-3d5424812efd@8g2000hse.googlegroups.com> References: <9ba8e57b-97d0-4b66-8f35-6c07d54b1f46@2g2000hsn.googlegroups.com> <5397f383-fbbc-4b61-a327-3d5424812efd@8g2000hse.googlegroups.com> Message-ID: <9187a60d0810211050g3d370c86xecffd19b94c8fc4d@mail.gmail.com> 2008/10/21 : > grrr thanks George, thanks Daniel, that's it. Works fine with real > tabs. Now this brings me to a follow-up: I have not prepared the input > ascii file, I just got if for post-processing (23 MB). Now it seems > that I would have to replace all series of spaces in this file with > real tabs at first.. How would you do that? Are there text editors > capable of doing this? If the file you got isn't really tab delimited, you shouldn't convert it to a tab delimited file before processing. Just process it as it is, a multiple-space-delimited file. f = open('file.txt') for line in f: line = line.strip().split() # do whatever with data print line f.close() Cl?vis From tjreedy at udel.edu Wed Oct 22 12:39:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Oct 2008 12:39:15 -0400 Subject: How can I handle the char immediately after its input, without waiting an endline? In-Reply-To: <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> Message-ID: rishi pathak wrote: > The below piece of code should give you some understanding > > import tty > import sys > tty.setraw(sys.stdin.fileno()) > char='' > print "Press x to exit" > while char != 'x' : > char = sys.stdin.read(1) > print "You entered : ",char > # Your code here Does not work on Windows, at least with 3.0, as tty fails trying to import termios. There, use msvcrt module "msvcrt.kbhit() Return true if a keypress is waiting to be read. msvcrt.getch() Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function. " > > > On Wed, Oct 22, 2008 at 2:34 PM, Lave > wrote: > > Hi, all. > > I'm a new comer. So This question maybe sutpid.:) > > I want to write something that handle every char immediately after its > input. Then tehe user don't need to type [RETURN] each time. How can I > do this? > > Thanks in advance. > > > -- > Regards > > Lave > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Regards-- > Rishi Pathak > Pune-Maharastra > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From smullen.uclick at gmail.com Tue Oct 21 16:47:37 2008 From: smullen.uclick at gmail.com (Samuel) Date: Tue, 21 Oct 2008 13:47:37 -0700 (PDT) Subject: Resizing Tif's to smaller gifs adds pixels References: <1fc506d8-2f1e-4f80-b0ee-05fc5f3bf90a@v30g2000hsa.googlegroups.com> <94qdnZyVwOLDoWPVnZ2dnUVZ_ojinZ2d@pdx.net> Message-ID: <08395ae4-9527-4b0b-ad1e-cdc9fb340e06@p49g2000hsd.googlegroups.com> Scott, I appreciate the quick response, but I need this in a GIF format. Samuel On Oct 21, 3:46?pm, Scott David Daniels wrote: > smullen.ucl... at gmail.com wrote: > > ...I need to scale a TIFF image from 1925x588 px to a GIF of 600xnnn px. > > I've tried the following code, but it leads to a lot of extra odd > > colored pixels being inserted into the resulting image. > > img = "tmp/tmsho20080901.tif" > > im = Image.open("tmp/tmsho20080901.tif") > > w, h = im.size > > im.thumbnail((600, h * 600 / w), Image.ANTIALIAS) > > This line is rather silly, making a result that you drop on the floor.> newimg = im.resize((600, int(h * (600.0 / w))), Image.ANTIALIAS) > > newimg.save("tmsho20080901.gif") > > ... > > > Using ImageMagick's convert I would do this... > > > convert -colors 256 -resize 600 -colorspace RGB -black-threshold 100 - > > contrast -intent Perceptual tmp/tmsho20080901.tif tmsho20080901.gif > > > I think it may have something to do with the palette or the number of > > colors alotted for the resulting image, but I'm really not a graphics > > guy. > > Yep, you are right. ?The issue is trying to reduce to a 256-color > pallette. ?Try using '.png' format (portable network graphics), that > allows a full palette for exact pixel images. > > Try something like this: > ? ? ?im = Image.open("tmp/tmsho20080901.tif") > ? ? ?w, h = im.size > ? ? ?im.thumbnail((600, h * 600 // w), > ? ? ? ? ? ? ? ? ? Image.ANTIALIAS).save("tmp/sho20080901.png") > > --Scott David Daniels > Scott.Dani... at Acm.Org From stef.mientki at gmail.com Thu Oct 2 15:46:27 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 02 Oct 2008 21:46:27 +0200 Subject: how to find the directory where python is installed ? In-Reply-To: References: <48E51DFC.4040003@gmail.com> Message-ID: <48E52513.1010507@gmail.com> Timothy Grant wrote: > On Thu, Oct 2, 2008 at 12:16 PM, Stef Mientki wrote: > >> hello, >> >> how can I determine the location of the Python installation under winXP / >> Linux, >> with a Python program ? >> >> thanks, >> Stef Mientki >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > This what you're looking for? > > (tjg at bastard%) python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys >>>> sys.executable >>>> > '/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python' > Yes that might be sufficient. thanks, Stef From lie.1296 at gmail.com Wed Oct 1 13:22:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 1 Oct 2008 17:22:32 +0000 (UTC) Subject: Peek inside iterator (is there a PEP about this?) References: <200810011046.33309.kyrie@uh.cu> Message-ID: On Wed, 01 Oct 2008 10:46:33 -0400, Luis Zarrabeitia wrote: > Hi there. > > For most use cases I think about, the iterator protocol is more than > enough. However, on a few cases, I've needed some ugly hacks. > > Ex 1: > > a = iter([1,2,3,4,5]) # assume you got the iterator from a function and > b = iter([1,2,3]) # these two are just examples. > > then, > > zip(a,b) > > has a different side effect from > > zip(b,a) > > After the excecution, in the first case, iterator a contains just [5], > on the second, it contains [4,5]. I think the second one is correct (the > 5 was never used, after all). I tried to implement my 'own' zip, but > there is no way to know the length of the iterator (obviously), and > there is also no way to 'rewind' a value after calling 'next'. > > Ex 2: > > Will this iterator yield any value? Like with most iterables, a > construct > > if iterator: > # do something > > would be a very convenient thing to have, instead of wrapping a 'next' > call on a try...except and consuming the first item. > > Ex 3: > > if any(iterator): > # do something ... but the first true value was already consumed and > # cannot be reused. "Any" cannot peek inside the iterator without # > consuming the value. > > Instead, > > i1, i2 = tee(iterator) > if any(i1): > # do something with i2 > > Question/Proposal: > > Has there been any PEP regarding the problem of 'peeking' inside an > iterator? No (or I'm not aware of any). Why? Because for some iterable, it is not possible to know in advance its length (video data stream, for example), or whether it'd ever end (the digits of pi). Second, in python, iterator is a use-once object, it is not designed to be reused. Some languages, especially the purely functional ones, allow multiple use of iterator because they guarantee immutability, python allows mutable object, and is unable to provide that. > Knowing if the iteration will end or not, and/or accessing the > next value, without consuming it? No, it is not possible to do that for some iterators. For example, this code: import time class Iterable(object): def __iter__(self): return self def next(self): return time.time() if you peeked the iterator in advance, the result would be different compared to the result when you actually need it. > Is there any (simple, elegant) way > around it? Simple, but probably not that elegant, if you need such a fine control, use while loop. > Cheers, > > -- > Luis Zarrabeitia (aka Kyrie) > Fac. de Matem?tica y Computaci?n, UH. > http://profesores.matcom.uh.cu/~kyrie From sulyokpeti at gmail.com Thu Oct 16 02:41:14 2008 From: sulyokpeti at gmail.com (sulyokpeti at gmail.com) Date: Wed, 15 Oct 2008 23:41:14 -0700 (PDT) Subject: Deviation from object-relational mapping (pySQLFace) References: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> <9afaa4af-0e7a-4dda-9afb-28971165fb9c@n33g2000pri.googlegroups.com> Message-ID: On okt. 15, 09:04, J Peyret wrote: > On Oct 12, 8:19?am, sulyokp... at gmail.com wrote: > > > I would like to get some opinions on this approach. > > Thanks. > > I realize I will be minority here, but... > > I've never quite understood why folks want to repeat the database's > metadata in XML files. ?I've gotten much better results just using > plain ol' SQL throughout, sprinkled in with generated-on-the-fly SQL. I guess you have not seen the examples: https://fedorahosted.org/pySQLFace/browser/examples They help to understand what I wrote. > > 1. ?A select clause identifies what is coming back from the db in the > cursor's description. ?20 lines of code shoves that in a dictionary > for each row for any result set. ?'Select * from ' works 90% of > the time for 1 table queries. ?What does XML add? Yes, you get the columns back without documentation for a programmer, who does not now a thing about RBDMS. If you are good at both python and that specific RDBMS you use, you can make it. XML is independent from both the programming language API-s and the RDBMS specific 'retrieve the metadata' solutions. This is a key to freely combine any programming language with any RDBMS. If you put RDBMS specific features in your python code, your solution will depend on that feature. If you don't, you loose the feature. > > 2. ?Inserts and deletes are relatively trivial to derive from > INFORMATION SCHEMA lookups on any given table and templates can be > generated for them. ?Updates are admittedly less trivial, but not > horribly so. True. But again the programmer has to know how to use a database, which is not always the case. > > 3. ?Query parameters can be added by simple %()s embedded in > the query templates. ? ?That works great with dictionaries. ?You can > extract them with a regular expression and replace them with '?' and a > list, if your DB-API flavor requires that. First time, I made the examples this way, but the code was ugly. So I switched to lists (positional parameters). > > 4. ?Plain ol' SQL can be cut and pasted in a query editor and can be > tested there. Yes. The DB designer does it, and exports the SQL,DML with documentation embedded in XML for the programming developers. Excellent idea! > > 5. ?If you unit test somewhat aggressively, any db-schema changes will > result in unhappy queries dying because they don't see the columns > that they expect in the resultsets. ?That keeps your Python code in > synch without feeding a layer of XML cruft. Who knows better any DB schema changes than a DB designer who exports that XML? If the change has an impact on the SQL interface, the programmers have to be alerted of course. > > 6. ?XML is plain nasty for "simple local usage" where you don't need > to communicate with a 3rd party app or module. ?Conversely, XML is > great when you need to communicate data "somewhere else, potentially > with recursive and nested structures". I guess you do not have the proof of this theorem. > > 7. ?ANSI SQL is actually quite portable, if you know what to avoid > doing. ...and by using that, you loose the RDBMS specific features. > > 8. ?Last, but not least. ?Performance. This is a bluff. > > In complex processing on a database with large volumes, the last thing > you want to do is to fetch data to your client codeline, process it > there, and spew it back to the database. ?Instead you want to shoot > off series of updates/deletes/insert-selects queries to the server and > you want to rely on set-based processing rather than row-by-row > approaches. ?How do ORMs+XML help here? I think there is a reason for server side programming too. > > My biggest hassle has been managing connection strings and catching > the weird Exception structures every Python db module figures it has > to re-implement, not the SQL itself. Connection string is also stored in my XML. > > Granted, if this were Java, you would need special data transfer > objects to encapsulate the results. ?But is not Java. ?And, also > granted, I _enjoy_ coding in SQL rather than trying to hide from it, > so YMMV. DB experts should not hide from SQL, but it is better to keep other people away. > > Bottom line: ?SQL is extremely dynamic in nature, even more so than > Python. ?Why shackle it to static XML files? To develop both sides (DB design and client coding) independently. > > P.S. > > SQL Alchemy _is_ something I've been meaning to look at, because it > seems like they also _like_ SQL. They do not _like_ SQL. They _like_ python. From fthiel at stny.rr.com Fri Oct 17 15:40:07 2008 From: fthiel at stny.rr.com (Frank L. Thiel) Date: Fri, 17 Oct 2008 19:40:07 GMT Subject: PythonWin --> drwatson Message-ID: I have installed PythonWin from the distribution. When I try to open it, the message "PyWin32 has encountered a problem ..." appears, and a drwatson error report is generated. Python 2.6 itself, from a cmd window or using IDLE, works without problem. I cannot find any reports of similar behavior in FAQs, forums, or general "googling", and am looking for suggestions of remedies. Running WinXP Home, SP3. Many thanks in advance. From mail at timgolden.me.uk Mon Oct 20 10:38:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 20 Oct 2008 15:38:57 +0100 Subject: pymssql - execute loads all results into memory! In-Reply-To: <92da89760810200732p733977dfu1ac1f44ec44ee436@mail.gmail.com> References: <767a6cf1-4968-4e95-8a0b-62adf871d399@s1g2000prg.googlegroups.com> <92da89760810200732p733977dfu1ac1f44ec44ee436@mail.gmail.com> Message-ID: <48FC9801.7060808@timgolden.me.uk> Eric Wertman wrote: >> I am trying to use pymssql, and have an issue where by the execute >> (not the fetch) is appearing to load all records into memory. >> >> if I execute >> >> con = pymssql.connect(...) >> cur = con.cursor() >> cur.execute(sql) >> rec = cur.fetchone() >> >> if I put in a query which returns a lot of records into "sql" then the >> execute never returns, pythons memory usage slowly ballons till the >> machine cant give anymore. If I put a sql query returning only few >> rows, then it works fine. >> >> So I am not sure why an execute would feel the need to load all rows, >> but its seriously crippling. Does anyone know if this is a bug or >> something I can "turn off" > > I ran into this myself. After some digging I discovered that what you > are after is a server-side cursor that isn't implemented yet in > pymssql. There is one in MySQLdb, but it's not the default behavior. > Regardless of your usage (fetchone vs fetchmany), the result set is > held client side. AFAIK the only workaround is to keep your result > set small (enough). If you use fetchmany and iterate over it > directly, it may keep your memory usage down, I can't remember if > that worked. I definitely tried making a generator with it, that did > not help. ... or just switch to pyodbc, for example, which behaves perfectly well with this snippet against a table of >24 million rows: import pyodbc conn = [ "Driver={SQL Server}", "Server=SVR17", "Database=TDI", "TrustedConnection=Yes" ] db = pyodbc.connect (";".join (conn)) q = db.cursor () q.execute ("SELECT * FROM revenue") # 24 million rows q.fetchone () q.close () TJG From casevh at gmail.com Tue Oct 14 01:09:51 2008 From: casevh at gmail.com (casevh) Date: Mon, 13 Oct 2008 22:09:51 -0700 (PDT) Subject: gmpy and counting None References: <20081013214347.5850f1ce@gmx.net> Message-ID: <958685e7-c582-4d37-a7aa-f7830eee0559@d1g2000hsg.googlegroups.com> On Oct 13, 12:43?pm, wrote: > Hi, > > I just stumbled upon the following issue (I am running Debian): > > $ python > Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> [2, None].count(None) > 1 > >>> from gmpy import mpz > >>> [mpz(2), None].count(None) > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: coercion to gmpy.mpz type failed > > > > Is this a bug in gmpy? > > If yes is there any way to issue the bug athttp://code.google.com/p/gmpy/ > without creating a gmail account? I've added it for you. > > Thanks > > Martin Thanks for reporting the issue. casevh From Claire.Mouton at inria.fr Fri Oct 17 10:48:14 2008 From: Claire.Mouton at inria.fr (Claire Mouton) Date: Fri, 17 Oct 2008 16:48:14 +0200 Subject: Interface to Matlab Message-ID: <200810171648.14393.Claire.Mouton@inria.fr> Hi, I would like to call Python functions from Matalab. How could I find an interface from Matlab to Python? Cheers, Claire From bdesth.quelquechose at free.quelquepart.fr Thu Oct 9 12:50:21 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 09 Oct 2008 18:50:21 +0200 Subject: NameError question - def(self,master) - master not in namespace within class? In-Reply-To: References: <665b0214-78ef-4df0-ac2a-6ca065d24758@1g2000prd.googlegroups.com> Message-ID: <48ee5234$0$6844$426a74cc@news.free.fr> bieffe62 at gmail.com a ?crit : bieffe, please, learn to snip irrelevant material... > On 9 Ott, 17:43, harijay wrote: (snip) >> NameError: name 'master' is not defined" (snip) >> #File runner.py >> #!/usr/bin/python >> import master >> import child >> >> if __name__=="__main__": >> print "RUNNING RUNNER" >> m = master.master("hj","oldhj") >> s = child.child(m) (snip) >> #File child.py >> class child(): >> def __init__(self,master): >> print "Master name is %s" % master.name >> print "Now seeting master name to setnameinchild in child.py " >> tmp = master.trash >> master.trash = master.name >> master.name = "setnameinchild" (snip) > > You need to have an import master in child.py too. Nope. The 'child' class is passed a 'master' instance when instanciated. You got confused by the bad naming. The convention in Python is to name classes in CamelCase. Your classes should be named 'Master' and 'Child'. From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 20 04:02:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 10:02:52 +0200 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? In-Reply-To: References: <48f4ed4b$0$6127$426a74cc@news.free.fr> <48f785f5$0$6537$426a74cc@news.free.fr> Message-ID: <48fc3b2c$0$22811$426a74cc@news.free.fr> Sebastian Wiesner a ?crit : > At Thu, 16 Oct 2008 18:21:38 +0200 wrote Bruno Desthuilliers > : >>> It doesn't look like there's >>> any way to browse the subversion any more, though. >> Doh :( >> >> Is there any way to get this version then ??? > svn co https://python-mode.svn.sourceforge.net/svnroot/python-mode/trunk/ > python-mode done !-) Ok. I obviously misunderstood Carl - I thought he meant the repository wasn't accessible anymore. Thanks Carl and Sebastian. From ed at leafe.com Fri Oct 24 12:37:35 2008 From: ed at leafe.com (Ed Leafe) Date: Fri, 24 Oct 2008 11:37:35 -0500 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: <880dece00810180612i5136dbe3j3ae452943770e6e3@mail.gmail.com> References: <880dece00810180612i5136dbe3j3ae452943770e6e3@mail.gmail.com> Message-ID: <23F22785-FECE-4E09-8666-A89F4271100A@leafe.com> On Oct 18, 2008, at 8:12 AM, Dotan Cohen wrote: > I often see mention of SMBs that either want to upgrade their Windows > installations, or move to Linux, but cannot because of inhouse VB > apps. Are there any Python experts who I can reference them to for > porting? I have nothing on hand at the moment, but I see this as a > need without an obvious answer. Sorry for the delay in responding, but someone just pointed out this post to me. You might want to take a look at Dabo, which is an integrated desktop application framework for Python (disclosure: I'm one of the authors). It allows you to visually create UIs that run unmodified on Windows, Linux and OS X. You can learn about it at http://dabodev.com -- Ed Leafe From rridge at csclub.uwaterloo.ca Tue Oct 21 08:19:13 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 21 Oct 2008 08:19:13 -0400 Subject: What was that, what was it? References: <82f51155-16fe-4e5c-a83b-040cf7695ff8@u75g2000hsf.googlegroups.com> Message-ID: Aaron Brady wrote: > If Python was a car, I think it would be a hybrid... Lawrence D'Oliveiro wrote: >I hope not. They're only good in the city, a waste of time once you get over >50 km/h. Sounds a lot like Python then, a waste of time if you need to go fast, but good for a lot of every day tasks. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From benjamin.kaplan at case.edu Mon Oct 20 12:54:38 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 20 Oct 2008 12:54:38 -0400 Subject: a question about Chinese characters in a Python Program In-Reply-To: <85553168-d673-4696-84c6-12311c1da858@g25g2000prf.googlegroups.com> References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> <010ca0e9$0$20670$c3e8da3@news.astraweb.com> <85553168-d673-4696-84c6-12311c1da858@g25g2000prf.googlegroups.com> Message-ID: On Mon, Oct 20, 2008 at 12:44 PM, est wrote: > On Oct 20, 11:46 pm, Steven D'Aprano cybersource.com.au> wrote: > > On Mon, 20 Oct 2008 06:30:09 -0700, est wrote: > > > Like I said, str() should NOT throw an exception BY DESIGN, it's a > basic > > > language standard. > > > > int() is also a basic language standard, but it is perfectly acceptable > > for int() to raise an exception if you ask it to convert something into > > an integer that can't be converted: > > > > int("cat") > > > > What else would you expect int() to do but raise an exception? > > > > If you ask str() to convert something into a string which can't be > > converted, then what else should it do other than raise an exception? > > Whatever answer you give, somebody else will argue it should do another > > thing. Maybe I want failed characters replaced with '?'. Maybe Fred wants > > failed characters deleted altogether. Susan wants UTF-16. George wants > > Latin-1. > > > > The simple fact is that there is no 1:1 mapping from all 65,000+ Unicode > > characters to the 256 bytes used by byte strings, so there *must* be an > > encoding, otherwise you don't know which characters map to which bytes. > > > > ASCII has the advantage of being the lowest common denominator. Perhaps > > it doesn't make too many people very happy, but it makes everyone equally > > unhappy. > > > > > str() is not only a convert to string function, but > > > also a serialization in most cases.(e.g. socket) My simple suggestion > > > is: If it's a unicode character, output as UTF-8; > > > > Why UTF-8? That will never do. I want it output as UCS-4. > > > > > other wise just ouput > > > byte array, please do not encode it with really stupid range(128) > ASCII. > > > It's not guessing, it's totally wrong. > > > > If you start with a byte string, you can always get a byte string: > > > > >>> s = '\x96 \xa0 \xaa' # not ASCII characters > > >>> s > > '\x96 \xa0 \xaa' > > >>> str(s) > > > > '\x96 \xa0 \xaa' > > > > -- > > Steven > > In fact Python handles characters well than most other open-source > programming languages. But still: > > 1. You can explain str() in 1000 ways, there are 1001 more confusing > error on all kinds of python apps. (Not only some of the scripts I've > written, but also famous enough apps like Boa Constructor > http://i36.tinypic.com/1gqekh.jpg. This sucks hard, right?) > > > 2. Anyone please kindly tell me how can I define a customized encoding > (namely 'ansi') which handles range(256) so I can > sys.setdefaultencoding('ansi') once and for all? > -- > http://mail.python.org/mailman/listinfo/python-list > There is no such thing as the "ansi" encoding. The only encoding defined by the American National Standards Institute is the 7-bit ASCII encoding that Python uses by default. You are probably thinking of cp-1252, the Windows Western European code page, which isn't actually an ANSI standard. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tino at wildenhain.de Tue Oct 7 09:43:57 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 07 Oct 2008 15:43:57 +0200 Subject: SMTPlib inside function, extra tab In-Reply-To: <65a01382-33d2-4790-82b3-d9acdcc13b5f@w7g2000hsa.googlegroups.com> References: <65a01382-33d2-4790-82b3-d9acdcc13b5f@w7g2000hsa.googlegroups.com> Message-ID: <48EB679D.80906@wildenhain.de> Hunter wrote: > I am writing a script that needs to send some emails. And I've used > smtplib in the past and it is pretty easy. But I thought, gee it > would be easier if I could just call it as a function, passing the > from, to, subject, and message text. So I wrote it up as a function > and it sort of works, but I get a weird error. When it runs it > inserts a "\t" tab character before each item during the send portion > (which I can see when I turn on debug). The end result is that I > don't get any body or subject in my emails. It works fine when I copy > the inside of the function and run it directly. It isn't a > dealbreaker, I can certainly just call it direct, but from a learning > Python perspective I'm wondering if anyone knows what exactly is > happening. I'm more interested in the why this is happening than a > solution (though that would be great too). Oh and if you could > explain it to me, with no CS background, that would be even better. > > I am working on Windows Vista with Python 2.5.2 (activestate). > > Thanks --Joshua > > Snip of script (more or less a copy/paste from effbot): > fromaddress = 'automation at mydomain.com' > tolist = ['it at mydomain.com','jhunter at mydomain.com'] > msgsubj = "Hello!" > messagebody = "This message was sent with Python's smtplib." > > > def send_mail(fromaddress,tolist,msgsubj,messagebody): > import smtplib > SERVER = "mymailserver.mydomain.com" > message = """\ > From: %s > To: %s > Subject: %s > %s > """ % (fromaddress, ", ".join(tolist),msgsubj, messagebody) ^^^^^ The tabs are exactly here. best is to use the mail package to generate mime compliant emails and use simple templates - which could in the easiest form just module level constants like: stdform=""" Hello %(greeting)s, this automated email is about %(subject)s ... """ and so on and then you use it with stdform % dict(greeting='Mr Ed',subject='writing emails') ... HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From carsten.haese at gmail.com Thu Oct 16 10:52:46 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 16 Oct 2008 10:52:46 -0400 Subject: Finding the instance reference of an object In-Reply-To: References: Message-ID: <3zIJk.5599$YU2.3294@nlpi066.nbdc.sbc.com> Astley Le Jasper wrote: > Sorry for the numpty question ... > > How do you find the reference name of an object? > > So if i have this > > bob = modulename.objectname() > > how do i find that the name is 'bob' Why do you need to find that? You know that its name is 'bob'. -- Carsten Haese http://informixdb.sourceforge.net From castironpi at gmail.com Thu Oct 9 01:54:13 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 8 Oct 2008 22:54:13 -0700 (PDT) Subject: Porn Addiction Solutions? References: Message-ID: <0b413c38-9558-4d1a-9ebb-9a5fd2de3491@p58g2000hsb.googlegroups.com> On Oct 8, 2:07?pm, pavement... at yahoo.com wrote: > Help, I'm addicted to porn. I've been spending a lot of time > downloading hardcore porn and masturbating to it. It's ruining my > life. I just found out that one of these sites somehow hacked my card > and rang up $5K in charges which they won't even refund me. Even with > that I haven't stopped my habit and it's only getting worse. How can I > end this addiction? > > Any suggestions? Do you want ideas for strategies for contending with it? Do you want to talk? Do you want ideas for other places to find people to talk to? From gagsl-py2 at yahoo.com.ar Tue Oct 21 01:16:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Oct 2008 03:16:01 -0200 Subject: hiding modules in __init__.py References: <1hzudrgmuhdrl$.9ofug6rn0u5u.dlg@40tude.net> Message-ID: En Sat, 18 Oct 2008 16:03:19 -0300, Brendan Miller escribi?: > How would I implement something equivalent to java's package private in > python? > > Say if I have > > package/__init__.py > package/utility_module.py > > and utility_module.py is an implementation detail subject to change. > > Is there some way to use __init__.py to hide modules that I don't want > clients to see? Or is the best practice just to name the module you don't > want clients to use _utility_module and have it private by convention? If you don't import utility_module in __init__ (or delete the name after using it), it won't show up if someone does "from package import *", nor in dir(package). Plus if you don't menction it in the docs, the only way to discover it would be to look at the directory contents - to "peek the implementation", I'd say. You could always name it _utility_module.py if you want to make perfectly clear that it's for internal use only, but I've seldom seen such module names. -- Gabriel Genellina From notvalid2 at sbcglobal.net Tue Oct 14 17:00:09 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 14 Oct 2008 14:00:09 -0700 Subject: Installing Python 2.4 over 2.4? In-Reply-To: References: Message-ID: Terry Reedy wrote: > Steve Holden wrote: >> W. eWatson wrote: >>> I suspect something has been corrupted in Python 2.4. Can I just >>> re-install on top of it, and still expect to have scipy and other pkgs >>> I've installed? >> >> On Windows, certainly - you can even uninstall and reinstall and retain >> your installed libraries. On Linux I am pretty sure the same is true, >> but caveat emptor. > > In Windows, at least, micro version upgrades are handled exactly this > way. When 2.5.3 comes out, for instance, the installer will replace > python files as needed in the current directories but leave > Python25/Lib/Site-Packages and any user-added directories alone. > That's good news. I was worried about libraries I had set up. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From stef.mientki at gmail.com Thu Oct 23 13:50:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 23 Oct 2008 19:50:17 +0200 Subject: ANN: gui_support, a convenience library for wxPython Message-ID: <4900B959.7080409@gmail.com> hello, gui_support is library for easy creation of GUI designs in wxPython. Although it's quit stable, it's part of a larger project and therefor has a lot of dependencies, but these can easily be removed. Warning: Although this library might be very attractive to newbies, the use of this library will prevent you from learning some of the basics of GUI, specially of containers / sizers in wxPython. Brief documentation can be found here http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_gui_support.html ( as this website will soon be moved, this docpage can always be found through the redirector http://pic.flappie.nl look under paragraph PyLab_Works | GUI_support ) Download: http://pylab-works.googlecode.com/files/Data_Python_Test.zip cheers, Stef From bj_666 at gmx.net Thu Oct 30 04:30:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Oct 2008 08:30:12 GMT Subject: Need some help speeding up this loop References: <6122f987-8948-4077-a2dd-48af0bf35cb6@l33g2000pri.googlegroups.com> Message-ID: <6mt9kkFici3jU2@mid.uni-berlin.de> On Wed, 29 Oct 2008 19:24:32 -0700, erikcw wrote: > I'm trying to write a loop that will build a list of "template strings". > > My current implementation is *really slow*. It took 15 minutes to > finish. (final len(list) was about 16k entries.) What is `list` here? Do you mean ``len(templates)``? > templates = [] > for c in combinations: > if len(states): > for state in states: > if type(geo) is City: > cities = state.city_set.all() > else: > cities = geo > for city in cities: > if type(city) is City: > city = city.city > templates.append(c.template.replace('{{ city }}', > city)) > templates.append(c.template) #just in case there are no > cities > templates = [k.replace('{{ state }}', > state.state).replace('{{ state_abbr }}', state.abbreviation) for k in > templates] It seems you are iterating over *all* accumulated templates so far, over and over again, even those which don't have those place holders anymore. Looks like the source of quadratic runtime for me. Ciao, Marc 'BlackJack' Rintsch From lfrogerscobalt at gmail.com Wed Oct 1 18:32:29 2008 From: lfrogerscobalt at gmail.com (Albertos) Date: Wed, 1 Oct 2008 15:32:29 -0700 (PDT) Subject: www megarotic - Free Message-ID: www megarotic . . . *******CLICK HERE******** http://vids365.cn/www-megarotic ***************************** . . . . . . . . . . . . www megarotic From bignose+hates-spam at benfinney.id.au Tue Oct 7 17:19:33 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 08 Oct 2008 08:19:33 +1100 Subject: Python pre-release announcements References: <87myhglta6.fsf@benfinney.id.au> Message-ID: <87iqs4je6y.fsf@benfinney.id.au> Terry Reedy writes: > Ben Finney wrote: > > Can I request, in the interest of reducing confusion, that any > > announcements of pre-release versions of 2.5.3 (or any other > > Python release) be announced *without* saying ?RELEASED: A > > not-really-release version of Python?. > > > > It's very confusing to see a progression of announcements with subject > > fields like: > > > > RELEASED: Python 2.8.not-ready-yet > > RELEASED: Python 2.8.alpha-1 > > RELEASED: Python 2.8.beta-1 > > RELEASED: Python 2.8.beta-2 > > RELEASED: Python 2.8 release candidate 1 > > RELEASED: Python 2.8 release candidate 2 > > RELEASED: Python 2.8 final > > I disagree. These say exactly what has happened and tell me what I > want to know, which is that something new has been released, which is > to say, made available for download. Which is entirely different from the ?release? implicit in e.g. ?release candidate?, hence they don't say what they appear to say. Since the latter term is unlikely to change, I'm asking that the announcements don't unnecessarily overload the meaning of ?release?. > I disagree. [ANN] could mean anything: planned? canceled? needs help? > ("Oh, 'released', why didn't you say so?") As above, ?released? is a poor term for this, since it *already* has connotations of ?all done, out the door, ready to go? as evidenced in ?release candidate? (not released, but we think it could be) and the distinction of the triumphant announcements that accompany *actual* releases. > I presume you would not be happy either with "[ANN] Python > x.y.whatever released". I hope it's clear why that's so, yes. > (I am currently using 3.rc1; the remaining problems do not currently > affect me and I accept the risk, which I view as small, that further > changes will affect code I write now.) Note that you are using a ?release candidate?, i.e. a version of software *that has not yet been released*. It would surely be clearer if the availability of that version were not announced with an implication that the software is both released and not-released. > If you want RELEASED replaced, suggest something short and not too > ugly that communicates "posted at python.org and available to be > downloaded, installed, tested, and used" at least as well. I suggest ?AVAILABLE?, then, to clearly limit the scope of what state is being announced. Whatever is chosen, please reserve ?RELEASED? for the commonly-expected meaning of something akin to ?no longer in intensive development or bug-hunting mode, now ready to go out on its own and be used with abandon by the masses?. -- \ ?The generation of random numbers is too important to be left | `\ to chance.? ?Robert R. Coveyou | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Fri Oct 17 16:17:28 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Oct 2008 09:17:28 +1300 Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <3fe70d4b-0dfe-4c60-8b16-1bc70ce96d25@j68g2000hsf.googlegroups.com> <80b69331-e241-4c05-8df9-03f8bdbfe0bb@y21g2000hsf.googlegroups.com> <01087685$0$20638$c3e8da3@news.astraweb.com> Message-ID: In message , Aaron "Castironpi" Brady wrote: > The purpose of a parameter is something that the caller can supply, but > doesn't have to. It is not for internal-use-only items. Exactly! From clp at rebertia.com Thu Oct 23 21:56:48 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 23 Oct 2008 18:56:48 -0700 Subject: How to examine the inheritance of a class? In-Reply-To: References: Message-ID: <47c890dc0810231856x26be5a69n9d93057cbe557edb@mail.gmail.com> On Thu, Oct 23, 2008 at 6:36 PM, John Ladasky wrote: > Hello again! > > Suppose that I have several subclasses which inherit from a base > class, thus: > > class Foo(object): > > class Spam1(Foo): > > class Spam2(Foo): > > class Spam3(Foo): > > etc. The list of subclasses is not fully defined. It is supposed to > be extensible by the user. > > Many methods will differ between these classes. However, there are > operations which may be performed between two Foo objects, OR between > any of Foo's derivatives. > > There are instances where I would like to perform type checking before > carrying out the operation. Rather than having to enumerate all of > Foo's subclasses (which would defeat my intent of extending the list > of subclasses anyway), I would like to see whether a class is DERIVED > from Foo. Where is this information stored in the class definition? In __bases__, e.g. Spam1.__bases__, which would be (,). In practice, you probably just want to use if isinstance(some_obj, Foo): which will be true for SpamN instances. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > From larry.bates at vitalEsafe.com Mon Oct 20 11:47:01 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Mon, 20 Oct 2008 10:47:01 -0500 Subject: windows / unix path In-Reply-To: <5bc219f8-07cd-4aaf-ad6f-8850fef62d60@m73g2000hsh.googlegroups.com> References: <5bc219f8-07cd-4aaf-ad6f-8850fef62d60@m73g2000hsh.googlegroups.com> Message-ID: Marcin201 wrote: > Is there an built-in functionality in python to convert Windows paths > to Unix paths? I am running into problems when creating data files on > Windows and the running them on a Unix platform. I create paths using > os.path.join. > > os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on > Win. When I read files created on Win under Unix this is a problem, > python cannot open 'Pictures\\01.jpg' > > Thanks, > > Marcin I use posixpath when I want to "force" forward slashes that I know will work on Linux. Actually the forward slashes work fine on Windows also (undocumented feature of Windows). -Larry From tjreedy at udel.edu Sat Oct 11 13:13:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Oct 2008 13:13:49 -0400 Subject: pyserial: failed to readlines() after many hours running. In-Reply-To: References: <1a690c10-a16d-4a43-b3b6-94caa5e0c0a0@z18g2000prn.googlegroups.com> Message-ID: Unknown wrote: > On 2008-10-11, zxo102 wrote: > >> I have a system. An instrument attched to 'com1' is wireless connected >> to many sensors at different locations. The instrument can forward >> the "commands" (from pyserial's write()) to those sensors. Based on >> the "commands", the sensors keep sending corresponding data back to >> the instrument which wraps up those data and put into "com1" . The >> readlines() of pyserial pick up those data for processing. >> The data ?string' does not have "\n". Do you have the option of having the instrument insert them between readings? > > If the data you're reading doesn't contain "\n", then you can't > use readline() or readlines(). Use .read() instead. From dcharno at comcast.net Wed Oct 15 18:28:41 2008 From: dcharno at comcast.net (dcharno) Date: Wed, 15 Oct 2008 18:28:41 -0400 Subject: problem using ctypes with MMX intrinsics In-Reply-To: References: <48F54102.40509@comcast.net> Message-ID: <48F66E99.7080401@comcast.net> Robert Kern wrote: > Well, stack alignment would be a problem with how the shared library > gets compiled, nothing to do with ctypes (I think). However, if you are The shared library is built with '-m32 -msse2' and works fine from a C/C++ test harness, so I think its compiled okay. > passing in arrays from ctypes, *they* may also be misaligned. Try to > check the addresses of the ctypes values you are passing in. I'm not > entirely sure how to do that, though. I'm only passing filenames and some string options through the API. All the data that gets processed with MMX/SSE is opened inside the shared library. From mhuening at zedat.fu-berlin.de Fri Oct 3 16:00:25 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Fri, 03 Oct 2008 22:00:25 +0200 Subject: SQLite In-Reply-To: References: <6kmhnoF8kljqU1@mid.uni-berlin.de> Message-ID: <6knbuhF8ps1rU1@mid.uni-berlin.de> Thanks! cursor.rowcount does exactly what I need. > Before going any further... make sure that SQLite's count_change is > enabled: > > PRAGMA count_changes > PRAGMA count_changes = 0 | 1 > > "Query or change the count-changes flag. Normally, when the > count-changes flag is not set, INSERT, UPDATE and DELETE statements > return no data. When count-changes is set, each of these commands > returns a single row of data consisting of one integer value - the > number of rows inserted, modified or deleted by the command. " > Looks like this is not really necessary. My database hat count_changes disabled, but rowcount seems to work anyway. Are there any pitfalls? Matthias From lie.1296 at gmail.com Wed Oct 1 04:07:43 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 1 Oct 2008 08:07:43 +0000 (UTC) Subject: ssh keepalive References: <34941e4c-c29c-4ae7-b062-13cd71bec86d@w32g2000hsf.googlegroups.com> Message-ID: On Wed, 01 Oct 2008 00:30:59 -0700, loial wrote: > I have a problem with a ssh connection in python > > I get the error > > 'NoneType' object has no attribute 'exec_command' > > I am thinking that maybe the ssh connection is timeing out. > > Since I have no control over the configuration of the ssh server(which > is AIX 5.23), is there anything I can do in python to ensure that the > ssh session does not timeout? No, it's a NoneType object (i.e. your variable contains None) Show us a bit of your code, so we can see why is None there. My guess is that you're trying to perform something on a function that does things in-place and doesn't return anything (e.g. list.append, list.sort) >>> a = [1, 3, 4, 2] >>> a = a.sort() >>> print a [None, None, None, None] >>> # should be >>> a = [1, 3, 4, 2] >>> a.sort() >>> print a [1, 2, 3, 4] From almar.klein at gmail.com Mon Oct 13 04:37:35 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 13 Oct 2008 10:37:35 +0200 Subject: class point in python In-Reply-To: References: Message-ID: I made a class to store sets of points a few months ago.I don't consider it finished enough to release it somewhere, but I'm happy to share it if you're interested. Send me an e-mail if you are. Almar 2008/10/12 rkmr.em at gmail.com > i am looking for a python implementation of this class, a point X,Y > representation > > http://msdn.microsoft.com/en-us/library/system.drawing.point_methods.aspx > > is there any library that has this class? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Oct 25 13:37:33 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 25 Oct 2008 10:37:33 -0700 (PDT) Subject: Building truth tables References: <3c615d52-fbd4-4ab3-9efe-fbadc60bf414@x41g2000hsb.googlegroups.com> <8b743462-2850-437d-b7f3-d40c1200064e@k7g2000hsd.googlegroups.com> Message-ID: On Oct 24, 5:53?am, andrea wrote: > On 26 Set, 20:01, "Aaron \"Castironpi\" Brady" > wrote: > > > > > Good idea. ?If you want prefixed operators: 'and( a, b )' instead of > > 'a and b', you'll have to write your own. ?('operator.and_' is bitwise > > only.) ?It may be confusing to mix prefix with infix: 'impl( a and b, > > c )', so you may want to keep everything prefix, but you can still use > > table( f, n ) like Tim said. > > After a while I'm back, thanks a lot, the truth table creator works, > now I just want to parse some strings to make it easier to use. > > Like > > (P \/ Q) -> S == S > > Must return a truth table 2^3 lines... > > I'm using pyparsing and this should be really simple, but it doesn't > allow me to recurse and that makes mu stuck. > The grammar BNF is: > > Var :: = [A..Z] > Exp ::= Var | !Exp ?| Exp \/ Exp | Exp -> Exp | Exp /\ Exp | Exp == > Exp > > I tried different ways but I don't find a smart way to get from the > recursive bnf grammar to the implementation in pyparsing... > Any hint? Use Forward to create a recursive grammar. Look at the examples page on the pyparsing wiki, and there should be several samples of recursive grammars. Here is a very simple recursive grammar, with no precedence to your operators: from pyparsing import oneOf, alphas, Forward, ZeroOrMore, Group, Optional var = oneOf(list(alphas)) op = oneOf(r"\/ /\ -> ==") expr = Forward() expr << Optional('!') + ( var | Group('(' + expr + ')') ) + ZeroOrMore(op + expr) test = "(P \/ Q) -> S == S" print expr.parseString(test).asList() prints: [['(', 'P', '\\/', 'Q', ')'], '->', 'S', '==', 'S'] Since these kinds of expressions are common, pyparsing includes a helper method for defining precedence of operations infix notation: from pyparsing import operatorPrecedence, opAssoc expr = operatorPrecedence(var, [ (r'!', 1, opAssoc.RIGHT), (r'\/', 2, opAssoc.LEFT), (r'/\\', 2, opAssoc.LEFT), (r'->', 2, opAssoc.LEFT), (r'==', 2, opAssoc.LEFT), ]) print expr.parseString(test).asList() prints: [[[['P', '\\/', 'Q'], '->', 'S'], '==', 'S']] HTH, -- Paul From luong8201 at hotmail.com Thu Oct 30 17:05:58 2008 From: luong8201 at hotmail.com (fx5900) Date: Thu, 30 Oct 2008 14:05:58 -0700 (PDT) Subject: Code not work - DESPERATE HELP :( In-Reply-To: References: <20253039.post@talk.nabble.com> Message-ID: <20255455.post@talk.nabble.com> Hi, I just went to go and get a coffee when i noticed a email, thought it was just usual spam. Read your message, and it worked. it was because i did not put they 'python' keyword infront. How did u figure it out? Although, cos i nver worked with python, things are bound to go wrong on the first hurdles right? Cheers :) Bill McClain-4 wrote: > > On 2008-10-30, fx5900 wrote: > >> Hi, > >> i am trying to convert an .osm (openstreetmap) file into gml format >> and >> finally to shapefile given this wiki info >> http://wiki.openstreetmap.org/index.php/GML. I'm using windows and when i >> entered the following commands osm2gml.py < map_01_data.osm > >> map_01_data.gml on my dos prompt i get a number of errors, some of which >> are bellow: > > Does this give any better results: > > python osm2gml.py < map_01_data.osm > map_01_data.gml > > -Bill > -- > Sattre Press In the Quarter > http://sattre-press.com/ by Robert W. Chambers > info at sattre-press.com http://sattre-press.com/itq.html > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Code-not-work---DESPERATE-HELP-%3A%28-tp20253039p20255455.html Sent from the Python - python-list mailing list archive at Nabble.com. From eckhardt at satorlaser.com Fri Oct 31 08:30:02 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Fri, 31 Oct 2008 13:30:02 +0100 Subject: Is there a time limit for replies? References: <57aaf1b8-d596-43e1-bb2c-d89815e6944d@e38g2000prn.googlegroups.com> Message-ID: Rafe wrote: > Can you recommend anything? I would like to avoid 1,000s of emails > flooding my account though. I like knode from KDE for browsing the Usenet. The Mozilla suite also contains a newsreader. Other than that, use a webmail account and configure a filter to file everything Pythonic into a separate folder. > It also has to work from behind a strict > corporate firewall. When a firewall prevents work from being done, then there is a simple technical solution. In any case, you might want to ask your sysadmin whether the company or their ISP has a newsserver which you could use. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From apardon at forel.vub.ac.be Wed Oct 8 07:54:03 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Oct 2008 11:54:03 GMT Subject: Upgrading an instance to a subclass Message-ID: I have a subclass of socket. class Mysocket (socket): ... But when I use the python library it will of course just return an instance of socket, like the SocketServer module. So now I was wondering if it is somehow possible to turn this instance into a Mysocket instance, either by somehow changing the original instance or producing a new instance that represents the same connection. -- Antoon Pardon From tjreedy at udel.edu Thu Oct 16 21:21:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Oct 2008 21:21:51 -0400 Subject: python3 - the hardest hello world ever ? In-Reply-To: <48F7A00E.9070708@skynet.be> References: <48f481af$0$2863$ba620e4c@news.skynet.be> <48f4f35e$0$25779$9b622d9e@news.freenet.de> <48F5C11C.3070807@igpm.rwth-aachen.de> <48f6438d$0$19075$9b622d9e@news.freenet.de> <48F6F6EE.9000704@igpm.rwth-aachen.de> <48f6f990$0$2492$9b622d9e@news.freenet.de> <48F7092D.2050806@igpm.rwth-aachen.de> <43dad1ee-fe99-4509-b79b-465bdcbe4a78@x41g2000hsb.googlegroups.com> <48F7A00E.9070708@skynet.be> Message-ID: Helmut Jarausch wrote: > I have always worked with latin-1 strings with an US locale under > python-2.x with x < 6 (I haven't tried 2.6, though). I hope to switch to > 3.0 as soon as possible. Having the luxury of not needing 3rd party extensions for my current work, I already have, and love it. A few month ago I still thought I had no personal need for Unicode. Then my daughter announced that she wanted to learn Japanese. My mind was changed. We will all be happier, I think, when output devices routinely accept UTF-8 streams and display the full current Unicode character set. tjr From jcd at sdf.lonestar.org Tue Oct 21 11:47:16 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 21 Oct 2008 11:47:16 -0400 Subject: Error In-Reply-To: References: Message-ID: <1224604036.7682.8.camel@aalcdl07.lib.unc.edu> On Tue, 2008-10-21 at 09:34 -0400, Philip Semanchuk wrote: > On Oct 21, 2008, at 9:05 AM, Amie wrote: > > > Hi, > > > > what does is the meaning of this error: int object is unsubscriptable. > > This is the code that I have written that seems to give me that: > > > > def render_sideMenu(self, ctx, data): > > def render_dataAge(unit): > > results = [(i[0], i[1] > > ) for i in unit] > > return self.dataTable(["Unit Name", "Current Data Age"], > > results, sortable=True), > > return > > self > > .enamel > > .,storage > > .getDataAge(int(self.arguments[0])).addCallback(render_dataAge) > > I can't see all of your code so I'm not sure, but it sounds like > you're treating a plain int object as if it was a sequence (like a > list or a tuple). My guess is that "i" in the code above is an int. > Try this Python code in the interpreter and you'll get the same error: > > >>> 1[0] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object is unsubscriptable > >>> > > -- OR -- > > >>> i = 1 > >>> i[0] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object is unsubscriptable > >>> > Indeed. In other words, unit is a list (or other iterable) of integers. It looks like you want it to be a list of tuples of some kind. >>> unit = [('inch', 4), ('pound', 16), ('yottabyte', 2)] >>> [i[0] for i in unit] ['inch', 'pound', 'yottabyte'] > > -- > http://mail.python.org/mailman/listinfo/python-list > From benjamin.kaplan at case.edu Thu Oct 2 16:49:35 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 2 Oct 2008 16:49:35 -0400 Subject: Professional quality scripts/code In-Reply-To: <50809a11-6f20-45fa-b2f4-128456ce1ce6@m74g2000hsh.googlegroups.com> References: <50809a11-6f20-45fa-b2f4-128456ce1ce6@m74g2000hsh.googlegroups.com> Message-ID: On Thu, Oct 2, 2008 at 4:38 PM, robean wrote: > I have been learning Python for the last 3 months or so and I have a > working (but somewhat patchy) sense of the the language. I've been > using a couple of the more popular Python books as well as online > resources. > > A question for experienced Python programmers: can you recommend > resources where I can look at high quality Python code and scripts? > I've spent some time at http://code.activestate.com/recipes/ but am > concerned that the quality of what is posted there can be somewhat hit > and miss. What I have in mind is a site like cpan, where one can look > at the actual source code of many of the modules and learn a thing or > two about idiomatic Perl programming from studying the better ones. > Any sites like that for Python? (You can of course look up Python > modules on docs.python.org, but, as far as I can tell, not the actual > source code). Many thanks. > If you want to look at the python source, you can either download the source tarballs for the latest release from python.org or you can look at the svn repository. (http://svn.python.org/projects/python/trunk). -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Oct 7 02:14:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Oct 2008 03:14:45 -0300 Subject: subprocess.Popen(..., cwd=...) and Makefile $(PWD) don't play nice References: <63d69d59-0614-4ff7-8431-eda4ff74c006@v72g2000hsv.googlegroups.com> Message-ID: En Mon, 06 Oct 2008 13:09:26 -0300, Miki escribi?: > Can anybody explain why Makefile $(PWD) does show the right directory > when running under subprocess.Popen(..., cwd=...) > > For example: > [18:07] tmp $cat /tmp/p/Makefile > all: > @echo $(PWD) > [18:07] tmp $cat t > #!/usr/bin/env python > > from subprocess import Popen > Popen(["make"], cwd="/tmp/p") > > [18:07] tmp $./t > /tmp > > The output of the "make" command should have been "/tmp/p" and not "/ > tmp" I've tried the equivalent version on Windows and it worked fine. And I can't see how make could find the Makefile at /tmp/p if the current directory were another one... (?) -- Gabriel Genellina From goldnery at gmail.com Sat Oct 18 06:52:51 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 18 Oct 2008 03:52:51 -0700 (PDT) Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> Message-ID: <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> On Oct 18, 12:39?pm, Duncan Booth wrote: > Gandalf wrote: > > how can I do width python a normal for loop width tree conditions like > > for example : > > > for x=1;x<=100;x+x: > > ? ? print x > > What you wrote would appear to be an infinite loop so I'll assume you meant > to assign something to x each time round the loop as well. The simple > Python translation of what I think you meant would be: > > x = 1 > while x <= 100: > ? ?print x > ? ?x += x > > If you really insist on doing it with a for loop: > > def doubling(start, limit): > ? ? x = start > ? ? while x <= limit: > ? ? ? ? yield x > ? ? ? ? x += x > > ... > > for x in doubling(1, 100): > ? ? print x I was hopping to describe it with only one command. most of the languages I know use this. It seems weird to me their is no such thing in python. it's not that I can't fined a solution it's all about saving code From rkmr.em at gmail.com Sat Oct 11 18:20:43 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sat, 11 Oct 2008 15:20:43 -0700 Subject: class point in python Message-ID: i am looking for a python implementation of this class, a point X,Y representation http://msdn.microsoft.com/en-us/library/system.drawing.point_methods.aspx is there any library that has this class? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil at riverbankcomputing.com Wed Oct 29 07:01:53 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Wed, 29 Oct 2008 11:01:53 +0000 Subject: [Novice]Installing eric4 with python 2.6 In-Reply-To: References: <4c4575360810282004j16683dcar3a5de823387a06bd@mail.gmail.com> Message-ID: <0031eae7e0aaaef99bf2276a65cf0c9f@localhost> On Wed, 29 Oct 2008 06:51:10 -0400, Steve Holden wrote: > Saurabh Agrawal wrote: >> Hi, >> >> I am fairly new to python. Coming from a world of IDEs, I wanted a >> fancier one than IDLE. Hence, I downloaded eric4. When I tried to >> compile it, it asked for PyQt4, which I again downloaded (exe for >> Windows XP) and installed it. It seems to be properly installed as I can >> invoke "import PyQt4" from IDLE without any complaints. >> >> However, when I try to install eric4, I am getting the following error: >> >> D:\Python26\eric4-4.2.2a>python install.py >> Sorry, please install PyQt4. >> Error: Module use of python25.dll conflicts with this version of Python. >> >> So, won't eric4 work with python 2.6? I have searched on the net for >> this, but am unable to find any solution. >> >> I am new to python, so please excuse if this has an obvious solution. >> Thanks. >> >> OS: Windows XP SP2. >> > Unfortunately when a new release comes out package authors don't always > rush to meet the demand for their software by providing a release for > the new version. > > If the download site doesn't specifically offer a 2.6-compatible version > that's likely the problem here, sorry :( PyQt supported Python 2.6 on the day it was released. A snapshot of the PyQt Windows installer for Python 2.6 can be downloaded from the same page as you downloaded the installer for Python 2.5. Phil From bieffe62 at gmail.com Mon Oct 6 10:24:51 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 6 Oct 2008 07:24:51 -0700 (PDT) Subject: how to start thread by group? References: Message-ID: On 6 Ott, 15:24, oyster wrote: > my code is not right, can sb give me a hand? thanx > > for example, I have 1000 urls to be downloaded, but only 5 thread at one time > def threadTask(ulr): > ? download(url) > > threadsAll=[] > for url in all_url: > ? ? ?task=threading.Thread(target=threadTask, args=[url]) > ? ? ?threadsAll.append(task) > > for every5task in groupcount(threadsAll,5): > ? ? for everytask in every5task: > ? ? ? ? everytask.start() > > ? ? for everytask in every5task: > ? ? ? ? everytask.join() > > ? ? for everytask in every5task: ? ? ? ?#this does not run ok > ? ? ? ? while everytask.isAlive(): > ? ? ? ? ? ? pass Thread.join() stops until the thread is finished. You are assuming that the threads terminates exactly in the order in which are started. Moreover, before starting the next 5 threads you are waiting that all previous 5 threads have been completed, while I believe your intention was to have always the full load of 5 threads downloading. I would restructure my code with someting like this ( WARNING: the following code is ABSOLUTELY UNTESTED and shall be considered only as pseudo-code to express my idea of the algorithm (which, also, could be wrong:-) ): import threading, time MAX_THREADS = 5 DELAY = 0.01 # or whatever def task_function( url ): download( url ) def start_thread( url): task=threading.Thread(target=task_function, args=[url]) return task def main(): all_urls = load_urls() all_threads = [] while all_urls: while len(all_threads) < MAX_THREADS: url = all_urls.pop(0) t = start_thread() all_threads.append(t) for t in all_threads if not t.isAlive(): t.join() all_threads.delete(t) time.sleep( DELAY ) HTH Ciao ----- FB From eckhardt at satorlaser.com Thu Oct 2 07:13:17 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 02 Oct 2008 13:13:17 +0200 Subject: using SSh problem! References: Message-ID: sa6113 wrote: > I want to connect form a windows machine to a Linux one using SSH (I use > Paramiko) and simply copy a file to Linux machine. > Would you please help me how should I start? For starters, I'd take a look at 'scp'. Other than that, what does the question you asked have to do with Python? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From Catherine.M.Moroney at jpl.nasa.gov Wed Oct 15 17:27:02 2008 From: Catherine.M.Moroney at jpl.nasa.gov (Catherine Moroney) Date: Wed, 15 Oct 2008 14:27:02 -0700 Subject: memory use with regard to large pickle files Message-ID: I'm writing a python program that reads in a very large "pickled" file (consisting of one large dictionary and one small one), and parses the results out to several binary and hdf files. The program works fine, but the memory load is huge. The size of the pickle file on disk is about 900 Meg so I would theoretically expect my program to consume about twice that (the dictionary contained in the pickle file plus its repackaging into other formats), but instead my program needs almost 5 Gig of memory to run. Am I being unrealistic in my memory expectations? I'm running Python 2.5 on a Linux box (Fedora release 7). Is there a way to see how much memory is being consumed by a single data structure or variable? How can I go about debugging this problem? Catherine From steve at REMOVE-THIS-cybersource.com.au Sat Oct 25 20:55:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Oct 2008 00:55:50 GMT Subject: Improving interpreter startup speed References: Message-ID: <0113b905$0$20667$c3e8da3@news.astraweb.com> On Sat, 25 Oct 2008 12:32:07 -0700, Pedro Borges wrote: > Hi guys, > > > Is there a way to improve the interpreter startup speed? Get a faster computer? > In my machine (cold startup) python takes 0.330 ms and ruby takes 0.047 > ms, after cold boot python takes 0.019 ms and ruby 0.005 ms to start. How are you measuring this? -- Steven From castironpi at gmail.com Sun Oct 12 01:25:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 11 Oct 2008 22:25:56 -0700 (PDT) Subject: Most compact "X if X else Y" idiom References: Message-ID: On Oct 12, 12:01?am, jbperez... at yahoo.com wrote: > I find myself having to do the following: > > ? x = (some complex expression) > ? y = x if x else "blah" > > and I was wondering if there is any built-in idiom that > can remove the need to put (some complex expression) > in the temporary variable x. > > e.g. something like the below: > > ?y= foobar ((some complex expression), "blah") > > I realized foobar() can be easily coded as: > ? def foobar(a,b): > ? ? if a: return a > ? ? else: return b > > But I was wondering if there was a built-in function or syntax > that already does this. You could take your chances on 'or', as follows: >>> (6+ (3<< 1) ) or 'blah' 12 >>> (6- (3<< 1) ) or 'blah' 'blah' You don't need to use the ternary statement: y = (some complex expression) if not y: y = "blah" If you find yourself using it a lot, why not add it to your site's utilities modules? Take your time, and if you find numerous uses, present them and make the case Python should have a built-in to do it, something like 'ditto' marks: (6- (3<< 1) ) if ditto else 'blah' From sam.falvo at gmail.com Wed Oct 8 14:24:39 2008 From: sam.falvo at gmail.com (Samuel A. Falvo II) Date: Wed, 8 Oct 2008 11:24:39 -0700 (PDT) Subject: Using subprocess module to launch a shell shell script that itself forks a process References: Message-ID: <55ad9b25-96f2-40d9-8eb9-f7ddb95e135e@u29g2000pro.googlegroups.com> On Oct 7, 6:23?pm, "Gabriel Genellina" wrote: > Is your shell script doing something else, apart from invoking the java ? > process? Obviously, yes. The script is some 150 lines long. But the hang-up occurs because of the forked Java process, not the other lines. > If not, you could just invoke java directly from Python. Also, ? > you set stdin=PIPE - is your java process expecting some input? you're not ? > writing anything to stdin. It does not expect input from stdin. However, this does not affect any OTHER scripts or commands I run. Let's remember to look at the objective facts: for shell scripts that launch child processes of their own, Python hangs. For all other types of commands, it works 100% as expected. > Anyway, it's better to use the communicate method instead (it uses select ? > to read from both stdout and stderr): That doesn't help me. > See ?http://docs.python.org/library/subprocess.html#subprocess.Popen.commu... I have. From bthayre at physics.ucsd.edu Mon Oct 20 15:08:38 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 20 Oct 2008 12:08:38 -0700 (PDT) Subject: quick newbie syntax question Message-ID: <536f9be2-4f02-4950-ac23-1b0fafc32cd3@i18g2000prf.googlegroups.com> Is it possible to do something like this syntactically: year = '2008' month = '09' limit = '31' for i in range(1,limit): temp = Table.objects.filter(date = year'-'month'-'i) <----screwed up syntax ...do something with temp return I know that the syntax within the filter statement is wrong. Is it even possible to do something like that? Any help is always appreciated. From jason.scheirer at gmail.com Wed Oct 1 15:10:45 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 1 Oct 2008 12:10:45 -0700 (PDT) Subject: decent interactive python shell on MS Windows? References: Message-ID: <89393fc8-5d6b-47a4-abef-801f4d52dbf4@l42g2000hsc.googlegroups.com> On Oct 1, 9:53?am, james.kiri... at gmail.com wrote: > Hi everyone, > > After having used Python on Linux for some time, I now have to do > Python coding on Windows. I am big fan of the interactive Python shell > to test, eg, regexps. > > Is there an interactive Python shell on Windows that supports: > > - easy copy-pasting to/from an editor? (as opposed to the cumbersome > "mark", "copy" and then "paste" sequence that any terminal on Windows > seems forced to adopt) > > - readline-like command history (up/down for previous/next command, > Ctr-R for searching, etc) ? > > I have tried the python.org shell (difficult copy-pasting), > ActiveState's (no readline command history) and iPython (difficult > copy-pasting). Do you know of any decent interactive python shell on > Windows that comes close to the friendliness of the standard one on > Linux? > > Thanks in advance > > James Which is the 'standard' one you use on Linux? Are you unhappy with Idle? It's there in your start menu under Python. You can also try PythonWin's python interpreter, which is pretty nice, and PyCrust/ PyShell/etc, which come with the wxPython demo bundle. Then you can move up to Komodo or the Wing IDE, which are more comprehensive but not really nice for just the sort of regex-testing, desktop calculator tasks where you want something up and running quickly. From rex.eastbourne at gmail.com Fri Oct 24 15:55:44 2008 From: rex.eastbourne at gmail.com (Rex) Date: Fri, 24 Oct 2008 12:55:44 -0700 (PDT) Subject: from package import * without overwriting similarly named functions? References: <80503fdf-7792-4571-825c-27e0c5a59cb5@u29g2000pro.googlegroups.com> Message-ID: <19038c13-9fd3-47c9-a80c-e0827af0274a@d70g2000hsc.googlegroups.com> If you're concerned about specific individual functions, you can use: from package1 import some_function as f1 form package2 import some_function as f2 From georgeryoung at gmail.com Mon Oct 20 22:41:33 2008 From: georgeryoung at gmail.com (zaarg) Date: Mon, 20 Oct 2008 19:41:33 -0700 (PDT) Subject: How is the logical processing being done for strings like 'Dog' and 'Cat' References: <299cad90-7aed-40ba-9d57-f1daa9cd1b9e@u57g2000hsf.googlegroups.com> Message-ID: <7c5fbb11-51c1-4d65-bd4a-c5d4b423abd6@r66g2000hsg.googlegroups.com> On Oct 20, 9:41?pm, Sumitava Mukherjee wrote: > Hi all, > I am a novice programmer in Python. > Please could you explain me the results (regarding logical operators). > > I get this: > > >>> print bool('God' and 'Devil') > > True > > [This is ok because (any) string is True, Not quite so. Be careful with this. The empty string gets False: print bool("") --> False Any *non-empty* string gets True. > so; (True and True) gives > True] > > >>> print('God' and 'Devil') > > Devil > > [This is what I don't get ] > and for that matter,I also checked out this: > > >>> 01 and 10 > > 10 Note that AND is a boolean operator, not a bit operator. If you want to hack bits of an integer, use the "binary bitwise operators" http://docs.python.org/reference/expressions.html#binary-bitwise-operations e.g. >>> 01 & 10 0 >>> 01 | 10 11 > > What is python doing when we type in ('God' and 'Devil') or key in (01 > and 10) ? From duncan.booth at invalid.invalid Wed Oct 15 06:45:51 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Oct 2008 10:45:51 GMT Subject: Win32api.MessageBox References: <054dc2ef-e1aa-40e7-881f-c61f1ad85e4c@q26g2000prq.googlegroups.com> <48f5a95d$0$12029$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Unkwntech a ?crit : >> When I use win32api.MessageBox from the interactive console from an >> app that runs at the command line, it works and displays my alert just >> fine however when I use it in a service that I built I can hear the >> 'beep' but the alert does not show and the program seems to stall >> waiting for the alert to close, how can I have the alert show so that >> the user can see what it says and press the button? > > I'm by no mean a Win32 expert, but IIRC, Windows 'services' (IOW : > daemons) are not suppose to directly interact with the user. Now you'd > better not take me on words on this... > It's an option when you install the service. By default services will run under the 'local system' account and have no access to the desktop. You can either give the service permission to interact with the desktop from the service properties (or specify --interactive if installing it with win32serviceutil). -- Duncan Booth http://kupuguy.blogspot.com From drobinow at gmail.com Sat Oct 18 17:09:55 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sat, 18 Oct 2008 14:09:55 -0700 (PDT) Subject: PythonWin --> drwatson References: Message-ID: On Oct 18, 4:31?pm, Dennis Lee Bieber wrote: > On Sat, 18 Oct 2008 15:00:03 GMT, "Frank L. Thiel" > declaimed the following in comp.lang.python: > > Thanks for your reply, Allan. ?I am not sure what you mean by "the > > Windows installer package" -- a *.msi file?. ?I cannot find a *.msi file > > at Sourceforge, which is where the came > > from. ?When I use the latter (I have uninstalled and reinstalled using > > this many times now!), I get no error entries in the Event Viewer. > > However, when I try to open PythonWin, the Event Viewer shows the > > following message: > > ? ? ? ? Do you have a version of python 2.6 installed? (I'm surprised the > standalone win32 package for Python 2.6 is even available already). > Granted, win32 is maintained as a separate package, but the ActiveState > Python download (which includes it by default) is still only on Python > 2.5.2 The standalone package has been available for months, since the Alpha stage I believe. I don't believe it will install without an installed Python 2.6. PythonWin 2.6 of Oct 2 2008 works for me. XP Pro service pack 3. [ActiveState is not really relevant to this discussion.] From hniksic at xemacs.org Tue Oct 7 03:45:39 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 07 Oct 2008 09:45:39 +0200 Subject: Array of dict or lists or ....? References: Message-ID: <87ljx0j1b0.fsf@mulj.homelinux.net> Tim Chase writes: >>> __repr__ = __str__ >> >> I don't know if that's a good practice. > > I've seen it in a couple places, and it's pretty explicit what it's > doing. But what's the point? Simply define __repr__, and both repr and str will pick it up. From tjreedy at udel.edu Thu Oct 9 18:03:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2008 18:03:37 -0400 Subject: Python HTML parser chokes on UTF-8 input In-Reply-To: <4m72s5xlgn.ln2@joeserver.homelan.net> References: <4m72s5xlgn.ln2@joeserver.homelan.net> Message-ID: Johannes Bauer wrote: > Hello group, > > I'm trying to use a htmllib.HTMLParser derivate class to parse a website > which I fetched via > httplib.HTTPConnection().request().getresponse().read(). Now the problem > is: As soon as I pass the htmllib.HTMLParser UTF-8 code, it chokes. The > code is something like this: I believe you are confusing unicode with unicode encoded into bytes with the UTF-8 encoding. Having a problem feeding a unicode string, not 'UFT-8 code', which in Python can only mean a UTF-8 encoded byte string. > > prs = self.parserclass(formatter.NullFormatter()) > prs.init() > prs.feed(website) > self.__result = prs.get() > prs.close() > > Now when I take "website" directly from the parser, everything is fine. > However I want to do some modifications before I parse it, namely UTF-8 > modifications in the style: > > website = website.replace(u"f??", u"b?r") > > Therefore, after fetching the web site content, I have to convert it to > UTF-8 first, modify it and convert it back: > > website = website.decode("latin1") # produces unicode > website = website.replace(u"f??", u"b?r") #remains unicode > website = website.encode("latin1") # produces byte string in the latin-1 encoding > > This is incredibly ugly IMHO, as I would really like the parser to just > accept UTF-8 input. To me, code that works is prettier than code that does not. In 3.0, text strings are unicode, and I believe that is what the parser now accepts. >However when I omit the reecoding to latin1: > > File "CachedWebParser.py", line 13, in __init__ > self.__process(website) > File "CachedWebParser.py", line 55, in __process > prs.feed(website) > File "/usr/lib64/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib64/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib64/python2.5/sgmllib.py", line 285, in parse_starttag > self._convert_ref, attrvalue) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 0: > ordinal not in range(128) When you do not bother to specify some other encoding in an encoding operation, sgmllib or something deeper in Python tries the default encoding, which does not work. Stop being annoyed and tell the interpreter what you want. It is not a mind-reader. > Annoying, IMHO, that the internal html Parser cannot cope with UTF-8 > input - which should (again, IMHO) be the absolute standard for such a > new language. The first version of Python came out in 1989, I believe, years before unicode. One of the features of the new 3.0 version is that is uses unicode as the standard for text. Terry Jan Reedy From jcd at sdf.lonestar.org Tue Oct 21 13:53:35 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 21 Oct 2008 13:53:35 -0400 Subject: Changing the middle of strings in a list--I know there is a better way. In-Reply-To: References: Message-ID: <1224611615.9133.9.camel@aalcdl07.lib.unc.edu> On Tue, 2008-10-21 at 10:28 -0700, Ben wrote: > Hello All: > > I am new to Python, and I love it!! I am running 2.6 on Windows. I > have a flat text file here is an example of 3 lines with numbers > changed for security: > > 999999999088869199999999990200810999999 > 999999999088869199999999990200810999999 > 999999999088869199999999990200810999999 > > > I want to be able to replace specific slices with other values. My > code below reads a file into a list of strings. Since strings are > immutable I can't assign different values to a specific slice of the > string. How can I accomplish this? I read some posts on string > formatting but I am having trouble seeing how I can use those features > of the language to solve this problem. > > The code below just puts an 'R' at the beginning of each line like > this: > > R999999999088869199999999990200810999999 > R999999999088869199999999990200810999999 > R999999999088869199999999990200810999999 > > > But what I want to do is change the middle of the string. Like this: > > R999999999088869CHANGED99990200810999999 > R999999999088869CHANGED99990200810999999 > R999999999088869CHANGED99990200810999999 > Well, it depends on what you want. Do you want to replace by location or by matched substring? One of the following functions might help. lines = ['999999999088869199999999990200810999999' '99999999088869199999999990200810999999' '9999999088869199999999990200810999999'] def replace_by_location(string, replacement, start, end): return string[:start] + replacement + string[end:] def replace_by_match(string, substr, replacement): return replacement.join(string.split(substr)) location_lines = [replace_by_location(x, 'CHANGED', 15, 22) for x in lines] match_lines = [replace_by_match(x, '1999999', 'CHANGED') for x in lines] print location_lines print match_lines Cheers, Cliff > #My Current Code > > # read the data file in as a list > F = open('C:\\path\\to\file', "r") > List = F.readlines() > F.close() > > #Loop through the file and format each line > a=len(List) > while a > 0: > > List.insert(a,"2") > a=a-1 > > # write the changed data (list) to a file > FileOut = open("C:\\path\\to\\file", "w") > FileOut.writelines(List) > FileOut.close() > > Thanks for any help and thanks for helping us newbies, > > -Ben > -- > http://mail.python.org/mailman/listinfo/python-list > From bockman at virgilio.it Sun Oct 19 06:13:44 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 19 Oct 2008 10:13:44 GMT Subject: Porting VB apps to Python for Window / Linux use References: <48FAE71B.2080205@gmail.com> <880dece00810190123n1aaffabfrd5e89178f7bee0d4@mail.gmail.com> Message-ID: <48fb0858$0$11368$5fc30a8@news.tiscali.it> Il Sun, 19 Oct 2008 10:34:23 +0200, Stef Mientki ha scritto: ... I'm very > satisfied with Python, and must say it's much more beautiful language > than Delphi, seen over the full width of programming. Although both > languages are Object Oriented, for some (unknown) reason it's 10 times > easier to maintain and extend libraries in Python than in Delphi. > I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! And > with wxPython and some tools I made, I almost have the same environment > as Delphi. > IMO: - dynamic typing - powerful built-in types like lists, sets and dictionaries - very rich function definition syntax, with multiple returns, yield, values passed by position and by name, automatic grouping of parameters in list/dictionaries - rich standard library, which becomes impressive if you accound for all the non standard modules that you find in internet. And, unlike another language wich shall remain unnamed (starts with J), most of python library modules have the same pratical approach of C standard library. Never used seriously delphi, but played a little with it: IIRC, under the nice IDE and GUI toolkit, the language itself is a kind of object-pascal. This would place it more or less at the same level of abstraction of Java, way below languages like python and ruby, Ciao ----- FB From castironpi at gmail.com Fri Oct 3 13:11:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 3 Oct 2008 10:11:04 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> <80ffbfcf-9fbc-458a-aaf0-ffea24db390f@34g2000hsh.googlegroups.com> <6km4oqF8ipieU1@mid.individual.net> Message-ID: <87fe64e7-82a4-4b3b-a0a0-e3f7b3ab5940@k30g2000hse.googlegroups.com> On Oct 3, 3:44?am, greg wrote: > jhermann wrote: > > I didn't see this mentioned in the thread yet: the double-lambda is > > unnecessary (and a hack). > > Well, the alternative -- abusing default argument values -- > is seen by many to be a hack as well, possibly a worse one. > It doesn't work in general, e.g. it fails if the function > needs to be called with a variable number of arguments. > > The double lambda is conceptually more sound in some > ways, and can be made to work correctly in all cases. > > The root of the problem actually has nothing to do with > lambdas or static vs. non-static scoping. It's the fact > that Python's for-loop doesn't create a new environment > for the loop variable each time around, but re-uses a > slot in the containing environment. > > Contrast this with Scheme, where the equivalent of a > for-loop *does* create a new environment for each > value of the loop variable. Effectively it's using a > double lambda, except that one of the lambdas is > folded into the syntax of the loop, so you don't > notice it. > > So if anything were to be done to the language to > fix this, it really should be focused on fixing the > semantics of the for-loop. Unfortunately, the > fact that the loop variable leaks out of the scope > of the loop is regarded as a feature, so anything > which changes that seems to be a non-starter. > > -- > Greg I agree that the default argument syntax is an abuse, but it accomplishes exactly what I want: to create a copy of a namespace. I don't think there's a way to create a closure in Python without another function, so you might need new syntax if you wanted to. Otherwise, using function syntax, I want a new namespace on each iteration that nests inside the old one, except for one variable which overrides the outer scope. I agree that a new variable isn't the obviously correct meaning of a for loop, and functions are the same as a new scope, just you have to call them, so why not use them as is? (untested) for i in range( 3 ): def f( n ): def g( ): return n return g closures[ i ]= f( i ) Or: (non-standard) for i in range( 3 ): closure f( i ): def g( ): return i return g closures[ i ]= f Here the only difference is whether you call 'f' or not. 'closure' would theoretically "call itself", and make a copy of its scope upon execution of the definition, overriding the arguments. So, functions are the same. From metallourlante at gmail.com Tue Oct 28 13:22:01 2008 From: metallourlante at gmail.com (Alex) Date: Tue, 28 Oct 2008 10:22:01 -0700 (PDT) Subject: Web crawler on python References: <43e872d5-9f54-4195-ab70-b71aa7f5cd85@y71g2000hsa.googlegroups.com> Message-ID: <319bf35c-7aca-495f-b7bf-da158bf39b63@p10g2000prf.googlegroups.com> On Oct 26, 9:54?pm, sonich wrote: > I need simple web crawler, > I found Ruya, but it's seems not currently maintained. > Does anybody know good web crawler on python or with python interface? You should try Orchid http://pypi.python.org/pypi/Orchid/1.1 or you can have a look at my project on launchpad https://code.launchpad.net/~esaurito/jazz-crawler/experimental. It's a single site crawler but you can easily modified it. Bye. Alex From kay.schluehr at gmx.net Fri Oct 10 14:03:40 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 10 Oct 2008 11:03:40 -0700 (PDT) Subject: python 3: sorting with a comparison function References: <6l74hpFauga7U1@mid.individual.net> Message-ID: On 10 Okt., 19:22, prueba... at latinmail.com wrote: > On Oct 10, 8:35 am, Kay Schluehr wrote: > > > On 9 Okt., 22:36, bearophileH... at lycos.com wrote: > > > > Yes, that's a wonderful thing, because from the code I see around > > > 99.9% of people see the cmp and just use it, totally ignoring the > > > presence of the 'key' argument, that allows better and shorter > > > solutions of the sorting problem. > > > Me too because I don't get this: > > > "key specifies a function of one argument that is used to extract a > > comparison key from each list element: key=str.lower. The default > > value is None." > > > Kay > > Don't know if further explanation is needed, but here is the deal: > > cmp is a function that receives two values and you return -1, 0 or 1 > depending if the first is smaller, equal or bigger. 99% of the time > you will do some operation on the values that come in and then do a if > statement with ">" or "<" and return -1,0,1. > > key is a function that receives one value and you return the value > that you would normally compare against. > > Let me show an example: > > >>> data=[(4,'v'),(2,'x'),(1,'a')] > >>> sorted(data) > > [(1, 'a'), (2, 'x'), (4, 'v')] > > OK, we sorted the data, but What if we want to sort by the letter > instead of the number? Let's use cmp: > > >>> def comp(x, y): > > ? ? ? key_of_x=x[1] > ? ? ? key_of_y=y[1] > ? ? ? if key_of_x < key_of_y: > ? ? ? ? return -1 > ? ? ? elif key_of_x > key_of_y: > ? ? ? ? return 1 > ? ? ? else: > ? ? ? ? return 0 #key_of_x == key_of_y > > >>> sorted(data,cmp=comp) > > [(1, 'a'), (4, 'v'), (2, 'x')] > > Very well, so how do we do this using key? > > >>> def keyfunc(x): > > ? ? ? key_of_x=x[1] > ? ? ? return key_of_x > > >>> sorted(data,key=keyfunc) > > [(1, 'a'), (4, 'v'), (2, 'x')] > > Same output. Very good. > > (Of course a smart python developer would use the operator module so > he doesn't even have to write keyfunc but this was just an example) > > In summary to transform most cmp functions to a key function you just > take the code that calculates the first value to be compared and leave > out the rest of the logic. > > Hope that was helpful. Yes, thanks a lot. In essence the "key" is a function that maps each list element onto a value of a type for which a known order is defined e.g. an integer. Applying sorted() sorts the list elements according to the list of those values. Sometimes it helps when people just make clear how they use technical terms instead of invoking vague associations. From http Thu Oct 2 01:27:42 2008 From: http (Paul Rubin) Date: 01 Oct 2008 22:27:42 -0700 Subject: RELEASED Python 2.6 final References: Message-ID: <7x4p3vefch.fsf@ruckus.brouhaha.com> Barry Warsaw writes: > http://docs.python.org/dev/whatsnew/2.6.html Wow! This is a very major upgrade with lots of welcome extensions. I hadn't been following the 2.6 efforts that closely so I am awed. Congrats! From gordallott at gmail.com Fri Oct 10 17:16:01 2008 From: gordallott at gmail.com (Gordon Allott) Date: Fri, 10 Oct 2008 22:16:01 +0100 Subject: extracting null pointer address from PyCObject with ctypes In-Reply-To: References: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> Message-ID: <48EFC611.9020306@gmail.com> Aaron "Castironpi" Brady wrote: > I see. If I understand, you have a PyCObject in a dictionary. > > Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr. Its > return type should be 'c_void_p', and you can use 'result.value' to > get the original pointer. > -- > http://mail.python.org/mailman/listinfo/python-list I have a hard time following that, if using ctypes you used PyDLL to call PyCObject_AsVoidPtr on the PyCObject I already have surely it would give me back a pointer (void for sake of simplicity) but it would be a pointer to a new PyCObject and thus calling result.value on it would only return the memory address of the new PyCObject? -- Gord Allott (gordallott at gmail.com) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From castironpi at gmail.com Fri Oct 17 18:50:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 17 Oct 2008 15:50:36 -0700 (PDT) Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> Message-ID: <610291a5-04b4-4d88-8e4b-d81da6c56576@k16g2000hsf.googlegroups.com> On Oct 17, 4:03?pm, Joe Strout wrote: > On Oct 17, 2008, at 2:36 PM, Steve Holden wrote: snip > And here, you're doing an assignment -- this is the only test of the ? > three that tests whether the parameter is passed by reference or by ? > value. ?The result: it's by value. > > > So, is it call by reference or not? > > Not. But it's not by value, q.e.d. snip > ...except, of course, that Python's syntax is cleaner... Excepting that thou then proceedst to 3. snip From areyoulookon at gmail.com Fri Oct 10 06:58:08 2008 From: areyoulookon at gmail.com (lookon) Date: Fri, 10 Oct 2008 03:58:08 -0700 (PDT) Subject: a regular expression problem Message-ID: <06c5bc01-7ca6-4f61-b856-c1d9efff739f@u29g2000pro.googlegroups.com> I want to use django to dispatch url. The url is like /test/Google/6,and my patten is r'^/test/(?P\b\W+ \b)/(?P\d+)$'. It works when the string is English(like Google), but fails when the string is in foreign language. Can anyone tell me the righ regular expression? Thank you! From hv at tbz-pariv.de Wed Oct 1 11:12:55 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 01 Oct 2008 17:12:55 +0200 Subject: Event-driven framework (other than Twisted)? In-Reply-To: References: <4d191607-14e3-42c4-8622-0cc4c7339550@d31g2000hsg.googlegroups.com> Message-ID: <6khibnF7p971U2@mid.individual.net> Phillip B Oldham schrieb: > On Oct 1, 9:25 am, Lie Ryan wrote: >> Most GUI package use event-driven model (e.g. Tkinter). > > I've noticed that. I'm thinking more for a web environment (instead of > MVC) or as a HTTP server. I know Twisted has TwistedWeb, but I'm > looking for alternatives. Please explain what you want to do. Maybe the spread toolkit can help you: http://www.spread.org/index.html HTH, Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From prologic at shortcircuit.net.au Thu Oct 2 07:02:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 2 Oct 2008 21:02:12 +1000 Subject: Event-driven framework (other than Twisted)? In-Reply-To: <4bb00bab-13eb-4b7d-99e5-8cbad58ebd47@z72g2000hsb.googlegroups.com> References: <4d191607-14e3-42c4-8622-0cc4c7339550@d31g2000hsg.googlegroups.com> <4bb00bab-13eb-4b7d-99e5-8cbad58ebd47@z72g2000hsb.googlegroups.com> Message-ID: On 10/2/08, Phillip B Oldham wrote: > On Oct 2, 1:28 am, "James Mills" wrote: > > Phillip, I have been developing a rather unique > > event-driven and component architecture library > > for quite some time that is (not twisted). Actually > > it's nothing like twisted, but based on 2 core > > concepts: > > * Everything is a Component > > * Everything is an Event > > > > It's currently called pymills.event > > Let me know if you're interested, I probably > > plan to re-package and re-branch this library > > (the event library) at some point. > > > I'd be very interested in seeing this. Component-based programming is > something which interests me also. Phillip, you can normally clone my library using Mercurial by doing: $ hg clone http://hg.shortcircuit.net.au/pymills/ If my VPS is still down, email me and I'll send you a tar.bz2 (or something). It may also interest you to know that I've ported my library to py3k and so far all tests are working :) Thanks, cheers James -- -- -- "Problems are solved by method" From stef.mientki at gmail.com Sun Oct 19 14:50:46 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 19 Oct 2008 20:50:46 +0200 Subject: What's the perfect (OS independent) way of storing filepaths ? In-Reply-To: <92da89760810191049s7d0fa4e5p675ae584d7b7bfbc@mail.gmail.com> References: <92da89760810191049s7d0fa4e5p675ae584d7b7bfbc@mail.gmail.com> Message-ID: <48FB8186.1040709@gmail.com> Eric Wertman wrote: >>> I (again) wonder what's the perfect way to store, OS-independent, >>> filepaths ? >>> > > I'm in agreement that perfect probably isn't applicable. If I were > doing this myself, I might store the information in a tuple: > > base = 'some root structure ('/' or 'C') > path = ['some','set','of','path','names'] > filename = 'somefile.ext' > > pathdata = (root,path,filename) > > and write a couple of simple functions to reconstruct them based on the os. > Eric, I like your idea. It looks like a workable technique, the user should initial define the roots once and everything works. It should even work for network drives and websites. Duncan, in windows it's begin to become less common to store settings in Docs&Settings, because these directories are destroyed by roaming profiles (a big reason why I can't run Picassa ;-( It's more common to follow the portable apps approach, store them in the application directory. Drobinow, I want to distribute an application with a large number of docs and examples. Now for this application I can put everything in subpaths of the main-application, but you triggered me to put a warning in my code if I go outside the application path. Another application I've in mind, is a data manager (now written in Delpi), in which I organize all my information: docs, websites, measurement data etc. Others, thank you for the ideas, you learende me some new os.path functions. cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From cvrebert at gmail.com Wed Oct 1 17:02:45 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Wed, 1 Oct 2008 14:02:45 -0700 Subject: Tkinter on WIndows XP opens a blank screen. How can I get rid of it? In-Reply-To: References: Message-ID: <13311BCD-C611-4C70-8CFB-763C7DE2F22E@gmail.com> Run your script using pythonw.exe instead of python.exe ; it doesn't open a console window and exists for this exact purpose. Cheers, Chris Rebert On Sep 30, 2008, at 1:28 PM, dudeja.rajat at gmail.com wrote: > Hi, > > > I m using Tkinter and Tix to create a GUI on Windows XP. So far I've > created the GUI and it just works. > > > But the problem is as soon as I double click on the script it > besides opening the GUI also opens a shell ( a blank screen) with > it. Pleas suggest how can I get rid of this blank screen. > > My program is staring as : > > > > myRoot = Tix.Tk() > myRoot.title("Test Automation") > > < some stuff> > < ...............> > > myRoot.mainloop() > > > Thanks and regadrs, > Rajat > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sat Oct 4 05:16:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 04 Oct 2008 19:16:35 +1000 Subject: how to get a class instance name during creation? References: <0453dfc1-fa3e-4d6d-840b-0e93b3d845d6@79g2000hsk.googlegroups.com> <48e68462$0$10441$426a34cc@news.free.fr> Message-ID: <87ljx4n2j0.fsf@benfinney.id.au> dmitrey writes: > On Oct 3, 9:46?pm, Bruno Desthuilliers > wrote: > > x = MyClass() > > y = x > > del x > > > > objects = [MyClass() for i in range(100)] > > > > If you can come with a meaningfull answer to "what's *the* name of > > any of the MyClass instance(s)" in both cases, then please let us > > know... > > I had seen the examples during google search, still I hoped for an > answer to my exact situation. I know for sure there will be no > renaming and creating like the above objects = [MyClass() for i in > range(100)]. You *know* this, *for sure*? The only way I can think of that would give you such certain knowledge that such a situation will not happen is an automated, full-coverage unit test suite of all code that uses your class. Which is an excellent position to be in, so I commend you on your diligence. So, why is it that you wish to restrict users of your class to never do such normal operations with instances as in the above examples? What problem are you solving by this restriction? -- \ ?Holy human pressure cookers, Batman!? ?Robin | `\ | _o__) | Ben Finney From leonhard.vogt at gmx.ch Thu Oct 2 16:09:38 2008 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Thu, 02 Oct 2008 22:09:38 +0200 Subject: Tkinter Entry blocked by tkFileDialog Message-ID: <2c1c3$48e52a6d$544b153e$30113@news.hispeed.ch> Hello I have the following problem in Python 2.5 on Windows XP. On Ubuntu I do not see the problem. I have a Tkinter application as in the following example The entry-widget is somehow blocked (i cannot type characters into it) when I call askopenfilename before I create the widget. Calling askopenfile again (by clicking the button) releases the block, I can type into the entry as expected. Could someone please try out the example and tell if you observe the blocked entry, too? Do you know a workaround? I want to call askopenfilename before creating the widgets, since i use it to choose a config file which controls the number and type of widgets I create. Regards Leonhard import Tkinter import tkFileDialog tk = Tkinter.Tk() tkFileDialog.askopenfilename() Tkinter.Entry(tk).grid() Tkinter.Button(tk, text='ask', command=tkFileDialog.askopenfilename).grid() tk.mainloop() From sjmachin at lexicon.net Tue Oct 21 19:10:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 21 Oct 2008 16:10:54 -0700 (PDT) Subject: a question about Chinese characters in a Python Program References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> <1736d4c0-8a8f-4587-a4a7-fe499a141162@e38g2000prn.googlegroups.com> <86f1524d-9608-4d5c-9963-c20dee0503e4@b38g2000prf.googlegroups.com> <873aiq5f5l.fsf@benfinney.id.au> Message-ID: <3dd16f7b-5b84-42f8-8144-13cc4badc1b4@t39g2000prh.googlegroups.com> On Oct 21, 11:03?pm, Ben Finney wrote: > John Machin writes: > > I don't understand the point or value of filtering out all byte values > > greater than 127 > > That's only done if the encoding isn't otherwise specified. In which > case, ASCII is the documented default encoding. In which case, it > *must* be restricted to code points 0+IBM-127, otherwise it's not ASCII. > > The value of doing this is to make it rapidly and repeatably apparent > when the programmer's assumptions about character encoding are false, > allowing the programming error to be fixed early rather than late. "make it rapidly and repeatably apparent ..." is much better achieved by raising an exception. > This is, in my estimation, of more value than heuristic magic to > +IBw-guess+IB0- the encoding, and the resultant debugging nightmare when > that guesswork fails in unpredictable ways later in the program's > life. Was I suggesting "heuristic magic"? What is that 0+IBM-127 +IBw-guess+IB0- gibberish in your posting? From stefan_ml at behnel.de Tue Oct 14 16:25:33 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 14 Oct 2008 22:25:33 +0200 Subject: C API with *args and **kw In-Reply-To: References: Message-ID: <48f5003d$0$17135$9b4e6d93@newsspool2.arcor-online.net> Miki wrote: > I'm try to write the C equivalent of: > > def kw(*args, **kw): > print "%d args" % len(args), > if "default" in kw: > print "default is %s" % kw["default"] > else: > print "no default" Consider using Cython instead, it will make your life a lot easier. The above is valid Cython code that the Cython compiler translates into optimised C code. http://cython.org/ Stefan From wegwerp at gmail.com Tue Oct 21 12:37:01 2008 From: wegwerp at gmail.com (Bas) Date: Tue, 21 Oct 2008 09:37:01 -0700 (PDT) Subject: Need some advice References: Message-ID: On Oct 21, 5:43 pm, azrael wrote: > Need some advice I advice to come up with a more specific subject line for your posts, might give you some more answers .... From castironpi at gmail.com Wed Oct 8 23:35:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 8 Oct 2008 20:35:00 -0700 (PDT) Subject: inspect feature Message-ID: <4a893f80-adfd-4998-94f4-a095d62f845e@x41g2000hsb.googlegroups.com> Hello, The 'inspect' module has this method: inspect.getargvalues(frame) It takes a frame and returns the parameters used to call it, including the locals as defined in the frame, as shown. >>> def f( a, b, d= None, *c, **e ): ... import inspect ... return inspect.getargvalues( inspect.currentframe() ) ... >>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' ) (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1, 'e': {'h': 'g hi'}, 'd': 'abc', 'inspect': }) However, if you wanted a decorator that examines the parameters to a function, you're out of luck. By the time you have a frame, you're already in the function. Perhaps it would not be as common as something like 'join' for example, or even the rest of the functions in 'inspect', but do you think something similar to 'getargvalues' that accepted a function and an argument list, and returned a dictionary mapping parameters to values, could be useful? From castironpi at gmail.com Sat Oct 11 01:06:46 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 10 Oct 2008 22:06:46 -0700 (PDT) Subject: extracting null pointer address from PyCObject with ctypes References: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> Message-ID: <42a9cf1a-b5a3-428f-b547-b0bb1d9b87e2@q35g2000hsg.googlegroups.com> On Oct 10, 10:54?pm, Gordon Allott wrote: > Aaron "Castironpi" Brady wrote: > snip > >?Last, you > > haven't mentioned an attempt with PyCObject_AsVoidPtr yet: > > > void* PyCObject_AsVoidPtr(PyObject* self) > > ? ? Return the object void * that the PyCObject self was created with. > > > Where does that get you? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > sorry yes you were right, I was reading PyCObject_AsVoidPtr as > PyCObject_FromVoidPtr :) > > using AsVoidPtr is a little confusing, this is the code I am using: > ? ? ? ? display = pygame.display.get_wm_info()['display'] > ? ? ? ? pyobj = py_object(display) > ? ? ? ? ref = pointer(pyobj) > > ? ? ? ? print pythonapi.PyCObject_AsVoidPtr(ref) > > it produces the following traceback: > Traceback (most recent call last): > ? File "pygametest.py", line 125, in > ? ? app = PyGameOGREApp() > ? File "pygametest.py", line 33, in __init__ > ? ? self._createWindow(width, height, fullscreen) > ? File "pygametest.py", line 64, in _createWindow > ? ? print pythonapi.PyCObject_AsVoidPtr(ref) > TypeError: PyCObject_AsVoidPtr with non-C-object > > - I think that's because its a pointer to the ctypes py_object() rather > than the PyCObject we are dealing with but I have no idea how to create > a pointer to that. > My pygame install just returns an integer in get_wm_info. Take a look: >>> pygame.display.get_wm_info() {'window': 1180066, 'hglrc': 0} >>> pygame.display.get_wm_info()['window'] 1180066 >>> ctypes.c_void_p( _ ) c_void_p(1180066) You're suggesting yours looks like this: >>> pygame.display.get_wm_info() { ... 'display': ctypes.py_object( 1180066 ), ... } What does type( display ) give you? From gagsl-py2 at yahoo.com.ar Thu Oct 2 01:20:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Oct 2008 02:20:59 -0300 Subject: Isolated environment for execfile References: Message-ID: En Wed, 01 Oct 2008 08:11:29 -0300, Igor Kaplan escribi?: > I got quite unusual problem and all my searches to find the answer on > my > own were not successful. > Here is the scenario: > I have the python program, let's call it script1.py, this program > needs to > execute another python script, let's call it script2.py. > In script1.py I have the statement: > execfile('script2.py') > Everything is fine beside one thing. The script2.py is pretty big > python > program which does a lot of things and also while runs, it modifies many > variables and module members, such for example as sys.path. So when > script2.py exits all changes which it does are visible in my main > program, > script1.py. Even more, I need to execute script2.py in loop, several > times > during script1.py session. And all changes, which script2.py does just > accumulate. > > I wander, is there any way to execute script2.py in it's own > environment, > so when script2.py exits, all modifications, which it is done in global > modules are gone? If you want a true isolated execution, start a new Python process: subprocess.call([sys.executable, "script2.py"]) But I feel this is not the right thing to do - instead of *executing* many times script2.py, maybe you have to *import* some functions or classes from it, and then use them. -- Gabriel Genellina From blabla at dungeon.de Wed Oct 15 05:21:51 2008 From: blabla at dungeon.de (hofer) Date: Wed, 15 Oct 2008 02:21:51 -0700 (PDT) Subject: replace mothod for only one object but not for a class References: Message-ID: On Oct 14, 7:50?pm, hofer wrote: > Hi, > > I have multiple objects all belonging to the same class > ?(which I didn't implement and whose code I don't want to modify) > > Now I'd like to change one method for one object only (after it has > been created) without adding any overhead > to the call of the other object's methods. > > Is this possible? > > Example > ##### This is NOT what I'd like to do > ##### as it overwrites the method for all objects of this class > o1 = aclass() > o2 = aclass() > # call original method > o1.method() > o2.method() > # overwrite the method for the entire class > aclass.method = mymethod > o1.method() # now new method > o2.method() # now new method > > ####### What doesn't work, but what I'd like to do > o1 = aclass() > o2 = aclass() > # call original method > o1.method() > o2.method() > # overwrite the method for the entire class > o1.method = mymethod > o1.method() # now new method > o2.method() # still old method > > thanks for any pointers. > > P.S. I guess, that there is a computer science term for what I try to > achieve. > If anybody knew it I would be interested to learn it as well. Thanks a lot this works. Though I must admint, that even after reading the doc I don't really understand why. From jordan.taylor2 at gmail.com Thu Oct 16 20:43:29 2008 From: jordan.taylor2 at gmail.com (Jordan) Date: Thu, 16 Oct 2008 17:43:29 -0700 (PDT) Subject: Unicode File Names Message-ID: I've got a bunch of files with Japanese characters in their names and os.listdir() replaces those characters with ?'s. I'm trying to open the files several steps later, and obviously Python isn't going to find '01-????.jpg' (formally '01-????.jpg') because it doesn't exist. I'm not sure where in the process I'm able to stop that from happening. Thanks. From bearophileHUGS at lycos.com Thu Oct 23 04:27:59 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 23 Oct 2008 01:27:59 -0700 (PDT) Subject: "Find" in list of objects References: <5816f329-67ca-4255-a1f2-bce72dbb8ae2@u46g2000hsc.googlegroups.com> Message-ID: <97162684-e463-429a-afa0-983c540ebb61@e17g2000hsg.googlegroups.com> Andreas M?ller: > is there a construct like > list.find (10, key='ID') You can create yourself a little convenience function, or you can use something like the following. First some testing code: class C: def __init__(self, id): self.id = id def __repr__(self): return "<%s>" % self.id seq = map(C, [1, -5, 10, 3]) print seq That prints: [<1>, <-5>, <10>, <3>] Then you can find the index of all the classes with id = 10: print [i for i, obj in enumerate(seq) if obj.id == 10] It returns a [2]. If seq doesn't contain the requires object(s) it returns an empty list. Or just the first, working lazily: print (i for i, obj in enumerate(seq) if obj.id == 10).next() This time if seq doesn't contain the requires object(s) it raises a StopIteration exception. You can of course wrap that into a function, using seq and 10 as arguments. Bye, bearophile From ppearson at nowhere.invalid Wed Oct 29 18:43:58 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 29 Oct 2008 22:43:58 GMT Subject: beutifulsoup References: <7d11954e-5e8b-4ed1-8c12-432c8ffef95b@k37g2000hsf.googlegroups.com> Message-ID: <6ms79dFil3scU1@mid.individual.net> On Wed, 29 Oct 2008 09:45:31 -0700 (PDT), luca72 wrote: > Hello > I try to use beautifulsoup > i have this: > sito = urllib.urlopen('http://www.prova.com/') > esamino = BeautifulSoup(sito) > luca = esamino.findAll('tr', align='center') > > print luca[0] > [The following long string has been wrapped.] >>> > > I need to get the following information: > 1)Only|G|BoT|05 > 2)#1 > 3)44.4MB > 4)Pc-prova.rar > with: print luca[0].a.string i get #1 > with print luca[0].td.string i get 44.4MB > can you explain me how to get the others two value Like you, I struggle with BeautifulSoup; but perhaps this will help while waiting for somebody smarter to join the thread: >>> soup = BeautifulSoup.BeautifulSoup( ... """""" ) >>> tr = soup.findAll( 'tr' ) >>> tr[0].findAll( text = True ) [u'#1', u'44.4MB', u' Pc-prova.rar '] >>> c = tr[0].findChild( attrs={"onclick": True} ) >>> print c[ "onclick" ] t('Only|G|BoT|05','#1'); -- To email me, substitute nowhere->spamcop, invalid->net. From harijay at gmail.com Mon Oct 13 15:22:24 2008 From: harijay at gmail.com (harijay) Date: Mon, 13 Oct 2008 12:22:24 -0700 (PDT) Subject: please solve References: Message-ID: <73dbaf6f-56c0-4b04-abff-886913556761@v28g2000hsv.googlegroups.com> On Oct 12, 12:15?pm, Raymond Cote wrote: > shweta mani wrote: > > hi folks, > > i have been assigned a project on Python. i need to execute a remote > > shell script file from a windows machine through SSH twisted or > > paramiko. if it is a normal file then directly with the command ?sh > > .sh it is getting executed. > > self.conn.sendRequest(self, 'exec', common.NS(sh test1.sh), wantReply > > = 1) > > You could take a look at the Fabric project for some ideas as to how to > do this: > ? ? > > --R ALso please look at the pexpect module. This allows you to supply "human" input to automate scripts that require it. Look at http://www.noah.org/wiki/Pexpect#Description_of_Pexpect Hope this helps Harijay From deets at nospam.web.de Thu Oct 9 05:14:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Oct 2008 11:14:00 +0200 Subject: ssh problem using paramiko? References: <19857268.post@talk.nabble.com> <6l3cfaFaf356U1@mid.uni-berlin.de> Message-ID: <6l60alFatt9jU1@mid.uni-berlin.de> Steve Holden wrote: > Diez B. Roggisch wrote: >> sa6113 wrote: >> >>> I couldn't find any good source for download Openssh on the net? >>> Would you please introduce a URL for download that? >> >> http://www.vapor.com/amtelnet/ >> >> it supports only SSHv1, but I guess that's ok. >> > No, you really don't want to use SSHv1. Amtelnet won't do, it's an SSH > *server* the OP needs, I understand. Why not openssh.org? The post was not intended to be meant serious. The OP has not provided *anything* on the system he uses, what he actually needs, and so forth. So I just searched for the most unlikely implementation. Diez From ms at cerenity.org Sat Oct 25 07:35:58 2008 From: ms at cerenity.org (Michael Sparks) Date: Sat, 25 Oct 2008 12:35:58 +0100 Subject: 2.6, 3.0, and truly independent intepreters References: Message-ID: Hi Andy, Andy wrote: > However, we require true thread/interpreter > independence so python 2 has been frustrating at time, to say the > least. ?Please don't start with "but really, python supports multiple > interpreters" because I've been there many many times with people. > And, yes, I'm aware of the multiprocessing module added in 2.6, but > that stuff isn't lightweight and isn't suitable at all for many > environments (including ours). This is a very conflicting set of statements and whilst you appear to be extremely clear on what you want here, and why multiprocessing, and associated techniques are not appropriate, this does sound very conflicting. I'm guessing I'm not the only person who finds this a little odd. Based on the size of the thread, having read it all, I'm guessing also that you're not going to have an immediate solution but a work around. However, also based on reading it, I think it's a usecase that would be generally useful in embedding python. So, I'll give it a stab as to what I think you're after. The scenario as I understand it is this: * You have an application written in C,C++ or similar. * You've been providing users the ability to script it or customise it in some fashion using scripts. Based on the conversation: * This worked well, and you really liked the results, but... * You only had one interpreter embedded in the system * You were allowing users to use multiple scripts Suddenly you go from: Single script, single memory space. To multiple scripts, unconstrained shared shared memory space. That then causes pain for you and your users. So as a result, you decided to look for this scenario: * A mechanism that allows each script to think it's the only script running on the python interpreter. * But to still have only one embedded instance of the interpreter. * With the primary motivation to eliminate the unconstrained shared memory causing breakage to your software. So, whilst the multiprocessing module gives you this: * With the primary motivation to eliminate the unconstrained shared memory causing breakage to your software. It's (for whatever reason) too heavyweight for you, due to the multiprocess usage. At a guess the reason for this is because you allow the user to run lots of these little scripts. Essentially what this means is that you want "green processes". One workaround of achieving that may be to find a way to force threads in python to ONLY be allowed access to (and only update) thread local values, rather than default to shared values. The reason I say that, is because the closest you get to green processes in python at the moment is /inside/ a python generator. It's nowhere near the level you want, but it's what made me think of the idea of green processes. Specifically if you have the canonical example of a python generator: def fib(): a,b = 1,1 while 1: a,b = b, a+b yield 1 Then no matter how many times I run that, the values are local, and can't impact each other. Now clearly this isn't what you want, but on some level it's *similar*. You want to be able to do: run(this_script) and then when (this_script) is running only use a local environment. Now, if you could change the threading API, such that there was a means of forcing all value lookups to look in thread local store before looking outside the thread local store [1], then this would give you a much greater level of safety. [1] I don't know if there is or isn't I've not been sufficiently interested to look... I suspect that this would also be a very nice easy win for many multi-threaded applications as well, reducing accidental data sharing. Indeed, reversing things such that rather than doing this: myLocal = threading.local() myLocal.X = 5 Allowing a thread to force the default to be the other way round: systemGlobals = threading.globals() systemGlobals = 5 Would make a big difference. Furthermore, it would also mean that the following: import MyModule from MyOtherModule import whizzy thing I don't know if such a change would be sufficient to stop the python interpreter going bang for extension modules though :-) I suspect also that this change, whilst potentially fraught with difficulties, would be incredibly useful in python implementations that are GIL-free (such as Jython or IronPython) Now, this for me is entirely theoretical because I don't know much about python's threading implementation (because I've never needed to), but it does seem to me to be the easier win than looking for truly independent interpreters... It would also be more generally useful, since it would make accidental sharing of data (which is where threads really hurt people most) much harder. Since it was raised in the thread, I'd like to say "use Kamaelia", but your usecase is slightly different as I understand it. You want to take existing stuff that won't be written in any particular way, to encourage it to be safely reusable in a shared environment. We do do that to an extent, but I'm guessing not quite as unconstrained as you. (We specifically require usage of things in a lightly constrained manner) I suspect though that this hypothetical ability to switch a thread to search thread locals (or only have thread locals) first would itself be incredibly useful as time goes on. Kamaelia implements the kind of model that this paper referenced in the thread advocates: http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf As you'll see from this recent Pycon UK presentation: http://tinyurl.com/KamaeliaPyconUK It goes a stage further though by actively providing metaphors based around components built using inboxes/outboxes designed *specifically* to encourage safe concurrency. (heritage wise, kamaelia owes more to occam & CSP than anything else) After all we've found times when concurrency using generators is good which is most of the time - it's probably the most fundamental unit of concurrency you can get, followed by true coroutines (greenlets). Next up is threads (you can put generators into threads, but not vice versa). Next up is processes (you can put threads in processes, but not vice versa). Finishing on a random note: The interesting thing from my perspective is you essentially want something half way between threads and processes, which I called green processes for want of a decent phrase. Now that's akin to sandboxing, but I suspect leaky sandboxing might be sufficient for you. (ie a sandbox where you have to try hard to break out the box as oppose to it being trivial) I'd be pretty certain that something like green processes, or "thread local only" would be useful in the future. After all, that along with decent sandboxing would be the sort of thing necessary to allow python to be embedded in a browser. (If flash used multiple processes, it'd kill most people's systems after all, and if they don't have something like green processes, flash would make web pages even worse...) Indeed, thread local only and globals accessed via STM [1] would be incredibly handy. (I say that because generator globals and globals accessed via a CAT (which is kamaelia specific thing, but similar conceptually), works extremely well) [1] even something as lightweight as http://www.kamaelia.org/STM If a "search thread local" approach or "thread local only" approach sounds reasonable, then it may be a "leaky sandbox" approach is perhaps worth investigating. After all, a leaky sandbox may be doable. Tuppence-worthy-ly-yours,. Michael. -- http://www.kamaelia.org/GetKamaelia From george.sakkis at gmail.com Tue Oct 14 15:32:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 14 Oct 2008 12:32:53 -0700 (PDT) Subject: inspect feature References: <4a893f80-adfd-4998-94f4-a095d62f845e@x41g2000hsb.googlegroups.com> <48edc501$0$10600$426a34cc@news.free.fr> <48ef13b8$0$11215$426a34cc@news.free.fr> <6efa0c25-c00e-4bf2-ac83-79594ad081cc@v30g2000hsa.googlegroups.com> <8f31aa64-6ad3-4a58-af1e-e743538f2fa7@u28g2000hsc.googlegroups.com> <6f80a3b3-de4e-4eb4-890f-8205b0073585@i20g2000prf.googlegroups.com> Message-ID: On Oct 14, 2:35 pm, "Aaron \"Castironpi\" Brady" wrote: > On Oct 14, 9:42 am, George Sakkis wrote: > > > > > On Oct 14, 3:06 am, "Gabriel Genellina" > > wrote: > > > > En Fri, 10 Oct 2008 14:18:53 -0300, Aaron "Castironpi" Brady > > > escribi?: > > > > > On Oct 10, 3:36 am, Bruno Desthuilliers > > > 42.desthuilli... at websiteburo.invalid> wrote: > > > >> I don't get what you're after ??? The decorator has full access to both > > > >> the actual params *and* the function's signature (via > > > >> inspect.getargspec). So your initial question "if you wanted a decorator > > > >> that examines the parameters to a function" seems fully answered. You > > > >> will indeed have to write a couple lines of code if you want the same > > > >> formating as the one you'd get with inspect.currentframe(), but what ? > > > > >> FWIW, Michele Simionato's decorator module has some trick to allow for > > > >> signature-preserving decorators, so you may want to have a look - but > > > >> I'm not sure if this would solve your problem - at least in a sane way. > > > > > It's not exactly the next Millennium problem, but there are some > > > > substantial checks you have to do on a per-parameter basis to see the > > > > same thing that a function sees, when all you have is *args, **kwargs. > > > > > You are wrapping a function with this signature: > > > > > def f( a, b, c= None, *d, **e ): > > > > > You want to find out the values of 'a', 'b', and 'c' in a decorator. > > > > You have these calls: > > > > > f( 0, 1, 'abc', 'def', h= 'ghi' ) > > > > f( 0, 1 ) > > > > f( 0, 1, h= 'abc' ) > > > > f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values > > > > > How do you determine 'a', 'b', and 'c'? > > > > I'm afraid you'll have to duplicate the logic described here: http://docs.python.org/reference/expressions.html#id9 > > > To my knowledge, there is no available Python code (in the stdlib or > > > something) that already does that. > > > I wrote such a beast some time ago; it's hairy but to the best of my > > knowledge it seems to reproduce the standard Python logic:http://code.activestate.com/recipes/551779/ > > > George > > I didn't see a 'got a duplicate argument for keyword "d"' error, but I > can add one if I need to. Why don't you try it out: >>> def f( a, b, c= None, *d, **e ): pass >>> getcallargs(f, 0, 1, 'abc', c= 'def' ) Traceback (most recent call last): File "", line 1, in File "getcallargs.py", line 53, in getcallargs "argument '%s'" % (f_name,arg)) TypeError: f() got multiple values for keyword argument 'c' George From code at pizzashack.org Mon Oct 20 17:09:25 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 20 Oct 2008 17:09:25 -0400 Subject: Python equivalent for C module In-Reply-To: <48fcdbcc$0$32727$426a74cc@news.free.fr> References: <48fcdbcc$0$32727$426a74cc@news.free.fr> Message-ID: <20081020210925.GD20797@dragontoe.org> On Mon, Oct 20, 2008 at 07:29:16PM +0200, Bruno Desthuilliers wrote: > This should have been: > > fprintf(STDERR, "DEBUG: %s", msg); No, it shouldn't have. If I turn on debugging, I want the debug messages to go to stdout, so that they can be captured along with the output (of which there is almost none anyway) to clearly indicate when they happened. > STDOUT is for *normal* program outputs. Debug informations, warnings, > and all verbosity should go to STDERR. That's your opinion, and I disagree. Besides which, if you're running a program in debug mode, you're DEBUGGING... "normal" does not apply. You're being rather presumptuous... you don't even know how my program is being used. > >Then in the modules that wanted to use it, I did: > > > >from debug import DEBUG, dprint > >But I got some weird behavior. The imported copy > > It's not a copy. Actually, I'm pretty sure it is; i.e. there are two copies of the name: one in the namespace of the module, and one in the namespace of the file into which I imported it. At the time they are created, they both point to the same object. Is that not the very definition of a copy? The object itself may exist only in one place, but it has two names; one in each namespace. > >of DEBUG is > >read-only; > > It's not read-only. The *object* very much is: it is immutable. The name of that object is DEBUG, and thus DEBUG is read-only. You can make DEBUG point to a different object by binding a different value to it, but if that value is of an immutable type, it will still be a read-only object. In the sentence I wrote, as well as in general, "DEBUG" actually refers to two different things: the object bound to the name, and the name itself. It's up to the reader to infer which sense is correct given the thing being said about it. It just so happens that the English sentence I wrote refers to both simultaneously. > Just use a fully qualified name, so you dont make DEBUG local: > > import debug > print debug.DEBUG > debug.DEBUG = True > print debug.DEBUG Right, several people have already pointed this out. Which leads me to believe that the point of your reply was to berate me into following your conventions, which I have no interest in doing, in part because they are counterproductive to my goals, and in part because they are counter to the way I've been programming for 25 years. Fortunately, it's not your call how I write my code. > Now note that ALL_UPPER names are - by convention - considered > 'constants'. If this is supposed to be altered, don't write it ALL_UPPER. YOUR convention, not mine. > Also and FWIW, Python has a logging module in it's stdlib. Please use it > instead of any half-backed squared-wheel homegrown solution. Note that the correct possessive form of "it" is "its" with no apostrophe. This was the only thing of value which you contributed, though really, using that is way overkill for my needs. If I've written bad code, by all means, please correct it. If I've written code in a style that you happen not to like, please feel free to keep that to yourself. > My 2 cents Must be Zimbabwe currency... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bdesth.quelquechose at free.quelquepart.fr Mon Oct 6 17:22:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Oct 2008 23:22:08 +0200 Subject: function(s) to decode a URL produced by encodeURIComponent in javascript In-Reply-To: <47020e3b-48dc-4568-bfeb-5cab217ec578@s9g2000prg.googlegroups.com> References: <47020e3b-48dc-4568-bfeb-5cab217ec578@s9g2000prg.googlegroups.com> Message-ID: <48ea8192$0$1793$426a34cc@news.free.fr> Merrick a ?crit : (answering to itself) > sorry for answering my > own question. Don't be sorry. You're doing a great service to everyone here by letting us know the problem is solved (so we don't bother answering), and to everyone that might have the same problem (and is able to use a search engine...) by providing the solution. From gagsl-py2 at yahoo.com.ar Tue Oct 7 03:15:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Oct 2008 04:15:35 -0300 Subject: Array of dict or lists or ....? References: <48EAC0DD.1000100@tim.thechases.com> Message-ID: En Mon, 06 Oct 2008 22:52:29 -0300, Tim Chase escribi?: >>> __repr__ = __str__ [bearophileHUGS at lycos.com wrote] >> I don't know if that's a good practice. > I've seen it in a couple places, and it's pretty explicit what it's > doing. __repr__ is used as a fallback for __str__, so just defining __repr__ (and leaving out __str__) is enough. -- Gabriel Genellina From mail at timgolden.me.uk Thu Oct 2 06:32:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 02 Oct 2008 11:32:59 +0100 Subject: using SSh problem! In-Reply-To: <19776775.post@talk.nabble.com> References: <19775680.post@talk.nabble.com> <19776775.post@talk.nabble.com> Message-ID: <48E4A35B.5020903@timgolden.me.uk> sa6113 wrote: > No, my problem isn't entering password or not ? > I want to know what should I do to connect between different platform and > copy a file . Did you try searching? This looks hopeful: http://commandline.org.uk/python/2008/may/28/sftp-python/ TJG From lipun4u at gmail.com Wed Oct 29 16:56:22 2008 From: lipun4u at gmail.com (asit) Date: Wed, 29 Oct 2008 13:56:22 -0700 (PDT) Subject: project in python References: <965c0c11-dd0f-40a3-a05e-95ba64fdc943@v16g2000prc.googlegroups.com> <49034e7d$0$17392$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <965e1b59-a4e8-40a0-b00e-37abdf9869a1@p10g2000prf.googlegroups.com> On Oct 28, 10:02?am, alex23 wrote: > On Oct 26, 2:51?am, Stefan Behnel wrote: > > > The more you spam people with your repetitive postings, the less likely it > > becomes that they are willing to answer you. > > In asit's defence, the Google Groups interface has been woefully > broken for the past 3-4 days. If e had posted via it, messages > wouldn't have been visible to em until today at the earliest. After all these search and queries, I have decided to make smething about Google API. Is there an API available for google group ??? From clp at rebertia.com Thu Oct 23 15:31:26 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 23 Oct 2008 12:31:26 -0700 Subject: Python Script Bug In-Reply-To: <925471f1-8c1d-4111-82d6-e84befd455a3@79g2000hsk.googlegroups.com> References: <925471f1-8c1d-4111-82d6-e84befd455a3@79g2000hsk.googlegroups.com> Message-ID: <47c890dc0810231231k46a421a9hca3f38f74c7e3856@mail.gmail.com> On Thu, Oct 23, 2008 at 11:54 AM, max.caly at gmail.com wrote: > Hello everyone, > I would like to know what isn't good in my script. > #!/usr/bin/python > # -*- coding: iso-8859-15 -*- > from time import strftime > import datetime > t = input(datetime.date) input() does not do what you think it does. You want raw_input(). raw_input() takes a string to prompt the user with and returns the string the user enters. You'll then pass the string to time.strptime() (along with a format string) to parse it into a time tuple. You'll then pass part of the time tuple to the datetime.date() constructor to get a date object. > global t 'global' declarations are only allowed (and only make sense) inside a function. Remove the above line. Based on some of the errors you've made, I'd recommend reading through Python's fine tutorial before going any further: http://docs.python.org/tutorial/index.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > print t.strftime("Day %w of the week a %A . Day %d of the month (%B). > ") > print t.strftime("Day %j of the year (%Y), in week %W of the year.") > raw_input() > i get error : > print t.strftime("Day %w of the week a %A . Day %d of the month > (%B). ") > AttributeError: 'tuple' object has no attribute 'strftime' > Thanks for your Help > -- > http://mail.python.org/mailman/listinfo/python-list > From george.sakkis at gmail.com Tue Oct 28 12:37:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 28 Oct 2008 09:37:10 -0700 (PDT) Subject: Database specialized in storing directed graphs? References: <829ee8a7-5956-49d7-9465-a83a06537c41@m32g2000hsf.googlegroups.com> Message-ID: On Oct 27, 8:32?pm, Carl Banks wrote: > I was wondering if anyone had any advice on this. > > This is not to study graph theory; I'm using the graph to represent a > problem domain. ?The graphs could be arbitrarily large, and could > easily have millions of nodes, and most nodes have a substantial > amount of data associated with them. ?Obviously I don't want a whole > such graph in memory at once, so libraries the just deal with in- > memory graphs are out. > > I know I could implement this with a relational DB, and I'd be fine > with a library that was built on top of one. ?But I'm hoping for > specialzed behavior useful for graphs. If you're looking for FOSS, the Boost graph library [1] or its parallel extension [2] is probably your best bet; it also comes with Python bindings but they are not maintained any more. For commercial solutions, Star-P [3] seems an interesting platform, with bindings to Matlab and Python. Freebase [4] is apparently built on a special graph database but unfortunately only the stored data are available, not the DB source code. George [1] http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/index.html [2] http://www.osl.iu.edu/research/pbgl/ [3] http://www.interactivesupercomputing.com/success/sparsematrices.php [4] http://www.freebase.com/help/faq#q7 From yogamatt1970 at gmail.com Tue Oct 7 11:21:40 2008 From: yogamatt1970 at gmail.com (yogamatt1970 at gmail.com) Date: Tue, 7 Oct 2008 08:21:40 -0700 (PDT) Subject: Race condition when generating .pyc files Message-ID: I have a large body of Python code which runs on many different (Unix) machines concurrently. Part of the code lives in one place, but most of it lives in directories which I find at runtime. I only have one copy of each Python source file and I think I'm hitting a race condition where two hosts attempt to import the same module at the same time. My import fails on one of the machines and the following exception is thrown: EOFError: EOF read where object expected My hypothesis is that there's contention between the two (or more) hosts when the module's .pyc file is generated. Possible solutions I see: 1) Running a cron job before my code executes which compiles all the python source first. 2) Making separate copies of all the .py files for each host running the code - I'd rather not do this, it seems like a big pain. 3) Inhibiting the generation of .pyc files altogether if that's even possible - I saw a PEP for a possible -R flag (http://www.python.org/ dev/peps/pep-0304/) but I don't think it has been added to a released version of Python yet plus I am stuck with Python 2.4 for the time being. Any and all help appreciated. Thanks. From prologic at shortcircuit.net.au Mon Oct 27 03:43:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 27 Oct 2008 17:43:35 +1000 Subject: Improving interpreter startup speed In-Reply-To: <7xtzayebgi.fsf@ruckus.brouhaha.com> References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> <5b8d13220810262215k16991346w9153bd37c31c409a@mail.gmail.com> <7xtzayebgi.fsf@ruckus.brouhaha.com> Message-ID: On Mon, Oct 27, 2008 at 5:36 PM, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > It's not optimal but it is very common (CGI for example). Which is why we (The Python Community) created WSGI and mod_wsgi. C"mon guys these "problems" are a bit old and out dated :) --JamesMills -- -- -- "Problems are solved by method" From clp at rebertia.com Fri Oct 10 02:27:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 9 Oct 2008 23:27:57 -0700 Subject: Total Python Noob In-Reply-To: References: Message-ID: <47c890dc0810092327m3df04551o23dffd8ff67e0430@mail.gmail.com> On Thu, Oct 9, 2008 at 11:22 PM, Tom Lake wrote: > I have Python 2.6 installed on Vista Ultimate. When I try to calculate > sqrt (or any transcendental functions) I get the following error > >>>> sqrt(2) > > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sqrt' is not defined > > What am I doing wrong? They're not buitltin, they're in the 'math' module (http://docs.python.org/library/math.html#module-math), which you need to import. e.g. import math print math.sqrt(4) Please also Read the Fine Tutorial at: http://docs.python.org/tutorial/index.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Tom Lake -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Tue Oct 14 16:15:11 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 14 Oct 2008 22:15:11 +0200 Subject: Implementing my own Python interpreter In-Reply-To: References: Message-ID: <48f4fdcf$0$17135$9b4e6d93@newsspool2.arcor-online.net> Ognjen Bezanov wrote: > Also, any pro's out there willing to chime on the feasibility of > implementing python to run directly on the hardware (without an > underlying OS)? I don't expect 100% compatibility, but would the basics > (branching, looping, arithmatic) be feasible? You should take a look at Cython, which translates Python code to C. It does not build a complete Interpreter (it doesn't reimplement the data types and their operations, for example), but it does implement most of the control flow and a lot of other things that make the generated code fast. In case you come to the conclusion that reimplementing Python is too big for a final year project, you might as well find a couple of good ideas in Cython's list of potential enhancements. Check the Wiki. http://cython.org/ Stefan From bj_666 at gmx.net Fri Oct 24 14:07:48 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Oct 2008 18:07:48 GMT Subject: portable python References: Message-ID: <6meh7kFg8n3fU2@mid.uni-berlin.de> On Fri, 24 Oct 2008 10:42:21 -0700, asit wrote: > I code in both windows and Linux. As python is portable, the o/p should > be same in both cases. But why the following code is perfect in windows > but error one in Linux ??? So what *is* the error on Linux!? > def scan(ip,port,timeout): > s = socket(AF_INET, SOCK_STREAM) > s.settimeout(timeout) > try: > result= s.connect_ex((ip, port)) > except: > print "Cannot connect to IP" > return > s.close() > return status[result] The bare ``except`` catches *all* errors in the ``try`` block, even those you might know about because they don't belong to the set of exceptions you expected. Like `NameError`, `MemoryError`, `KeyboardInterrupt`, ? And the function can return two quite different types? > if (len(sys.argv) == 4): > ip=sys.argv[1] > minrange = int(sys.argv[2]) > maxrange = int(sys.argv[3]) > timeout = 3 > > ports=range(minrange,maxrange+1) > > for port in ports: > print str(port) + " : " + scan(ip,port,timeout) ?one of which is `None` and that will blow up here, regardless of platform. In [18]: " : " + None --------------------------------------------------------------------------- Traceback (most recent call last) /home/bj/ in () : cannot concatenate 'str' and 'NoneType' objects Ciao, Marc 'BlackJack' Rintsch From info at egenix.com Wed Oct 15 17:06:55 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 15 Oct 2008 23:06:55 +0200 Subject: [egenix-info] Re: ANN: eGenix mxODBC - ODBC Database Interface for Python 3.0.2 In-Reply-To: <48F636B2.9020100@udel.edu> References: <48F60F56.4020609@egenix.com> <48F636B2.9020100@udel.edu> Message-ID: <48F65B6F.2070301@egenix.com> On 2008-10-15 20:30, Terry Reedy wrote: > FYI > I initially parsed the subject line as > "eGenix mxODBC - ODBC Database Interface" for "Python 3.0.2" > and thought, "Wow, already prepared for the future" (6 months to a year) > ;-). It's going to look even better when we release version 4.0 in a year or so ;-) FWIW, we're still waiting for the dust to settle before going for a Py3k port of the mx C extensions. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 15 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From ldo at geek-central.gen.new_zealand Tue Oct 21 00:48:19 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 21 Oct 2008 17:48:19 +1300 Subject: What was that, what was it? References: <82f51155-16fe-4e5c-a83b-040cf7695ff8@u75g2000hsf.googlegroups.com> Message-ID: In message <82f51155-16fe-4e5c-a83b-040cf7695ff8 at u75g2000hsf.googlegroups.com>, Aaron Brady wrote: > If Python was a car, I think it would be a hybrid... I hope not. They're only good in the city, a waste of time once you get over 50 km/h. > Plus there's nothing about sarcasm in the Zen. That's why it's the Zen. :) From steve at REMOVE-THIS-cybersource.com.au Sat Oct 25 05:04:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Oct 2008 09:04:01 GMT Subject: How can I handle the char immediately after its input, without waiting an endline? References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> <29de18070810220417p331e17c1rbd9db9cb1fd9d578@mail.gmail.com> Message-ID: <0112d9f3$0$20624$c3e8da3@news.astraweb.com> On Sat, 25 Oct 2008 08:36:32 +0000, Lie Ryan wrote: >>>> I want to write something that handle every char immediately after >>>> its input. Then tehe user don't need to type [RETURN] each time. How >>>> can I do this? >>>> >>>> Thanks in advance. > > Don't you think that getting a one-character from console is something > that many people do very often? No. I can't think of any modern apps that use one character commands like that. One character plus a modifier (ctrl or alt generally) perhaps, but even there, it's mostly used in GUI applications. > Do you think that all these platform > independent code should be moved to the interpreter level instead Absolutely not! There's no need for it to be given a keyword or special syntax. But maybe there should be a standard library function for it. > (and > raises the appropriate error when the platform somehow cannot do > unbuffered input)? So python developer could do something like this: > > raw_input(bufferring = 0) No. Leave raw_input as it is. A better interface would be: import input_services c = input_services.get_char() Eventually the module could grow other services as well. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Oct 16 20:54:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Oct 2008 00:54:17 GMT Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <01006451$0$20646$c3e8da3@news.astraweb.com> <010771b8$0$20638$c3e8da3@news.astraweb.com> Message-ID: <0107db6a$0$20638$c3e8da3@news.astraweb.com> On Thu, 16 Oct 2008 12:18:49 -0700, Aaron \"Castironpi\" Brady wrote: [snip] >> If Python re-evaluated the default value i=i at runtime, the above >> would break. > > Not with a mere extra lambda. Not so. It has nothing to do with lambda, lambda just happens to be a convenient example. Here's the code I demonstrated: >>> for i in xrange(len(callbacks)): ... callbacks[i] = lambda s, i=i: '%d %s' % (i, s) ... >>> for cb in callbacks: ... print cb('string') ... 0 string 1 string 2 string 3 string At the end of the first loop, i == 3. If the default value i=i was re- evaluated each time the function was called, then i would get the value 3 each time, which is the same behaviour you get from the version with this: callbacks[i] = lambda s: '%d %s' % (i, s) Worse, because you're now relying on i as a global, it's subject to strange and mysterious bugs if you later change i and then call the callback. > The fact that a syntax is an opportunity > to have a behavior does not imply that it should have one. The fact > that newbies ask about these semantics doesn't imply that they'd ask > about another one just as much. The fact that these semantics have > these two uses, doesn't imply that the others don't have more. Nowhere did I say that the one logically implies the other. I was asked for examples of how the current behaviour is useful, not to prove that the current behaviour logically follows from first principles. If you want to use a programming language where function default values are re- evaluated at runtime, you know where to find them. By the way, for the record I myself has found that behaviour useful on occasion. But that's easy to do with current Python: def spam(x, y=None): if y is None: # re-evaluate the default value at runtime y = get_some_other_value() return x + y So if you want that behaviour, you can get it. But if Python's semantics changed, then how would you implement today's semantics where the default is evaluated once only? I don't think you can. So Python's current semantics allows the behaviour you want, but in a slightly inconvenient form; but the re-evaluate-at-runtime semantics would prevent the behaviour I want completely. > Immutable defaults behave identically in both. Not quite. To have immutable defaults behave identically, you would need to remove at least one more feature of Python: the ability to set a default value to an arbitrary expression, not just a literal. Why do you need to do this? This toy example demonstrates the problem if you don't: yy = 3 # immutable value bound to the name yy def spam(x, y=yy-1): return x + y will have the *expression* yy-1 re-evaluated when they call the function. That means that even though 2 is immutable, you can no longer rely on the default value being 2, or even existing at all. (What if I del yy at some point, then call the function?) So now to get the behaviour you desire, you not only have to change the way Python functions are implemented (and that will have a real and significant performance cost), but you also have to change the parser to only allow literals as default values. Note that there is absolutely nothing wrong with using an expression when setting default values. But you have to prohibit it, or else introduce unexpected behaviour which will trip up not just noobs but everybody. And then you'll have noobs writing in weekly asking why they can't write "def foo(x, y=10**6)" instead of y=10000000. -- Steven From jarausch at igpm.rwth-aachen.de Wed Oct 15 06:10:31 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 15 Oct 2008 12:10:31 +0200 Subject: python3 - the hardest hello world ever ? In-Reply-To: <87y70qbzam.fsf@benfinney.id.au> References: <48f481af$0$2863$ba620e4c@news.skynet.be> <87y70qbzam.fsf@benfinney.id.au> Message-ID: <6lltspFc1okmU2@mid.dfncis.de> Ben Finney wrote: > Helmut Jarausch writes: > >> I have to set an internal property (with leading underscore) >> for each output file I'm using - right? > > If you're referring to the source encoding declaration: No, > underscores have no effect. The specification is at > . > >> #!/usr/local/bin/python3.0 >> # _*_ coding: latin1 _*_ > > I'm not sure why you use underscores in this line. The usual form is > to use a mode line as recognised by Emacs:: > > # -*- coding: latin1 -*- > > or Vim:: > > # vim: fileencoding=latin1 : > No, I meant the underscore in sys.stdout._encoding='latin1' ^ As for the source encoding, I have used the underscore version which seems to work, as well. Thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From james.kirin39 at gmail.com Wed Oct 1 15:18:37 2008 From: james.kirin39 at gmail.com (james.kirin39 at gmail.com) Date: Wed, 1 Oct 2008 12:18:37 -0700 (PDT) Subject: decent interactive python shell on MS Windows? References: <89393fc8-5d6b-47a4-abef-801f4d52dbf4@l42g2000hsc.googlegroups.com> Message-ID: <8acf812d-5266-4144-aa6a-72056eba3b70@m36g2000hse.googlegroups.com> On Oct 1, 3:10?pm, Jason Scheirer wrote: > On Oct 1, 9:53?am, james.kiri... at gmail.com wrote: > > > > > Hi everyone, > > > After having used Python on Linux for some time, I now have to do > > Python coding on Windows. I am big fan of the interactive Python shell > > to test, eg, regexps. > > > Is there an interactive Python shell on Windows that supports: > > > - easy copy-pasting to/from an editor? (as opposed to the cumbersome > > "mark", "copy" and then "paste" sequence that any terminal on Windows > > seems forced to adopt) > > > - readline-like command history (up/down for previous/next command, > > Ctr-R for searching, etc) ? > > > I have tried the python.org shell (difficult copy-pasting), > > ActiveState's (no readline command history) and iPython (difficult > > copy-pasting). Do you know of any decent interactive python shell on > > Windows that comes close to the friendliness of the standard one on > > Linux? > > > Thanks in advance > > > James > Dear all Thank you for your excellent replies. With your help all is good now, and my python coding is as productive as before. :) ~james From __peter__ at web.de Sun Oct 5 11:15:27 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Oct 2008 17:15:27 +0200 Subject: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x] References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> <87myhjcu7g.fsf@hbox.dyndns.org> <00f89ca3$0$20633$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > PEP 3113 offers the following recommendation for refactoring tuple > arguments: > > def fxn((a, (b, c))): > pass > > will be translated into: > > def fxn(a_b_c): > (a, (b, c)) = a_b_c > pass > > and similar renaming for lambdas. > http://www.python.org/dev/peps/pep-3113/ > > > I'd like to suggest that this naming convention clashes with a very > common naming convention, lower_case_with_underscores. That's easy enough > to see if you replace the arguments a, b, c above to something more > realistic: > > def function(vocab_list, (result, flag), max_value) > > becomes: > > def function(vocab_list, result_flag, max_value) > > Function annotations may help here, but not everyone is going to use them > in the same way, or even in a way that is useful, and the 2to3 tool > doesn't add annotations. > > It's probably impossible to avoid all naming convention clashes, but I'd > like to suggest an alternative which distinguishes between a renamed > tuple and an argument name with two words: > > def function(vocab_list, (result, flag), max_value): > pass > > becomes: > > def function(vocab_list, t__result_flag, max_value): > result, flag = t__result_flag > pass > > The 't__' prefix clearly marks the tuple argument as different from the > others. The use of a double underscore is unusual in naming conventions, > and thus less likely to clash with other conventions. Python users are > already trained to distinguish single and double underscores. And while > it's three characters longer than the current 2to3 behaviour, the length > compares favorably with the original tuple form: > > t__result_flag > (result, flag) Let's see what the conversion tool does: $ cat tmp.py g = lambda (a, b): a*b + a_b $ 2to3 tmp.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: ws_comma --- tmp.py (original) +++ tmp.py (refactored) @@ -1,1 +1,1 @@ -g = lambda (a, b): a*b + a_b +g = lambda a_b1: a_b1[0]*a_b1[1] + a_b RefactoringTool: Files that need to be modified: RefactoringTool: tmp.py So the current strategy is to add a numerical suffix if a name clash occurs. The fixer clearly isn't in final state as for functions instead of lambdas it uses xxx_todo_changeme. > What do people think? Is it worth taking this to the python-dev list? I suppose that actual clashes will be rare. If there is no clash a_b is the best name and I prefer trying it before anything else. I don't particularly care about what the fallback should be except that I think it should stand out a bit more than the current numerical suffix. xxx1_a_b, xxx2_a_b,... maybe? Peter From callen314 at gmail.com Thu Oct 9 20:29:32 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 9 Oct 2008 17:29:32 -0700 (PDT) Subject: Python 2.6, GUI not working on vista? References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> Message-ID: as a 20 year observer of microsoft, I have to say this is not amazing at all... and I do not mean that as a random put down of Microsoft. Microsoft often develops things in response to demand... but they don't always fit in their system well, and thus are not really used in the spirit of the demand... meanwhile, bullet items are added to many a software box and magazine review. I would not presume to know more that Microsoft about that as a business practice, but as an engineering practice, it speaks for itself. From dave.dibiase at gmail.com Thu Oct 2 23:07:02 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Thu, 2 Oct 2008 23:07:02 -0400 Subject: Fun with reverse sorts Message-ID: Hi there, I'm sorting an expansive list descending according to a list of tuples. Basically it has to sort the last value in the tuple (3) but if they are the same then it should resort to using the second last value (2). Now according to my very limited testing I've somewhat figured out that this SHOULD work: list.sort(lambda a, b: (cmp(a[3], b[3]), cmp(a[2], b[2])) [a[3] == b[3]], reverse = True) Here's an example of the list: [(34,23,54,34), (34,23,230,34), (34,23,523,334), (34,23,15,17), (34,23,54,17), (45,23,43,123), (564,23,543,23), (23,54,600,23), (34,54,23,654), (43,54,32,34)] My first question is in regards to style first. The style guide for Python doesn't seem to state this (if it has I missed it) but should I be doing reverse=True or reverse = True with the spaces. lol this is so miniscule but it's good to know. Also, does this function look/feel right to all the pros out there. Is there a better way of doing it? I'm still wrapping my head around ways of accomplishing proper sorts! Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Fri Oct 17 09:34:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 17 Oct 2008 06:34:13 -0700 (PDT) Subject: Dictionary of Dicts question References: <59077563-2BFE-4DA6-853F-79965F1017C2@strout.net> <75c49b3e-96f1-4c9e-98b9-7c0e7b4fa815@u75g2000hsf.googlegroups.com> Message-ID: MRAB: > for line in open(path): > fields = line.split("\t") > data[tuple(fields[ : 2])] = fields[2 : ] Keeping the key as a string may have some memory/performance advantages (not tested): for line in open(path): fields = line.split("\t") data[fields[0] + fields[1]] = map(float, islice(fields, 2, None)) Or probably faster (not tested): for line in open(path): parts = s.rsplit("\t", 6) data[parts[0]] = map(float, islice(parts, 1, None)) Or (not tested): for line in open(path): parts = s.rsplit("\t", 6) data[parts[0]] = [float(parts[i]) for i in xrange(1, 7)] Having a built-in xsplit/xsplitr method here probably helps significantly. If the FP numbers are really precise then you can compare them as strings too, but that's quite unsafe. Bye, bearophile From circularfunc at gmail.com Mon Oct 6 03:14:37 2008 From: circularfunc at gmail.com (process) Date: Mon, 6 Oct 2008 00:14:37 -0700 (PDT) Subject: Pr. Euler 18, recursion problem References: <48e9ac7e@dnews.tpgi.com.au> Message-ID: On Oct 6, 8:13?am, Aidan wrote: > process wrote: > > I am trying to solve project euler problem 18 with brute force(I will > > move on to a better solution after I have done that for problem 67). > >http://projecteuler.net/index.php?section=problems&id=18 > > > However I can't get the recursive function right. > > > I always have to use return right? Unless I am printing? So I can?t > > stack to diffferent recursive calls after each other like so: > > recur_left(t, p) > > recur_right(t,p+1) > > > Some stuff I have tried: > > > def recur(tree, pos): > > ? ? if not tree: > > ? ? ? ? return [] > > ? ? else: > > ? ? ? ? return [[tree[0][pos]] + recur(tree[1:], pos)] + \ > > ? ? ? ? ? ? ? ?[[tree[0][pos]] + recur(tree[1:], pos+1)] > > >>>> recur([[1],[2,3],[4,5,6]],0) > > [[1, [2, [4], [4]], [2, [5], [5]]], [1, [3, [5], [5]], [3, [6], [6]]]] > > > SO it is kind of working, just not exactly like I want. > > A more easily parseable/readable result would be nice, I want to be > > able to sum() over each path preferrably. > > > So the result should be: > > [[1,2,4],[1,2,5],[1,3,5],[1,3,6]] > > > I know conceptually what has to be done. > > Base case: empty tree, return [] > > Else: recur to the left and to the right. > > This is just my opinion, but I felt the non-brute force solution to this > problem was actually simpler than trying to define a brute force > recursive solution.... I tried to implement a brute force algorithm at > first, until I had an epiphany with regard to how simple the problem > actually was. ?Then I faced palmed. But let's say you have [[1],[1,10],[1,2,300],[100000,1,1,1]]. you must check all solutions right? there is no pattern. if you start from the bottom and eliminate paths that seem to be losing can you regain that later up in the pyramid if it turns out one side gets bigg again? From info at egenix.com Wed Oct 15 11:42:14 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 15 Oct 2008 17:42:14 +0200 Subject: ANN: eGenix mxODBC - ODBC Database Interface for Python 3.0.2 Message-ID: <48F60F56.4020609@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC - ODBC Database Interface for Python Version 3.0.2 mxODBC is our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-3.0.2-GA.html ________________________________________________________________________ INTRODUCTION mxODBC provides an easy-to-use, high-performance, reliable and robust Python interface to ODBC compatible databases such as MS SQL Server, MS Access, Oracle Database, IBM DB2 and Informix , Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more. The "eGenix mxODBC - ODBC Database Interface for Python" product is a commercial extension to our open-source eGenix mx Base Distribution. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS mxODBC 3.0.2 is a patch-level release and includes the following updates: * Python 2.6 support mxODBC 3.0.2 is now available for Python 2.6, compiled with the same MS VS 2008 edition used by the Python developers to build Python 2.6 binaries for enhanced compatibility. * Enhanced support for using TEXT and VARCHAR columns with binary data ODBC drivers which need the Python type binding, like e.g. the FreeTDS ODBC driver, will now be able to pass binary data to text columns in most cases. * Updated work-arounds for various ODBC drivers eGenix always aims to make using mxODBC as easy and robust as possible. For this reason, we regularly add or update work-arounds for problems found in recent ODBC driver versions. This release includes updated or new work-arounds for the MySQL ODBC driver, the Informix ODBC driver and the SQL Server 2005 ODBC driver. * Enhanced Python datetime module support mxODBC 3.0 already supports the datetime module found in Python 2.4 and later. With this release, we have additionally added support for the datetime module found in Python 2.3. For the full set of changes please check the mxODBC change log: http://www.egenix.com/products/python/mxODBC/changelog.html ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ In order to use the eGenix mxODBC package you will first need to install the eGenix mx Base package: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING You are encouraged to upgrade to this latest mxODBC release, especially if you are using MS SQL Server or Informix as database server. Customers who have purchased mxODBC 3.0 licenses can download and install this patch-level release on top of their existing installations. The licenses will continue to work with version 3.0.2. Users of mxODBC 2.0 will have to purchase new licenses from our online shop in order to upgrade to mxODBC 3.0.2. You can request 30-day evaluation licenses by visiting our web-site at http://www.egenix.com/products/python/mxODBC/#Evaluation or writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 15 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From jnoller at gmail.com Thu Oct 30 13:00:06 2008 From: jnoller at gmail.com (Jesse Noller) Date: Thu, 30 Oct 2008 13:00:06 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> References: <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> <49027bfa$0$16028$9b622d9e@news.freenet.de> <16acff7d-e3a4-4be0-a042-e74845501cb3@k16g2000hsf.googlegroups.com> <49057647$0$26690$9b622d9e@news.freenet.de> <49078e11$0$8568$9b622d9e@news.freenet.de> <4fd837d4-6cc1-4f50-b324-6b903cc59b5c@g61g2000hsf.googlegroups.com> Message-ID: <4222a8490810301000k7c703c10x5db78711e6d7f44f@mail.gmail.com> On Thu, Oct 30, 2008 at 12:05 PM, Andy O'Meara wrote: > On Oct 28, 6:11 pm, "Martin v. L?wis" wrote: >> > Because then we're back into the GIL not permitting threads efficient >> > core use on CPU bound scripts running on other threads (when they >> > otherwise could). >> >> Why do you think so? For C code that is carefully written, the GIL >> allows *very well* to write CPU bound scripts running on other threads. >> (please do get back to Jesse's original remark in case you have lost >> the thread :-) >> > > I don't follow you there. If you're referring to multiprocessing, our > concerns are: > > - Maturity (am I willing to tell my partners and employees that I'm > betting our future on a brand-new module that imposes significant > restrictions as to how our app operates?) > - Liability (am I ready to invest our resources into lots of new > python module-specific code to find out that a platform that we want > to target isn't supported or has problems?). Like it not, we're a > company and we have to show sensitivity about new or fringe packages > that make our codebase less agile -- C/C++ continues to win the day in > that department. > - Shared memory -- for the reasons listed in my other posts, IPC or a > shared/mapped memory region doesn't work for our situation (and I > venture to say, for many real world situations otherwise you'd see end- > user/common apps use forking more often than threading). > FWIW (and again, I am not saying MP is good for your problem domain) - multiprocessing works on windows, OS/X, Linux and Solaris quite well. The only platforms it has problems on right now *BSD and AIX. It has plenty of tests (I want more more more) and has a decent amount of usage is my mail box and bug list are any indication. Multiprocessing is not *new* - it's a branch of the pyprocessing package. Multiprocessing is written in C, so as for the "less agile" - I don't see how it's any less agile then what you've talked about. If you wanted true platform insensitivity, then Java is a better bet :) As for your final point: > - Shared memory -- for the reasons listed in my other posts, IPC or a > shared/mapped memory region doesn't work for our situation (and I > venture to say, for many real world situations otherwise you'd see end- > user/common apps use forking more often than threading). > I philosophically disagree with you here. PThreads and Shared memory as it is today, is largely based on Java's influence on the world. I would argue that the reason most people use threads as opposed to processes is simply based on "ease of use and entry" (which is ironic, given how many problems it causes). Not because they *need* the shared memory aspects of it, or because they could not decompose the problem into Actors/message passing, but because threads: A> are there (e.g. in Java, Python, etc) B> allow you to "share anything" (which allows you to take horrible shortcuts) C> is what everyone "knows" at this point. Even luminaries such as Brian Goetz and many, many others have pointed out that threading, as it exists today is fundamentally difficult to get right. Ergo the "renaissance" (read: echo chamber) towards Erlang-style concurrency. For many "real world" applications - threading is just "simple". This is why Multiprocessing exists at all - to attempt to make forking/IPC as "simple" as the API to threading. It's not foolproof, but the goal was to open the door to multiple cores with a familiar API: Quoting PEP 371: "The pyprocessing package offers a method to side-step the GIL allowing applications within CPython to take advantage of multi-core architectures without asking users to completely change their programming paradigm (i.e.: dropping threaded programming for another "concurrent" approach - Twisted, Actors, etc). The Processing package offers CPython a "known API" which mirrors albeit in a PEP 8 compliant manner, that of the threading API, with known semantics and easy scalability." I would argue that most of the people taking part in this discussion are working on "real world" applications - sure, multiprocessing as it exists today, right now - may not support your use case, but it was evaluated to fit *many* use cases. Most of the people here are working in Pure python, or they're using a few extension modules here and there (in C). Again, when you say threads and processes, most people here are going to think "import threading", "fork()" or "import multiprocessing" Please correct me if I am wrong in understanding what you want: You are making threads in another language (not via the threading API), embed python in those threads, but you want to be able to share objects/state between those threads, and independent interpreters. You want to be able to pass state from one interpreter to another via shared memory (e.g. pointers/contexts/etc). Example: ParentAppFoo makes 10 threads (in C) Each thread gets an itty bitty python interpreter ParentAppFoo gets a object(video) to render Rather then marshal that object, you pass a pointer to the object to the children You want to pass that pointer to an existing, or newly created itty bitty python interpreter for mangling Itty bitty python interpreter passes the object back to a C module via a pointer/context If the above is wrong, I think possible outlining it in the above form may help people conceptualize it - I really don't think you're talking about python-level processes or threads. -jesse From theller at python.net Wed Oct 22 13:45:58 2008 From: theller at python.net (Thomas Heller) Date: Wed, 22 Oct 2008 19:45:58 +0200 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: References: Message-ID: <6m974kFfs9nlU1@mid.individual.net> Andy schrieb: > Dear Python dev community, > > [...] Basically, > we use embedded python and use it to wrap our high performance C++ > class set which wraps OpenGL, DirectX and our own software renderer. > In addition to wrapping our C++ frameworks, we use python to perform > various "worker" tasks on worker thread (e.g. image loading and > processing). However, we require *true* thread/interpreter > independence so python 2 has been frustrating at time, to say the > least. [...] > > Sadly, the only way we could get truly independent interpreters was to > put python in a dynamic library, have our installer make a *duplicate* > copy of it during the installation process (e.g. python.dll/.bundle -> > python2.dll/.bundle) and load each one explicitly in our app, so we > can get truly independent interpreters. In other words, we load a > fresh dynamic lib for each thread-independent interpreter (you can't > reuse the same dynamic library because the OS will just reference the > already-loaded one). Interesting questions you ask. A random note: py2exe also does something similar for executables build with the 'bundle = 1' option. The python.dll and .pyd extension modules in this case are not loaded into the process in the 'normal' way (with some kind of windows LoadLibrary() call, instead they are loaded by code in py2exe that /emulates/ LoadLibrary - the code segments are loaded into memory, fixups are made for imported functions, and marked executable. The result is that separate COM objects implemented as Python modules and converted into separate dlls by py2exe do not share their interpreters even if they are running in the same process. Of course this only works on windows. In effect this is similar to using /statically/ linked python interpreters in separate dlls. Can't you do something like that? > So, my question becomes: is python 3 ready for true multithreaded > support?? Can we finally abandon our Frankenstein approach of loading > multiple identical dynamic libs to achieve truly independent > interpreters?? I've reviewed all the new python 3 C API module stuff, > and all I have to say is: whew--better late then never!! So, although > that solves modules offering truly independent interpreter support, > the following questions remain: > > - In python 3, the C module API now supports true interpreter > independence, but have all the modules in the python codebase been > converted over? Are they all now truly compliant? It will only take > a single static/global state variable in a module to potentially cause > no end of pain in a multiple interpreter environment! Yikes! I don't think this is the case (currently). But you could submit patches to Python so that at least the 'official' modules (builtin and extensions) would behave corectly in the case of multiple interpreters. At least this is a much lighter task than writing your own GIL-less interpreter. My 2 cents, Thomas From abhishekmishra3 at gmail.com Sun Oct 19 06:52:10 2008 From: abhishekmishra3 at gmail.com (Abhishek Mishra) Date: Sun, 19 Oct 2008 03:52:10 -0700 (PDT) Subject: keyword in package name. References: <6m0bk2Fe8qbdU1@mid.uni-berlin.de> Message-ID: On Oct 19, 2:06?pm, Marc 'BlackJack' Rintsch wrote: > > `com_spam.app1`!? ?I would even recommend this with domains that don't > clash with keywords because if several people start to use this package > name convention you will get name clashes at package level. ?Say there > are two vendors with a `com` TLD, how do you install their packages? ? > Into the same `com/` subdirectory? ?The `__init__.py` of which vendor > should live at the `com/` directory level? ?If you install them into two > different directories but want to import modules from both vendors -- how? > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Ah, you have opened my eyes. I should have asked myself before why I did not face such a clash. (because no-one uses this convention!) I guess the way to go is not use the tld, but just a unique company/ product name. Thanks, Abhishek Mishra From steve at holdenweb.com Wed Oct 29 07:29:15 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Oct 2008 07:29:15 -0400 Subject: [2.5.1] "UnicodeDecodeError: 'ascii' codec can't decode byte"? In-Reply-To: References: Message-ID: <4908490B.9050104@holdenweb.com> Ulrich Eckhardt wrote: > Gilles Ganault wrote: >> I'm getting this error while downloading and parsing web pages: >> >> ===== >> title = m.group(1) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position >> 48: ordinal not in range(128) >> ===== >> >> From what I understand, it's because some strings are Unicode, and >> hence contain characters that are illegal in ASCII. > > You just need to use a codec according to the encoding of the webpage. Take > a look at > http://wiki.python.org/moin/Python3UnicodeDecodeError > It is about Python 3, but the principles apply nonetheless. In any case, > throwing the error at a websearch will turn up lots of solutions. > I won't believe that statement is producing the error until I see a traceback. As far as I'm aware the re module can handle Unicode. Getting a UnicodeDecodeError in an assignment would be unusual to say the least. Though it's not, I suppose, impossible that calling the .group() method of a match object might, it seems unlikely. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From kyosohma at gmail.com Thu Oct 9 16:39:14 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 9 Oct 2008 13:39:14 -0700 (PDT) Subject: book recommendation for Python newbie? References: Message-ID: <7197ffdb-aeee-420f-9b66-b23bfff90b96@s50g2000hsb.googlegroups.com> On Oct 9, 3:00?pm, Joe Strout wrote: > I'm trying to (gently) convince my business partner that we should be ? > adding Python to our core toolset. ?He's never used it before, apart ? > from poking around in the tutorial a bit at my urging. ?But he's got a ? > birthday coming up, and I'd like to get him a book that will help him ? > make the transition more smoothly and enjoyably. > > In case it matters: his background is mainly in databases (originally ? > 4D, more recently MySQL), and his current primary tools are REALbasic ? > (which is a statically typed language with semantics similar to Java) ? > and PHP. ?He's primarily a Mac user, but occasionally has to dabble in ? > Linux or Windows. ?If we do make this change, he'll be using Python in ? > a professional capacity to develop commercial apps. > > There are a lot of Python books out there... which one would you ? > recommend in this case? > > Thanks, > - Joe A lot of people recommend Lutz's "Learning Python". While I haven't read it, I have read his follow-up "Programming Python" and it was good. You might also look at Hetland's "Beginning Python" or even the "Python for Dummies" book. Mike From castironpi at gmail.com Sat Oct 25 19:04:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 25 Oct 2008 16:04:59 -0700 (PDT) Subject: Consequences of importing the same module multiple times in C++? References: Message-ID: <699cb83c-bec3-4cc9-8de0-97a7a0f9aa02@26g2000hsk.googlegroups.com> On Oct 24, 2:23?pm, Robert Dailey wrote: > Hi, > > I'm currently using boost::python::import() to import Python modules, > so I'm not sure exactly which Python API function it is calling to > import these files. I posted to the Boost.Python mailing list with > this question and they said I'd probably get a better answer here, so > here it goes... > > If I do the following: > > using namespace boost::python; > import( "__main__" ).attr( "new_global" ) = 40.0f; > import( "__main__" ).attr( "another_global" ) = 100.0f: > > Notice that I'm importing twice. What would be the performance > consequences of this? Do both import operations query the disk for the > module and load it into memory? Will the second call simply reference > a cached version of the module loaded at the first import() call? > > Thanks. Docs: Note For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter ? or, if it?s just one module you want to test interactively, use reload(), e.g. reload(modulename). From python.list at tim.thechases.com Fri Oct 24 14:27:27 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 24 Oct 2008 13:27:27 -0500 Subject: from package import * without overwriting similarly named functions? In-Reply-To: <80503fdf-7792-4571-825c-27e0c5a59cb5@u29g2000pro.googlegroups.com> References: <80503fdf-7792-4571-825c-27e0c5a59cb5@u29g2000pro.googlegroups.com> Message-ID: <4902138F.2050001@tim.thechases.com> > I have multiple packages that have many of the same function names. Is > it possible to do > > from package1 import * > from package2 import * > > without overwriting similarly named objects from package1 with > material in package2? How about a way to do this that at least gives a > warning? Yeah, just use from package2 import * from package1 import * then nothing in package1 will get tromped upon. However, best practices suggest leaving them in a namespace and not using the "import *" mechanism for precisely this reason. You can always use module aliasing: import package1 as p1 import package2 as p2 so you don't have to type "package1.subitem", but can instead just write "p1.subitem". I prefer to do this with packages like Tkinter: import Tkinter as tk ... tk.Scrollbar... so it doesn't litter my namespace, but also doesn't require me to type "Tkinter.Scrollbar", prefixing with "Tkinter." for everything. -tkc From Jiandong.Ge at gmail.com Fri Oct 17 22:21:39 2008 From: Jiandong.Ge at gmail.com (JD) Date: Fri, 17 Oct 2008 19:21:39 -0700 (PDT) Subject: algorizm to merge nodes References: <4e08df3e-e91d-4940-8bdb-c7ff852e5de2@a19g2000pra.googlegroups.com> Message-ID: <35d2e34c-f3b7-4b41-b382-74ff91dfcd17@26g2000hsk.googlegroups.com> It could be a very good "homework assignmet". This is for a real application. each item in the list represent two terminals of a resistor. All the resistors in the list are shorted, I need to figure out how many independent nets are there. JD On Oct 17, 4:16 pm, Paul McGuire wrote: > On Oct 17, 3:20 pm, JD wrote:> Hi, > > > I need help for a task looks very simple: > > > > I smell "homework assignment". > > -- Paul From sebsauvage at gmail.com Fri Oct 3 16:46:31 2008 From: sebsauvage at gmail.com (sebsauvage at gmail.com) Date: Fri, 3 Oct 2008 13:46:31 -0700 (PDT) Subject: Remove "Server:" header References: <48E62816.4020902@byoteki.com> Message-ID: On 3 oct, 20:17, "Gabriel Genellina" wrote: > > sebsauv... at gmail.com wrote: > >> I'm using SimpleHTTPServer (work well) but it always sends "Server" > >> header in response: > >> How can I remove that ? > > En Fri, 03 Oct 2008 11:11:34 -0300, Gary M. Josack ? > escribi?: > > > you've got ?self.send_header('Server', self.version_string()) in the ? > > send_response method of the BaseHTTPRequestHandler class in the ? > > BaseHTTPServer module. Long story, short, it's going to be a lot of work ? > > to get rid of. > > One can always write a customized RequestHandler, and just copy the ? > send_response method omiting the offending line. (Ok, you have to check ? > whether it still works with the next Python release... a warning triggered ? > by a new sys.version would be enough to remember that) I see. No choice but to override the method with a copy of the source :-/ I guess I'll have to do with that. Thanks. From ishoej at gmail.com Mon Oct 6 06:39:44 2008 From: ishoej at gmail.com (Holger) Date: Mon, 6 Oct 2008 03:39:44 -0700 (PDT) Subject: how to get the thighest bit position in big integers? References: <70c1db4f-7454-438a-ab06-3de9d34d10b7@v15g2000hsa.googlegroups.com> Message-ID: <4a740d13-ad4d-4d20-b03d-11497c89662d@w7g2000hsa.googlegroups.com> On 6 Okt., 10:37, Mark Dickinson wrote: > See alsohttp://bugs.python.org/issue3439 > where there's a proposal to expose the _PyLong_NumBits method. ?This > would give an O(1) solution. Doesn't that depend on the underlying implementation? Anyway, here's a pretty one (I think): def highest_bit(n, maxbits = 256): bit = 0 while maxbits > 1: maxbits = maxbits >> 1 mask_b = ((1<> maxbits else: n = b return bit I suspect you would call that a O(logn)) solution Holger From mg at daimi.au.dk Sun Oct 5 04:38:43 2008 From: mg at daimi.au.dk (Martin Geisler) Date: Sun, 05 Oct 2008 10:38:43 +0200 Subject: Tuple parameter unpacking in 3.x References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> Message-ID: <87myhjcu7g.fsf@hbox.dyndns.org> Steven D'Aprano writes: > On Sat, 04 Oct 2008 22:57:23 +0200, Martin Geisler wrote: > > Here's another alternative. Compare: > >>>> x = (2, 3) >>>> (lambda (a,b): a*b)(x) > 6 > > with this: > >>>> (lambda a,b: a*b)(*x) > 6 Letting the callbacks take several arguments would definitely be the nicest syntax, but I'm unfortunately restricted by the Twisted framework: there all functions in a callback chain return one result which is passed to the next callback as the first argument. That is why I do a fair amount of tuple unpacking in my code. >> From reading the PEP-3113 I got the impression that the author >> thought that this feature was unused and didn't matter. With this I >> wish to say that it matters to me. > > Alas, I think it's too late. I feel your pain. Thanks! And I know it's too late, I should have found out about this earlier :-( > The final release of Python 3.0 hasn't been made yet. If you really > care strongly about this, you could write to the python-dev mailing > list and ask if it is worth trying to change their mind about tuple > unpacking. They'll almost certainly say no, but there's a chance it > might be reverted in 3.1. I can't see this being changed back and forth like that, so I don't think I'll bother. But thanks for the support. -- Martin Geisler VIFF (Virtual Ideal Functionality Framework) brings easy and efficient SMPC (Secure Multi-Party Computation) to Python. See: http://viff.dk/. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From tjreedy at udel.edu Mon Oct 27 00:49:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 27 Oct 2008 00:49:30 -0400 Subject: capturing ESC, page up/down in Python In-Reply-To: <904ag4tj076fg7dpravt08pnp51l8l6vrn@4ax.com> References: <324e7007-70a9-474a-b395-a4c61ce7aa76@d31g2000hsg.googlegroups.com> <904ag4tj076fg7dpravt08pnp51l8l6vrn@4ax.com> Message-ID: > jordilin wrote: >> Is there any way to capture the keyboard events ESC, page up (next >> page), page down (previous page) in Python?. I mean, how can I capture >> if user presses one of those keys in a terminal based application? I >> was thinking about pygame.key.get_pressed from the pygame module, but >> I don't feel really happy about importing pygame in a non related game >> project. Much of Pygame is a wrapper for the SDL library. Would you be happier using that part if it had been called PySDL? From clp at rebertia.com Fri Oct 17 16:35:42 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 17 Oct 2008 13:35:42 -0700 Subject: algorizm to merge nodes In-Reply-To: <4e08df3e-e91d-4940-8bdb-c7ff852e5de2@a19g2000pra.googlegroups.com> References: <4e08df3e-e91d-4940-8bdb-c7ff852e5de2@a19g2000pra.googlegroups.com> Message-ID: <47c890dc0810171335o543e4929o110efcaa907ea5e0@mail.gmail.com> (Disclaimer: completely untested) from collections import defaultdict merged = defaultdict(list) for key, val in your_list_of_pairs: merged[key].append(val) result = [[key]+vals for key, vals in merged.items()] Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Fri, Oct 17, 2008 at 1:20 PM, JD wrote: > Hi, > > I need help for a task looks very simple: > > I got a python list like: > > [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c', > 'u'], ['b', 'p']] > > Each item in the list need to be merged. > > For example, 'a', 'b' will be merged, 'c', 'd' will be merged. > > Also if the node in the list share the same name, all these nodes need > be merged. > > For example, ['a', 'b'], ['a', 'g'] ['b', 'p'] will be merged to ['a', > 'b', 'g', 'p'] > > The answer should be: > > [['a', 'b', 'g', 'p'], ['c', 'd', 'u'], ['e', 'f', 'k']] > > Anyone has a solution? > > Thanks, > > JD > -- > http://mail.python.org/mailman/listinfo/python-list > From R.Brodie at rl.ac.uk Tue Oct 7 12:11:08 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 7 Oct 2008 17:11:08 +0100 Subject: time References: Message-ID: "Gabriel Rossetti" wrote in message news:mailman.2124.1223392354.3487.python-list at python.org... . > I'm a UTC/GMT +1, I tried obtaining the UTC time, it says it's 2 hours earlier than the > current time (14:59). I tried various other methods, I still get the wrong time. Does > anyone have an idea with what is wrong? It would be helpful to specify a named timezone. 2 hours earlier would be expected for central Europe, it being summer. Sorry if that's obvious. From mccredie at gmail.com Thu Oct 30 20:39:56 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 30 Oct 2008 17:39:56 -0700 (PDT) Subject: Printing with interspersed element References: Message-ID: On Oct 30, 2:10?pm, "Paulo J. Matos" wrote: > On Thu, Oct 30, 2008 at 8:42 PM, Arnaud Delobelle > > > > wrote: > > On Oct 30, 8:07 pm, "Paulo J. Matos" wrote: > >> Hi all, > > >> I guess this is a recurring issue for someone who doesn't really know > >> the python lib inside out. There must be a simple way to do this. > >> I have a list of objects [x1, x2, x3, ..., xn] and I have defined a > >> print method for them print_obj(). Now I want to print them > >> intersepersed by an element. > >> If I print [x1, x2, x3] interspersed by the element 10: > >> x1.print_obj() 10 x2.print_obj() 10 x3.print_obj() > > >> Now, the question is, what's the best way to do this? > > > Defining a print_obj() method is probably a bad idea. ?What if you > > want to print to a file for example? ?Instead you can define a > > __str__() method for your objects and then use the join() method of > > strings like this: > > > print ' 10 '.join(str(x) for x in lst) > > Thanks for the tip but that has an issue when dealing with potentially > millions of objects. You are creating a string in memory to then dump > to a file [or screen] while you could dump to the file [or screen] as > you go through the original string. Right? Then I hope you are using stackless, because you are going to stack overflow _way_ before you recurse 1 million times. def print_list(seq, sep=','): seq = iter(seq) print seq.next(), for item in seq: print sep, print item, print Matt From deets at nospam.web.de Thu Oct 16 12:53:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 16 Oct 2008 18:53:29 +0200 Subject: Finding the instance reference of an object In-Reply-To: <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> References: <3zIJk.5599$YU2.3294@nlpi066.nbdc.sbc.com> <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> Message-ID: <6lp9s9Fdj72hU1@mid.uni-berlin.de> Astley Le Jasper schrieb: > On 16 Oct, 16:52, Carsten Haese wrote: >> Astley Le Jasper wrote: >>> Sorry for the numpty question ... >>> How do you find the reference name of an object? >>> So if i have this >>> bob = modulename.objectname() >>> how do i find that the name is 'bob' >> Why do you need to find that? You know that its name is 'bob'. >> >> -- >> Carsten Haesehttp://informixdb.sourceforge.net > > I'm creating mulitple instances, putting them in a list, iterating > through the list to send them to some functions where process them > with some instance specific parameters. Something along the lines of: > > bob = someobject() > harry = someobject() > fred = someobject() > > parameterdict = {'bob':(0,1,2),'harry':(3,4,5),'fred':(6,7,8)} > people_list = (bob, harry, fred) > > for person in people_list: > add_parameters(person) > > def add_parameters(person) > mytuple = parameterdict[??????instance.name????] > person.x = mytuple[0] > person.y = mytuple[1] > person.z = mytuple[2] > > ... alternatively there is probably a very much easier way of doing > it. Why not simply do bob = someobject(0, 1, 2) ? Diez From fuzzyman at gmail.com Sun Oct 5 14:52:27 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 5 Oct 2008 11:52:27 -0700 (PDT) Subject: Python 2.6: Determining if a method is inherited Message-ID: <0b330a07-75bb-41a8-8ded-98a2f6ea76b1@v53g2000hsa.googlegroups.com> Hello all, I may well be being dumb (it has happened before), but I'm struggling to fix some code breakage with Python 2.6. I have some code that looks for the '__lt__' method on a class: if hasattr(clr, '__lt__'): However - in Python 2.6 object has grown a default implementation of '__lt__', so this test always returns True. >>> class X(object): pass ... >>> X.__lt__ >>> X.__lt__ == object.__lt__ False So how do I tell if the X.__lt__ is inherited from object? I can look in the '__dict__' of the class - but that doesn't tell me if X inherits '__lt__' from a base class other than object. (Looking inside the method wrapper repr with a regex is not an acceptable answer...) Some things I have tried: >>> X.__lt__.__self__ >>> dir(X.__lt__) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__name__', '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> X.__lt__.__func__ Traceback (most recent call last): File "", line 1, in AttributeError: 'method-wrapper' object has no attribute '__func__' Michael Foord -- http://www.ironpythoninaction.com/ From max at alcyone.com Mon Oct 13 22:47:52 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 13 Oct 2008 19:47:52 -0700 Subject: Suggestion for the PythonDevelopment for next version In-Reply-To: References: Message-ID: azrael wrote: > I know that. enumerate is a great function. But this way it always > adds some complexity. That objection doesn't really make sense. Your suggestion is far more complex: It requires that an `index` attribute be added to every element in an iteration. What's the lifetime of that attribute? Is it a real attribute, permanently attached to the item? What about for objects that already have an `index` attribute? If it's a "virtual" attribute, how long does it last? Is the iterated object a newly-created wrapper object for the purposes of providing that attribute? If so, how do you make that more efficient than just creating a new object for each object you iterate over? And so on. Just use `enumerate`. That's what it's there for. > I think that it is more better to give a man a > better tool then to let him play with a not so good one. People like > Python because of his simplicity in comparison with c++. Maybe People > would like him even more it would be a bit more simple but the same > powerfull. The problem is your suggestion would make Python a worse tool, not a better one. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Triumph cannot help being cruel. -- Jose Ortega y Gasset From luke.leighton at googlemail.com Mon Oct 13 05:09:01 2008 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 13 Oct 2008 02:09:01 -0700 (PDT) Subject: Python on JavaScript VM's (such as V8)? References: <1926ef1e-2c5e-4ef6-8a33-b360b02520a7@b38g2000prf.googlegroups.com> <31ea0481-bc7d-476e-92ce-df28b86eed11@o40g2000prn.googlegroups.com> <359581f5-b111-4a29-8bfc-0e1ada08c4fb@d31g2000hsg.googlegroups.com> <267a97c2-707a-43a6-a868-44a11b003f0d@v39g2000pro.googlegroups.com> Message-ID: <39c0fd8f-ec4b-4fed-bdc8-321eb8276442@17g2000hsk.googlegroups.com> On Oct 7, 10:15 pm, Fuzzyman wrote: > On Oct 2, 1:06 pm,lkcl wrote: > > > On Sep 3, 10:02 pm, bearophileH... at lycos.com wrote: > > > > Berco Beute: > > > > > I wonder what it would take to implement Python inJavaScriptso it > > > it's been done. http://pyjamas.sf.net > > That's hardly an implementation of Python inJavascript- someone _is_ considering validating the pyjs.py interpreter to ensure that it's NP complete. however, it's an academic exercise that's not driven by an actual real-world need. basically, running pyjs.py and the standard python 2.5 "compile" module under pyv8. just for kicks :) so, the beginnings of the process - to bootstrap your way entirely into javascript-land, where you'd be able to "input" python and have it compiled _to_ javascript _by_ a python-to-javascript compiler which _itself_ has been compiled to javascript - the foundations have been laid. and it's not _as_ crazy as it sounds. sufficient tests to demonstrate unequivocably that the equivalent javascript _is_ equivalent; you then have pyv8 empirically demonstrating a ten times - TEN times for goodness sake - performance increase - that's got to be worth it. especially if it can be done "automagically", behind the scenes, so that when you type "python myapp.py" instead of executing forth-like byte code (myapp.pyc) you "execute" javascript (myapp.pyj). > it's a > partial Python toJavascripttranslator. compiler. python to javascript _compiler_ :) with a more complete python-to-javascript compiler in http://code.google.com/p/pyjamas subversion - you'll need the llpamies branch, but you'll _also_ need to go back to around sep 2007. somewhere in between then and now, luis tried to add proper support for **kwargs and he didn't complete it. > Still looks good though. yeh :) From smukh at cognobytes.com Mon Oct 20 21:41:23 2008 From: smukh at cognobytes.com (Sumitava Mukherjee) Date: Mon, 20 Oct 2008 18:41:23 -0700 (PDT) Subject: How is the logical processing being done for strings like 'Dog' and 'Cat' Message-ID: <299cad90-7aed-40ba-9d57-f1daa9cd1b9e@u57g2000hsf.googlegroups.com> Hi all, I am a novice programmer in Python. Please could you explain me the results (regarding logical operators). I get this: >>> print bool('God' and 'Devil') True [This is ok because (any) string is True, so; (True and True) gives True] >>> print('God' and 'Devil') Devil [This is what I don't get ] and for that matter,I also checked out this: >>> 01 and 10 10 What is python doing when we type in ('God' and 'Devil') or key in (01 and 10) ? From steve at holdenweb.com Tue Oct 28 09:59:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Oct 2008 09:59:28 -0400 Subject: Sorting a list In-Reply-To: References: Message-ID: RC wrote: > unsortedList = list(["XYZ","ABC"]) > > sortedList = unsortedList.sort() > print sortedList > > > Why this return None? > How do I get return as ["ABC", "XYZ"]? The list's .sort method returns None because it modifies the list in-place, so after the call it is sorted. So you can either not assign the list and use unsortedList (whose name now belies its sorted condition) or you can use sprtedList = sorted(unsortedList) since the sorted() function returns a sorted copy of its argument. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Lie.1296 at gmail.com Fri Oct 10 14:12:23 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 10 Oct 2008 11:12:23 -0700 (PDT) Subject: Efficient Bit addressing in Python. References: <004c01c92a5f$2ed15420$0d00a8c0@hendrik> <48EDEFCE.4020300@wildenhain.de> <003801c92b10$57eb9da0$0d00a8c0@hendrik> <48EF216B.5010708@wildenhain.de> Message-ID: <88177abc-5496-44c9-b151-6a006025f284@s50g2000hsb.googlegroups.com> On Oct 11, 5:27?am, "Hendrik van Rooyen" wrote: > This of course means that there has to be another > thread active to actually do the i/o on a periodic basis, > gathering the outputs and writing them out, and reading > the inputs and scattering them to the various named input > bits Not necessarily. You've mentioned two ways. > I would even not mind if I have to write: > > if e_stop(): > ? ? put_everything_off() > > or: > > set(push,1) > PS: Umm, a little bit off note: set is a built-in name, I'm a little confused whether you meant on creating a "set" or setting the push bit to 1, if the latter case it might be better to use set and clear instead of passing a second parameter (and also to choose another name). Alternatively, there is one more way: if bb.e_stop: bb.e_stop = 0 where bb is some kind of "property bag" and .e_stop is a "property" instead of an "instance member". > > > This approach has the advantage that you can > > > add a ninth "dirty" bit to indicate that the "byte" > > > in question needs to be written out. > > > What do you mean by "written out" to where? > > See above explanation - see also a recent thread here > about "Python string immutability broken" where I posted the > prototype ctypes code, if you are really interested... > > > > Is there not some OO way of hiding this > > > bit banging complexity? > > > foo & bar is complex? So you want to replace foo + bar > > as well with something? ;) > > > > Using getters and setters? - I tend to go "tilt" > > > like a cheap slot machine when I read that stuff. > > > Getters setters? Where would that improve the situation > > beside having to write lots of unneccessary code? > > Not necessarily unnecessary - the getters and setters could be > used to actually do the i/o to the relevant card when anything > makes an access to one of the bits on the memory representation > of that card - that would obviate the necessity for a second thread... Rather than directly using getters and setters, I'd go with property. It (usually) makes a cleaner external interface of the class. And for the mess of having to write lots of boilerplate codes, you _could_ dynamically generate the boilerplate code from a dictionary (of name to bit position) and currying (or something to that effect). Alternatively, you could also do some magic with getattr and setattr. From joe at strout.net Mon Oct 6 10:19:58 2008 From: joe at strout.net (Joe Strout) Date: Mon, 6 Oct 2008 08:19:58 -0600 Subject: type-checking support in Python? Message-ID: I'm just re-learning Python after nearly a decade away. I've learned a good healthy paranoia about my code in that time, and so one thing I'd like to add to my Python habits is a way to both (a) make intended types clear to the human reader of the code, in a uniform manner; and (b) catch any type errors as early and automatically as possible. I found the "typecheck" module (http://oakwinter.com/code/typecheck/), but I notice that it hasn't been updated since 2006, and it's not included with the Python distribution. Are there other modules providing similar functionality that I should consider instead? Also, I'll probably be considering a lint-like tool at some point... are there any that allow you to declare some extra type information, and have that checked at lint time? Finally, one thing I've considered is adopting some identifier prefixes indicating type. Maybe "iFoo" for integer, "fFoo" for floating-point numbers, "d" for dictionary, "l" for list, "t" for tuple, "o" for object, and "v" for variable types that may be more than one of the above. I gather (from just a couple days of browsing) that such a naming convention isn't common in the Python community, but is there anyone else here who does it? I'd rather adopt an existing standard (even if it's not widely used) than make one up. Many thanks, - Joe From bj_666 at gmx.net Sat Oct 18 14:37:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Oct 2008 18:37:54 GMT Subject: heapreplace, methodcaller References: <848dd2c3-d13f-4922-9991-63d7664d4123@y79g2000hsa.googlegroups.com> Message-ID: <6luoo2F9rpqhU1@mid.uni-berlin.de> On Sat, 18 Oct 2008 07:01:26 -0700, bearophileHUGS wrote: > Hello, I'm experimenting more with Python 2.6 and its numerous changes. > > [?] > > Regarding the operators module, this syntax: methodcaller('replace', > 'old', 'new') > > Has this meaning: > lambda s: s.replace('old', 'new') > > I don't know if methodcaller() is faster than that lambda but: > - It's not shorter; > - For me it's not more readable; Then use the ``lambda``. Your example has just literal constants. Let's take this example: methodcaller(meth, arg_a, arg_b) which is expressed as ``lambda`` function: lambda x, m=meth, a=arg_a, b=arg_b: getattr(x, meth)(a, b) Which is longer and IMHO less readable than `methodcaller()`. > - If it's faster than the lambda, then maybe CPython can start > performing a little more optimizations, like turning that tiny lambda > into inlined code. How? The functions in `operator` are meant to be passed directly or to to create other functions that are passed as HOFs into other functions. So the compiler doesn't know in which functions they are used in the end and it's possible that different functions are used there too. Ciao, Marc 'BlackJack' Rintsch From james.harris.1 at googlemail.com Fri Oct 17 18:32:18 2008 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 17 Oct 2008 15:32:18 -0700 (PDT) Subject: Parsing a file with iterators References: Message-ID: On 17 Oct, 16:42, Luis Zarrabeitia wrote: > I need to parse a file, text file. The format is something like that: > > TYPE1 metadata > data line 1 > data line 2 > ... > data line N > TYPE2 metadata > data line 1 > ... > TYPE3 metadata > ... > > And so on. The type and metadata determine how to parse the following data > lines. When the parser fails to parse one of the lines, the next parser is > chosen (or if there is no 'TYPE metadata' line there, an exception is thrown). > > This doesn't work: > > === > for line in input: > parser = parser_from_string(line) > parser(input) > === > > because when the parser iterates over the input, it can't know that it finished > processing the section until it reads the next "TYPE" line (actually, until it > reads the first line that it cannot parse, which if everything went well, should > be the 'TYPE'), but once it reads it, it is no longer available to the outer > loop. I wouldn't like to leak the internals of the parsers to the outside. > > What could I do? > (to the curious: the format is a dialect of the E00 used in GIS) The main issue seems to be that you need to keep the 'current' line data when a parser has decided it doesn't understand it so it can still be used to select the next parser. The for loop in your example uses the next() method which only returns the next and never the current line. There are two easy options though: 1. Wrap the input file with your own object. 2. Use the linecache module and maintain a line number. http://blog.doughellmann.com/2007/04/pymotw-linecache.html -- HTH, James From weiguo6 at gmail.com Wed Oct 8 19:36:44 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Wed, 8 Oct 2008 16:36:44 -0700 Subject: A question about funcation parameter and self defined object Message-ID: Hi, I defined a class called vec3 which contains x, y, z and in another function, I tried to call a function which takes a vec3 as a parameter, but it seems that parameter is passed as a generic object and I can not access x , y, z in my vec3. Could anyone help me with that? class vec3: def __init__(self, x_ = 0.0, y_ = 0.0, z_ = 0.0): self.x = x_ self.y = y_ self.z = z_ class mat4: def translation( traV = vec3() ): tranM.rowLst[index][0] = traV.x AttributeError: 'NoneType' object has no attribute 'x' Could anyone help me how to turn the traV as type of vec3() instead of NoneType object? Thanks a lot, Wei -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcd at sdf.lonestar.org Fri Oct 3 10:28:54 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 03 Oct 2008 10:28:54 -0400 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <9omdnSLTM7iatHvVnZ2dnUVZ_uudnZ2d@posted.visi> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> <6klo5eF8ghmdU1@mid.individual.net> <9omdnSLTM7iatHvVnZ2dnUVZ_uudnZ2d@posted.visi> Message-ID: <1223044134.5925.1.camel@aalcdl07.lib.unc.edu> On Fri, 2008-10-03 at 09:15 -0500, Grant Edwards wrote: > On 2008-10-03, greg wrote: > > Lawrence D'Oliveiro wrote: > >> In message <00f15d41$0$20617$c3e8da3 at news.astraweb.com>, Steven D'Aprano > >> wrote: > >> > >> > (2) Even when the source is available, it is sometimes a legal trap to > >> > read it with respect to patents and copyright. > >> > >> That's not how patents work. > > > > I don't think that's how copyrights work either. As far as > > I know, whether something is deemed a derivative work is > > judged on the basis of how similar it is to another work, > > not whether its author had knowledge of the other work. > > As long as you express an idea in an original way, it > > shouldn't matter where you got the idea from. > > IANAL, but IIRC it does matter when it comes to establishing > punative damages. If you knowingly and intentionally infringe > a patent, I think you're libel for more damages than if you > accidentally re-invent something. At least that's what I was > told... > s/libel/liable/ When talking about legal matters, it's kind of an important distinction. From grante at visi.com Fri Oct 10 17:57:24 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 10 Oct 2008 16:57:24 -0500 Subject: Read data from Serial Command References: <6PednQiTyPLyW3LVnZ2dnUVZ_uednZ2d@posted.visi> Message-ID: On 2008-10-10, brianrpsgt1 wrote: > Thanks for the message > > What exactly is happening is that the return is "None" for the command > that I am sending. If I connect through Hyperterminal and execute the > 'sh nw enc' command, it returns 'WEP' It looks to me like you're never reading from the serial port. All you're calling is write(). Also, are you sure that the device doesn't expect commands to be termined by carriage returns? >> > import serial >> > import time >> > >> > s = serial.Serial(port=1, timeout=None, baudrate=9600) >> > print s >> > time.sleep(5) >> > print "Enter CFG" >> > s.write('CFG') >> > print "Change baud" >> > s.baudrate=115200 >> > print s >> > time.sleep(5) >> > print "New line" >> > s.write('\n') >> > >> > >> > time.sleep(2) >> > print "Show Encryption Setting" >> > nw = s.write('sh nw enc') >> > time.sleep(1) Try changing that to s.write('sh nw enc') time.sleep(1) nw = s.read(1024) >> > print nw >> > s.close() There are plenty of example programs at: http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/ -- Grant Edwards grante Yow! at BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI- visi.com From bj_666 at gmx.net Thu Oct 23 15:48:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Oct 2008 19:48:45 GMT Subject: why would 'import win32com' fail? References: Message-ID: <6mc2otFfv9sgU6@mid.uni-berlin.de> On Thu, 23 Oct 2008 12:21:29 -0700, bill wrote: > I am trying to access Excel from Python. Many of the examples started > with: > > import win32com > .... > blah, blah > > I try that from my Python shell and it fails. What am I missing here? The `win32com` module? It is not part of the standard library. Ciao, Marc 'BlackJack' Rintsch From gslindstrom at gmail.com Mon Oct 20 14:16:12 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 20 Oct 2008 13:16:12 -0500 Subject: Using LDAP Message-ID: I am attempting to use python-ldap to connect to our company ldap server. I have downloaded and installed python-ldap 2.3.2 on my Ubuntu system and have been working through the "LDAP Programming with Python" documentation. I am confused because the documentation states that "After an LDAP object is created and before any other operations can be attempted over the connection, a bind operation must be performed" (p7), but in the example in section 1.1.5, it shows using the ldap.initialize() statement then a search_s() statement; with no bind(). I've keep getting a "Can't contact LDAP server" error when running in iPython, but I can hit the LDAP server using PHP. Do I need to run a bind statement of some sort after initialize()? Thanks, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From musiccomposition at gmail.com Wed Oct 8 17:28:26 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 8 Oct 2008 14:28:26 -0700 (PDT) Subject: utf-8 read/write file References: Message-ID: <6cd45025-d01b-429a-ae4c-24a08db2b9c7@b2g2000prf.googlegroups.com> On Oct 8, 12:49?pm, Bruno wrote: > Hi! > > I have big .txt file which i want to read, process and write to another .txt file. > I have done script for that, but im having problem with croatian characters > (?,?,?,?,?). Can you show us what you have so far? > How can I read/write from/to file in utf-8 encoding? import codecs data = codecs.open("my-utf8-file.txt").read() > I read file with fileinput.input. > > thanks From duncan.booth at invalid.invalid Sun Oct 5 05:43:24 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Oct 2008 09:43:24 GMT Subject: Tuple parameter unpacking in 3.x References: <871vyyy8mb.fsf@hbox.dyndns.org> <87zllkm630.fsf@hbox.dyndns.org> <00f7fee1$0$20633$c3e8da3@news.astraweb.com> <87myhjcu7g.fsf@hbox.dyndns.org> Message-ID: Martin Geisler wrote: > Letting the callbacks take several arguments would definitely be the > nicest syntax, but I'm unfortunately restricted by the Twisted > framework: there all functions in a callback chain return one result > which is passed to the next callback as the first argument. That is why > I do a fair amount of tuple unpacking in my code. If you only have to contend with that one pattern then you could write a decorator to unpack a single argument. Maybe not ideal, but then you have the option to write: @unpacked def product(a, b): return a*b ci.addCallback(product) or ci.addCallback(unpacked(lambda a,b: a*b)) for some suitable definition of unpacked. From seidymam at gmail.com Thu Oct 30 06:50:47 2008 From: seidymam at gmail.com (Seid Mohammed) Date: Thu, 30 Oct 2008 13:50:47 +0300 Subject: Python-list Digest, Vol 61, Issue 443 In-Reply-To: References: Message-ID: <179b305e0810300350s3aef0b00p7ddb29cfb41ca5f0@mail.gmail.com> ok but still i am not clear with my problem. if i test this one ============== kk ='how old are you' >>> len(kk) 15 ========== but in my case ========== >>> abebe = '??? ?? ??' >>> len(abebe) 23 ========== why the lenght is 23 while I am expecting to be 9 only. becuase I have 9 characters(including space) just typed. there must be a kind of trick over it. thanks all Seid M On 10/30/08, 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..." > -- "RABI ZIDNI ILMA" From greg at cosc.canterbury.ac.nz Thu Oct 30 20:38:23 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 31 Oct 2008 13:38:23 +1300 Subject: Finding the instance reference of an object In-Reply-To: References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <6mv26iFj3ktfU1@mid.individual.net> Douglas Alan wrote: > greg writes: > >>Seems to me that (1) describes exactly how parameter passing >>works in Python. So why insist that it's *not* call by value? > > Because there's an important distinction to be made, The distinction isn't about parameter passing, though, it's about the semantics of *assignment*. Once you understand how assigment works in Python, all you need to know then is that parameters are passed by assigning the actual parameter to the formal parameter. All else follows from that. This holds for *all* languages that I know about, both static and dynamic. Once you know how assignment works in the language concerned, then you know how parameter passing works as well. There is no need for new terms. > and the > distinction has been written up in the Computer Science literature > since Lisp first starting using the same argument passing semantics as > Python back in 1958. The semantics are called "call by sharing". I still think it's an unnecessary term, resulting from confusion on the part of the authors about the meanings of the existing terms. If there's any need for a new term, it would be "assignment by sharing". Although there's already a term in use for that, too -- it's known as reference assignment. > Many mainstream programming languages other than Python now use call > by sharing. They include Java, JavaScript, Ruby, ActionScript, and C#. I would say they use assignment by sharing, and call by value. -- Greg From robinvaiya at gmail.com Sat Oct 11 11:08:47 2008 From: robinvaiya at gmail.com (robin) Date: Sat, 11 Oct 2008 08:08:47 -0700 (PDT) Subject: Scanning error Message-ID: PROBLEM I connect to my laptop to scan pictures, and each time, each single time the scanner will start scanning an inch but it stops and I get the message Cannot communicate with scanner. Cable may be disconnected or scanner may be turned off. Check status. Scanner driver will be closed. Code: 2,155,0"The closest I get is it will scan one or two, but same problem persists. Today I totally cannot scan one thing! What is wrong? find solution here http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer From steve at holdenweb.com Thu Oct 30 00:31:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Oct 2008 00:31:11 -0400 Subject: is there a way to access postgresql in python3.0rc1 In-Reply-To: References: <81f2badd0810290443o6bbbd29sc64dbb50cfbdd63f@mail.gmail.com> Message-ID: Terry Reedy wrote: > davy zhang wrote: >> I'm currently on a project, it could last for at least 1 or 2 years. >> so I choose python3 as server side programing language. >> All I found on are python2.x ready libraries, Is there any library is >> python3.0 ready? or just under alpha ,beta or something, I don't much >> features, just basic functions are OK > > Python3.0 final should be released in about a month. Extension > libraries will start appearing after that. You will have to ask the > maintainers of a particular library what their plans are for Python 3. > Some will port very easily and could be available soon. Others will > take more work and may not appear so soon. > Please note, however, that Python 3.x is not likely to be as well-supported by extension modules as Python 2.x for some considerable time. The OP may therefore wish to reconsider his choice of Python 3.0. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From nick-groups at back-pain-self-help.com Wed Oct 29 02:26:50 2008 From: nick-groups at back-pain-self-help.com (Nick Mellor) Date: Tue, 28 Oct 2008 23:26:50 -0700 (PDT) Subject: how to get the thighest bit position in big integers? References: Message-ID: <3c25c2cd-0357-47b0-b51d-fb38a55bd54e@t18g2000prt.googlegroups.com> On Oct 6, 3:40?am, Gary Herron wrote: > mmgar... at gmx.de wrote: > > Hi, > > > I'm using python to develop some proof-of-concept code for a > > cryptographic application. My code makes extended use of python's > > native bignum capabilities. > > > In many cryptographic applications there is the need for a function > > 'get_highest_bit_num' that returns the position number of the highest > > set bit of a given integer. For example: > > > ? ?get_highest_bit_num( (1 << 159)) ? ? == 159 > > ? ?get_highest_bit_num( (1 << 160) - 1) == 159 > > ? ?get_highest_bit_num( (1 << 160)) ? ? == 160 > > How about a binary search? > > > > >>> from bisect import bisect > >>> BITS = [1< >>> bisect(BITS, 1<<159) > 159 > >>> bisect(BITS, 1<<160-1) > 159 > >>> bisect(BITS, 1<<160) > 160 > > I have no clue if this is faster or not. ?The comparison function used > in the search is (potentially) slow, but the search is O(log n) on the > number of bits rather than O(n), so its worth a test. > > If you run timing test, let us know the results. > > Gary Herron > > > I implemented this the following way: > > > def get_highest_bit_num(r): > > ? ? i = -1 > > ? ? while r > 0: > > ? ? ? ? r >>= 1 > > ? ? ? ? i = i + 1 > > ? ? return i > > > This works, but it is a very unsatisfying solution, because it is so > > slow. > > > My second try was using the math.log function: > > > import math > > r = (1 << 160) - 1 > > print highest_bit_num(r) ? ? ? ? ? ? ?# prints out 159 > > print math.floor(math.log(r, 2)) ? ? ?# prints out 160.0 > > > We see that math.log can only serve as a heuristic for the highest bit > > position. For small r, for example r = (1 << 16) - 1, the result from > > math.log(, 2) is correct, for big r it isn't any more. > > > My question to the group: Does anyone know of a non-hackish way to > > determine the required bit position in python? I know that my two > > ideas > > can be combined to get something working. But is there a *better* way, > > that isn't that hackish? > > > cheers, > > mmg > > -- > >http://mail.python.org/mailman/listinfo/python-list > > The following might be worth a try. It's faster the fewer set bits there are in the original number, and lightning fast if there are only one or two: def get_highest_bit_num(i): while i>0: highestbit, i = i, i & (i-1) return highestbit >>> highestbit(1<<31) 2147483648L >>> highestbit(1<<4) 16 >>> highestbit(3<<4) 32 Note that it returns the value of the highest bit, not its position. All it's doing is successively ANDing i with (i-1) until i is zero, then returning the previous value of i. It works because i & (i-1) has a useful property: it returns i less its least significant set bit: i=6 (binary 110) => i & (i-1)==4 (binary 100) i=3328 => (binary 1101_0000_0000) then i & (i-1)==3072 (binary 1100_0000_0000) (underscores for readability) As far as I know there isn't another piece of logic that helps you extract the most significant bit as simply :-) Best wishes, Nick From mccredie at gmail.com Thu Oct 23 12:52:47 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 23 Oct 2008 09:52:47 -0700 (PDT) Subject: logging module References: Message-ID: <1ad8f307-087f-4900-92bc-9390657f05f2@f40g2000pri.googlegroups.com> On Oct 23, 7:58?am, "Werner F. Bruhin" wrote: > I am starting to use the logging module. > > Simple log to file and/or console work very nicely. > > Even managed to get TimedRotatingFileHandler to work. > > The problem I am trying to solve. > > 1. I would like to have a "log viewer" a wxPython based app to be able > to look at a log generated by another script. Running in a separate process? That isn't possible. Okay, well, it isn't possible without doing a fair amount of work on your own. You would probably need to create a handler that writes everything to a pipe or a socket, and then have your second application read from the pipe/socket and display it. I don't think that feature exists right now though. Matt From steve at REMOVE-THIS-cybersource.com.au Sun Oct 19 07:57:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Oct 2008 11:57:59 GMT Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> <010aa307$0$20653$c3e8da3@news.astraweb.com> <7accf6cb-06b4-4db1-ba76-b3965eb3528e@i18g2000prf.googlegroups.com> <010ae139$0$20653$c3e8da3@news.astraweb.com> <4f1908c0-ff38-4224-a13a-901309e9025f@p10g2000prf.googlegroups.com> Message-ID: <010b19e6$0$20653$c3e8da3@news.astraweb.com> On Sun, 19 Oct 2008 03:17:51 -0700, John Machin wrote: > Steven D'Aprano wrote: > >> On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote: >> >> > On Oct 19, 2:30?pm, Steven D'Aprano > > cybersource.com.au> wrote: >> > [snip] >> >> making your code easy to read and easy to maintain is far more >> >> important. >> >> >> >> for x in (2**i for i in xrange(10)): >> >> ? ? print x >> >> >> >> will also print 1, 2, 4, 8, ... up to 1000. >> > >> > I would say up to 512; perhaps your understanding of "up to" differs >> > from mine. >> >> Well, mine is based on Python's half-open semantics: "up to" 1000 >> doesn't include 1000, and the highest power of 2 less than 1000 is 512. > > We're talking about an English sentence, not a piece of Python code. > When you say "I'm taking the train to X", do you get off at the station > before X, as in "getting off at Redfern"? But I don't say "I'm taking the train UP TO X". Intervals in English are often ambiguous, which is why people often explicitly say "up to and including...". But in this specific case, I don't see why you're having difficulty. Whether 1000 was included or not makes no difference, because 1000 is not a power of 2. -- Steven From mseagoe at gmail.com Tue Oct 28 10:43:25 2008 From: mseagoe at gmail.com (Mark) Date: Tue, 28 Oct 2008 07:43:25 -0700 (PDT) Subject: Unpacking byte strings from a file of unknown size References: <5adcb40f-3b97-4fb7-b534-ab323bdb7636@s1g2000prg.googlegroups.com> Message-ID: <2e14bd33-0370-4bfd-91ad-4683a2c7d05e@s9g2000prg.googlegroups.com> Thanks I tested your solution and that works. One of the things that didn't work was for chunk in myfile.read(10): info1, info2, info3 = struct.unpack(' megarotic hot . . . *******CLICK HERE******** http://vids365.cn/megarotic-hot ***************************** . . . . . . . . . . . . megarotic hot From michele.simionato at gmail.com Wed Oct 8 23:42:00 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 8 Oct 2008 20:42:00 -0700 (PDT) Subject: MRO inconsistency: why? References: Message-ID: On Oct 8, 9:09?pm, Ravi wrote: > Why the following code gives inconsistent method resolution order > error: > If you want to know all the nitty-gritty details about the MRO (including the reason for the error you get) you should read this: http://www.python.org/download/releases/2.3/mro/ HTH, M. Simionato From bborcic at gmail.com Sun Oct 5 19:59:39 2008 From: bborcic at gmail.com (bborcic at gmail.com) Date: Sun, 5 Oct 2008 16:59:39 -0700 (PDT) Subject: ABCs -> infix syntax for isinstance() ? References: <48e68361$0$19710$426a74cc@news.free.fr> Message-ID: <9d5b851d-c764-4515-b015-4117d76c9652@v53g2000hsa.googlegroups.com> Bruno Desthuilliers dixit : > Boris Borcic a ?crit : > > > Given the ABC innovation, maybe an infix syntax for isinstance() would > > be good. > > > Possibilities : > > > - stealing "is" away from object identity. As a motivation, true use > > cases for testing object identity are rare; > > "x is None" is a *very* common test. Using a _marker object as default > arg value when you want to accept None as a meaningfull value is pretty > common. (a) Okay, 3to2 can take care of "x is NoneType" and/or "x == None". The latter could also be a compiler optimization. (b) Give me None==False and in exchange I will adopt "x is None" as sacred forever :) (not quite BTW, how much future do you think is there in turning 2to3 into some usable 3to2 ? What about "NtoM" as a more generic Python project ?) > Testing a class identity often happens when writing metaclasses This kind-of-talks for Terry's proposition : adding a __contains__ to type, looks like easier to pass before lead metaclass-writers. Or if not easier to pass, easier to write a simple patch for. So "x in Number" syntax. A intriguing wider proposition would be to transpose Ruby's notion of "Open Classes" to Python built-in metaclasses (or just to type itself ?). Let's threaten lead metaclass-writers with *that* if they don't settle on just type.__contains__ = lambda cls,i : isinstance(i,cls) !! :) Cheers, BB From duncan.booth at invalid.invalid Sun Oct 26 05:23:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Oct 2008 09:23:41 GMT Subject: How can I handle the char immediately after its input, without waiting an endline? References: <29de18070810220204v4ada4da1k3c1c5b599f3b24b6@mail.gmail.com> <180b672e0810220216i6b5df18cq17f17724047d468f@mail.gmail.com> <29de18070810220417p331e17c1rbd9db9cb1fd9d578@mail.gmail.com> <0112d9f3$0$20624$c3e8da3@news.astraweb.com> <011333d4$0$20616$c3e8da3@news.astraweb.com> Message-ID: Lie Ryan wrote: > And as far as I know, it is impossible to implement a "press any key" > feature with python in a simple way (as it should be). "press any key" is a misfeature at the best of times. Quite apart from the people who can't find the key with 'any' written on it there are also the people who can't figure out why it 'Ctrl', 'Alt', 'Shift', 'Caps Lock' aren't keys (not to mention the smartass's who think Ctrl+Break is a key). It is better to always ask for a specific key. Have you tried Google? Googling for "python getch" gives http://snippets.dzone.com/posts/show/915 as the first hit. From tlake at twcny.rr.com Fri Oct 10 02:52:23 2008 From: tlake at twcny.rr.com (Tom Lake) Date: Fri, 10 Oct 2008 02:52:23 -0400 Subject: Total Python Noob References: Message-ID: "Chris Rebert" wrote in message news:mailman.2304.1223620458.3487.python-list at python.org... > On Thu, Oct 9, 2008 at 11:22 PM, Tom Lake wrote: >> I have Python 2.6 installed on Vista Ultimate. When I try to calculate >> sqrt (or any transcendental functions) I get the following error >> >>>>> sqrt(2) >> >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'sqrt' is not defined >> >> What am I doing wrong? > > They're not buitltin, they're in the 'math' module > (http://docs.python.org/library/math.html#module-math), which you need > to import. > e.g. > import math > print math.sqrt(4) > > Please also Read the Fine Tutorial at: > http://docs.python.org/tutorial/index.html Great! Thanks so much! Tom Lake From reckoner at gmail.com Fri Oct 24 14:11:40 2008 From: reckoner at gmail.com (Reckoner) Date: Fri, 24 Oct 2008 11:11:40 -0700 (PDT) Subject: big objects and avoiding deepcopy? Message-ID: <5e5bfdda-9f90-44c5-a558-f089538f6831@q30g2000prq.googlegroups.com> I am writing an algorithm that takes objects (i.e. graphs with thousands of nodes) into a "hypothetical" state. I need to keep a history of these hypothetical objects depending on what happens to them later. Note that these hypothetical objects are intimately operated on, changed, and made otherwise significantly different from the objects they were copied from. I've been using deepcopy to push the objects into the hypothetical state where I operate on them heavily. This is pretty slow since the objects are very large. Is there another way to do this without resorting to deepcopy? by the way, the algorithm works fine. It's just this part of it that I am trying to change. Thanks in advance. From sjmachin at lexicon.net Sat Oct 18 04:32:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Oct 2008 01:32:28 -0700 (PDT) Subject: Unicode File Names References: <72f742a5-25fd-4e5c-8eaa-d234f226ac02@p31g2000prf.googlegroups.com> <311aa0af-6acd-45b6-b89b-c5aebe957afe@75g2000hso.googlegroups.com> <48f83fab$0$5199$9b622d9e@news.freenet.de> <90767c14-aafc-40a7-b2d2-0497738ed51f@p31g2000prf.googlegroups.com> <48f988c4$0$5243$9b622d9e@news.freenet.de> Message-ID: On Oct 18, 5:57?pm, "Martin v. L?wis" wrote: > > Should the note be removed, or should it say something like "Unicode > > file names are supported. New in Python 2.6."? Is there anything else > > that should be mentioned? > > The note should be corrected, documenting the behaviour implemented. > > > More on cp437: I see where you mentioned to the patch author that a > > unicode string should be encoded in cp437 if possible, but this was > > not done -- it first tries ascii. What are your views on what encoding > > should be assumed if the utf8 flag is not set? > [lots of enlightenment snipped] Thanks heaps, Martin. Cheers, John From python.list at tim.thechases.com Fri Oct 31 15:02:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 31 Oct 2008 14:02:24 -0500 Subject: split() and string.whitespace In-Reply-To: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> References: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> Message-ID: <490B5640.3080206@tim.thechases.com> > I am unable to figure out why the first two statements work as I > expect them to and the next two do not. Namely, the first two spit the > sentence into its component words, while the latter two return the > whole sentence entact. > > import string > from string import whitespace > mytext = "The quick brown fox jumped over the lazy dog.\n" > > print mytext.split() > print mytext.split(' ') > print mytext.split(whitespace) > print string.split(mytext, sep=whitespace) Split does its work on literal strings, or if a separator is not specified, on a set of data, splits on arbitrary whitespace. For an example, try s = "abcdefgbcdefgh" s.split("c") # ['ab', 'defgb', 'defgh'] s.split("fgb") # ['abcde', 'cdefgh'] string.whitespace is a string, so split() tries to use split on the literal whitespace, not a set of whitespace. -tkc From mr.spoon21 at gmail.com Wed Oct 22 09:49:38 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Wed, 22 Oct 2008 15:49:38 +0200 Subject: Ordering python sets In-Reply-To: References: <8f67b6f80810220522r49b0f588qf9d6001f62c080f0@mail.gmail.com> Message-ID: <8f67b6f80810220649h57c67bdg34a41a559c95d7f4@mail.gmail.com> On Wed, Oct 22, 2008 at 3:37 PM, Peter Otten <__peter__ at web.de> wrote: > Tim Chase wrote: > >> Though for each test, in 2.3, 2.4, and 2.5 that I've got >> installed on my local machine, they each printed "s" in-order, >> and the iteration occurred in-order as well, even without the >> added "sorted(list(s))" code. > > You need more tests then ;) > >>>> list(set([1,1000])) > [1000, 1] It seems to me that it orders elements when you add using the add() method, but if you create a set starting from a list, it may result unordered. Anyway, the add() fails to order if you try to add a float in a set of integers. > By the way, sorted(s) is sufficient; sorted() accepts arbitrary iterables. I'll try with this. From deets at nospam.web.de Thu Oct 23 04:55:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Oct 2008 10:55:36 +0200 Subject: substitution __str__ method of an instance References: Message-ID: <6masftFg2h2oU1@mid.uni-berlin.de> netimen wrote: > I couldn't substitute __str__ method of an instance. Though I managed > to substitute ordinary method of an instance: > > from types import MethodType > > class Foo(object): > pass > > class Printer(object): > > def __call__(self, obj_self): > return 'printed' > > f = Foo() > > f.printer = MethodType(Printer(), f, Foo) > print f.printer() # works fine - I get: 'printed' > > print f # get: <__main__.Foo object at 0x00D69C10> > f.__str__ = MethodType(Printer(), f, Foo) > print f # still get: <__main__.Foo object at 0x00D69C10>. Why? > Foo.__str__ = MethodType(Printer(), None, Foo) > print f # works fine - I get: 'printed' > > > How can I substitute __str__ method of an instance? You can't. Special methods are only looked up on classes. Diez From deets at nospam.web.de Mon Oct 13 12:15:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Oct 2008 18:15:28 +0200 Subject: Suggestion for the PythonDevelopment for next version References: Message-ID: <6lhagrFcdi0lU1@mid.uni-berlin.de> azrael wrote: > I know that. enumerate is a great function. But this way it always > adds some complexity. I think that it is more better to give a man a > better tool then to let him play with a not so good one. People like > Python because of his simplicity in comparison with c++. Maybe People > would like him even more it would be a bit more simple but the same > powerfull. But the added complexity of your approach of setting an attribute at runtime that can - add arbitrary costs (who knows that setting the attribute might not invoke a RPC-call?) for *every* enumeration of a list - conflict with multithreaded access or even only cartesian products of the same list of objects, rendering it simply useless is *less* hassle than putting a simple enumerate in place, just when needed? You sure have an interesting view of complexity. Not exactly text-book-based though. Diez From Jiandong.Ge at gmail.com Fri Oct 17 17:45:15 2008 From: Jiandong.Ge at gmail.com (JD) Date: Fri, 17 Oct 2008 14:45:15 -0700 (PDT) Subject: algorizm to merge nodes References: <4e08df3e-e91d-4940-8bdb-c7ff852e5de2@a19g2000pra.googlegroups.com> <87c05cc0-937c-4764-be99-ae7cad981a56@8g2000hse.googlegroups.com> Message-ID: <5afc36b9-b4b3-48bb-87a1-4704433c25a0@a18g2000pra.googlegroups.com> Thanks, This one really works. JD On Oct 17, 3:17 pm, bearophileH... at lycos.com wrote: > JD, you probably need the algorithm for connected components of an > undirected graph. > > For example you can do that with my graph lib:http://sourceforge.net/projects/pynetwork/ > > from graph import Graph > g = Graph() > data = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], > ['c', 'u'], ['b', 'p']] > g.addArcs(data, bi=True) > > print g.connectedComponents() > # Output: [['a', 'b', 'g', 'p'], ['c', 'u', 'd'], ['e', 'k', 'f']] > > Bye, > bearophile From venutaurus539 at gmail.com Wed Oct 8 05:34:02 2008 From: venutaurus539 at gmail.com (venutaurus539 at gmail.com) Date: Wed, 8 Oct 2008 02:34:02 -0700 (PDT) Subject: Problem while reading an outlook in box using python. References: <9c6e93b4-e2f1-4155-a081-2479e5596bb6@2g2000hsn.googlegroups.com> Message-ID: May I know how to check whether my Outlook is installed with CDO components? There is no entry in my Registry Database with the name MAPI.Session. Thank you, Venu. From python-url at phaseit.net Tue Oct 21 10:08:00 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 21 Oct 2008 14:08:00 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Oct 21) Message-ID: QOTW: "Trust me. Sean is absolutely correct. I'm currently in the process of converting a large Perl project to Python (and learning Python at the same time) and the improvement in code is incredible. After you learn Python, you'll come to despise Perl." - Pat http://groups.google.com/group/comp.lang.python/msg/667b00a4964237c8 A class decorator is a better choice than a metaclass for some tasks, according to R. Hettinger: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2619be0766e5cf75/ Dealing with character encodings other than ASCII still appears to be hard: http://groups.google.com/group/comp.lang.python/browse_thread/thread/51376149681d3c52/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/44bc715ec177fac6/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3b5bdaf51248b3/ Alternative ways to work with a database - other than plain DBAPI or using an ORM: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bc2e76e8f06c5ab4/ Default mutable arguments, newbies that never read docs, and antigravity (continued from previous week): http://groups.google.com/group/comp.lang.python/browse_thread/thread/a103cc269cec69dd/ Call-by-value? Call-by-reference? Call-by-object? Call-by-name? Which is the right term? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6163956596a8c082/ Using reversed domain names as package identifiers is discouraged: http://groups.google.com/group/comp.lang.python/browse_thread/thread/dc77e7c775295654/ Python certification: should exist? would it be a good thing? http://groups.google.com/group/comp.lang.python/browse_thread/thread/83b0fb9fe9f42ba3/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html 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/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. 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://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf 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://www.python.org/dev/peps/pep-0042/ 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 Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes 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!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From nullius.filius at gmail.com Wed Oct 15 21:56:10 2008 From: nullius.filius at gmail.com (nullius.filius at gmail.com) Date: Wed, 15 Oct 2008 18:56:10 -0700 (PDT) Subject: rope python-emacs problem References: Message-ID: <2fd66f8d-a26b-4e9f-9f38-f1dcc63ff64b@1g2000prd.googlegroups.com> On Oct 15, 7:19?pm, "Rustom Mody" wrote: > Ive been trying to useropefor python in emacs and I get > a backtrace which starts with > AttributeError: 'module' object has no attribute 'samefile' > > Any ideas? I searched for a variable 'samefile' in ropemacs and its associated packages. I couldn't find one. That is not to say there wasn't one because ropemacs is in flux more than most packages with frequent rewrites. May I can suggest to start again and use the most recent packages- Pymacs-0.24beta1, rope-0.9, and ropemacs-0.6. I installed these about a week ago when I installed Python 2.6, and it was painless (Windows OS and Emacs 22). From alex.m.gusarov at gmail.com Tue Oct 21 00:56:30 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Tue, 21 Oct 2008 11:56:30 +0700 Subject: How to get all variables of some module in that module Message-ID: Hello, I have a following module and in its end I want to initalize collection of tables: Module: from sqlalchemy import * metadata = MetaData() calendars_table = Table('calendars', metadata, Column('id', Integer, primary_key=True), Column('title', Unicode(50)), Column('color', Unicode(6)), ) events_table = Table('events', metadata, Column('id', Integer, primary_key=True), Column('calendar', Integer, ForeignKey('calendars.id')), Column('date', Date), Column('title', Unicode(50)), Column('description', Unicode(1000)), Column('color', Unicode(6)), ) tables_collection = {} Here I want to get all Table instances of current module and put them into dictionary by names, but I don't know how I can get all variables of current module in the end of this module. Please, give me a hint. -- Best regards, Alex Gusarov From rustompmody at gmail.com Thu Oct 16 03:46:19 2008 From: rustompmody at gmail.com (rustom) Date: Thu, 16 Oct 2008 00:46:19 -0700 (PDT) Subject: Emacs users: feedback on diffs between python-mode.el and python.el? References: <48f66642$0$8018$426a74cc@news.free.fr> Message-ID: <7921db67-00fb-4da7-a925-b631fba85f82@t18g2000prt.googlegroups.com> On Oct 16, 12:54?am, Bruno Desthuilliers wrote: > Lawrence D'Oliveiro a ?crit : > > > I find Emacs modes just too confusing. I do all my editing in fundamental > > mode. > > Sounds like buying a cray supercomputer to end up doing computation by > hand... Reminds me of a funny story about one of our university profs. At a time when we used DOS and unix (on terminals) he got a very high end SGI workstation. And promptly shouted at the sysads because he could not see his C:> prompt. From castironpi at gmail.com Mon Oct 20 17:47:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 20 Oct 2008 14:47:34 -0700 (PDT) Subject: Mail reader & spam References: gd070v$7n4$1@aioe.org Message-ID: On Oct 13, 2:19?pm, Cousin Stanley wrote: > > I'm hesitating to change news readers .... > > .... > > ? You might try the python-based ?XPN ?news client at .... > > ? ? ?http://xpn.altervista.org/index-en.html > > ? I've used it for the past few years > ? and like it very much .... > > -- > Stanley C. Kitching > Human Being > Phoenix, Arizona Dear Human Being, Hi, I tried it out. I like the layout definitely, plus the feel of it, colors, etc. It doesn't do the things I named that I like though. It's threading is buggy and watch flags don't propagate consistently. And there isn't any less spam. Google has a full screen of topics. Click on one, and get the full thread. It's (contraction) a lot more bandwidth, which might be important to people still on phone modems. From xnews2 at fredp.lautre.net Wed Oct 1 14:54:30 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 01 Oct 2008 18:54:30 GMT Subject: Are there any python micro-frameworks (like ruby's Camping)? References: <609d9426-671b-488f-b170-c51ca34e857a@p25g2000hsf.googlegroups.com> <85c9ada8-cca1-4267-a25e-2ae201e20c64@q9g2000hsb.googlegroups.com> Message-ID: Phillip B Oldham said : > On Oct 1, 10:29?am, Michele Simionato > wrote: >> How about wsgiref in the standard library? It is as small as you can >> get without resorting to CGI. > > Interesting... I'll be sure to check that out also. > > Someone also mentioned Paste/WebOb, so now I have 3 to test. > > Any others? I'd add Snakelets (in stasis, but interesting) and Karrigell (alive and well). web.py is probably closest to what you're looking for though. From stef.mientki at gmail.com Sun Oct 19 03:51:55 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 19 Oct 2008 09:51:55 +0200 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: References: Message-ID: <48FAE71B.2080205@gmail.com> Lawrence D'Oliveiro wrote: > In message , Dotan > Cohen wrote: > > >> I often see mention of SMBs that either want to upgrade their Windows >> installations, or move to Linux, but cannot because of inhouse VB >> apps. >> > > Probably best to leave those legacy VB apps alone and develop new > replacements in a more open, cross-platform language, like Python. > Sorry but for GUI design, Python is pre-historic ;-) Stef From michele.simionato at gmail.com Fri Oct 3 05:24:42 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 3 Oct 2008 02:24:42 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> <80ffbfcf-9fbc-458a-aaf0-ffea24db390f@34g2000hsh.googlegroups.com> <6km4oqF8ipieU1@mid.individual.net> Message-ID: <4269ceab-963f-4f30-8bae-5593fe24328f@l62g2000hse.googlegroups.com> On Oct 3, 10:44?am, greg wrote: > So if anything were to be done to the language to > fix this, it really should be focused on fixing the > semantics of the for-loop. Unfortunately, the > fact that the loop variable leaks out of the scope > of the loop is regarded as a feature, so anything > which changes that seems to be a non-starter. And Guido stated many times in the past that he is happy with the for loop as it is, so I don't think this will never change, even if the question keep getting asked here and there. Notice that even generator expressions, where the loop variable does not leak outside the loop, have the same behavior. The behavior of the list comprehension is a good test of how much functional a language is; Common Lisp and Python behaves in the same way (there is a single loop variable which is mutated at each iteration) wherea Scheme and Haskell introduce a new binding at each iteration. From steve at REMOVE-THIS-cybersource.com.au Sat Oct 18 23:30:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Oct 2008 03:30:46 GMT Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> Message-ID: <010aa307$0$20653$c3e8da3@news.astraweb.com> On Sat, 18 Oct 2008 03:52:51 -0700, Gandalf wrote: > I was hopping to describe it with only one command. most of the > languages I know use this. > It seems weird to me their is no such thing in python. it's not that I > can't fined a solution it's all about saving code It shouldn't be about saving code. There's no shortage of code so that we have to conserve it. But there is a shortage of time and effort, so making your code easy to read and easy to maintain is far more important. for x in (2**i for i in xrange(10)): print x will also print 1, 2, 4, 8, ... up to 1000. -- Steven From dullrich at sprynet.com Tue Oct 21 12:05:46 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 21 Oct 2008 11:05:46 -0500 Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <256f2adc-184c-4e18-993e-b8e031febcd0@v72g2000hsv.googlegroups.com> Message-ID: In article <256f2adc-184c-4e18-993e-b8e031febcd0 at v72g2000hsv.googlegroups.com>, Paul McGuire wrote: > On Oct 14, 1:36?pm, "David C. Ullrich" wrote: > > >[...] > > > In particular default parameters should work the way the user > > expects! The fact that different users will expect different > > things here is no excuse... > > > Are you being sarcastic? Why would you think that? Seems like a perfectly reasonable request. > Short of "import mindreading", I don't know > how Python would know which behavior a given user would expect. I guess that's why I'm not a programmer - not able to think this sort of thing through properly. Thanks. This explains a lot of other things I've wondered about for years, like why I need to tell the waitress whether I want tea or coffee, why I sometimes need to switch channels on my TV... that's always been what I like about c.l.py, getting answers to questions I haven't even asked. -- David C. Ullrich From tjreedy at udel.edu Sat Oct 4 23:49:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 04 Oct 2008 23:49:35 -0400 Subject: having a function in a separate file In-Reply-To: References: Message-ID: Maryam Saeedi wrote: > Hi all, > > I have a very basic question. I was wondering if I can have a function > in a separate file Yes, the separate file become a module. > and in my main file sort of import that function and Yes. either of import somemod # and use somemod.func from somemod import func # and use func > if so are all the variables local The function can access built-in objects and objects in the module it is defined in. Otherwise, it has locals just as usual. > and if I need any variables in the function I should give it as an input? Yes. > I need to call a function in many different tasks and I am improving > that function so I prefer to make the changes only once. If you have any > example I really appreciate it. Look at Python coded files in the the standard library. Look in .../Pythonx.y/Lib to find them. tjr From martin at librador.com Mon Oct 27 18:21:25 2008 From: martin at librador.com (Martin Vilcans) Date: Mon, 27 Oct 2008 23:21:25 +0100 Subject: Type feedback tool? In-Reply-To: <49059CEE.3020209@egenix.com> References: <49059CEE.3020209@egenix.com> Message-ID: Thanks everyone for the suggestions. I've implemented a simple solution using sys.settrace. It's quite nice because it doesn't require any instrumentation of the code (it works like a debugger that traps all function calls). Here's the output I get right now when "profiling" Skip's example code (but without using decorators): fib2 (testee.py:8) 1 arguments n: (1) (23) main (testee.py:17) 0 arguments fib (testee.py:1) 1 arguments n: (9) (15) This means that fib2 has been called once with a float in the n parameter, and 23 times with an int, etc. There's more work to be done to make this a robust tool (which is why I was hoping there already existed a tool for this). It should handle varargs and keyword arguments properly, and probably needs to handle exceptions better. I'll see if I can run it on real code tomorrow and see if the results are useful. Martin On Mon, Oct 27, 2008 at 11:50 AM, M.-A. Lemburg wrote: > On 2008-10-26 13:54, Martin Vilcans wrote: >> Hi list, >> >> I'm wondering if there's a tool that can analyze a Python program >> while it runs, and generate a database with the types of arguments and >> return values for each function. In a way it is like a profiler, that >> instead of measuring how often functions are called and how long time >> it takes, it records the type information. So afterwards, when I'm >> reading the code, I can go to the database to see what data type >> parameter "foo" of function "bar" typically has. It would help a lot >> with deciphering old code. >> >> When I googled this, I learned that this is called "type feedback", >> and is used (?) to give type information to a compiler to help it >> generate fast code. My needs are much more humble. I just want a >> faster way to understand undocumented code with bad naming. > > You could try the trace module: > > http://www.python.org/doc/2.5.2/lib/module-trace.html > > but I'm not sure whether that includes parameter listings. > > Or write your own tracing function and then plug it into your > application using sys.settrace(): > > http://www.python.org/doc/2.5.2/lib/debugger-hooks.html#debugger-hooks > > The frame object will have the information you need: > > http://www.python.org/doc/2.5.2/ref/types.html#l2h-143 > > in f_locals. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Oct 27 2008) >>>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -- martin at librador.com http://www.librador.com From fernandena at gmail.com Wed Oct 15 09:48:44 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Wed, 15 Oct 2008 06:48:44 -0700 (PDT) Subject: BDSM in BDSM mpeg Message-ID: BDSM http://youtubeplayer.byethost9.com/jpeg/bdsm.html BDSM From steve at REMOVE-THIS-cybersource.com.au Sat Oct 25 21:09:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Oct 2008 01:09:04 GMT Subject: is it "legal" to pace the module's doc string after some imports ? References: Message-ID: <0113bc1d$0$20667$c3e8da3@news.astraweb.com> On Sun, 26 Oct 2008 02:31:01 +0200, Stef Mientki wrote: > hello, > > I wonder if it's "legal" to pace the module's doc string after some > imports ? > > I mean something like this: > > from language_support import _ > __doc__ = _(0, """ > some documentation > """ Doc strings are normal objects like anything else, so the above should work fine. The only "magic" that happens with doc strings is that if you have a bare string immediately after a class, method or function definition, or at the top of the module, it gets picked up by the compiler and assigned to __doc__. You can do anything you like to it. You might even do this: # top of module """This is some documentation blah blah blah """ try: from language_support import _ __doc__ = _(0, __doc__) except ImportError: pass and it should just work. -- Steven From invalid at invalid Thu Oct 30 17:40:17 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 30 Oct 2008 16:40:17 -0500 Subject: Printing with interspersed element References: Message-ID: On 2008-10-30, Paulo J. Matos wrote: > On Thu, Oct 30, 2008 at 8:42 PM, Arnaud Delobelle > wrote: >> On Oct 30, 8:07 pm, "Paulo J. Matos" wrote: >>> Hi all, >>> >>> I guess this is a recurring issue for someone who doesn't really know >>> the python lib inside out. There must be a simple way to do this. >>> I have a list of objects [x1, x2, x3, ..., xn] and I have defined a >>> print method for them print_obj(). Now I want to print them >>> intersepersed by an element. >>> If I print [x1, x2, x3] interspersed by the element 10: >>> x1.print_obj() 10 x2.print_obj() 10 x3.print_obj() >>> >>> Now, the question is, what's the best way to do this? >> >> Defining a print_obj() method is probably a bad idea. What if you >> want to print to a file for example? Instead you can define a >> __str__() method for your objects and then use the join() method of >> strings like this: >> >> print ' 10 '.join(str(x) for x in lst) > > Thanks for the tip but that has an issue when dealing with potentially > millions of objects. You are creating a string in memory to then dump > to a file [or screen] while you could dump to the file [or screen] as > you go through the original string. Right? If you want to do it "on the fly", then try something like this: iter = [1,2,3,4,5].__iter__() sys.stdout.write(str(iter.next())) for n in iter: sys.stdout.write(',' +str(n)) -- Grant Edwards grante Yow! The SAME WAVE keeps at coming in and COLLAPSING visi.com like a rayon MUU-MUU ... From roy at panix.com Wed Oct 22 10:30:52 2008 From: roy at panix.com (Roy Smith) Date: Wed, 22 Oct 2008 10:30:52 -0400 Subject: Ordering python sets References: <8f67b6f80810220522r49b0f588qf9d6001f62c080f0@mail.gmail.com> Message-ID: In article , Mr.SpOOn wrote: > It seems to me that it orders elements when you add using the add() > method, but if you create a set starting from a list, it may result > unordered. Arrrggghhh! None of these behaviors are guaranteed. The docs say, "A set object is an unordered collection". If you write code which depends on a set preserving order, are going to get burned. If you want something that preserves order, use a list. If the O(n) lookup time of a list is too slow, you can get O(log n) with heapq. If you truly need O(1) lookup time AND need to preserve order, you might consider writing a class which does something like stores the values in a list, but use a dict to map value -> list_index, and maintains both data structures in parallel. Or, roll your own tree structure. Or wait for true STL-style trees to be added to Python :-) From marco.bizzarri at gmail.com Tue Oct 28 14:41:20 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Tue, 28 Oct 2008 19:41:20 +0100 Subject: Unit Testing: a couple of questions In-Reply-To: <994232ce-aab8-4e8b-831b-7d4e4a7d6b60@d42g2000prb.googlegroups.com> References: <994232ce-aab8-4e8b-831b-7d4e4a7d6b60@d42g2000prb.googlegroups.com> Message-ID: <3f0d61c40810281141u515332b8uc5f4a3fd04e5c4e1@mail.gmail.com> On Tue, Oct 28, 2008 at 3:56 PM, Emanuele D'Arrigo wrote: > Hi everybody, > > I'm just having a go with Unit Testing for the first time and my > feeling about it in short is: Neat! > > I'm a bit worried about the time it's taking me to develop the tests > but after only a day or so I'm already much faster than when I started > with it and the code is already much improved in terms of robustness. > A couple of "philosophical" questions have emerged in the process. > > 1) Granularity > Given a simple class > > class myClass(): > def __init__(self, data): > __data = data; > > def getData(self): > return __data > > def setData(self, data): > __data = data > > I've been wondering: where do I stop in terms of testing for things > that could go wrong? In this case for example, it might be reasonable > to expand the class to make sure it only receives integers and test > accordingly, i.e.: > > def setData(self, data): > try: > data = int(data) > except ValueError: > raise ValueError("Argument received cannot be converted to > integer: " + data) > > But would it be reasonable to test also for the assignment operators? > After all, if, for some strange reason, there isn't enough memory, > couldn't even __data = data potentially fail? > > 2) Testing in isolation > I'm not entirely clear on this point. I can see how I need to test > each path of the program flow separately. But should a test -only- > rely on the object being tested and mock ones in supporting roles? IMHO, don't do that. Mocking everything and anything can become incredibly complex. Wait to do it. As usual, experience plays a big role on this; start mocking on what will make your test *simpler* and easier to write and to understand, for you today and for you tomorrow (and remember that you tomorrow is a different one from you today). Before writing a mock, ask yourself: can I use a real object? The both of you know the behaviour of the real object; you hadn't to think about what some you yesterday wrote inside it. > I.e. would this be wrong if SupportObject is not a mockup? > > def testObjectToBeTested _forReallyBadError(self): > supportObject = SupportObject() > objectToBeTested = ObjectToBeTested() > result = objectToBeTested.addSupportObject(supportObject) > self.failIf(result != kSuccess, "Support Object could not be > added!") > I can see how if the SupportObject class had a bug introduced in it, > this test would fail even though it has nothing to do with the > ObjectToBeTested class. > However, creating mock objects can be quite an > overhead (?). I'm wondering if there is a threshold, even a fuzzy one, > under which it isn't worth doing and a test like the one above is > "good enough". > What do you guys think? > > Manu > -- > http://mail.python.org/mailman/listinfo/python-list > Creating mock objects in python can be quite easy; even more if you're on a greenfield project, and not with some thousands or ten of thousands of legacy code around. So, the burden is not that much. If you end using more than a couple of mocks in one test, most probably there is something wrong, and it would be better if you reconsider your design. Also, think if you really need mock object in your tests. Can't it be easier to use a "real" object? Unless creating it is really complex, and making it show the behaviour you want it to show is hard or unclear, you can use it directly. You wont' use a mock for a datetime object, am I right? Moreover, don't fight your problem (integrating your objects) at the wrong level (unit testing); you'll need integration tests, where you use your *REAL* object end-to-end, maybe even talking with other subsystems, in order to check that you are working for real. And there,maybe, you could discover that your discipline failed and you didn't changed the signature of the method of a mock object after you changed it in the real one. It happens, so, put your tests in place to catch this problem. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From bedouglas at earthlink.net Tue Oct 14 15:34:19 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 14 Oct 2008 12:34:19 -0700 Subject: App Question. Message-ID: <56af01c92e33$dc2e6e50$0301a8c0@tmesa.com> Hi list!! Got a question, and I can't find a good answer for, so I figured i'd post here. I'm working on a project that involves a number of smaller apps to be developed, and run. In order to build this overall application, I'm trying to find a web based app that I can use to manage the entire process. I need to be able to create the basic app, and then to test the app, and then to run the app in a production environment. I need to be able to schedule when the app is tested/run in the production system, as well as be able to track the status of the test/production app. My overall system will have 100's of these smaller child apps. Has anyone heard of, or have any pointers to any kind of webbased app that I can use (open source) to manage this entire kind of process. I would prefer a web based app, that runs on a LAMP platform to manage this overall process.... Thanks From python.list at tim.thechases.com Fri Oct 24 06:06:23 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 24 Oct 2008 05:06:23 -0500 Subject: dictionary In-Reply-To: References: Message-ID: <49019E1F.2040409@tim.thechases.com> >>>> ["%s="%s" % (k,v) for k,v in d.items()] > File "", line 1 > ["%s="%s" % (k,v) for k,v in d.items()] > ^ > SyntaxError: EOL while scanning single-quoted string You have three quotation marks... you want "%s=%s" not "%s="%s" -tkc From netimen at gmail.com Fri Oct 31 14:57:10 2008 From: netimen at gmail.com (netimen) Date: Fri, 31 Oct 2008 11:57:10 -0700 (PDT) Subject: brackets content regular expression References: <405e1745-2b3e-4ab7-812d-f9dbba2dad45@o40g2000prn.googlegroups.com> <461dc81d-e71f-4c72-ac5f-74afab74af28@o40g2000prn.googlegroups.com> Message-ID: Thank's but if i have several top-level groups and want them match one by one: text = "a < b < ? > d > here starts a new group: < e < f > g >" I want to match first " b < ? > d " and then " e < f > g " but not " b < ? > d > here starts a new group: < e < f > g " On 31 ???, 20:53, Matimus wrote: > On Oct 31, 10:25?am, netimen wrote: > > > I have a text containing brackets (or what is the correct term for > > '>'?). I'd like to match text in the uppermost level of brackets. > > > So, I have sth like: 'aaaa 123 < 1 aaa < t bbb < a ff > > 2 > > > bbbbb'. How to match text between the uppermost brackets ( 1 aaa < t > > bbb < a ff > > 2 )? > > > P.S. sorry for my english. > > I think most people call them "angle brackets". Anyway it should be > easy to just match the outer most brackets: > > >>> import re > >>> text = "aaaa 123 < 1 aaa < t bbb < a ff > > 2 >" > >>> r = re.compile("<(.+)>") > >>> m = r.search(text) > >>> m.group(1) > > ' 1 aaa < t bbb < a ff > > 2 ' > > In this case the regular expression is automatically greedy, matching > the largest area possible. Note however that it won't work if you have > something like this: " ". > > Matt From gagsl-py2 at yahoo.com.ar Thu Oct 9 10:47:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Oct 2008 11:47:18 -0300 Subject: inspect bug References: <9d6c6041-c1e2-448c-8fa3-0462a13e3d6b@o40g2000prn.googlegroups.com> Message-ID: En Thu, 09 Oct 2008 00:24:20 -0300, Aaron "Castironpi" Brady escribi?: > Found this bug. It's in 2.6, too bad. Posting here is not going to help much, it just will be lost. Would be better to file a bug report at http://bugs.python.org/ -- Gabriel Genellina From prologic at shortcircuit.net.au Tue Oct 28 22:28:52 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 29 Oct 2008 12:28:52 +1000 Subject: How to get high precision timer in python? In-Reply-To: References: Message-ID: 2008/10/29 ?? : > 2008/10/29 James Mills : >> On Wed, Oct 29, 2008 at 12:14 PM, ?? wrote: >>> I use python2.5 in WindowsXP. If using time.time() as timer, it seems >> >> On the win32 platform should you not >> be using time.clock vs. time.time ? >> > > Well, whatelse can I use? try time.clock cheers James -- -- -- "Problems are solved by method" From wdraxinger at darkstargames.de Tue Oct 28 07:08:07 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 28 Oct 2008 12:08:07 +0100 Subject: Python barcode decoding References: Message-ID: Robocop wrote: > Any tips would be great! The open source OCR software 'gocr' does also implement some 1D barcode recognition. In my experience it does this better then recognizing the text: http://jocr.sourceforge.net/ I know about only one open source library for the DataMatrix 2D code, but this certain library is excellent: http://www.libdmtx.org/ Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From invalid at invalid Fri Oct 31 10:06:39 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 31 Oct 2008 09:06:39 -0500 Subject: Is there a time limit for replies? References: Message-ID: On 2008-10-31, Ulrich Eckhardt wrote: > Rafe wrote: > >> I tried to post some follow-ups to some issues I posted in the >> hopes of helping others, but I only get "reply to author" and >> "forward", but no "reply" option (using GoogleGroups). Is >> there some kind of time limit to reply? > > Two things: > > 1. Google Groups is by far not the best interface to the > Usenet. Using a dedicated newsserver and a real newsclient > would be much much better. > > 2. This newsgroup is actually a mailinglist with a > mail-to-news gateway connecting it to the Usenet. Anything > can happen with a mediocre newsclient like GG and possibly > wacky setups of mailclient and the gateway. Au contraire! It's the mailing list that is actually a Usenet newsgroup to which some people subscribe using a gateway. In either case, Hr. Eckhardt's advice is spot-on: either subscribe to the mailing list or point a newsreader and any one of a dozen or so free NNTP servers. Many people (myself included) filter out posts from GoogleGroups in order to avoid spam. > If you are interested in this group/mailinglist, get at least > a real newsclient or simply subscribe to the mailinglist > itself. -- Grant Edwards grante Yow! ... I see TOILET at SEATS ... visi.com From almar.klein at gmail.com Fri Oct 3 10:54:04 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 3 Oct 2008 16:54:04 +0200 Subject: execute a function before and after any method of a parent class In-Reply-To: References: Message-ID: Maybe you can use __getattribute__. I tried it, but got stuck trying to let __getattribute__ work normal without calling itself. class A(object): def foo(self): print "hi" class B(A): def __getattribute__(self,name): try: fun = A.__dict__[name] except KeyError: fun = None if fun and callable(fun): self._before_any_method_of_A() result = fun(self) self._after_any_method_of_A() return result else: # do some stuff to act normal try: # erm, this invokes __getattribute__, which will invoke again, # and again, and again... return self.__dict__[name] except KeyError: pass try: return B.__dict__[name] except KeyError: pass def _before_any_method_of_A(self): print "before" def _after_any_method_of_A(self): print "after" b = B() b.foo() greetings, Almar 2008/10/3 TP > Hi everybody, > > I would like to be able to specialize an existing class A, so as to obtain > a > class B(A), with all methods of B being the methods of A preceded by a > special method of B called _before_any_method_of_A( self ), and followed by > a special method of B called _after_any_method_of_A( self ). > > The goal is to avoid to redefine explicitly in B all methods of A. > > Is this possible in Python? > > Thanks a lot > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z > (55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vizualbod at vizualbod.com Sun Oct 12 09:07:25 2008 From: vizualbod at vizualbod.com (Frank Malina @ vizualbod.com) Date: Sun, 12 Oct 2008 06:07:25 -0700 (PDT) Subject: Decrease code redundancy without breaking references References: <6a7d9a7a-83e8-4d60-9cf9-fc11adc657a2@t65g2000hsf.googlegroups.com> Message-ID: There is the following source structure: /packages/... /packages/global_settings.py # this is the global settings file imported from each client settings file /clients/... /clients/client1/settings.py # client specific settings file (see code above), each client is running in its own process so they never clash /clients/client2/settings.py /clients/client3/settings.py ... Now how to remove the repetitive bork, bork, bork if it relies on the clients settings. I am still learning python, help appreciated. From bdesth.quelquechose at free.quelquepart.fr Thu Oct 16 12:26:23 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 16 Oct 2008 18:26:23 +0200 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? In-Reply-To: <3b1fef83-8dc8-47ef-9a41-bad653ae717c@42g2000pry.googlegroups.com> References: <3d63ffc6-8c28-401e-8983-90a7571b4cac@p49g2000hsd.googlegroups.com> <3b1fef83-8dc8-47ef-9a41-bad653ae717c@42g2000pry.googlegroups.com> Message-ID: <48f78712$0$6537$426a74cc@news.free.fr> rustom a ?crit : (snip) > > I am interested in knowing which mode supports better the use of pdb > inside emacs? Since you mention this, I think I remember having a couple issues here with python-mode.el - but that was a long time ago, and I usually don't use pdb within the emacs-python-shell (most of the time when I have to drop to pdb, it's for Zope or Django related stuff that requires too much environment settings to make pdb-inside-emacs a viable solution). From prologic at shortcircuit.net.au Wed Oct 22 23:58:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 23 Oct 2008 13:58:10 +1000 Subject: socket programming (client-server) error In-Reply-To: <9120038f-c6d3-4a24-81bf-1c404e9606e3@l33g2000pri.googlegroups.com> References: <9120038f-c6d3-4a24-81bf-1c404e9606e3@l33g2000pri.googlegroups.com> Message-ID: On Thu, Oct 23, 2008 at 1:49 PM, ryan wrote: > any ideas? As mentioned before, try: * Turning _off_ _all_ _firewalls_. cheers James -- -- -- "Problems are solved by method" From clp at rebertia.com Thu Oct 16 16:44:21 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 16 Oct 2008 13:44:21 -0700 Subject: Dictionary of Dicts question In-Reply-To: References: Message-ID: <47c890dc0810161344p2e68cb3dib23cf91a08a8d800@mail.gmail.com> On Thu, Oct 16, 2008 at 12:19 PM, John Townsend wrote: > I'm working with a Dictionary of Dicts. Something like this: > > myDict = { > 'TestName': { > 'FileName':{ > > 'ct_init':1234, > > 'psl_init':5678, > > 'total_test_time':7890, > > 'psl_shutdown':8765, > > 'ct_shutdown':9021, > > 'total_time':3421, > }, > } > } > > Accessing values is pretty straightforward (nice change from my Perl days). > For example: > > myDict['TestName']['FileName']['ct_shutdown'] > > in Python interpreter yields > > 9021 > > However, when I try to add, let's say, a new FileName entry, I end up > replacing the previous FileName entry. > > In Python interpreter, I try: > > myDict['TestName'] = {'NewFileName': {}, } > > I get > > {'TestName': {'NewFileName': {}}} Right, this clobbers the existing entry with this new blank one. This is evidenced by the fact that you're performing an _assignment_ on a dictionary key rather than calling a _mutator_ method on a dictionary value. A dictionary has only one value for a given key (but importantly, that value can be a list). > > So, how do I add a new entry without replacing the old entry? Switch to a Dict of Lists of Dicts and append to the appropriate list when adding the new entry, or preferably, start using objects instead of ad-hoc nested dictionaries. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks > > John Townsend (5-7204), > AGM-FL and PSL QE Lead > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From hniksic at xemacs.org Tue Oct 28 16:35:22 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 28 Oct 2008 21:35:22 +0100 Subject: import foo vs. python -m foo References: Message-ID: <871vy0mp9x.fsf@mulj.homelinux.net> Simon Bierbaum writes: > Hi all, > > what is the difference between saying "import foo" in an interactive > prompt and starting one using "python -m foo"? The -m switch is not > covered in the man page, is it even officially supported? My copy of the man page states: -m module-name Searches sys.path for the named module and runs the corresponding .py file as a script. > I'm asking because one of my modules fails on import in the second > version but succeeds in the first. It probably contains buggy code inside "if __name__ == '__main__': ...". From ewertman at gmail.com Mon Oct 20 16:39:06 2008 From: ewertman at gmail.com (Eric Wertman) Date: Mon, 20 Oct 2008 16:39:06 -0400 Subject: Python certification In-Reply-To: References: <8763nr9yh7.fsf@benfinney.id.au> <1ddcea72-7773-42f0-8ada-0ede7f2cdf3d@p59g2000hsd.googlegroups.com> <92da89760810200552t2d0e736dp5eade6ffd77dd1c7@mail.gmail.com> Message-ID: <92da89760810201339x5aaa829am8dec8061ca460d46@mail.gmail.com> > Given the way that medical/legal licensing is used to stifle competition, > prevent innovation, and keep people from earning a living delivering simple > services that people need at prices they can afford, 'more like' would have > to be done very carefully. To draw an analogy... imagine, if you will, a system where pharmaceutical companies are the leading source of doctor certifications. While I'm sure there are many valid arguments that would show today's system is far from perfect, I'm thinking that would be a worse horror by some order of magnitude. From deets at nospam.web.de Wed Oct 22 06:10:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 22 Oct 2008 12:10:23 +0200 Subject: Python search path (on Windows) References: Message-ID: <6m8cg5Ffi1bpU1@mid.uni-berlin.de> wooly booly wrote: > I would like to execute a Python script from Windows command line: > > Python myscript.py > > This works if myscript.py resides in the current folder. My question is: > Is it possible to execute the command above from another folder? > > I put the script's folder in the PYTHONPATH environment variable but this > didn't help. Then you could try Python -m myscript Diez From seun.osewa at gmail.com Thu Oct 16 21:29:24 2008 From: seun.osewa at gmail.com (Seun Osewa) Date: Thu, 16 Oct 2008 18:29:24 -0700 (PDT) Subject: Unicode File Names References: Message-ID: <9cc95884-4a59-4289-a599-c9f029c9f72a@l64g2000hse.googlegroups.com> Try Python 3. Python 3 strings are native by default, so the os.listdir() in Python 3 should support the Japanese characters. On Oct 17, 1:43 am, Jordan wrote: > I've got a bunch of files with Japanese characters in their names and > os.listdir() replaces those characters with ?'s. I'm trying to open > the files several steps later, and obviously Python isn't going to > find '01-????.jpg' (formally '01-????.jpg') because it doesn't exist. > I'm not sure where in the process I'm able to stop that from > happening. Thanks. From bj_666 at gmx.net Wed Oct 8 14:07:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Oct 2008 18:07:11 GMT Subject: Python syntax question References: <4b32a20a-666b-4b1a-ac79-8b2802071bcd@n1g2000prb.googlegroups.com> Message-ID: <6l4b6fFakp4rU2@mid.uni-berlin.de> On Wed, 08 Oct 2008 11:02:49 -0700, Daniel wrote: > Here is one error I get when I try to import it: > >>>> import Rpyc > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\site-packages\Rpyc\__init__.py", line 7, in > > from Rpyc.Lib import rpyc_excepthook > File "C:\Python25\lib\site-packages\Rpyc\Lib.py", line 65 > print("======= Remote traceback =======", file=stderr) > ^ > SyntaxError: invalid syntax > > The little carrot points to the equal sign ('=') in 'file=stderr' > > What's the syntax problem? That's Python?3.0 syntax where ``print`` is not a keyword anymore but a function. Won't work with Python?2.5. Ciao, Marc 'BlackJack' Rintsch From tino at wildenhain.de Sat Oct 4 02:36:28 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 04 Oct 2008 08:36:28 +0200 Subject: encoding ascii data for xml In-Reply-To: <67956a08-0bd3-47d3-8a50-dc3aa0843553@q35g2000hsg.googlegroups.com> References: <67956a08-0bd3-47d3-8a50-dc3aa0843553@q35g2000hsg.googlegroups.com> Message-ID: <48E70EEC.4050700@wildenhain.de> harrelson wrote: > I have a large amount of data in a postgresql database with the > encoding of SQL_ASCII. Most recent data is UTF-8 but data from > several years ago could be of some unknown other data type. Being > honest with myself, I am not even sure that the most recent data is > always UTF-8-- data is entered on web forms and I wouldn't be > surprised if data of other encodings is slipping in. First I would highly recommend to clean up the database and get everything into UTF-8, then re-initdb the cluster with a correct utf-8 locale and database encoding "unicode", then cleanly restore the data. This way the database can make sure further inserts are with the correct encoding and you only have to do the cleanup once - not every time your xml interface gets used. ... > > import xml.dom.minidom > print chr(3).encode('utf-8') > dom = xml.dom.minidom.parseString( "%s" % > chr(3).encode('utf-8') ) > chr(3) is the ascii character for "end of line". I would think that > trying to encode this to utf-8 would fail but it doesn't-- I don't get Nope, ascii (ord(x) < 128) is contained in utf-8. So 3 is indeed a valid codepoint in utf-8. > a failure till we get into xml land and the parser complains. My > question is why doesn't encode() blow up? It seems to me that > encode() shouldn't output anything that parseString() can't handle. It just can't be put literally into XML - this is another step. You basically need to encode into xml charref or have your xml library do so. It seems a little googling turns up this one, which might be helpful: http://www.xml.com/pub/a/2002/11/13/py-xml.html Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From arnodel at googlemail.com Thu Oct 30 16:42:02 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Oct 2008 13:42:02 -0700 (PDT) Subject: Printing with interspersed element References: Message-ID: <11411cfb-3ef6-4c9c-9d58-99d18085106c@u57g2000hsf.googlegroups.com> On Oct 30, 8:07?pm, "Paulo J. Matos" wrote: > Hi all, > > I guess this is a recurring issue for someone who doesn't really know > the python lib inside out. There must be a simple way to do this. > I have a list of objects [x1, x2, x3, ..., xn] and I have defined a > print method for them print_obj(). Now I want to print them > intersepersed by an element. > If I print [x1, x2, x3] interspersed by the element 10: > x1.print_obj() 10 x2.print_obj() 10 x3.print_obj() > > Now, the question is, what's the best way to do this? Defining a print_obj() method is probably a bad idea. What if you want to print to a file for example? Instead you can define a __str__() method for your objects and then use the join() method of strings like this: print ' 10 '.join(str(x) for x in lst) HTH -- Arnaud From tino at wildenhain.de Thu Oct 23 03:56:38 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 23 Oct 2008 09:56:38 +0200 Subject: [APSW] SELECT COUNT(*) not succesfull? In-Reply-To: References: Message-ID: <49002E36.2030303@wildenhain.de> Gilles Ganault wrote: > Hello > > I'm trying to use the APSW package to access a SQLite database, but > can't find how to check if a row exists. I just to read a > tab-separated file, extract a key/value from each line, run "SELECT > COUNT(*)" to check whether this tuple exists in the SQLite database, > and if not, run an INSERT. > > The problem is that "if not row" isn't run: > > ========== > import apsw > > connection=apsw.Connection("test.sqlite") > cursor=connection.cursor() > > data = {} > > f = open("data.tsv", "r") > textlines = f.readlines() > f.close() > > p = re.compile('^(\d+)\t(\d+)$') > for line in textlines: > m = p.search(line) > if m: > data[m.group(1)] = m.group(2) > > for (key,value) in data.items(): > sql = "SELECT COUNT(*) FROM mytable WHERE key='%s'" % key > row=cursor.execute(sql) > > #Why not run? > if not row: > print "Row doesn't exist : %s" % key > sql = "INSERT INTO mytable (key,value) VALUES ('%s',%u)" % > key,value > cursor.execute(sql) > > connection.close(True) > sys.exit() > ========== > > Any idea what's wrong with the above? Apart from the other comments, what is obviously wrong is the way you aliased the variables into SQL. Please read on parametrized queries, e.g. the following should work: sql = "SELECT COUNT(*) FROM mytable WHERE key=%s" cursor.execute(sql,(key,)) (see also SQL injection) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bruno.42.desthuilliers at websiteburo.invalid Wed Oct 29 04:54:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 29 Oct 2008 09:54:18 +0100 Subject: Deviation from object-relational mapping (pySQLFace) In-Reply-To: <2deea470-6025-444d-af5e-143260401e83@t41g2000hsc.googlegroups.com> References: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> <2bf206be-281a-4405-93f6-49b0e33a331e@d70g2000hsc.googlegroups.com> <2deea470-6025-444d-af5e-143260401e83@t41g2000hsc.googlegroups.com> Message-ID: <490824ae$0$29412$426a74cc@news.free.fr> sulyokpeti at gmail.com a ?crit : > On okt. 22, 06:27, huy wrote: (snip) >> Best use of XML for SQL generation/use I have seen is Ibatis SQLMAPS. >> >> This focuses on the right things i.e queries and mapping values to/ >> from objects. >> >> It would be great if python had such a tool. >> > I have looked into Ibatis SQLMAPS. It claims that its biggest > advantage is simplicity over other frameworks and ORMs. Well... "Simplicity" is here to be taken relatively to the Java world standards, I guess !-) From steve at REMOVE-THIS-cybersource.com.au Tue Oct 28 18:45:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Oct 2008 22:45:18 GMT Subject: How to get an object's name as a string? References: <9dc6f89d-4f85-402f-8191-21158597445d@c36g2000prc.googlegroups.com> Message-ID: <01178ed7$0$20630$c3e8da3@news.astraweb.com> On Tue, 28 Oct 2008 09:15:50 -0600, Joe Strout wrote: > On Oct 28, 2008, at 8:41 AM, Shannon Mayne wrote: > >> I would like to create objects with algorithmically determined names >> based on other object names and use object names for general algorithm >> input. > > What do you mean by the "name" of an object? Objects don't generally > have names, unless you explicitly define a .name property and assign > them names. > > (Variables have names, of course, but a variable isn't an object -- it's > just a reference to an object. Many variables may refer to the same > object, so it doesn't make any sense to ask for the name of THE variable > which may be referring to an object at the moment.) That explanation makes no sense. Given the assignment: x = 57 if the name of x isn't 'x', then what on earth can it possibly mean to ask for the name of a variable? In languages like Python, the term "variable" is misleading and confusing. Python's programming model has objects (values), and names. Best to use language that describes what Python actually does, rather than use language that describes what other languages do. -- Steven From raymond.chui at nospam.noaa.gov Tue Oct 28 09:45:19 2008 From: raymond.chui at nospam.noaa.gov (RC) Date: Tue, 28 Oct 2008 09:45:19 -0400 Subject: Sorting a list Message-ID: unsortedList = list(["XYZ","ABC"]) sortedList = unsortedList.sort() print sortedList Why this return None? How do I get return as ["ABC", "XYZ"]? From darcy at druid.net Sat Oct 11 09:58:51 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 11 Oct 2008 09:58:51 -0400 Subject: connection reset by peer error In-Reply-To: References: Message-ID: <20081011095851.a9cbe7db.darcy@druid.net> On Sat, 11 Oct 2008 15:52:48 +0200 gigs wrote: > I connect to web site with httplib.HTTPConnection. after some time i get this > error: 104 "connection reset by peer". What exception i should use to catche > this error Well, what exception do you get? Your traceback should tell you. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From paul at boddie.org.uk Mon Oct 20 06:47:48 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 20 Oct 2008 03:47:48 -0700 (PDT) Subject: a question about Chinese characters in a Python Program References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> Message-ID: <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> On 20 Okt, 07:32, est wrote: > > Personally I call it a serious bug in python Normally I'd entertain the possibility of bugs in Python, but your reasoning is a bit thin (in http://bugs.python.org/issue3648): "Why cann't Python just define ascii to range(256)" I do accept that it can be awkward to output text to the console, for example, but you have to consider that the console might not be configured to display any character you can throw at it. My console is configured for ISO-8859-15 (something like your magical "ascii to range(256)" only where someone has to decide what those 256 characters actually are), but that isn't going to help me display CJK characters. A solution might be to generate UTF-8 and then get the user to display the output in an appropriately configured application, but even then someone has to say that it's UTF-8 and not some other encoding that's being used. As discussed in another recent thread, Python 2.x does make some reasonable guesses about such matters to the extent that it's possible automatically (without magical knowledge). There is also the problem about use of the "str" built-in function or any operation where some Unicode object may be converted to a plain string. It is now recommended that you only convert to plain strings when you need to produce a sequence of bytes (for output, for example), and that you indicate how the Unicode values are encoded as bytes (by specifying an encoding). Python 3.x doesn't really change this: it just makes the Unicode/text vs. bytes distinction more obvious. Paul From martin at v.loewis.de Sat Oct 18 03:20:37 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 18 Oct 2008 09:20:37 +0200 Subject: inserting Unicode character in dictionary - Python In-Reply-To: References: <6ls02jFdqe8iU3@mid.uni-berlin.de> Message-ID: <48f98e46$0$5166$9b622d9e@news.freenet.de> > 2. Exactly what Unicode you get would be dependent on Python properly > interpreting the bytes in the source file -- which you can make it do by > adding something like "-*- coding: utf-8 -*-" in a comment at the top of > the file. That depends on the Python version. Up to (and including) 2.4, the bytes on the disk where interpreted as Latin-1 in absence of an encoding declaration. In 2.5, not having an encoding declaration is an error. In 3.x, in absence of an encoding declaration, the bytes are interpreted as UTF-8 (giving an error when ill-formed UTF-8 sequences are encountered). > 3. Without the "u" prefix, you'll have some 8-bit string, whose > interpretation is... er... here's where I get a bit fuzzy. What if your > source file is set to utf-8? You need to distinguish between the declared encoding, and the intended (editor) encoding also. Some editors (like Emacs or IDLE) interpret the declaration, others may not. What you see on the display is the editor's interpretation; what Python uses is the declared encoding. However, Python uses the declared encoding just for Unicode strings. > Do you then have a proper UTF-8 string, > but the problem is that none of the standard Python library methods know > how to properly interpret UTF-8? There is (probably) no such thing as a "proper UTF-8 string" (in the sense in which you probably mean it). Python doesn't have a data type for "UTF-8 string". It only has a data type "byte string". It's up to the application whether it gets interpreted in a consistent manner. Libraries are (typically) encoding-agnostic, i.e. they work for UTF-8 encoded strings the same way as for, say, Big-5 encoded strings. > 4. In Python 3.0, this silliness goes away, because all strings are > Unicode by default. You still need to make sure that the editor's encoding and the declared encoding match. Regards, Martin From hniksic at xemacs.org Thu Oct 23 09:25:02 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 23 Oct 2008 15:25:02 +0200 Subject: Slow comparison between two lists References: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> <874p33cxm9.fsf@mulj.homelinux.net> <02c90b8b-126d-47b3-99ec-9c0117a916ab@c60g2000hsf.googlegroups.com> Message-ID: <87zlkvbg0h.fsf@mulj.homelinux.net> bearophileHUGS at lycos.com writes: >> internal = set(list_internal) > ... > > To do that the original poster may have to define a __hash__ and > __eq__ methods in his/her class. You're right. The OP states he implements __eq__, so he also needs a matching __hash__, such as: def __hash__(self, other): return (hash(self.xcoord) ^ hash(self.ycoord) ^ hash(self.streetname) ^ hash(self.streetno)) From ldo at geek-central.gen.new_zealand Sun Oct 26 19:12:11 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Oct 2008 12:12:11 +1300 Subject: Triple-quoted strings hath not the Python-nature References: <48fe5b90$0$26638$9b622d9e@news.freenet.de> Message-ID: In message <48fe5b90$0$26638$9b622d9e at news.freenet.de>, Robert Lehmann wrote: > I would feel greatly offended if I had to indent all *raw* data. You mean raw strings? From tjreedy at udel.edu Wed Oct 22 02:49:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Oct 2008 02:49:14 -0400 Subject: IDLE home page? In-Reply-To: <9e2f512b0810211801x67a39556u5f132def7937ed52@mail.gmail.com> References: <9e2f512b0810211801x67a39556u5f132def7937ed52@mail.gmail.com> Message-ID: Sebastian Bassi wrote: > If I put IDLE in the search box at python.org, the first hit is: > http://www.python.org/idle/ > But this page is a directory without any index file: > > Index of /idle > > Icon Name Last modified Size > Description[DIR] Parent Directory - > [ ] Makefile 26-Aug-2005 10:30 90 > [DIR] doc/ 26-Aug-2005 10:30 - > [TXT] links.h 26-Aug-2005 10:30 235 > > If I see the "ABOUT" windows (under HELP in the IDLE menu), there is > also a link to http://www.python.org/idle/ > (see here: http://imagebin.ca/view/0OE3jc.html) > > So the question is: Is there an official page for IDLE or a file is missing? Depending on the answer you get here, you might send the same observation and question to webmaster at python.org From Afro.Systems at gmail.com Thu Oct 23 07:01:53 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 23 Oct 2008 04:01:53 -0700 (PDT) Subject: How to get the time of message Received of an outlook mail in python.. References: Message-ID: On Oct 23, 12:04?pm, "venutaurus... at gmail.com" wrote: > Hi,, > ? ? ? How can we access the time of message received ( UTC time) of an > outlook mail in python? As far as I know the time which it displays in > the mail is not the exact time... this UTC time will be present in > MIME Header of an outlook mail. > > Any Help is appreciated..and thanks in advance,, > Venu. You may google for how to utilize outlook using OLE-COM automation When finding out how, implement it using python's com wrappers From ggpolo at gmail.com Thu Oct 30 08:21:12 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 30 Oct 2008 10:21:12 -0200 Subject: how to get full-text search of pysqlite3 work in python2.5.2 In-Reply-To: <6bd6a76a-ce23-40cb-aa53-432a937fc5fa@u28g2000hsc.googlegroups.com> References: <6bd6a76a-ce23-40cb-aa53-432a937fc5fa@u28g2000hsc.googlegroups.com> Message-ID: On 10/30/08, hawk wrote: > Hi, > my environment is debian, python 2.5.2. > when i call con.enable_load_extension(True), the following message > prompt out. > debian:~# python2.5 > Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sqlite3 > >>> con = sqlite3.connect(":memory:") > >>> con.enable_load_extension(True) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'sqlite3.Connection' object has no attribute > 'enable_load_extension' > enable_load_extension was added in pysqlite 2.5, but python 2.5.2 includes an older version of pysqlite. > Thanks > Hawk > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ms at cerenity.org Tue Oct 28 06:30:54 2008 From: ms at cerenity.org (Michael Sparks) Date: Tue, 28 Oct 2008 10:30:54 +0000 Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: Philip Semanchuk wrote: > On Oct 25, 2008, at 7:53 AM, Michael Sparks wrote: >> Glenn Linderman wrote: >>> In the module multiprocessing environment could you not use shared >>> memory, then, for the large shared data items? >> >> If the poshmodule had a bit of TLC, it would be extremely useful for >> this,... http://poshmodule.sourceforge.net/ > > Last time I checked that was Windows-only. Has that changed? I've only tested it under Linux where it worked, but does clearly need a bit of work :) > The only IPC modules for Unix that I'm aware of are one which I > adopted (for System V semaphores & shared memory) and one which I > wrote (for POSIX semaphores & shared memory). > > http://NikitaTheSpider.com/python/shm/ > http://semanchuk.com/philip/posix_ipc/ I'll take a look at those - poshmodule does need a bit of TLC and doesn't appear to be maintained. > If anyone wants to wrap POSH cleverness around them, go for it! If > not, maybe I'll make the time someday. I personally don't have the time do do this, but I'd be very interested in hearing someone building an up-to-date version. (Indeed, something like this would be extremely useful for everyone to have in the standard library now that the multiprocessing library is in the standard library) Michael. -- http://www.kamaelia.org/Home From abhishekmishra3 at gmail.com Sun Oct 19 02:05:38 2008 From: abhishekmishra3 at gmail.com (Abhishek Mishra) Date: Sat, 18 Oct 2008 23:05:38 -0700 (PDT) Subject: keyword in package name. Message-ID: Hello Everyone, I have the habit of using domain names (of either the application or company) in reverse in package names. for e.g. com.spam.app1 I've recently started a project for an indian domain (tld = .in), which leads to a package name like in.spam.app1 This causes a syntax error, as "in" is a keyword. I understand that this is an unfortunate "feature", but has anyone faced this problem before, and is there a possible workaround. P.S. this would also be a problem for the iceland domains (tld = .is). TLDs: http://data.iana.org/TLD/tlds-alpha-by-domain.txt Python Keywords: http://www.python.org/doc/2.5.2/ref/keywords.html Regards, Abhishek Mishra From sthembilengidi at gmail.com Wed Oct 22 07:23:41 2008 From: sthembilengidi at gmail.com (Amie) Date: Wed, 22 Oct 2008 04:23:41 -0700 (PDT) Subject: Create a message References: Message-ID: <59980636-fd0f-405e-8cc0-625034932c34@17g2000hsk.googlegroups.com> On Oct 22, 12:44?pm, "James Mills" wrote: > On Wed, Oct 22, 2008 at 8:21 PM, Amie wrote: > > I would like to know if it's possible to display a message using > > python, if so can you show me an example. > > I saw something like:" from twisted.python import log > > log.msg" in some programs but am not too sure how it works > > Define "message". > > Message could be: > ?* a GUI related/rendered message > ?* a Web-based related/rendered message > ?* a simple (stdout) printed message > ?* a stored log message, syslog, etc > > Simplest example: > > >>> print "Hello World" > > Hello World > > cheers > James > > -- > -- > -- "Problems are solved by method" for example, I wanna display a message that contains a persons age from the database like so: "Your age is 25". kind of like a messagebox From merrick at gmail.com Mon Oct 6 15:51:23 2008 From: merrick at gmail.com (Merrick) Date: Mon, 6 Oct 2008 12:51:23 -0700 (PDT) Subject: function(s) to decode a URL produced by encodeURIComponent in javascript Message-ID: I encoded a URL in javascript and would like to decode it in python. The urllib.unquote does not have an optional safe argument and I cannot find how to do urldecode. From steve at REMOVE-THIS-cybersource.com.au Thu Oct 16 21:30:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Oct 2008 01:30:30 GMT Subject: Finding the instance reference of an object References: <3186c750-d961-4d5b-b0cd-6e364f85ab7e@k37g2000hsf.googlegroups.com> <22da8999-5472-47b3-ab26-bde636184447@k37g2000hsf.googlegroups.com> Message-ID: <0107e3e6$0$20638$c3e8da3@news.astraweb.com> On Thu, 16 Oct 2008 11:51:43 -0700, Aaron \"Castironpi\" Brady wrote: > If you're sure it's unique, why not just scan through the pairs in > locals()? > > for k, v in locals(): > if v is the_object_im_looking_for: > name_im_looking_for= k > > This method can sometimes return more than one name, due to the variable > ordering of objects in dictionaries. Because: (1) in general, objects can have no name at all, or multiple names, so this won't work in general (although it may work in a specific case); (2) it's awfully inefficient if you are doing it a lot; and (3) even if it works and you can afford to pay the cost, it is almost certainly the Wrong Way to solve the problem at hand. -- Steven From simon at brunningonline.net Thu Oct 16 08:25:18 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 16 Oct 2008 13:25:18 +0100 Subject: Best way to spawn process on back end computer In-Reply-To: <1e5e14be-4d24-44c9-8867-76b46dd47573@t41g2000hsc.googlegroups.com> References: <1e5e14be-4d24-44c9-8867-76b46dd47573@t41g2000hsc.googlegroups.com> Message-ID: <8c7f10c60810160525n58c10302qf5283e9890b391f0@mail.gmail.com> 2008/10/16 sophie_newbie : > I'm running a python cgi script on a frontend web server and I want it > to spawn another script (that takes a long time to run) on a backend > number crunching server thats connected to the same network. What do > you think is the best way to do this? I have a few ideas but I'm sure > there is a "best" way to go about this. http://edit.kamaelia.org/ might be qworth a look. -- Cheers, Simon B. simon at brunningonline.net From nobody at nospam.noway Fri Oct 10 09:52:06 2008 From: nobody at nospam.noway (RossRGK) Date: Fri, 10 Oct 2008 09:52:06 -0400 Subject: FLexible formatted text involving nested lists? In-Reply-To: References: Message-ID: davidsands wrote: > > The tuple() type-conversion function will do what you need: > > print fmts[0] % tuple(bigList[0]) > print fmts[1] % tuple(bigList[1]) > print fmts[2] % tuple(bigList[2]) > I never thought of the tuple type conversion - that looks promising. Thanks for that! R. From raj.indian.08 at gmail.com Tue Oct 14 09:11:26 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Tue, 14 Oct 2008 06:11:26 -0700 (PDT) Subject: Reg: Installation problems in psycopg2 References: <4720aa3b-bdf9-4f8b-b134-45508c2811cd@t39g2000prh.googlegroups.com> Message-ID: <447c01da-ce3f-4961-95c2-cafe9058f830@p10g2000prf.googlegroups.com> Hi Philip, Thank you. I have posted the same in psycopg mailing list too. I had setup the pg_config value too, but even then the error was coming. Hi Dave, Thank you for the quick reply. Regards Raj K From ldo at geek-central.gen.new_zealand Mon Oct 13 00:26:48 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 13 Oct 2008 17:26:48 +1300 Subject: type-checking support in Python? References: <0100470d$0$20646$c3e8da3@news.astraweb.com> Message-ID: In message <0100470d$0$20646$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > ... just for the record "dimensions" are not "units". Yeah, OK. "unit" = "dimensions" x "multiplier". Where "multiplier" can be arbitarily set to 1 for SI units. From andy55 at gmail.com Wed Oct 22 14:45:47 2008 From: andy55 at gmail.com (Andy) Date: Wed, 22 Oct 2008 11:45:47 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <6m974kFfs9nlU1@mid.individual.net> Message-ID: <1e40e9df-fc39-4c8c-bbd4-05c9f9a37d67@75g2000hso.googlegroups.com> Hi Thomas - I appreciate your thoughts and time on this subject. > > The result is that separate COM objects implemented as Python modules and > converted into separate dlls by py2exe do not share their interpreters even > if they are running in the same process. ?Of course this only works on windows. > In effect this is similar to using /statically/ linked python interpreters > in separate dlls. ?Can't you do something like that? You're definitely correct that homebrew loading and linking would do the trick. However, because our python stuff makes callbacks into our C/C++, that complicates the linking process (if I understand you correctly). Also, then there's the problem of OS X. > > - In python 3, the C module API now supports true interpreter > > independence, but have all the modules in the python codebase been > > converted over? ?Are they all now truly compliant? ?It will only take > > a single static/global state variable in a module to potentially cause > > no end of pain in a multiple interpreter environment! ?Yikes! > > I don't think this is the case (currently). ?But you could submit patches > to Python so that at least the 'official' modules (builtin and extensions) > would behave corectly in the case of multiple interpreters. ?At least > this is a much lighter task than writing your own GIL-less interpreter. > I agree -- and I've been considering that (or rather, having our company hire/pay part of the python dev community to do the work). To consider that, the question becomes, how many modules are we talking about do you think? 10? 100? I confess that I'm no familiar enough with the full C python suite to have a good idea of how much work we're talking about here. Regards, Andy From joe at strout.net Tue Oct 28 21:02:48 2008 From: joe at strout.net (Joe Strout) Date: Tue, 28 Oct 2008 19:02:48 -0600 Subject: How to get an object's name as a string? In-Reply-To: <01178ed7$0$20630$c3e8da3@news.astraweb.com> References: <9dc6f89d-4f85-402f-8191-21158597445d@c36g2000prc.googlegroups.com> <01178ed7$0$20630$c3e8da3@news.astraweb.com> Message-ID: <27934022-8BAC-42E0-B2DE-5762B6325E83@strout.net> On Oct 28, 2008, at 4:45 PM, Steven D'Aprano wrote: >> What do you mean by the "name" of an object? Objects don't generally >> have names, unless you explicitly define a .name property and assign >> them names. >> >> (Variables have names, of course, but a variable isn't an object -- >> it's >> just a reference to an object. Many variables may refer to the same >> object, so it doesn't make any sense to ask for the name of THE >> variable >> which may be referring to an object at the moment.) > > That explanation makes no sense. Given the assignment: > > x = 57 > > if the name of x isn't 'x', then what on earth can it possibly mean to > ask for the name of a variable? Perhaps you're skimming rather than reading carefully? Variables do have names, as I pointed out, and the name of x is indeed 'x'. But that's not what the OP was asking for -- in your example, he'd be asking for the name of 57 (expecting it to be 'x'). Numbers don't have names; objects don't have names; variables have names, and may refer to numbers or objects. > In languages like Python, the term "variable" is misleading and > confusing. Oh good grief. Now you're going to try to discard the standard term "variable" as well? All right then, if you really insist on making Python more mysterious by making up new terms for perfectly ordinary and standard programming concepts, then I suggest the following: variable: "ariablevay" value: "aluvay" reference: "eferencevay" call-by-value: "allcay-ibay-aluvay" call-by-reference: (no term needed, since Python doesn't have it) There. Now we've got a simple mapping from standard terminology to properly mystical Python-culture terms that are nonetheless easy to learn. Agreed? Best, - Joe P.S. Shannon: don't listen to Steven. He's out to confuse you and make Python seem much harder and complex than it really is. From badmuthahubbard at gmail.com Wed Oct 29 17:59:46 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Wed, 29 Oct 2008 23:59:46 +0200 Subject: Finding the instance reference of an object In-Reply-To: References: <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> Message-ID: <8200bab70810291459m35c90a26vb0a91f9564b97cb@mail.gmail.com> On Wed, Oct 29, 2008 at 5:27 PM, Dale Roberts wrote: > Don't you know? There is really only *ONE* case, and, you are right, > it is Pass By Value. There is no such thing as Pass By Reference at > the physical CPU level at all, right? If there is, show it to me. Pass > By Reference is just a silly idiom developed by high-minded CS > academics to confuse the rest of us. It has no practical use and > should not be given its own name, when we already have a good an > proper name for it. > > Let me demonstrate with 3 examples of a function definition, and the > appropriate calling syntax for that function in C++, all sharing the > common "int i" global variable: > > int i = 5; > > myfunc(int &val){} /*CALL:*/ myfunc(i); // "ByRef" (ya, right!) > myfunc(int val){} /*CALL:*/ myfunc(i); // ByVal > myfunc(int *val){} /*CALL:*/ myfunc(&i); // Joe's ByVal > > The first is what all the fakers call "Pass By Reference" - sheesh, > how naive. We all know that what *really* happens internally is that > the *address* of val (A VALUE itself, or course) is copied and passed > on the stack, right? There couldn't be a more straightforward example > of Pass By Value (unless it's an inline function, or optimized away, > or possibly when implemented in a VM, or...). It passes the *address* > of i by value, then we can access the *value* of i too via > indirection. Hmm, did we need to have two definitions of VALUE there? > Well, never mind, no one will notice... > > The next is obviously pass by value. It's right out there. The value > of i (which is what we are talking about, right?) is copied out, and > passed right on the stack in plain daylight where we can all see it. > > How about the third? Pass By Value, obviously, of course. This is the > version you are defending, right? The parameter's value, &i, is > evaluated and copied right onto the stack, just like in the first > example. In fact, if you compare the assembler output of the first and > third examples, you may not even see a difference. Never mind the > actual contents of that pesky "i" variable that most people are > referring to when they use the term "value". We don't need to dress up > example 3 and call it an "idiom" where we are really passing a so- > called "reference" of the variable "i". Indeed! Don't insult our > intelligence. We can all see that it's an address passed by value, > plain and simple. > > > Pass By Reference? So "postmodern". Who needs it. Show me a so-called > "reference". I've looked at the assembler output and have never seen > one. There is no such thing. You are so right! We also don't need "object-oriented programming". I looked at the motherboard and I don't see any objects moving around! I don't see any values being passed, either. When I turn on the TV and see Chuck Norris, though, I know it's only a reference to Chuck Norris, or I would be blinded. The only case he needs is "Pass By Roundhouse Kick". -Chuckk -- http://www.badmuthahubbard.com From znfmail-pythonlang at yahoo.com Mon Oct 13 08:50:41 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Mon, 13 Oct 2008 08:50:41 -0400 Subject: strip module bug Message-ID: I'm using versions 2.5.2 and 2.5.1 of python and have encountered a potential bug. Not sure if I'm misunderstanding the usage of the strip function but here's my example. var = "detail.xml" print var.strip(".xml") ### expect to see 'detail', but get 'detai' var = "overview.xml" print var.strip(".xml") ### expect and get 'overview' I have a work around using the replace function which happens to be the better choice for my script anyhow. But am curious about the strip module. Any thoughts? Is it removing the 'l' in detail because the strip function text ends in 'l'? From gagsl-py2 at yahoo.com.ar Mon Oct 27 03:46:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Oct 2008 05:46:03 -0200 Subject: Improving interpreter startup speed References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> Message-ID: En Sun, 26 Oct 2008 23:52:32 -0200, James Mills escribi?: > On Mon, Oct 27, 2008 at 4:12 AM, Benjamin Kaplan > wrote: >> You must be in a real big hurry if half a second matters that much to >> you. >> Maybe if it took 5 seconds for the interpreter to start up, I could >> understand having a problem with the start up time. > > +1 This thread is stupid and pointless. > Even for a so-called cold startup 0.5s is fast enough! I don't see the need to be rude. And I DO care for Python startup time and memory footprint, and others do too. Even if it's a stupid thing (for you). -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Fri Oct 31 05:12:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Oct 2008 09:12:31 GMT Subject: Finding the instance reference of an object References: <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <011a5e82$0$20638$c3e8da3@news.astraweb.com> <6mvps2Fir02jU1@mid.individual.net> Message-ID: <011ac4c4$0$20643$c3e8da3@news.astraweb.com> On Fri, 31 Oct 2008 20:22:23 +1300, greg wrote: > Steven D'Aprano wrote: > >> Which definition of call-by-value? Certainly not the one that most >> people are familiar with, where c-b-v implies that calling a function >> with a large array will copy the entire array. > > But that's only true in languages where *assigning* a large array will > also copy the entire array. Maybe, maybe not. To be consistent, it should be true. But how do you know if a language you are unfamiliar with is consistent? In any case, to somebody only familiar with the classical value-vs- reference model, Python seems rather inconsistent: x = 1 y = x # does assignment make copies? y += 1 assert x == 1 => succeeds, which implies that Python makes a copy when assigning x = [1] y = x # does assignment make copies? y += [1] assert x == [1] => fails, which implies that Python uses references when assigning Hence you get people who argue that Python does call-by-value for numbers and call-by-reference for lists -- and yes, I've seen people make that exact argument. The reality is that Python isn't inconsistent, it merely seems to be if you assume it is some other language. Python actually treats numbers and lists identically. When people discover that Python's behaviour doesn't fall neatly into their preconceived notions of c-b-v and c-b-r, there are two ways of dealing with that: (1) Accept that perhaps there's at least one more way of doing assignment and parameter passing. (2) Or jump through hoops trying to force how Python works to somehow match your preconceptions. > This does not happen in Python, therefore > there is no reason to suppose that it will happen when passed as a > parameter. Of course there is a reason: we've been told that Python is call by value, and call by value implies that a copy is made when you pass it to a function. The fact that many programmers already have an idea of what they think c-b-v implies is what makes calling Python c-b-v such a pernicious mistake. If you want to call Python "call by ginger" I won't object, because most people have no preconceived ideas of what call by ginger means and therefore won't be lured into incorrect assumptions about Python. > Before you can understand parameter passing, whether by-value or > by-reference, you first have to understand how assignment works *in the > language concerned*, not some other language you happen to know > previously. It's certainly true that the baggage people bring from their previous languages can sometimes be a serious barrier, but that especially happens when folk insist on using the same terminology to describe different things. For example, to somebody coming to Python from Lisp or Scheme, the word "list" carries particular connotations. It's unfortunate that Python lists are not like Lisp lists, but we're stuck with that now, and besides there's only so many good names for a list-like array, and whatever name was chosen would trip up somebody. Another example, augmented assignment in Python trips up C programmers, because x += y looks the same but behaves differently than x += y in C. There's enough difficulty with learning a new programming language without people adding to it by misusing terms like "call by value" to describe what Python does. -- Steven From bborcic at gmail.com Thu Oct 23 10:17:22 2008 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 23 Oct 2008 16:17:22 +0200 Subject: Function to Add List Elements? In-Reply-To: <47c890dc0810221306n6887ce06qcc8a3c6feed4342b@mail.gmail.com> References: <47c890dc0810221306n6887ce06qcc8a3c6feed4342b@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Wed, Oct 22, 2008 at 12:59 PM, Henry Chang wrote: >> This seems like a simple problem, but I can't find a simple solution. >> >> Suppose I have two lists of integers. >> >> List A = [A1, A2, A3] >> List B = [B1, B2, B3] >> >> I just simply want a new list, such as: >> >> List C = [C1, C2, C3] >> >> where: >> >> C1 = A1 + B1 >> C2 = A2 + B2 >> C3 = A3 + B3 >> >> Is there a simple function to do this? > > A one-liner in fact: > > summed = [sum(pair) for pair in zip(listA, listB)] or a two-liner : from operator import add summed = map(add,listA,listB) or a hybrid : summed = map(sum,zip(listA,listB)) Cheers, BB From mujunshan at gmail.com Fri Oct 24 00:51:02 2008 From: mujunshan at gmail.com (mujunshan at gmail.com) Date: Thu, 23 Oct 2008 21:51:02 -0700 (PDT) Subject: How to get the actual address of a object Message-ID: <39964422-a965-4dc0-8018-81e1c2e373a0@a29g2000pra.googlegroups.com> Hi,I have a strange idea:is there any way to get memory address of a object. For example: i = 10 addr = get_address(i) address will be assigned a integer which is pointer of object i,then I want to recast addr into another integer: j = cast(addr,) I think it is easy to get it by modifying source code of python,but I would like to know if there was an existing one. many thanks From mail at microcorp.co.za Sun Oct 12 16:19:25 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 12 Oct 2008 22:19:25 +0200 Subject: Efficient Bit addressing in Python. Message-ID: <000a01c92ca7$f602a9a0$0d00a8c0@hendrik> Ross Ridge wrote: >Unfortunately from your other posts you do seem to be working on >a single byte a time, so my technique probably won't be efficient. Its a bit more - the hardware allows for 64 lines in and 64 lines out. >You probably want just want to be using constants and bit masking. >Something like: 8< ------------- standard and and or examples ---------------- This is approximately how I was doing it before I started the thread, but I was unsatisfied, and started looking for a way to directly address the bits, more as a further exploration of Python. >Bit twiddling like this is pretty basic. Yes it is, and in what we do it is also pervasive, and I miss my 8051/8031 assembler instructions where I can do an atomic "jump if bit set then clear' on a named bit in the bit addressable space, as well as a direct set or clear of a named bit, without resorting to anding and oring of bytes. Now I know that I can never do the jump in python, but I had hoped that I could get close to the direct set and clear, and the thread has been useful in that it has rubbed my nose into a lot of corners where I would otherwise never have gone. (like the gmpy stuff, for instance, and mucking around with bitfield-like classes, and the binascii stuff.) And I now _almost_ have my direct bit addressability... However - Python has failed to show me "the one and only one obvious way". *grins and ducks* Thanks to all who responded. - Hendrik From jnoller at gmail.com Fri Oct 24 15:48:57 2008 From: jnoller at gmail.com (Jesse Noller) Date: Fri, 24 Oct 2008 15:48:57 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <7b622486-0588-4447-a76c-4271ac2fecdf@75g2000hso.googlegroups.com> Message-ID: <4222a8490810241248n7dddf17dkea22fb7407525e67@mail.gmail.com> On Fri, Oct 24, 2008 at 3:17 PM, Andy O'Meara wrote: > I'm a lousy writer sometimes, but I feel bad if you took the time to > describe threads vs processes. The only reason I raised IPC with my > "messaging isn't very attractive" comment was to respond to Glenn > Linderman's points regarding tradeoffs of shared memory vs no. > I actually took the time to bring anyone listening in up to speed, and to clarify so I could better understand your use case. Don't feel bad, things in the thread are moving fast and I just wanted to clear it up. Ideally, we all want to improve the language, and the interpreter. However trying to push it towards a particular use case is dangerous given the idea of "general use". -jesse From steve at REMOVE-THIS-cybersource.com.au Mon Oct 13 18:20:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Oct 2008 22:20:02 GMT Subject: docpicture References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> <010374c5$0$20641$c3e8da3@news.astraweb.com> <18675.34993.962044.115182@montanaro-dyndns-org.local> Message-ID: <0103c2da$0$20671$c3e8da3@news.astraweb.com> On Mon, 13 Oct 2008 16:41:58 -0500, skip wrote: >>> Nothing. It's just a doc string containing a bunch of hex codes. Doc >>> strings are ignored by the interpreter (AIUI). > > Benjamin> I mean what happens when you type help() into the > interactive Benjamin> console on the command line? You will see the > docstrings, and Benjamin> there will be a whole bunch of random hex > characters there. > > If an IDE can be trained to recognize and display such a picture I sorta > assume help() can be trained to recognize and ignore it. And if not, it's no big deal. Your help string has a clearly labeled few lines of hex: Help on function spam: spam(...) spam spam spam spam spam spam spam spam spam spam with a fried egg on top === begin docpicture === 1234567890ABCDEF 1234567890ABCDEF 1234567890ABCDEF 1234567890ABCDEF === end docpicture === Or similar. I'm sure people will cope, especially since it should be relatively rare. -- Steven From bdesth.quelquechose at free.quelquepart.fr Fri Oct 3 15:44:15 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 03 Oct 2008 21:44:15 +0200 Subject: "Exploding" (**myvariable) a dict with unicode keys In-Reply-To: References: <6e32b9f8-d785-408b-a1ae-6a86244e9643@u57g2000hsf.googlegroups.com> <48e667dc$0$2561$9b622d9e@news.freenet.de> <48e672a2$0$14318$9b622d9e@news.freenet.de> Message-ID: <48e691f7$0$31358$426a74cc@news.free.fr> Devin a ?crit : (snip) > Oh. I read somewhere that UTF-8 variable names we're supported. utf-8 is *not* unicode. From mccredie at gmail.com Thu Oct 16 19:12:46 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 16 Oct 2008 16:12:46 -0700 (PDT) Subject: ImportError in python 2.5 in C API DLL References: Message-ID: On Oct 16, 10:58?am, Henrik wrote: > Hi, > > We are upgrading from Python 2.3 to verion 2.5 and when we recompile > we get ImportError. > > To test we took the spam example from the web documentation and > compiled it with Py23 and it imports without a problem. Changing the > libs in visual studio 2008 to point to Py25 and we get: > > >>> import spam > > Traceback (most recent call last): > ? File "", line 1, in > ImportError: No module named spam > > > > Would really appreciate any assistance. > > H > > ---------------------------------------------------------------------------------------------------------------------- > #include "stdafx.h" > #ifdef _MANAGED > #pragma managed(push, off) > #endif > BOOL APIENTRY DllMain( HMODULE hModule, > ? ? ? ? ? ? ? ? ? ? ? ?DWORD ?ul_reason_for_call, > ? ? ? ? ? ? ? ? ? ? ? ?LPVOID lpReserved > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?) > { > ? ? return TRUE;} > > #ifdef _MANAGED > #pragma managed(pop) > #endif > static PyObject * > spam_system(PyObject *self, PyObject *args) > { > ? ? const char *command; > ? ? int sts; > ? ? if (!PyArg_ParseTuple(args, "s", &command)) > ? ? ? ? return NULL; > ? ? sts = system(command); > ? ? return Py_BuildValue("i", sts);} > > static PyMethodDef PyBSMethods[] = { > ? ? ? {"spam", (PyCFunction) spam_system, METH_VARARGS|METH_KEYWORDS, > "Hi"}, > ? ? ? {NULL, NULL, 0, NULL} ? ? ? ?/* Sentinel */}; > > extern "C" { > ? ? ? __declspec(dllexport) void initspam(void) > ? ? ? { > ? ? ? ? ? ? PyObject* module = Py_InitModule("spam", PyBSMethods); > ? ? ? ? ? ? PyObject* d = PyModule_GetDict(module); > ? ? ? }} > > ---------------------------------------------------------------------------------------------------------------------- What about the simple stuff like: did you put your dll/pyd file where python 2.5 can find it? Are you including the correct Python.h, are you linking against the correct library (python25.lib or python25_d.lib)? Have you tried debugging with the "python -v" option (shows import trace messages)? Matt From code at pizzashack.org Tue Oct 14 18:33:07 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 14 Oct 2008 18:33:07 -0400 Subject: Set Environment for java based tools thru python script In-Reply-To: <672bde6c-3b91-4133-9824-676fa62f3369@u29g2000pro.googlegroups.com> References: <672bde6c-3b91-4133-9824-676fa62f3369@u29g2000pro.googlegroups.com> Message-ID: <20081014223307.GD19751@dragontoe.org> On Mon, Oct 13, 2008 at 05:07:16PM -0700, replysonika at gmail.com wrote: > I run a Java app with subprocess from Python script. This python > script is called from another Python Wrapper. > > > python = subprocess.Popen(["toolname.sh", "-args", arg1, arg2], > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) This (toolname.sh) looks like a shell script (though technically, there's no reason it couldn't be a python script). Unfortunately, from what you've written here, it's neither clear what processes start what processes, nor what the intended result is. You have said you have 3 programs, but you've only shown the interactions between two of them. My suggestion would be to rewrite your request, explicitly name the processes (even if it is just with letters, A, B, and C), and show which processes start which other processes, and probably explain a little about what each one is supposed to do. That said, see below. > I can run it manually from the command line. But fails when I execute > the wrapper Python script > > How do I source the java environment from the wrapper. It fails with > the following message. > > ...16605 Segmentation fault $JAVA_HOME/bin/java $JAVA_OPTIONS - > classpath $CLASSPATH xxxxxxxxxxxxxxxxxxxxxx "$@".... Again, it's not clear what you're trying to do, but I'm assuming you have some script that sets environment variables, and that's what you mean by "source the java environment..." If so, you can't. You either need to source the environment before running the Python program, or have the python program read a file that contains the environment and do its own parsing, setting the environment variables appropriately. A child process, in general, can not insert environment variables into the environment of its parent. If what you're trying to do isn't covered by the above, then I think you'll need to try to explain it better. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jnoller at gmail.com Tue Oct 7 14:22:14 2008 From: jnoller at gmail.com (Jesse Noller) Date: Tue, 7 Oct 2008 14:22:14 -0400 Subject: Builing Python 2.6 on AIX 5.2 In-Reply-To: <98fe221e-1849-41e0-a5e7-584a4e557064@l42g2000hsc.googlegroups.com> References: <238e9869-b645-47a3-bd4a-e5d567667a40@64g2000hsu.googlegroups.com> <98fe221e-1849-41e0-a5e7-584a4e557064@l42g2000hsc.googlegroups.com> Message-ID: <4222a8490810071122k6a7a0f35q7bca667003b40801@mail.gmail.com> Thanks for posting this to the tracker mattias - as soon as I can steal some time, I'll dig into it and see if I can get it teed up for the patch release. On Tue, Oct 7, 2008 at 6:24 AM, brasse wrote: > On Oct 6, 10:16 am, brasse wrote: >> Hello! >> >> I am having some trouble building Python 2.6 on AIX. The steps I have >> taken are: >> >> export PATH=/usr/bin/:/usr/vacpp/bin/ >> ./configure --with-gcc=xlc_r --with-cxx=xlC_r --disable-ipv6 >> make >> >> This is the error message I'm seeing: >> ./Modules/ld_so_aix xlc_r -bI:Modules/python.exp build/ >> temp.aix-5.2-2.6/home/mabr/Python-2.6/Modules/_multiprocessing/ >> multiprocessing.o build/temp.aix-5.2-2.6/home/mabr/Python-2.6/Modules/ >> _multiprocessing/socket_connection.o build/temp.aix-5.2-2.6/home/mabr/ >> Python-2.6/Modules/_multiprocessing/semaphore.o -L/usr/local/lib -o >> build/lib.aix-5.2-2.6/_multiprocessing.so >> ld: 0711-317 ERROR: Undefined symbol: .sem_timedwait >> ld: 0711-317 ERROR: Undefined symbol: .CMSG_SPACE >> ld: 0711-317 ERROR: Undefined symbol: .CMSG_LEN >> ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more >> information. >> *** WARNING: renaming "_multiprocessing" since importing it failed: No >> such file or directory >> error: No such file or directory >> make: The error code from the last command is 1. >> >> Have someone on this list had similar problems? Am I missing some >> libraries? The configure script runs without errors, I would have >> expected some kind of error there if I was missing something. >> >> Regards, >> Mattias > > OK. I have made some changes in the source that lets me build on AIX > 5.2. I thought I could post the patch here and perhaps someone can > tell me if I am on the wrong track or if this is an OK fix on AIX. > > Basically I have changed setup.py to define HAVE_SEM_TIMED_WAIT=0 on > aix. I have also defined CMESG_SPACE and CMESG_LEN in terms of > _CMSG_ALIGN (see http://homepage.mac.com/cjgibbons/rubyonaixhowto/x72.html) > in multipocessing.c. (I realise that this breaks some other platforms, > but right now I just need to build on AIX). > > Here is a patch: > > diff -Naur Python-2.6/Modules/_multiprocessing/multiprocessing.c > Python-2.6-clean-patch/Modules/_multiprocessing/multiprocessing.c > --- Python-2.6/Modules/_multiprocessing/multiprocessing.c > 2008-06-14 00:38:33.000000000 +0200 > +++ Python-2.6-clean-patch/Modules/_multiprocessing/ > multiprocessing.c 2008-10-07 12:23:55.000000000 +0200 > @@ -8,6 +8,13 @@ > > #include "multiprocessing.h" > > +#ifndef CMSG_SPACE > +#define CMSG_SPACE(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + > _CMSG_ALIGN(len)) > +#endif > +#ifndef CMSG_LEN > +#define CMSG_LEN(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + (len)) > +#endif > + > PyObject *create_win32_namespace(void); > > PyObject *pickle_dumps, *pickle_loads, *pickle_protocol; > diff -Naur Python-2.6/setup.py Python-2.6-clean-patch/setup.py > --- Python-2.6/setup.py 2008-09-30 02:15:45.000000000 +0200 > +++ Python-2.6-clean-patch/setup.py 2008-10-07 12:23:34.000000000 > +0200 > @@ -1277,6 +1277,14 @@ > ) > libraries = [] > > + elif platform.startswith('aix'): > + macros = dict( > + HAVE_SEM_OPEN=1, > + HAVE_SEM_TIMEDWAIT=0, > + HAVE_FD_TRANSFER=1 > + ) > + libraries = ['rt'] > + > else: # Linux and other > unices > macros = dict( > HAVE_SEM_OPEN=1, > > Perhaps this should go to some other list? > > :.:: mattias > -- > http://mail.python.org/mailman/listinfo/python-list > From michele.simionato at gmail.com Thu Oct 2 00:51:57 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 1 Oct 2008 21:51:57 -0700 (PDT) Subject: RELEASED Python 2.6 final References: Message-ID: <8b762681-4582-4410-b3a7-c27fe79c789b@x41g2000hsb.googlegroups.com> On Oct 2, 5:46?am, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I ? > am happy to announce the release of Python 2.6 final. Cool! I have just downloaded the Mac installer and did the installation on my Intel MacBook, however it seems I have some issue with Tkinter: $ python2.6 Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/lib-tk/Tkinter.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/lib-dynload/_tkinter.so, 2): Library not loaded: / Library/Frameworks/Tcl.framework/Versions/8.5/Tcl Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/lib-dynload/_tkinter.so Reason: no suitable image found. Did find: /Library/Frameworks/Tcl.framework/Versions/8.5/Tcl: mach-o, but wrong architecture /Library/Frameworks/Tcl.framework/Versions/8.5/Tcl: mach-o, but wrong architecture Any hints? From steve at holdenweb.com Thu Oct 30 00:44:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Oct 2008 00:44:11 -0400 Subject: Why gives "k = 09" a syntax error ? In-Reply-To: References: <4908B8FC.5010200@gmail.com> <6772c5db-cdcc-4f79-9a24-1da8e849c870@34g2000hsh.googlegroups.com> Message-ID: Cameron Laird wrote: > In article <6772c5db-cdcc-4f79-9a24-1da8e849c870 at 34g2000hsh.googlegroups.com>, > Mensanator wrote: >> On Oct 29, 2:44 pm, Stef Mientki wrote: >>> Guilherme Polo wrote: >>>> On 10/29/08, Stef Mientki wrote: >>>>> hello, >>>>> Why gives "k = 09" a syntax error ? >>>> 09 is not a valid octal number. Instead use 011. >>>> Ok, I guess you were not aware that prefixing a number with a '0' >>>> would cause python to parse it as an octal and now you know. >>> thanks guys, >>> I didn't realize there were still people using octal notation ;-) >> Windows users don't have much need for it, but it's still >> popular with the 'Nix crowd. > . > . > . > I contest that; my observation is that it's entirely an artifact > of legacy software, and regarded as no better than a distraction > by even the most narrow human 'Nixers, or the hardware types who > might at one time have found octal natural. My own origins were > in hardware, Unix, and other DEC OSs, so I consider myself as > likely as anyone to think in octal--and I rarely do. > > While I can't accept the "popular" part, I agree with you that > Unix people are at least more likely to recognize the 0-prefix. > They are also more likely to write chmod 330 file than chmod ug=rw file regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Graham.Dumpleton at gmail.com Thu Oct 23 23:13:26 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 23 Oct 2008 20:13:26 -0700 (PDT) Subject: What happened to python-dev's Google Group? References: <8855353d-c393-48d5-850a-b45a947756c3@x41g2000hsb.googlegroups.com> Message-ID: On Oct 24, 12:58?pm, Robert Kern wrote: > Giampaolo Rodola' wrote: > >http://groups.google.com/group/python-dev2 > > It seems it no longer exists. What happened? > > I don't know, but something happened to the numpy-discussion Google Group > gateway, too. Maybe there was a mass culling of such gateways that weren't being > maintained, or something like that. Not this again. This happened back in August, with a whole range of groups seemingly vanishing, including the group for web.py. They came back eventually, but of course Google doesn't say anything about what happened. http://groups.google.com/group/Is-Something-Broken/browse_frm/thread/bfe5e1d3c9ac958a A more recent thread complaining about most recent disappearances is at: http://groups.google.com/group/Is-Something-Broken/browse_frm/thread/119ef1b00796f058# Graham From elzapp at elzapp.com Thu Oct 30 04:37:31 2008 From: elzapp at elzapp.com (Bard Aase) Date: Thu, 30 Oct 2008 09:37:31 +0100 Subject: Unicode Problem In-Reply-To: <179b305e0810300028t3efa8319vf9094f166c38cfbf@mail.gmail.com> References: <179b305e0810300028t3efa8319vf9094f166c38cfbf@mail.gmail.com> Message-ID: <257224ff0810300137q34e6d17u4c8d13b47d82ca2b@mail.gmail.com> On Thu, Oct 30, 2008 at 8:28 AM, Seid Mohammed wrote: > I am new to python. > I want to print Amharic character using the Python IDLE. > here goes somple code > ============================================================== >>>> abebe = '??? ?? ??' >>>> abebe > '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 \xe1\x89\xa0\xe1\x88\xb6 > \xe1\x89\xa0\xe1\x88\x8b' >>>> print abebe > ??? ?? ?? >>>> abeba = ['???','??','??'] >>>> abeba > ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', > '\xe1\x89\xa0\xe1\x88\x8b'] >>>> print abeba > ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', > '\xe1\x89\xa0\xe1\x88\x8b'] >>>> len(abebe) > 23 > ======================== > so my question is > 1)why >>> abebe prints '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 > \xe1\x89\xa0\xe1\x88\xb6 \xe1\x89\xa0\xe1\x88\x8b' instead of ??? ?? > ?? > 2) why >>> print abeba don't print the expected ??? ?? ?? string when you print strings from the interpreter using >>> abeba it will escape any non-ascii characters. if you, instead print it using >>> print abeba it will print the proper characters, as long as your terminal supports it. -- mvh base (B?rd Aase) MSN: msn at elzapp.com http://blog.elzapp.com :wq From deets at nospam.web.de Tue Oct 7 11:14:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 07 Oct 2008 17:14:54 +0200 Subject: several version of eggs References: <61032031-edf2-41e6-be66-b3d6406fd154@j68g2000hsf.googlegroups.com> <6l1abjFa6tusU1@mid.uni-berlin.de> <4e089e6f-ba0a-407f-9fbb-5a314af736fc@m74g2000hsh.googlegroups.com> Message-ID: <6l1cncFa74k2U1@mid.uni-berlin.de> Sed wrote: >> you need to easy_install with -m/--multi-version. All of your packages. > Unfortunately, this is not even working :( It is. dir at client8049:/tmp$ virtualenv --no-site-packages test New python executable in test/bin/python2.5 Installing setuptools............done. dir at client8049:/tmp$ . test/bin/activate (test)dir at client8049:/tmp$ easy_install-2.5 -m SQLAlchemy==0.4.4 Searching for SQLAlchemy==0.4.4 Reading http://pypi.python.org/simple/SQLAlchemy/ Reading http://www.sqlalchemy.org Best match: SQLAlchemy 0.4.4 Downloading http://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-0.4.4.zip#md5=4b1d072f6493421088126e451bd8cb6e Processing SQLAlchemy-0.4.4.zip Running SQLAlchemy-0.4.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xhMYOI/SQLAlchemy-0.4.4/egg-dist-tmp-WTjxmH zip_safe flag not set; analyzing archive contents... sqlalchemy.databases.mysql: module MAY be using inspect.stack Installed /tmp/test/lib/python2.5/site-packages/SQLAlchemy-0.4.4-py2.5.egg Because this distribution was installed --multi-version, before you can import modules from this package in an application, you will need to 'import pkg_resources' and then use a 'require()' call similar to one of these examples, in order to select the desired version: pkg_resources.require("SQLAlchemy") # latest installed version pkg_resources.require("SQLAlchemy==0.4.4") # this exact version pkg_resources.require("SQLAlchemy>=0.4.4") # this version or higher Processing dependencies for SQLAlchemy==0.4.4 Finished processing dependencies for SQLAlchemy==0.4.4 (test)dir at client8049:/tmp$ easy_install-2.5 -m SQLAlchemy==0.4.6 Searching for SQLAlchemy==0.4.6 Reading http://pypi.python.org/simple/SQLAlchemy/ Reading http://www.sqlalchemy.org Best match: SQLAlchemy 0.4.6 Downloading http://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-0.4.6.tar.gz#md5=3d1e737bb408de25b2fadb19a736b40e Processing SQLAlchemy-0.4.6.tar.gz Running SQLAlchemy-0.4.6/setup.py -q bdist_egg --dist-dir /tmp/easy_install-pJtAmh/SQLAlchemy-0.4.6/egg-dist-tmp-PW4OHw zip_safe flag not set; analyzing archive contents... sqlalchemy.databases.mysql: module MAY be using inspect.stack Installed /tmp/test/lib/python2.5/site-packages/SQLAlchemy-0.4.6-py2.5.egg Because this distribution was installed --multi-version, before you can import modules from this package in an application, you will need to 'import pkg_resources' and then use a 'require()' call similar to one of these examples, in order to select the desired version: pkg_resources.require("SQLAlchemy") # latest installed version pkg_resources.require("SQLAlchemy==0.4.6") # this exact version pkg_resources.require("SQLAlchemy>=0.4.6") # this version or higher Processing dependencies for SQLAlchemy==0.4.6 Finished processing dependencies for SQLAlchemy==0.4.6 (test)dir at client8049:/tmp$ python2.5 Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlalchemy Traceback (most recent call last): File "", line 1, in ImportError: No module named sqlalchemy >>> import pkg_resources >>> pkg_resources.require("SQLAlchemy==0.4.4") [SQLAlchemy 0.4.4 (/tmp/test/lib/python2.5/site-packages/SQLAlchemy-0.4.4-py2.5.egg)] >>> import sqlalchemy >>> sqlalchemy.__file__ '/tmp/test/lib/python2.5/site-packages/SQLAlchemy-0.4.4-py2.5.egg/sqlalchemy/__init__.pyc' >>> Diez From henning.vonbargen at arcor.de Fri Oct 24 03:19:48 2008 From: henning.vonbargen at arcor.de (henning.vonbargen at arcor.de) Date: Fri, 24 Oct 2008 00:19:48 -0700 (PDT) Subject: python3 - the hardest hello world ever ? References: <48f481af$0$2863$ba620e4c@news.skynet.be> <48f4f35e$0$25779$9b622d9e@news.freenet.de> <48F5C11C.3070807@igpm.rwth-aachen.de> <48f6438d$0$19075$9b622d9e@news.freenet.de> <48F6F6EE.9000704@igpm.rwth-aachen.de> Message-ID: > Many thanks, it works when setting the LANG environment variable. BTW: For Windows users, when running Python command-line programs, you can also modify the properties of the "cmd.exe" window and tell windows to use the TT Lucida Console font instead of the raster font. Then, before starting the Python program, do a CHCP 1252 This way the sys.stdout.encoding will be cp1252 (tested with Python 2.4.3 and 2.5.1). From ttboy86 at gmail.com Thu Oct 30 12:19:07 2008 From: ttboy86 at gmail.com (Felipe De Bene) Date: Thu, 30 Oct 2008 09:19:07 -0700 (PDT) Subject: HTML File Parsing References: <49077399$0$31880$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <270d013d-4a6f-480a-9777-55d5cbb1ab20@k37g2000hsf.googlegroups.com> On Oct 28, 6:18 pm, Stefan Behnel wrote: > Felipe De Bene wrote: > > I'm having problems parsing anHTMLfile with the following syntax : > > >
#144.4MB Pc-prova.rar
""" ... """#1""" ... """44.4MB""" ... """ Pc-prova.rar
> > > > > > and so on.... > > > whenever I feed the parser with such file I get the error : > > > HTMLParser.HTMLParseError: bad end tag: "", at > > line 515, column 45 > > YourHTMLpage is notHTML, i.e. it is broken. Python's HTMLParser is not made > for parsing brokenHTML. However, you can use the parse of lxml.htmlto fix up > yourHTMLfor you. > > http://codespeak.net/lxml/ > > Stefan Actually i fetch from an application that i thought it should act like this and as I told you, the program is ready to be shipped so rewriting an entire class that has public methods would be a real pain. I really had to find a way to work this out by using the python's parser instead of external libraries. But thanks anyway for the clue, I might start working on a similar project next and this library may be a good and a less painful path. Thanks :D Felipe. From steve at REMOVE-THIS-cybersource.com.au Fri Oct 24 09:17:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Oct 2008 13:17:45 GMT Subject: dictionary References: Message-ID: <0111c3f1$0$20632$c3e8da3@news.astraweb.com> On Fri, 24 Oct 2008 10:04:32 +0000, Duncan Booth wrote: > asit wrote: > >> ["%s="%s" % (k,v) for k,v in d.items()] > > The first " opens a string, the second " terminates it, the third " > opens it again, and you don't have a fourth " in your line to close it. > > Try using an editor which supports syntax colouring (even Idle does > this) and the problem will be instantly apparent. Or just read the exception, which explained exactly what's wrong: "EOL while scanning single-quoted string" What are programmers coming to these days? When I was their age, we were expected to *read* the error messages our compilers gave us, not turn to the Interwebs for help as soon there was the tiniest problem. -- Steven who is having a "you damn kids get off my lawn" moment... From ldo at geek-central.gen.new_zealand Fri Oct 17 03:53:01 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 17 Oct 2008 20:53:01 +1300 Subject: docpicture References: <6b75c492-e612-44ed-a166-d798747f2fff@v30g2000hsa.googlegroups.com> <010374c5$0$20641$c3e8da3@news.astraweb.com> <18675.34993.962044.115182@montanaro-dyndns-org.local> <0103c2da$0$20671$c3e8da3@news.astraweb.com> Message-ID: In message , Pete Forman wrote: > Maybe someone would like to play with the data URL scheme (RFC 2397) > to meet the OP's desire to embed the image. AFAIK a downside is that > MS are only starting to support that in IE8. Firefox, Konqueror and Safari already support it. So it's not as though users of all major platforms cannot access it. From castironpi at gmail.com Wed Oct 1 23:27:05 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 1 Oct 2008 20:27:05 -0700 (PDT) Subject: TypeError: can't pickle HASH objects? References: <90876c28-070e-44bf-87d2-b2f6629c9dcc@d31g2000hsg.googlegroups.com> Message-ID: <11c7ac04-b535-4135-81a5-ec7c73638134@l62g2000hse.googlegroups.com> On Oct 1, 2:50?pm, est wrote: > >>> import md5 > >>> a=md5.md5() > >>> import pickle > >>> pickle.dumps(a) > > Traceback (most recent call last): > ? File "", line 1, in > ? File "C:\Python25\lib\pickle.py", line 1366, in dumps > ? ? Pickler(file, protocol).dump(obj) > ? File "C:\Python25\lib\pickle.py", line 224, in dump > ? ? self.save(obj) > ? File "C:\Python25\lib\pickle.py", line 306, in save > ? ? rv = reduce(self.proto) > ? File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex > ? ? raise TypeError, "can't pickle %s objects" % base.__name__ > TypeError: can't pickle HASH objects > > Why can't I pickle a md5 object? Is it because md5 algorithm needs to > read 512-bits at a time? > > I need to md5() some stream, pause(python.exe quits), and resume > later. ?It seems that the md5 and hashlib in ?std module could not be > serialized? > > Do I have to implement md5 algorithm again for this special occasion? > > Or is there anyway to assige a digest when creating md5 objects? Can you just pickle the stream, the part of it you've read so far? From badmuthahubbard at gmail.com Mon Oct 27 19:20:56 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 28 Oct 2008 01:20:56 +0200 Subject: Finding the instance reference of an object In-Reply-To: <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> References: <3zIJk.5599$YU2.3294@nlpi066.nbdc.sbc.com> <7c1d9b78-c200-436c-8820-5d4ba8699613@v15g2000hsa.googlegroups.com> Message-ID: <8200bab70810271620i2f928819h6f7f06cfb7cedfb3@mail.gmail.com> I'm sorry to say I'm pretty confused by the example, but if you want something like bob = module.object() frank = module.object() and then to know that bob is bob from a list of instances, you could instead do something like: for person in listofnames: temp = module.object(person) list.append(temp) where the __init__ function assigns the argument to object.nametag or something. This way you can retrieve the name from an index into the list, or retrieve the index by searching for the name... -Chuckk On Thu, Oct 16, 2008 at 5:04 PM, Astley Le Jasper wrote: > On 16 Oct, 16:52, Carsten Haese wrote: >> Astley Le Jasper wrote: >> > Sorry for the numpty question ... >> >> > How do you find the reference name of an object? >> >> > So if i have this >> >> > bob = modulename.objectname() >> >> > how do i find that the name is 'bob' >> >> Why do you need to find that? You know that its name is 'bob'. >> >> -- >> Carsten Haesehttp://informixdb.sourceforge.net > > I'm creating mulitple instances, putting them in a list, iterating > through the list to send them to some functions where process them > with some instance specific parameters. Something along the lines of: > > bob = someobject() > harry = someobject() > fred = someobject() > > parameterdict = {'bob':(0,1,2),'harry':(3,4,5),'fred':(6,7,8)} > people_list = (bob, harry, fred) > > for person in people_list: > add_parameters(person) > > def add_parameters(person) > mytuple = parameterdict[??????instance.name????] > person.x = mytuple[0] > person.y = mytuple[1] > person.z = mytuple[2] > > ... alternatively there is probably a very much easier way of doing > it. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From neil.linux at gmail.com Fri Oct 17 02:45:44 2008 From: neil.linux at gmail.com (neil) Date: Fri, 17 Oct 2008 14:45:44 +0800 Subject: Error when import pycurl Message-ID: Guys, I meet a error when I import pycurl. Python 2.5.2 (r252:60911, Sep 8 2008, 16:01:08) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pycurl Traceback (most recent call last): File "", line 1, in ImportError: /usr/local/lib/python2.5/site-packages/pycurl.so: undefined symbol: curl_multi_socket_action >>> The libcurl version is 7.19.0 and pycurl version is pycurl-7.19.0. How can I solve this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sun Oct 19 11:40:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Oct 2008 15:40:32 GMT Subject: What's the perfect (OS independent) way of storing filepaths ? References: <010b4bb3$0$20653$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > In Linux, config files should go into: > > ~/./ or /etc// > > In Windows (which versions?) then should go into the Documents And > Settings folder, where ever that is. > > There's no single string which can represent both of these conventions! The first of those should do nicely for both Linux and Windows: >>> os.path.normpath(os.path.expanduser('~/.appname')) 'C:\\Documents and Settings\\Duncan\\.appname' From tjreedy at udel.edu Wed Oct 29 17:28:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Oct 2008 17:28:16 -0400 Subject: Filter function and lists In-Reply-To: References: Message-ID: John Townsend wrote: > I?m trying to figure out how to use filter to walk through a list. > > If I try a simple scripts like this: > > def greaterthanten (number): > #pdb.set_trace() > if (number > 10): > ret_val = 1 > > else: > ret_val = 0 > > return ret_val > > old_list = [1,2,20,30,5] > > new_list = filter(greaterthanten, old_list) > > #new_list becomes [20, 30] > > The script works as I would expect. However, what if I need to pass more > than one argument to the function? Can I do that with filter? Or does > filter work only with function that take only a single arg? The latter. Other functions could be wrapped to bind all parameters except the list element. Or write an explicit loop. From ldo at geek-central.gen.new_zealand Fri Oct 3 23:15:04 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 04 Oct 2008 16:15:04 +1300 Subject: lint for Python? References: Message-ID: In message , Pat wrote: > In module one, I have a function: > > def foo( host, userid, password ): > pass > > In module two, I call that function: > > foo( userid, password) > > lint doesn't find that error and it won't be caught until it's called > while the program is running. I don't want that error found at 3AM. > > I've never used a language that didn't catch that type of error. Because in Python, it's not necessarily an error. Every name you define in Python is just a variable, and can have its value changed at any time: the compiler can't tell that foo won't have a different value put into it between the definition of the function and the actual call. From riteshn at gmail.com Thu Oct 2 21:12:57 2008 From: riteshn at gmail.com (Ritesh Nadhani) Date: Thu, 2 Oct 2008 18:12:57 -0700 Subject: Spawing a daemon from my app and closing only when the daemon is done its job Message-ID: <3ce825820810021812t579e54a6lb0d419e13d6dbca6@mail.gmail.com> Hello So I have a wxPython GUI app. I have two independent modules which are command line are more of a daemon app which does separate but related processing for the whole system. Now, I am able to spawn the daemons and even close it when my wxPython app closes. But what I want is that if the daemon is in between its work (which is 90% I/O work), I need to get notified by the daemon and disallow the user from closing the app or let know the daemon that it needs to shut down cleanly now and when it does, it sends a notification to my wxPython app again that it is good to close down. I can use wxPython's interprocess communication methods to implement but as a separate necessity the daemon should be able to run independently without the need of wxPython. Any idea how should I approach/solve the problem? -- Ritesh http://www.riteshn.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From thorsten at thorstenkampe.de Thu Oct 9 13:36:28 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 9 Oct 2008 19:36:28 +0200 Subject: Python 2.6, GUI not working on vista? References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> Message-ID: * Mensanator (Tue, 7 Oct 2008 10:58:24 -0700 (PDT)) > On Oct 7, 12:40?pm, Thorsten Kampe wrote: > > * Lawrence D'Oliveiro (Mon, 06 Oct 2008 23:18:10 +1300) > > > In message , Thorsten Kampe > > > wrote: > > > > * Lawrence D'Oliveiro (Sun, 05 Oct 2008 22:13:46 +1300) > > > > > >> In message <48e75d94$0$25303$426a7... at news.free.fr>, Michel Claveau - > > > >> NoSpam SVP ; merci wrote: > > > > > >> > Another way is to de-activate UAC. > > > > > >> Please don't be stupid! > > > > > > He's not stupid. Disabling UAC is the recommended way to get rid of > > > > these problems. > > > > > Disabling UAC is NOT recommended. > > > > YOU don't recommend it. I don't "recommend" it either - all the people I > > know (and this includes Microsoft techsupport people) do it anyway > > without recommendation. > > Be that as it may, it is still enabled by default, isn't it? > > So advice that requires it to be disabled (or the Administrator > account enabled) ought to mention such a pertinent fact, shouldn't it? The fact that it's enabled by default is totally irrelevant for the advise. T. From tjreedy at udel.edu Sat Oct 25 21:50:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Oct 2008 21:50:36 -0400 Subject: Ordering python sets In-Reply-To: References: <2513d8ae-97ec-4b81-9ce0-f9e78bb5fa7c@r66g2000hsg.googlegroups.com> Message-ID: Lie Ryan wrote: > On Sat, 25 Oct 2008 18:20:46 -0400, Terry Reedy wrote: >>> a = list([1, 2, 3, 4, 5], implementation = 'linkedlist') >> For this to work, the abstract list would have to know about all >> implementations of the abstraction. > > /the exact syntax isn't really important/ > /abstract type and implementation separation is the important point/ > > Actually, if I want to force it, that syntax could work using the same > magic used by event-based systems: registration. ABCs have registration method. The builtin ABCs have appropriate builtin classes preregistered. >>> import collections as co >>> mu = co.MutableSequence >>> issubclass(list, mu) True I believe user classes that inherit from an ABC are also registered, and other can be registered explicitly. >Although I agree it > might be a bit cumbersome to do registration for something like this, but > as I've said before, exact syntax is not really important. Then why do you object to current mylist = linkedlist(data) and request the harder to write and implement mylist = list(data, implementation = 'linkedlist') ? tjr From ivanov.maxim at gmail.com Wed Oct 15 05:15:07 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Wed, 15 Oct 2008 02:15:07 -0700 (PDT) Subject: multiprocessing: Queue.get_nowait() never returns data Message-ID: <069b7fd2-1167-405e-b34c-efbcdd7327a8@g17g2000prg.googlegroups.com> I stuck in new multiprocessing module (ex. processing). I dont' understand why queue.get_nowait() never returns data, but always raises Empty, even if it is guaranteed that queue is not empty. I've created small test case, here it is: http://pastebin.ca/1227666 Hope someone could explain why I'm wrong.It designed for 2.6 with multiprocessing module,but it's trivial to convert it to processing module for 2.5, just replace multiprocessing with "processing" and "freeze_support" with "freezeSupport" From castironpi at gmail.com Sun Oct 5 15:12:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 05 Oct 2008 14:12:00 -0500 Subject: how to get the thighest bit position in big integers? In-Reply-To: References: Message-ID: <48E91180.2050608@gmail.com> Duncan Booth wrote: > mmgarvey at gmx.de wrote: > >> My question to the group: Does anyone know of a non-hackish way to >> determine the required bit position in python? I know that my two >> ideas >> can be combined to get something working. But is there a *better* way, >> that isn't that hackish? >> > How about using the hex representation of the value? > > OFFSET = dict(("%x"%i, int(c)) for i,c in enumerate("5433222211111111")) > def get_highest_bit_num(r): > s = "%x"%r > return len(s) * 4 - OFFSET[s[0]] > -- > http://mail.python.org/mailman/listinfo/python-list > You can replace the dict if it's faster. OFFSET= tuple( int(x) for x in "5433222211111111" ) def get_highest_bit_num(r): s = "%x"%r return len(s) * 4 - OFFSET[int(s[0],16)] P.S. Back home, this sort of 'nitpicking' would be judged unconstructive. Worth pointing out, or not worth saying? P.S.S. 'Thighest' bit? I thought the spam filters would catch that. From bruno.42.desthuilliers at websiteburo.invalid Thu Oct 23 12:24:12 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 23 Oct 2008 18:24:12 +0200 Subject: Question about scope In-Reply-To: References: Message-ID: <4900a518$0$12849$426a34cc@news.free.fr> Pat a ?crit : > I have a Globals class. Not sure it's such a great idea, but anyway... What's the use case for this class ? There are perhaps better (or at least more idiomatic) solutions... > In it, I have a variable defined something like this: > > remote_device_enabled = bool Could you show actual code ? It would really help. But it seems your 'Globals' class is mostly 1/ a singleton and 2/ used for application wide settings. Is that right ? > In one module, I assign True/False to Globals.remote_device_enabled. Directly to the class ? Please, once again, provide real code. Well... not necessarily your whole code, but at least minimal working code that reproduces the problem. > Once set, this value never changes. > > In another module, at the top after the imports statements, I tried this: > > from Globals import * The convention is to use lower case names for modules (and MixedCase names for classes). This avoids confusion between synonym classes and modules... > RDE = Globals.remote_device_enabled > > This way, I thought that I could just use 'if RDE:' > > Within the functions, however, I get a different value. What am I > misunderstanding? Not enough informations, and my crystal ball is out for repair. Sorry. Perhaps some actual code may help ?-) > I tried this at the top of the module (but it didn't word): > > global RDE Outside a function body, the 'global' statement is a no-op. In Python, 'global' really means 'module-level', so anything defined at the module level is already as global as it can be. > RDE = Globals.remote_device_enabled > > Of course, within a function, the variable using the same two lines of > code assigns the correct value to RDE. Sorry Pat, but there's just not enough context for us to guess what's wrong. It's easy enough to get it wrong with real code, so trying to guess is just a waste of time. From bearophileHUGS at lycos.com Sat Oct 4 08:46:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 4 Oct 2008 05:46:46 -0700 (PDT) Subject: lint for Python? References: Message-ID: <2a54ef01-ccf6-4281-b8de-d46e558a1fb8@l42g2000hsc.googlegroups.com> Pat: I know about 3 different lints for Python, there's PyFlake too. But I don't know if it does what you want. > I've never used a language that didn't catch that type of error. What dynamic languages have you used in the past? > I'm quite surprised that Python is being used by a number of major > companies. How you catch these types of errors? Writing tests. You must adapt your coding style to the language you use. In Java/C++ your static type system catches those bugs for you, in dynamic languages you have to catch them with testing (or lints, if they are present). Languages like Haskell with a type system much stronger than Java/C++ ones help you catch even more bugs/problems at compile time, so you need more time to have a clean compilation, but you have less bugs later (but tests are useful in Haskell too, see QuickCheck, that has inspired lot of similar tools for other languages, Python included). Bye, bearophile From bearophileHUGS at lycos.com Wed Oct 15 08:20:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 15 Oct 2008 05:20:56 -0700 (PDT) Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> Message-ID: Few suggestions for your code: - Use xrange instead of range. - Loop over lists where you can instead of their indexes. - array.array("B", somestring) may help you because it gives a byte "view" of a string. - Using psyco helps a lot for such kind of code. - I think numpy arrays can contain text/chars too, so it may offer you ways to speed up your code a lot. - Generally Python is fit to download pages from the net or to act as glue between different subsystems, or to do bulk string processing, etc, but for grunt low-level works like this it's often too much slow, and you can use other lower-level languages. - You can use a lib already written, or use an extension, for example you can try ShedSkin, or Pyd. Bye, bearophile From benjamin.kaplan at case.edu Tue Oct 7 12:59:51 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 7 Oct 2008 12:59:51 -0400 Subject: equivalent of py2exe in other os In-Reply-To: References: <48EB2CCB.9010805@al.com.au> <48EB4142.9020808@telcotec.se> <48EB4B79.1030605@al.com.au> Message-ID: On Tue, Oct 7, 2008 at 10:58 AM, Joe Strout wrote: > On Oct 7, 2008, at 8:43 AM, Benjamin Kaplan wrote: > > I believe that all (or nearly all) Unix variants come with Python >> preinstalled. Ubuntu, at least, has a lot of system programs written in >> Python. Even Mac OS X requires Python. >> > > Yes, but with significant differences between different Python > distributions, you might be safer bundling whatever version of Python your > app requires with the app itself. Otherwise, you risk your app failing (and > probably puking up runtime exceptions all over the poor user's lap) on some > distros or versions. > > (My Mac OS X machine comes with Python 2.5.1, for example, which is hardly > the latest.) > 1) 2.6 doesn't break backwards-compatibility, just don't use anything added in 2.6 and you're fine. 2)wx hasn't been compiled for 2.6 yet, so the OP is probably still using 2.5 and there are no api changes between 2.5.1 and 2.5.2 > Best, > - Joe > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Oct 13 05:15:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Oct 2008 11:15:34 +0200 Subject: Making class attributes non-case-sensitive? References: <640ad8cf-2bac-4907-accd-6ba92bac2219@a3g2000prm.googlegroups.com> Message-ID: <6lghtiFbvu75U1@mid.uni-berlin.de> Rafe wrote: > Hi, > > I'm working within an application (making a lot of wrappers), but the > application is not case sensitive. For example, Typing obj.name, > obj.Name, or even object.naMe is all fine (as far as the app is > concerned). The problem is, If someone makes a typo, they may get an > unexpected error due accidentally calling the original attribute > instead of the wrapped version. Does anyone have a simple solution for > this? > > I can protect against some cases just by making an 'alias': > class AClass(object): > def name(self): > print "hello" > > Name = name > > ...but this doesn't protect against typos, it gets more complicated > with multi-word attribute names, and it makes my epydocs confusing to > read since all spelling versions are shown (I AM concerned about my > docs being clear, but not as much as stopping typo related errors). > > I thought about using my wrapper's __getattr__ and __setattr__, but I > I am concerned about the overhead of every delegated attribute call > running a search and compare (.lower() based compare?). > > Any ideas or precedence? Ideas? Don't do that... Seriously: where does that code come from, who's typing it? If it is python, then make people follow python's rules. If it is some sort of homebrewn language you map to python, adapt the mapper to enforce lower-case and make all your properties lower case. Diez From jr9445 at ATT.COM Wed Oct 29 12:58:09 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 29 Oct 2008 11:58:09 -0500 Subject: parsing MS word docs -- tutorial request In-Reply-To: <504bbcdb-2ba1-4ac8-85e1-e86d693a214a@z6g2000pre.googlegroups.com> References: <504bbcdb-2ba1-4ac8-85e1-e86d693a214a@z6g2000pre.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of > bp.tralfamadore at gmail.com > Sent: Tuesday, October 28, 2008 10:26 AM > To: python-list at python.org > Subject: parsing MS word docs -- tutorial request > > All, > > I am trying to write a script that will parse and extract data from a > MS Word document. Can / would anyone refer me to a tutorial on how to > do that? (perhaps from tables). I am aware of, and have downloaded > the pywin32 extensions, but am unsure of how to proceed -- I'm not > familiar with the COM API for word, so help for that would also be > welcome. > > Any help would be appreciated. Thanks for your attention and > patience. > > ::bp:: > -- > http://mail.python.org/mailman/listinfo/python-list Word Object Model: http://msdn.microsoft.com/en-us/library/bb244515.aspx Google for sample code to get you started. From steve at REMOVE-THIS-cybersource.com.au Wed Oct 22 23:44:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Oct 2008 03:44:54 GMT Subject: Triple-quoted strings hath not the Python-nature References: Message-ID: <010fec39$0$20657$c3e8da3@news.astraweb.com> On Tue, 21 Oct 2008 21:58:57 +1300, Lawrence D'Oliveiro wrote: > If triple-quoted strings had the Python-nature, then they would take > indentation into account. Thus: > > """this > is a > multi-line > string.""" > > would be equivalent to > > "this\n is a\n multi-line\nstring." > > and not > > "this\n is a\n multi-line\n string." I disagree. Triple-quoted strings are exactly the same as other strings: they capture *exactly* what you put in them, and don't add or subtract characters which the language designer imagines might be irrelevant for some people some of the time. " xyz " gives the exact string " xyz " and not "xyz", no matter how convenient such behaviour would be for those who want only "xyz". If you want to strip whitespace from the string, you can strip whitespace from the string yourself. Similarly """abc xyz """ results in the exact string you put inside the quotes. Python doesn't try to guess whether or not the spaces are significant. If you want to strip whitespace, or any other character, you can do so yourself. In other words, triple-quoted strings absolutely DO have the Python- nature, because they refuse to guess what the programmer intends to do with the string later. If you don't want the spaces, either don't put them in in the first place, or remove them yourself. Don't expect Python to guess whether you want the spaces or not. -- Steven From ldo at geek-central.gen.new_zealand Sun Oct 19 19:42:06 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 20 Oct 2008 12:42:06 +1300 Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> <010845d8$0$20638$c3e8da3@news.astraweb.com> <01087204$0$20638$c3e8da3@news.astraweb.com> <010a9c3f$0$20653$c3e8da3@news.astraweb.com> Message-ID: In message , Lawrence D'Oliveiro wrote: > In message <010a9c3f$0$20653$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote: >> >>> Data can come in fractional bits. That's how compression works. >> >> If you don't believe me, try compressing a single bit and see if you get >> a "fractional bit". > > If both states of the bit are not equally likely, then you do indeed have > a fractional bit, since > > nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2 Oops, sorry, the formula should of course be nrbits = - P[bit = 0] * logbase2(P[bit = 0]) - P[bit = 1] * logbase2(P[bit = 1]) From castironpi at gmail.com Mon Oct 20 14:13:51 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 20 Oct 2008 11:13:51 -0700 (PDT) Subject: Python equivalent for C module References: Message-ID: <39f93896-15ef-4e3c-8875-fd8e8ed6c955@x16g2000prn.googlegroups.com> On Oct 20, 12:19?pm, Derek Martin wrote: snip > > I'm specifically trying to avoid having to create a debug object and > pass it around... All modules should have visibility into the state of > whether DEBUG is turned on or off, and be able to use dprint(). ?Can > Python do this? > > I tried creating debug.py as such: > > ---- debug.py ---- > DEBUG = True > def dprint(msg): > ? ? if DEBUG: > ? ? ? ? print("DEBUG: %s" % msg) > ---- end ---- > > Then in the modules that wanted to use it, I did: > > from debug import DEBUG, dprint > > But I got some weird behavior. ?The imported copy of DEBUG is > read-only; if you update it, the name DEBUG points to a different > object which the other modules can't see. ?After doing some reading of > the docs, this behavior is explained and understood (though obviously > not what I want). ?It just occured to me that I might be able to get > around that by using a setter function in the module itself... I'll > try this later. > > The other weird behavior was, once I changed the value of DEBUG, > dprint() started to behave oddly. ?No matter what I passed as an > argument (and no matter what I set the value of DEBUG to be), it > started printing the exact literal string: > > DEBUG: %s > > whenever it was called. ?It was as if the function couldn't see the > parameter msg, which was passed via the call. ?Most unexpected, and > definitely undesirable. > It should work if you set the attribute of the module directly. (untested) import debug debug.DEBUG= True debug.DEBUG= False Your idea of a module getter/setter should work too. def set_debug( val ): global DEBUG DEBUG= val Can't help with the other problem. Simplify a little with just print( msg ). From eckhardt at satorlaser.com Thu Oct 30 11:06:57 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 30 Oct 2008 16:06:57 +0100 Subject: Ascii codec can't encode References: <7a61ad70-bc83-4df3-b9f7-b6b6ff741056@r66g2000hsg.googlegroups.com> <4886d042-d5fb-493c-8735-c60584ad03fb@c60g2000hsf.googlegroups.com> <6mtih9Fici3jU4@mid.uni-berlin.de> <4bf40e64-8012-48c5-99ce-02060166f1a5@q9g2000hsb.googlegroups.com> Message-ID: luca72 wrote: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 8: ordinal not in range(128) > > I have solve in this way: > > file_ricerca = codecs.open('ri', 'wb', 'ISO-8859-15', 'repalce') That should be 'replace' instead of 'repalce', I assume you just mistyped it here. In any case, you could use 'UTF-8', which is a good default encoding and which further allows the full range of Unicode characters. > That is not exact what i want because instead of the '?' i get '?' but > the loop contine. Hmmm, weird, I'd say that ISO-8859-15 should support the accented '?'. However, this could also be caused by how you look at the file. If the editor you use to open it uses a different encoding, it will display garbage. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From phillip.oldham at gmail.com Wed Oct 1 04:55:57 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 1 Oct 2008 01:55:57 -0700 (PDT) Subject: Event-driven framework (other than Twisted)? References: <4d191607-14e3-42c4-8622-0cc4c7339550@d31g2000hsg.googlegroups.com> Message-ID: On Oct 1, 9:25?am, Lie Ryan wrote: > Most GUI package use event-driven model (e.g. Tkinter). I've noticed that. I'm thinking more for a web environment (instead of MVC) or as a HTTP server. I know Twisted has TwistedWeb, but I'm looking for alternatives. From greg at cosc.canterbury.ac.nz Fri Oct 3 02:53:41 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 03 Oct 2008 18:53:41 +1200 Subject: Comparing float and decimal In-Reply-To: References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> Message-ID: <6klu9hF8ibgaU1@mid.individual.net> Terry Reedy wrote: > Documenting the problem properly would mean changing the set > documentation ... from their current > math set based definitions to implementation based definitions It could be documented that the mathematical definitions hold only if the equality relations between all the elements involved are transitive, and leave the semantics in other cases undefined. Then in the Decimal module it could be warned that the equality relations between int-float and int-Decimal are not transitive, perhaps noting that this can cause problems with sets and dicts. -- Greg From andy55 at gmail.com Tue Oct 28 12:14:34 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Tue, 28 Oct 2008 09:14:34 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <63d8aa77-f863-4d8c-b135-2088d0b68760@a70g2000hsh.googlegroups.com> <0b92de73-de5a-4c1b-862a-7d52d3747def@m74g2000hsh.googlegroups.com> Message-ID: <3e0f4e1a-9289-4f14-b3fe-8ee2f745ba75@k36g2000pri.googlegroups.com> On Oct 27, 10:55?pm, Glenn Linderman wrote: > And I think we still are miscommunicating! ?Or maybe communicating anyway! > > So when you said "object", I actually don't know whether you meant > Python object or something else. ?I assumed Python object, which may not > have been correct... but read on, I think the stuff below clears it up. > > > Then when you mentioned thousands of objects, I imagined thousands of > Python objects, and somehow transforming the blob into same... and back > again. ? My apologies to you and others here on my use of "objects" -- I'm use the term generically and mean it to *not* refer to python objects (for the all the reasons discussed here). Python only makes up a small part of our app, hence my habit of "objects" to refer to other APIs' allocated and opaque objects (including our own and OS APIs). For all the reasons we've discussed, in our world, python objects don't travel around outside of our python C modules -- when python objects need to be passed to other parts of the app, they're converted into their non- python (portable) equivalents (ints, floats, buffers, etc--but most of the time, the objects are PyCObjects, so they can enter and leave a python context with negligible overhead). I venture to say this is pretty standard when any industry app uses a package (such as python), for various reasons: - Portability/Future (e.g. if we do decode to drop Python and go with Lua, the changes are limited to only one region of code). - Sanity (having any API's objects show up in places "far away" goes against easy-to-follow code). - MT flexibility (because we always never use static/global storage, we have all kinds of options when it comes to multithreading). For example, recall that by throwing python in multiple dynamic libs, we were able to achieve the GIL-less interpreter independence that we want (albeit ghetto and a pain). Andy From akitada at gmail.com Sat Oct 25 02:39:46 2008 From: akitada at gmail.com (Akira Kitada) Date: Sat, 25 Oct 2008 15:39:46 +0900 Subject: Cannot build _multiprocessing, math, mmap and readline of Python 2.6 on FreeBSD 4.11 w/ gcc 2.95.4 Message-ID: <90bb445a0810242339p5dd7b37p46bfe468100c05b5@mail.gmail.com> Hi list, I was trying to build Python 2.6 on FreeBSD 4.11 and found it failed to build some of the modules. """ Failed to find the necessary bits to build these modules: _bsddb _sqlite3 _tkinter gdbm linuxaudiodev spwd sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _multiprocessing math mmap readline """ Because I don't have Berkeley DB, SQLite3 tk, GDBM installed on the system and running FreeBSD, there is no wonder it failed to build _bsddb, _sqlite3, _tkinter, gdbm, linuxaudiodev, spwd and sunaudiodev. The problem is it failed to build _multiprocessing, math, mmap and readline. Here are the outputs of each build failure. """ building '_multiprocessing' extension creating build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/_multiprocessing gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DHAVE_SEM_OPEN=1 -DHAVE_FD_TRANSFER=1 -DHAVE_SEM_TIMEDWAIT=1 -IModules/_multiprocessing -I. -I/usr/home/build/dev/Python-2.6/./ Include -I. -IInclude -I./Include -I/usr/local/include -I/usr/home/build/dev/Python-2.6/Include -I/usr/home/build/dev/Python-2.6 -c /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c -o b uild/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.o In file included from /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.h:24, from /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c:9: /usr/include/arpa/inet.h:89: warning: parameter has incomplete type /usr/include/arpa/inet.h:92: warning: parameter has incomplete type /usr/include/arpa/inet.h:96: warning: parameter has incomplete type /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c: In function `multiprocessing_sendfd': /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c:102: storage size of `dummy_iov' isn't known /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c:102: warning: unused variable `dummy_iov' /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c: In function `multiprocessing_recvfd': /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c:137: storage size of `dummy_iov' isn't known /usr/home/build/dev/Python-2.6/Modules/_multiprocessing/multiprocessing.c:137: warning: unused variable `dummy_iov' """ """ building 'cmath' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I/usr/home/build/dev/Python-2.6/./Include -I. -IInclude -I./Include -I/usr/local/include -I/usr/home/build/dev/Python-2.6/I nclude -I/usr/home/build/dev/Python-2.6 -c /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c -o build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/cmathmodule.o /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c: In function `special_type': /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c:79: warning: implicit declaration of function `copysign' /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c: In function `c_acos': /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c:152: warning: implicit declaration of function `asinh' /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c: In function `c_atanh': /usr/home/build/dev/Python-2.6/Modules/cmathmodule.c:345: warning: implicit declaration of function `log1p' gcc -shared build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/cmathmodule.o -L/usr/local/lib -lm -o build/lib.freebsd-4.11-RELEASE-i386-2.6/cmath.so building 'math' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I/usr/home/build/dev/Python-2.6/./Include -I. -IInclude -I./Include -I/usr/local/include -I/usr/home/build/dev/Python-2.6/I nclude -I/usr/home/build/dev/Python-2.6 -c /usr/home/build/dev/Python-2.6/Modules/mathmodule.c -o build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/mathmodule.o /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `m_atan2': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:118: warning: implicit declaration of function `copysign' /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_acosh': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:272: `acosh' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:272: (Each undeclared identifier is reported only once /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:272: for each function it appears in.) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_asinh': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:276: `asinh' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_atanh': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:283: `atanh' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_copysign': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:288: `copysign' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_log1p': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:301: `log1p' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_ldexp': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:666: `copysign' used prior to declaration /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:670: `copysign' used prior to declaration /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_modf': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:699: `copysign' used prior to declaration /usr/home/build/dev/Python-2.6/Modules/mathmodule.c: In function `math_pow': /usr/home/build/dev/Python-2.6/Modules/mathmodule.c:901: `copysign' used prior to declaration """ """ building 'mmap' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I/usr/home/build/dev/Python-2.6/./Include -I. -IInclude -I./Include -I/usr/local/include -I/usr/home/build/dev/Python-2.6/I nclude -I/usr/home/build/dev/Python-2.6 -c /usr/home/build/dev/Python-2.6/Modules/mmapmodule.c -o build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/mmapmodule.o /usr/home/build/dev/Python-2.6/Modules/mmapmodule.c: In function `initmmap': /usr/home/build/dev/Python-2.6/Modules/mmapmodule.c:1440: warning: implicit declaration of function `my_getallocationgranularity' gcc -shared build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/mmapmodule.o -L/usr/local/lib -o build/lib.freebsd-4.11-RELEASE-i386-2.6/mmap.so *** WARNING: renaming "mmap" since importing it failed: build/lib.freebsd-4.11-RELEASE-i386-2.6/mmap.so: Undefined symbol "my_getallocationgranularity" """ """ building 'readline' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I/usr/home/build/dev/Python-2.6/./Include -I. -IInclude -I./Include -I/usr/local/include -I/usr/home/build/dev/Python-2.6/I nclude -I/usr/home/build/dev/Python-2.6 -c /usr/home/build/dev/Python-2.6/Modules/readline.c -o build/temp.freebsd-4.11-RELEASE-i386-2.6/usr/home/build/dev/Python-2.6/Modules/readline.o In file included from /usr/include/readline/readline.h:37, from /usr/home/build/dev/Python-2.6/Modules/readline.c:31: /usr/include/readline/keymaps.h:40: warning: function declaration isn't a prototype /usr/include/readline/keymaps.h:41: warning: function declaration isn't a prototype /usr/include/readline/keymaps.h:42: warning: function declaration isn't a prototype /usr/include/readline/keymaps.h:43: warning: function declaration isn't a prototype In file included from /usr/home/build/dev/Python-2.6/Modules/readline.c:31: /usr/include/readline/readline.h:343: warning: function declaration isn't a prototype /usr/home/build/dev/Python-2.6/Modules/readline.c:38: syntax error before `rl_compentry_func_t' /usr/home/build/dev/Python-2.6/Modules/readline.c:38: warning: function declaration isn't a prototype /usr/home/build/dev/Python-2.6/Modules/readline.c: In function `set_completion_display_matches_hook': /usr/home/build/dev/Python-2.6/Modules/readline.c:216: `rl_compdisp_func_t' undeclared (first use in this function) /usr/home/build/dev/Python-2.6/Modules/readline.c:216: (Each undeclared identifier is reported only once /usr/home/build/dev/Python-2.6/Modules/readline.c:216: for each function it appears in.) /usr/home/build/dev/Python-2.6/Modules/readline.c:216: syntax error before `)' /usr/home/build/dev/Python-2.6/Modules/readline.c: At top level: /usr/home/build/dev/Python-2.6/Modules/readline.c:669: warning: `on_completion_display_matches_hook' defined but not used """ Because FreeBSD is not listed on http://www.python.org/dev/peps/pep-0011/, I suppose it's still a supported platform. Any help, suggestions would be appreciated. Thanks, Akira From castironpi at gmail.com Fri Oct 17 14:16:18 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 17 Oct 2008 11:16:18 -0700 (PDT) Subject: Normalizing arguments References: Message-ID: <8fb7f718-ca6c-44e0-9370-e9452c6e1aa8@75g2000hso.googlegroups.com> On Oct 17, 12:37?pm, Dan Ellis wrote: > On Oct 17, 6:17?pm, "Chris Rebert" wrote: > > > Why do you want/need this magical g() function considering that, as > > you yourself point out, Python already performs this normalization for > > you? > > A caching idea I'm playing around with. > > @cache > def some_query(arg1, arg2): > ? ? # Maybe do SQL query or something > ? ? return result > > cache returns a function that does: > ? ? - Make a key from its arguments > ? ? - If key is in the cache: > ? ? ? ? - Return result from cache > ? ? - If it isn't: > ? ? ? ? - Call some_query with the same arguments > ? ? ? ? - Cache and return the result George Sakkis has a recipe that might help. http://code.activestate.com/recipes/551779/ It was discussed here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/91a24f281c59d4a4/31357f9cb4c7bdeb?lnk=st&q=#31357f9cb4c7bdeb From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 13 03:53:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 13 Oct 2008 09:53:20 +0200 Subject: Deviation from object-relational mapping (pySQLFace) In-Reply-To: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> References: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> Message-ID: <48f2fe70$0$15495$426a74cc@news.free.fr> sulyokpeti at gmail.com a ?crit : > I have made a simple python module to handle SQL databases: > https://fedorahosted.org/pySQLFace/wiki > Its goal to separate relational database stuff (SQL) from algorythmic s/algorythmic/algorithmic !-) > code (python). A SQLFace is a facade initialized with a configuration > file (XML). It provides callable command objects for each sql query. > The call substitutes template variables with its parameters, and > returns the result of the query. > I would like to get some opinions on this approach. Going back to the wiki... Tell you later. From luke.leighton at googlemail.com Wed Oct 15 06:02:17 2008 From: luke.leighton at googlemail.com (lkcl) Date: Wed, 15 Oct 2008 03:02:17 -0700 (PDT) Subject: Compiling Webkit-Glib and PyWebkitGTK for Win32 References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> <93a1db5d-97ac-4cd3-9e6b-de7026265a65@p49g2000hsd.googlegroups.com> <3e6db299-7b82-490e-b9b3-ea6cf10f237e@y79g2000hsa.googlegroups.com> Message-ID: <1a6ceec1-5a22-4dda-8fff-c1fb0a8cc33a@u29g2000pro.googlegroups.com> terry, hi: instructions to ensure that you have the right build environment for windows is here: http://webkit.org/building/tools.html it's not made clear whether the use of VS 2005 will _automatically_ download all of the build dependencies for you - you'll have to find out :) regarding pywebkitgtk: http://www.python.org/doc/2.5.2/ext/win-cookbook.html not sure how much use this will be, but i'm sure you'll definitely need gnu autoconf and friends, so i'd start here: http://gnuwin32.sourceforge.net/ l. From mensanator at aol.com Wed Oct 29 20:34:50 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 29 Oct 2008 17:34:50 -0700 (PDT) Subject: Filter function and lists References: Message-ID: On Oct 29, 4:28?pm, Terry Reedy wrote: > John Townsend wrote: > > I?m trying to figure out how to use filter to walk through a list. > > > If I try a simple scripts like this: > > > def greaterthanten (number): > > ? ? ? ? ? ? ? ? #pdb.set_trace() > > ? ? ? ? ? ? ? ? if (number > 10): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ret_val = 1 > > > ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ret_val = 0 > > > ? ? ? ? ? ? ? ? return ret_val > > > old_list = [1,2,20,30,5] > > > new_list = filter(greaterthanten, old_list) > > > #new_list becomes [20, 30] > > > The script works as I would expect. However, what if I need to pass more > > than one argument to the function? Can I do that with filter? Or does > > filter work only with function that take only a single arg? That single argument could be a list. >>> old_list = [1,2,20,30,5] >>> def power_of_10(a): if a[0]%10==0 and a[0]>> new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in old_list])] >>> new_list [20, 30] >>> the_limit = 25 >>> new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in old_list])] >>> new_list [20] > > The latter. ?Other functions could be wrapped to bind all parameters > except the list element. ?Or write an explicit loop.- Hide quoted text - > > - Show quoted text - From chemila at 163.com Thu Oct 23 06:00:53 2008 From: chemila at 163.com (chemila66@hotmail.com) Date: Thu, 23 Oct 2008 03:00:53 -0700 (PDT) Subject: Module for creating a screenshot of a web page given a URL? In-Reply-To: <87sllaolo2.fsf@reportlab.com> References: <1152129798.085736.144430@a14g2000cwb.googlegroups.com> <1152131406.993573.95650@m79g2000cwm.googlegroups.com> <1152220089.063405.82870@s16g2000cws.googlegroups.com> <87sllaolo2.fsf@reportlab.com> Message-ID: <20127934.post@talk.nabble.com> John J. Lee wrote: > > dananrg at yahoo.com writes: > >> > Untestetd, but I'm pretty sure something like this will do. >> > If you need more control, and on windows, try pywinauto >> >> I do need it to run on Windows. I'll check out pywinauto. Thanks. > > Note he didn't say you *need* pywinauto to run on Windows. > > > John > -- > http://mail.python.org/mailman/listinfo/python-list > > Is there anyway to do the same job in linux? The ImageGrab doesn't support for linux system. If anyone knows that, please, reply me. Thanks a lot. -- View this message in context: http://www.nabble.com/Module-for-creating-a-screenshot-of-a-web-page-given-a-URL--tp5188873p20127934.html Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Wed Oct 22 22:06:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 23 Oct 2008 00:06:35 -0200 Subject: add method to class dynamically? References: <20081022123711.29191.462710133.divmod.quotient.43175@ohm> Message-ID: En Wed, 22 Oct 2008 10:37:11 -0200, Jean-Paul Calderone escribi?: > On Wed, 22 Oct 2008 08:29:08 -0400, Neal Becker > wrote: >> I have a class (actually implemented in c++ using boost::python). For >> an instance of this class, 'r', I'd like to support len (r). I don't >> want to add it to the c++ code, because this is a unique situation: >> this class should not normally support len(). >> >> So I try: >> r = ring_int (10) >> r.__len__ = lambda: 10 >> >> This doesn't work: >>>>> len(r) >> TypeError: object of type 'ring_int' has no len() > Special methods aren't looked up in the instance dict of instances of > new-style classes. Exactly what constitutes the set of "special methods" > is a bit undefined. Consider anything that CPython has to look up to > satisfy some other operation, such as len or +, to be a special method > and don't rely on _either_ it being looked up on the instance or it _not_ > being looked up on the instance (ie, don't put a method there and expect > it > not to be called). The methods which are actually considered special by > CPython can change and has in the past. All special methods have names like "__special__" (except "next" -used in the iterator protocol- which will become __next__ in 3.0; any others?) - this is stated here http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers. (But I'm sure you already knew that) To the OP: you may use a "template method". In the C++ class do the equivalent of: class Ring_int(int): def __len__(self): return self._len_impl() def _len_impl(self): raise NotImplementedError Now you can override _len_impl in the instance: py> r = Ring_int(10) py> r._len_impl = lambda: 10 py> len(r) 10 Note that hasattr(r, '__len__') is true, don't use that check in this case. -- Gabriel Genellina From mail at microcorp.co.za Sat Oct 11 23:50:40 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 12 Oct 2008 05:50:40 +0200 Subject: Efficient Bit addressing in Python. Message-ID: <002a01c92c1f$193853e0$0d00a8c0@hendrik> Lie wrote: >> This of course means that there has to be another >> thread active to actually do the i/o on a periodic basis, >> gathering the outputs and writing them out, and reading >> the inputs and scattering them to the various named input >> bits > >Not necessarily. You've mentioned two ways. True. >> I would even not mind if I have to write: >> >> if e_stop(): >> put_everything_off() >> >> or: >> >> set(push,1) >> > >PS: Umm, a little bit off note: set is a built-in name, I'm a little >confused whether you meant on creating a "set" or setting the push bit >to 1, if the latter case it might be better to use set and clear >instead of passing a second parameter (and also to choose another >name). > True. this was a brain fart - should have been setbit or something. >.Alternatively, there is one more way: >if bb.e_stop: > bb.e_stop = 0 >where bb is some kind of "property bag" and .e_stop is a "property" >instead of an "instance member". > what is the advantage? 8<----------------------------- >Rather than directly using getters and setters, I'd go with property. >It (usually) makes a cleaner external interface of the class. And for >the mess of having to write lots of boilerplate codes, you _could_ >dynamically generate the boilerplate code from a dictionary (of name >to bit position) and currying (or something to that effect). >Alternatively, you could also do some magic with getattr and setattr. I am not too sure I know how... - Hendrik From clp at rebertia.com Wed Oct 8 16:47:05 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 8 Oct 2008 13:47:05 -0700 Subject: Inefficient summing In-Reply-To: <969403b6-613c-448f-a1c4-535d8a78c124@f37g2000pri.googlegroups.com> References: <969403b6-613c-448f-a1c4-535d8a78c124@f37g2000pri.googlegroups.com> Message-ID: <47c890dc0810081347o3c64f83at366e6a3ed65f933b@mail.gmail.com> I personally would probably do: from collections import defaultdict label2sum = defaultdict(lambda: 0) for r in rec: for key, value in r.iteritems(): label2sum[key] += value ratio = label2sum["F1"] / label2sum["F2"] This iterates through each 'r' only once, and (imho) is pretty readable provided you know how defaultdicts work. Not everything has to unnecessarily be made a one-liner. Coding is about readability first, optimization second. And optimized code should not be abbreviated, which would make it even harder to understand. I probably would have gone with your second solution if performance was no object. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com On Wed, Oct 8, 2008 at 1:23 PM, beginner wrote: > Hi All, > > I have a list of records like below: > > rec=[{"F1":1, "F2":2}, {"F1":3, "F2":4} ] > > Now I want to write code to find out the ratio of the sums of the two > fields. > > One thing I can do is: > > sum(r["F1"] for r in rec)/sum(r["F2"] for r in rec) > > But this is slow because I have to iterate through the list twice. > Also, in the case where rec is an iterator, it does not work. > > I can also do this: > > sum1, sum2= reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), ((r["F1"], > r["F2"]) for r in rec)) > sum1/sum2 > > This loops through the list only once, and is probably more efficient, > but it is less readable. > > I can of course use an old-fashioned loop. This is more readable, but > also more verbose. > > What is the best way, I wonder? > > > -a new python programmer > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Thu Oct 23 06:24:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Oct 2008 12:24:10 +0200 Subject: substitution __str__ method of an instance References: Message-ID: <6mb1lvFfpgheU1@mid.uni-berlin.de> Christian Heimes wrote: > netimen wrote: >> How can I substitute __str__ method of an instance? > > It's not possible. For performance and other reasons most __*__ methods > are looked up on the type only. Is that documented somewhere? I *know* it is that way, yet I'd like to have place to read up on it (and point to when this question pops up) Diez From jnoller at gmail.com Fri Oct 24 12:30:18 2008 From: jnoller at gmail.com (Jesse Noller) Date: Fri, 24 Oct 2008 12:30:18 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> Message-ID: <4222a8490810240930h67991afer66b66fcc93a891c4@mail.gmail.com> On Fri, Oct 24, 2008 at 10:40 AM, Andy O'Meara wrote: >> > 2) Barriers to "free threading". As Jesse describes, this is simply >> > just the GIL being in place, but of course it's there for a reason. >> > It's there because (1) doesn't hold and there was never any specs/ >> > guidance put forward about what should and shouldn't be done in multi- >> > threaded apps >> >> No, it's there because it's necessary for acceptable performance >> when multiple threads are running in one interpreter. Independent >> interpreters wouldn't mean the absence of a GIL; it would only >> mean each interpreter having its own GIL. >> > > I see what you're saying, but let's note that what you're talking > about at this point is an interpreter containing protection from the > client level violating (supposed) direction put forth in python > multithreaded guidelines. Glenn Linderman's post really gets at > what's at hand here. It's really important to consider that it's not > a given that python (or any framework) has to be designed against > hazardous use. Again, I refer you to the diagrams and guidelines in > the QuickTime API: > > http://developer.apple.com/technotes/tn/tn2125.html > > They tell you point-blank what you can and can't do, and it's that's > simple. Their engineers can then simply create the implementation > around those specs and not weigh any of the implementation down with > sync mechanisms. I'm in the camp that simplicity and convention wins > the day when it comes to an API. It's safe to say that software > engineers expect and assume that a thread that doesn't have contact > with other threads (except for explicit, controlled message/object > passing) will run unhindered and safely, so I raise an eyebrow at the > GIL (or any internal "helper" sync stuff) holding up an thread's > performance when the app is designed to not need lower-level global > locks. > > Anyway, let's talk about solutions. My company looking to support > python dev community endeavor that allows the following: > > - an app makes N worker threads (using the OS) > > - each worker thread makes its own interpreter, pops scripts off a > work queue, and manages exporting (and then importing) result data to > other parts of the app. Generally, we're talking about CPU-bound work > here. > > - each interpreter has the essentials (e.g. math support, string > support, re support, and so on -- I realize this is open-ended, but > work with me here). > > Let's guesstimate about what kind of work we're talking about here and > if this is even in the realm of possibility. If we find that it *is* > possible, let's figure out what level of work we're talking about. > >From there, I can get serious about writing up a PEP/spec, paid > support, and so on. Point of order! Just for my own sanity if anything :) I think some minor clarifications are in order. What are "threads" within Python: Python has built in support for POSIX light weight threads. This is what most people are talking about when they see, hear and say "threads" - they mean Posix Pthreads (http://en.wikipedia.org/wiki/POSIX_Threads) this is not what you (Adam) seem to be asking for. PThreads are attractive due to the fact they exist within a single interpreter, can share memory all "willy nilly", etc. Python does in fact, use OS-Level pthreads when you request multiple threads. The Global Interpreter Lock is fundamentally designed to make the interpreter easier to maintain and safer: Developers do not need to worry about other code stepping on their namespace. This makes things thread-safe, inasmuch as having multiple PThreads within the same interpreter space modifying global state and variable at once is, well, bad. A c-level module, on the other hand, can sidestep/release the GIL at will, and go on it's merry way and process away. POSIX Threads/pthreads/threads as we get from Java, allow unsafe programming styles. These programming styles are of the "shared everything deadlock lol" kind. The GIL *partially* protects against some of the pitfalls. You do not seem to be asking for pthreads :) http://www.python.org/doc/faq/library/#can-t-we-get-rid-of-the-global-interpreter-lock http://en.wikipedia.org/wiki/Multi-threading However, then there are processes. The difference between threads and processes is that they do *not share memory* but they can share state via shared queues/pipes/message passing - what you seem to be asking for - is the ability to completely fork independent Python interpreters, with their own namespace and coordinate work via a shared queue accessed with pipes or some other communications mechanism. Correct? Multiprocessing, as it exists within python 2.6 today actually forks (see trunk/Lib/multiprocessing/forking.py) a completely independent interpreter per process created and then construct pipes to inter-communicate, and queue to do work coordination. I am not suggesting this is good for you - I'm trying to get to exactly what you're asking for. Fundamentally, allowing total free-threading with Posix threads, using the same Java-Model for control is a recipe for pain - we're just repeating mistakes instead of solving a problem, ergo - Adam Olsen's work. Monitors, Actors, etc have all been discussed, proposed and are being worked on. So, just to clarify - Andy, do you want one interpreter, $N threads (e.g. PThreads) or the ability to fork multiple "heavyweight" processes? Other bits for reading: http://www.boddie.org.uk/python/pprocess.html (as an alternative the multiprocessing) http://smparkes.net/tag/dramatis/ http://osl.cs.uiuc.edu/parley/ http://candygram.sourceforge.net/ From kirk at athena.daycos.com Mon Oct 13 14:12:35 2008 From: kirk at athena.daycos.com (Kirk Strauser) Date: Mon, 13 Oct 2008 13:12:35 -0500 Subject: RegExp: "wontmatch"-function References: Message-ID: <86vdvwl5yk.fsf@athena.daycos.com> At 2008-10-13T16:40:07Z, pjacobi.de at googlemail.com writes: def nomatch(value): return not(value == '' or pattern.match(value)) -- Kirk Strauser The Day Companies From sjmachin at lexicon.net Thu Oct 16 17:22:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Oct 2008 14:22:23 -0700 (PDT) Subject: xor incongruences References: <48f79dc2$0$1083$4fafbaef@reader1.news.tin.it> Message-ID: On Oct 17, 7:02?am, Michele wrote: > Hi, > I write a simple encoder in python and Java; they do the same > computations, with the same inputs No they don't. > however they won't produce the same > output. > Let me explain with code. You have a strange understanding of the word "explain". > > First of all, you need a test file for input: > $ dd if=/dev/urandom of=test.img bs=1048576 count=1 > > I have attached the code. > As you can see we have xor-red the same inputs (bitlists are the same, > thus the selected blocks to xor are the same - you can easily see it, > whenever a block is xor-red both programs will print out its hash). > But here comes the strange: the random_block that the > create_random_block function returns is not the same: in Java this block > has an hash which is different from the Python one. > Why? > > Thank you > > [test.py1K ] > ? ? ? ? random_block = ['0']*blocksize This initialises each element to '0'. ord('0') is 48, not 0. Either I'm hallucinating, or I pointed this out to you in response to your previous posting (within the last few days). > ? ? ? ? ? ? ? ? ? ? random_block[j] = chr(ord(random_block[j]) ^ ord(block[j])) > > [Test.java2K ] > ? ? ? ? ? ? ? ? byte[] random_block = new byte[16384]; Presumably java initialises each element to 0 (or maybe random gibberish); it is highly unlikely to be 48! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? random_block[j] = (byte) (random_block[j] ^ block[j]); From digitig at gmail.com Mon Oct 6 17:40:59 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 6 Oct 2008 22:40:59 +0100 Subject: When Python should not be used? In-Reply-To: References: Message-ID: 2008/10/6 Andrea Francia : > The right tool depends on the current problem. > > While some python users prefer to talk about when Python is the right tool I > think that it is more instructive to know when it is not. > > Please, could you let me know what do you think about that? I don't think it would be the best tool for mission critical / safety of life applications, or for hard real-time embedded systems. There are also areas where domain-specific languages have advantages over general purpose languages (although the domain-specific language can be wrapped in a Python library, of course, as is the case with regexp support). Logic languages still seem to have the edge over imperative in some AI and theorem proving applications (although I suppose one /could/ implement Prolog in Python, if Prolog is what you need it's probably best to go straight there). -- Tim Rowe From mail at timgolden.me.uk Fri Oct 17 05:04:36 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 17 Oct 2008 10:04:36 +0100 Subject: Getting windows error while making a backup In-Reply-To: References: Message-ID: <48F85524.6000900@timgolden.me.uk> dudeja.rajat at gmail.com wrote: > Hi, > > I've this backup script that having some problems. Please some one suggest > what is that I'm missing in it. > This backup script deletes the previous backups and then create a new backup > by simply renaming the original folder to backup folder and creates a new > folder. > > The folder contains many files and folders and many .svn (i.e. hidden and > readonly files and directories) > > Well things seems to be done correctly but at times while renaming the > folder to backup I get this error > WindowsError: [Error 5] Access is denied The most obvious possiblity (there are others) is that you don't have permission to delete / rename the files. That's a question of NTFS permissions, not readonly-ness. Have you checked? It could also be that the file is encrypted and that you're not among the permitted users, but that's less likely. If you need to, you can take ownership and grant yourself the access you need to complete the operation. TJG From gh at ghaering.de Thu Oct 30 12:45:40 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 30 Oct 2008 17:45:40 +0100 Subject: Is psyco available for python 2.6? In-Reply-To: References: Message-ID: bearophileHUGS at lycos.com wrote: > sert: >> I used the windows installer for the latest version of psyco, >> which is labeled as compatible with 2.5, but it gives the >> following error: >> ImportError: DLL load failed: The specified module could not be >> found. (check that the compiled extension 'C:\Python26\lib\site- >> packages\psyco\_psyco.pyd' is for the correct Python version; >> this is Python 2.6) > > I think you have tried to install something compiled for Python 2.5 on > Python 2.6, therefore it doesn't work. > At the moment Psyco isn't available for Python 2.6, you will probably > have to wait some months (or use Python 2.5+Psyco in the meantime). psyco seems to just work on Linux with Python 2.6. So it is probably "only" a matter of compiling it on Windows for Python 2.6. -- Gerhard From google at mrabarnett.plus.com Mon Oct 20 18:44:05 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 20 Oct 2008 15:44:05 -0700 (PDT) Subject: windows / unix path References: <5bc219f8-07cd-4aaf-ad6f-8850fef62d60@m73g2000hsh.googlegroups.com> Message-ID: <46460c5d-f922-4219-a6d5-9228f460d905@b1g2000hsg.googlegroups.com> On Oct 20, 4:47?pm, Larry Bates wrote: > Marcin201 wrote: > > Is there an built-in functionality in python to convert Windows paths > > to Unix paths? ?I am running into problems when creating data files on > > Windows and the running them on a Unix platform. ?I create paths using > > os.path.join. > > > os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on > > Win. ?When I read files created on Win under Unix this is a problem, > > python cannot open 'Pictures\\01.jpg' > > > Thanks, > > > Marcin > > I use posixpath when I want to "force" forward slashes that I know will work on > Linux. ?Actually the forward slashes work fine on Windows also (undocumented > feature of Windows). > FYI, in Windows the standard is for commandline options to begin with a slash, eg dir /b, but as long as the path doesn't begin with one you'll be OK. :-) From tjreedy at udel.edu Mon Oct 20 02:12:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Oct 2008 02:12:02 -0400 Subject: ANN: pyparsing 1.5.1 released In-Reply-To: References: <15333a57-bc22-4f37-adfb-d7aa1f16819b@m73g2000hsh.googlegroups.com> Message-ID: Rob Williscroft wrote: > AIUI the idea is that you write your 2.x python code (and tests) so > that when they are processed by 2to3.py you get valid python 3.x > code that will pass all its tests. > > You then maintain your 2.x code base adding another test where the > code (and tests) is run through 2to3.py and then python 3.x runs > the test suite. > > Presumably you only need to start maintining a 3.x code base when > you start adding 3.x specific features or abandon support for > 2.x python. http://wiki.python.org/moin/Early2to3Migrations reports some early experiences (some a year old). Martin's was edited most recently, but even his report misses recent changes to 2to3. From __peter__ at web.de Tue Oct 14 03:04:38 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Oct 2008 09:04:38 +0200 Subject: documentation: what is "::="? References: Message-ID: Anita Kean wrote: > I'm guessing something like "if and only if" is implicated here? > But for example, if I import the sys module and perform the following > three commands, > print sys.path > sys.path.__str__() > str(sys.path) > > the first two give me the python path, and the last reports an error: >> >> >>> str(sys.path) >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python2.5/locale.py", line 244, in str >> return format("%.12g", val) >> File "/usr/lib/python2.5/locale.py", line 147, in format >> formatted = percent % value >> TypeError: float argument required >> > What is it I'm not understanding here? Before these three commands you have probably executed from locale import * This has imported the locale.str() function that now shadows the builtin str(). Had you imported locale with import locale (which is the recommended approach unless you're really know what you're doing) you would have gained access to the functions in the module as, e. g. locale.str(...) and still be able to access the built-ins in the usual way. Peter From damien.wyart at free.fr Fri Oct 17 04:25:19 2008 From: damien.wyart at free.fr (Damien Wyart) Date: Fri, 17 Oct 2008 10:25:19 +0200 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? References: <48f4ed4b$0$6127$426a74cc@news.free.fr> Message-ID: <48f84bef$0$21822$426a74cc@news.free.fr> * Carl Banks in comp.lang.python: > The python-mode.el on Subversion (python-mode's Subversion on source > forge, not the ancient version of python-mode in the Python > repository) has a fix for this issue. It doesn't look like there's any > way to browse the subversion any more, though. The viewvc interface is still there: http://svn.sourceforge.net/viewvc/python-mode/trunk/python-mode/ -- DW From pjacobi.de at googlemail.com Fri Oct 10 17:56:53 2008 From: pjacobi.de at googlemail.com (pjacobi.de at googlemail.com) Date: Fri, 10 Oct 2008 14:56:53 -0700 (PDT) Subject: How to uninstall/update modules Message-ID: <4b06dbde-605b-42ce-b34d-a40d01f67f68@u57g2000hsf.googlegroups.com> Dear All, It seems I don't understand how Python packages are handled. Here's my specific problem * I'm on Win32 * I've installed Enthought Python 2.5 because it got all the numerical stuff included * Later I tried to install Twisted 8.1 Twisted ended up in C:\Python\Lib\site-packages\twisted But there's an older Twisted included in the Enthought distribution. It is at C:\Python\Lib\site-packages\Twisted-2.5.0.0002-py2.5-win32.egg Now, the strange thing (for the uninitiated, like me) is: When doing a "import twisted" I get to older version in directory Twisted-2.5.0.0002-py2.5-win32.egg, not the newer version in directory twisted. (A) What magic is going on in redirecting the import? (B) How can I switch to use the newer version? Regards, Peter From martin at v.loewis.de Wed Oct 1 15:12:24 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 01 Oct 2008 21:12:24 +0200 Subject: How to emit UTF-8 from console mode? In-Reply-To: References: <48e31066$0$2548$9b622d9e@news.freenet.de> Message-ID: <48E3CB98.8000705@v.loewis.de> > But what are we doing here? Can you convince me that we are emitting UTF-8? Most definitely not. We are emitting cp1251. > I need UTF-8 because I need to experiment with some OS function calls that > give me UTF-16 and I need to emit UTF-16 or UTF-8. Try setting the code page to 65001, and emit the UTF-8 explicitly. Regards, Martin From SoniaTerpugova at gmail.com Sun Oct 26 16:54:33 2008 From: SoniaTerpugova at gmail.com (sonich) Date: Sun, 26 Oct 2008 13:54:33 -0700 (PDT) Subject: Web crawler on python Message-ID: <43e872d5-9f54-4195-ab70-b71aa7f5cd85@y71g2000hsa.googlegroups.com> I need simple web crawler, I found Ruya, but it's seems not currently maintained. Does anybody know good web crawler on python or with python interface? From rafesacks at gmail.com Mon Oct 13 05:11:12 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 13 Oct 2008 02:11:12 -0700 (PDT) Subject: Making class attributes non-case-sensitive? Message-ID: <640ad8cf-2bac-4907-accd-6ba92bac2219@a3g2000prm.googlegroups.com> Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this? I can protect against some cases just by making an 'alias': class AClass(object): def name(self): print "hello" Name = name ...but this doesn't protect against typos, it gets more complicated with multi-word attribute names, and it makes my epydocs confusing to read since all spelling versions are shown (I AM concerned about my docs being clear, but not as much as stopping typo related errors). I thought about using my wrapper's __getattr__ and __setattr__, but I I am concerned about the overhead of every delegated attribute call running a search and compare (.lower() based compare?). Any ideas or precedence? Cheers, - Rafe From greg at cosc.canterbury.ac.nz Fri Oct 3 02:00:43 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 03 Oct 2008 18:00:43 +1200 Subject: Python is slow? In-Reply-To: <00f226c8$0$20617$c3e8da3@news.astraweb.com> References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: <6klr66F8jlspU1@mid.individual.net> Steven D'Aprano wrote: > We agree that the restriction is artificial, and I think irrational I think it's irrational for another reason, too -- it's actually vacuous. There's nothing to prevent you creating a set of patches that simply say "Delete all of the original source and replace it with the following". Then you're effectively distributing the modified source in its entirety, just with a funny header at the top of each source file that serves no useful purpose. -- Greg From bp.tralfamadore at gmail.com Wed Oct 29 15:13:05 2008 From: bp.tralfamadore at gmail.com (bp.tralfamadore at gmail.com) Date: Wed, 29 Oct 2008 12:13:05 -0700 (PDT) Subject: parsing MS word docs -- tutorial request References: <504bbcdb-2ba1-4ac8-85e1-e86d693a214a@z6g2000pre.googlegroups.com> Message-ID: <9d4713c4-8527-45d3-9725-707631243096@f77g2000hsf.googlegroups.com> Thanks everyone -- very helpful! I really appreciate your help -- that is what makes the world a wonderful place. peace. ::bp:: From chaim at chaim.com Fri Oct 31 15:12:04 2008 From: chaim at chaim.com (Chaim Krause) Date: Fri, 31 Oct 2008 12:12:04 -0700 (PDT) Subject: split() and string.whitespace References: <1ab23c46-a8c8-4892-a640-cd0c74a7fcdd@l33g2000pri.googlegroups.com> <6n12pcFj5ggvU3@mid.uni-berlin.de> Message-ID: <7b46dcf9-4f27-4ffd-9ea8-bd033a025454@r37g2000prr.googlegroups.com> The documentation I am referencing states... The sep argument may consist of multiple characters (for example, "'1, 2, 3'.split(', ')" returns "['1', '2', '3']"). So why doesn't the latter two split on *any* whitespace character, and is instead looking for the sep string as a whole? From benjamin.kaplan at case.edu Sun Oct 12 20:32:37 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 12 Oct 2008 20:32:37 -0400 Subject: Upgrading from 2.5 to 2.6 In-Reply-To: <9gt4f4934btvoh6cdc1lql61moi0409lmm@4ax.com> References: <9gt4f4934btvoh6cdc1lql61moi0409lmm@4ax.com> Message-ID: On Sun, Oct 12, 2008 at 6:16 PM, Daniel Klein wrote: > Are there any guidelines for upgrading from 2.5 to 2.6? > > Do you have to uninstall 2.5, or does the installer do that for you? > > I have wxPython, mod_python and Django installed. Will these have to > reinstalled/reconfigured for 2.6? > > Platform: Windows XP Pro SP3 > You can actually have 2 python installations side by side. 2.5 is located in C:\Python25, and 2.6 will go into C:\Python26. Each version of Python has its own site-packages folder, so you'll need to reinstall them. For pure python libraries like django, you can just reinstall the version you already have. For wrapped c and c++ libraries (like wxPython and mod_python), you need to download python 2.6 versions. I don't think mod_python has a 2.6 binary out yet, so you'll have to either compile from source or wait for the next release if you want to upgrade python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From riteshn at gmail.com Thu Oct 2 20:52:58 2008 From: riteshn at gmail.com (Ritesh Nadhani) Date: Thu, 2 Oct 2008 17:52:58 -0700 Subject: Python import path issue. Suggestions and ideas? Message-ID: <3ce825820810021752x28da6f44yba48a9543e96b22a@mail.gmail.com> Hello All So my sourcecode has the following structure: / - app.py - commonlib.py - app.cnf - module/ - module/submodule/ - module/submodule/app2.py Commonlib is generally used for one method: def GetConfValue(section, item): config = ConfigParser.ConfigParser() config.read( "app.cnf" ) return config.get(section, item) So in app.py, I have: from commonlib import * and I can use the method, GetConfValue(). Now, if I want to use the same method in app2.py, so if I do: from CommonLib import * - it naturally throws up an error. So as a first reaction, I created another file - app2_dummy.py in the same folder as app.py, and added the code: from module.submodule.app2 import main as app2main app2main() which as you can see - a very bad way!!!! Doing a Google search threw up bunch of stuff on os.path.append and looking at it, I added the following two lines at top of app2.py sys.path.append("/".join(os.path.abspath(sys.argv[0]).split('/')[:-3])) looks ugly but adds the path correctly and I can use, import CommonLib. So my question, is this the correct way of doing things? This means I will have to put this line in every python script in that folder and subsequent folder. Why I ask is that when I was calling GetConfValue() from app2.py, it gave me error that app.cnf was not found which is probably due to the fact that app2.py was started from module/submodule/, so I changed the method to: def GetConfValue(section, item): config = ConfigParser.ConfigParser() config.read( os.path.dirname(__file__) + os.sep + "app.cnf" ) return config.get(section, item) which then works. I even found that you can tell Python to add folder using .pth but I added app.pth in module/submodule/ and had the line: ../../ but it didnt work either (I believe I am doing something very stupid on that part.....) Thoughts? Ritesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at gmail.com Thu Oct 2 16:16:40 2008 From: circularfunc at gmail.com (process) Date: Thu, 2 Oct 2008 13:16:40 -0700 (PDT) Subject: Inheritance but only partly? Message-ID: Let's say I have a class X which has 10 methods. I want class Y to inherit 5 of them. Can I do that? Can I do something along the lines of super(Y, exclude method 3 4 7 9 10) ? From bruno.42.desthuilliers at websiteburo.invalid Fri Oct 31 05:00:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 31 Oct 2008 10:00:56 +0100 Subject: Finding the instance reference of an object In-Reply-To: <6mvrbiFj3eh4U1@mid.individual.net> References: <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> <01163fa5$0$20637$c3e8da3@news.astraweb.com> <6mndsaFhn3eqU1@mid.individual.net> <6mv3bnFj2qd8U1@mid.individual.net> <011a60c1$0$20638$c3e8da3@news.astraweb.com> <74580085-b9ec-4f5a-b063-3875e0d8f22e@g17g2000prg.googlegroups.com> <6mvrbiFj3eh4U1@mid.individual.net> Message-ID: <490ac92f$0$26517$426a74cc@news.free.fr> greg a ?crit : > Aaron Brady wrote: > >> Maybe I missed this part. What does the phrase, "value of variable x" >> mean in Python? > > I didn't use the phrase "value of variable x" anywhere in my > definitions, so it doesn't matter what it means, or even > whether it means anything at all. > >> If "value of 'x'" is not defined, we should agree on a definition >> that's really clear and useful, favoring useful. After that's >> established, we can proceed to evaluating what 'call by value' would >> behave like, which would then determine if Python behaves like it. > > There you go, getting distracted by that annoying word > "value". Forget about it, we don't need it! > Err... So what does "call by value" means if "values" doesn't mean anything ?-) From mccredie at gmail.com Fri Oct 24 19:53:55 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 24 Oct 2008 16:53:55 -0700 (PDT) Subject: Global dictionary or class variables References: Message-ID: <049456c3-e033-47a3-aa22-f5e0603d15d7@o40g2000prn.googlegroups.com> On Oct 24, 1:44?pm, Mr.SpOOn wrote: > Hi, > in an application I have to use some variables with fixed valuse. > > For example, I'm working with musical notes, so I have a global > dictionary like this: > > natural_notes = {'C': 0, 'D': 2, 'E': 4 ....} > > This actually works fine. I was just thinking if it wasn't better to > use class variables. > > Since I have a class Note, I could write: > > class Note: > ? ? C = 0 > ? ? D = 2 > ? ? ... > > Which style maybe better? Are both bad practices? It really depends on how you plan to use them. I might use a dictionary if I'm likely be handling the notes as characters. If they are just constants that I plan to use in my program, I would probably just define a set of global names. The best practice I have found is a combination. NOTES = C,D,E,F,G,A,B = "CDEFGAB" note_2_step = dict(C=0, D=2, E=4, F=5, G=7, A=9, B=11) This allows you to do both. There are schemes where you might want to use a class, but without more information it doesn't really seem necessary. Globals are frowned upon, but constant tend to be just fine. Matt From brandon.g.jones at gmail.com Fri Oct 10 15:39:12 2008 From: brandon.g.jones at gmail.com (Reacher) Date: Fri, 10 Oct 2008 12:39:12 -0700 (PDT) Subject: Porn Addiction Solutions? References: Message-ID: <98d8299c-db0d-431d-ab0d-240f92e3de89@v72g2000hsv.googlegroups.com> On Oct 8, 2:07?pm, pavement... at yahoo.com wrote: > Help, I'm addicted to porn. I've been spending a lot of time > downloading hardcore porn and masturbating to it. It's ruining my > life. I just found out that one of these sites somehow hacked my card > and rang up $5K in charges which they won't even refund me. Even with > that I haven't stopped my habit and it's only getting worse. How can I > end this addiction? > > Any suggestions? Try calling the base class constructor: [code] class Foo < Bar def initialize super end end [/code] oh wait ....... nevermind From dmcc.usenet at gmail.com Thu Oct 2 14:18:24 2008 From: dmcc.usenet at gmail.com (David McClosky) Date: Thu, 2 Oct 2008 11:18:24 -0700 (PDT) Subject: Unpickling Exception-type objects Message-ID: <8ad4ecda-2c45-4ef7-b38c-2e7895271f1c@p59g2000hsd.googlegroups.com> Hi everyone, I'm stumped over what is probably (hopefully?) a very simple problem. Suppose I have a class that multiply inherits from two classes, call them A and B. A inherits from a class that takes any number of arguments in __init__. B does not inherit from anything and requires one argument. For reasons I don't understand, if A inherits from Exception, unpickling fails due to a TypeError: __init__() takes exactly 2 arguments (1 given) If A in inherits from a class that also takes any number of arguments, the TypeError vanishes. To illustrate: # ------------------------------------ import pickle class Parent: def __init__(self, *optional): self.optional = optional for Base in (Parent, Exception): print "Base =", Base print class A(Base): pass class B: def __init__(self, required): self.required = required class Child(A, B): def __init__(self, *args): A.__init__(self) B.__init__(self, *args) def test_dump(obj): print 'obj:', type(obj), obj.__dict__ pickle.dump(obj, file('/tmp/pickle.p', 'w'), -1) try: loaded = pickle.load(file('/tmp/pickle.p')) print 'loaded', type(loaded), loaded.__dict__ except TypeError, e: print 'failed to load', e print test_dump(Child(7)) # ------------------------------------ I get the following output in python 2.5.2: # ------------------------------------ Base = __main__.Parent obj: {'required': 7, 'optional': ()} loaded {'required': 7, 'optional': ()} Base = obj: {'required': 7} failed to load __init__() takes exactly 2 arguments (1 given) # ------------------------------------ Any help on this would be greatly appreciated. Thanks, David From bignose+hates-spam at benfinney.id.au Mon Oct 6 20:37:05 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 07 Oct 2008 11:37:05 +1100 Subject: The recent SPAM messages, and a suggested solution References: Message-ID: <87vdw5kzpq.fsf@benfinney.id.au> "Barak, Ron" writes: > I think most of us are annoyed by the recent SPAM messages that > crept onto our list. Note that ?spam?, referring to unsolicited bulk messages, is not an acronym for anything and so is not capitalised. The term ?SPAM? in uppercase rather refers to the Hormel Foods product. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but if we give peas a chance, won't the lima beans feel | _o__) left out?? ?_Pinky and The Brain_ | Ben Finney From ldo at geek-central.gen.new_zealand Sat Oct 18 22:57:12 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 19 Oct 2008 15:57:12 +1300 Subject: Kicking off a python script using Windows Scheduled Task References: Message-ID: In message , korean_dave wrote: > Does anyone know how to properly kick off a script using Windows > Scheduled Task? The script calls other python modules within itself. > HERE'S THE CATCH: > I am used to running the script directly from the command window and > the print() is very handy for us to debug and monitor. When running > the task from Windows Scheduled Task, we'd like to be able to view the > command window and keep it up after the Task has completed... Why not redirect stdout and stderr to a log file, and tail that? Another option might be screen . From bj_666 at gmx.net Thu Oct 2 20:02:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Oct 2008 00:02:12 GMT Subject: del and sets proposal References: Message-ID: <6kl5o4F8jbc3U1@mid.uni-berlin.de> On Thu, 02 Oct 2008 15:39:55 -0700, Chris Rebert wrote: > On Thu, Oct 2, 2008 at 3:20 PM, Larry Bates > wrote: >> a = set([1,2,3,4,5]) >> del a[1] > > Sets don't support subscripting, so if you can't go 'a_set[something]', > why would you expect to be able to be able to 'del' such an expression? > What would the subscription even mean without the 'del'? It doesn't make > sense and would just be inconsistent. Then add subscription access too. By aliasing `__getitem__()` to `__contains__()`. And `__setitem__()` could be implemented to add or remove objects by assigning truth values. So hypothetically: >>> a = set([1, 2, 3]) >>> a[1] True >>> a[4] False >>> a[2] = False >>> a set([1, 3]) >>> a[4] = True >>> a set([1, 3, 4]) >>> del a[1] >>> a set([3, 4]) I wouldn't want that addition to `set`\s but at least it can be implemented without introducing inconsistencies. Ciao, Marc 'BlackJack' Rintsch From ms at cerenity.org Sat Oct 25 07:50:27 2008 From: ms at cerenity.org (Michael Sparks) Date: Sat, 25 Oct 2008 12:50:27 +0100 Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: Andy O'Meara wrote: > Yeah, that's the idea--let the highest levels run and coordinate the > show. Yes, this works really well in python and it's lots of fun. We've found so far you need at minimum the following parts to a co-ordination little language: Pipeline Graphline Carousel Seq OneShot PureTransformer TPipe Filter Backplane PublishTo SubscribeTo The interesting thing to me about this is in most systems these would be patterns of behaviour in activities, whereas in python/kamaelia these are concrete things you can drop things into. As you'd expect this all becomes highly declarative. In practice the world is slightly messier than a theoretical document would like to suggest, primarily because if you consider things like pygame, sometimes you have only have a resource instantiated once in a single process. So you do need a mechanism for advertising services inside a process and looking those up. (The Backplane idea though helps with wrapping those up a lot I admit, for certain sorts of service :) And sometimes you do need to just share data, and when you do that's when STM is useful. But concurrent python systems are fun to build :-) Michael. -- http://www.kamaelia.org/GetKamaelia From fabiofz at gmail.com Sat Oct 18 18:17:35 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 18 Oct 2008 19:17:35 -0300 Subject: IDE Question In-Reply-To: References: <7069e0d8-ec46-44a9-8604-d2fa5b33c26c@m36g2000hse.googlegroups.com> <5695f4bb-cc2a-4faf-b643-44e34434a97b@d70g2000hsc.googlegroups.com> Message-ID: > Isn't Eclipse kind of project oriented? I.e. not suited for opening a > single file, anywhere, and viewing/editing it. I get the impression > that it prefers to have some "project" or "workspace" file which > groups a set of files and contains configuration, build rules and so > on. The guy three postings up suggested a general-purpose text editor. Yes, it prefers to have a project or workspace (which really helps you navigating through the source, so, it's one thing I usually see as positive, not negative). Still, you can use it to edit files outside of its workspace -- that's supported on Pydev -- but it looses some of those features (which are not usually available on regular editors anyway, so, that'd probably be ok if comparing with an editor, not an IDE) > (As a side note: I don't use Eclipse myself, but I have seen novice > programmers editing Python code with it, and what saw wasn't > impressive. They *did* some kind of Python "plugin" installed, but > were sitting there pressing SPACE to indent every line manually.) Not sure which plugin they had, but I'm pretty positive that if they had Pydev installed they'd have auto-indent without any problems (I can assure you that auto-indent is a feature that received a lot of attention in Pydev). Cheers, Fabio From daniel.watrous at gmail.com Fri Oct 17 12:48:25 2008 From: daniel.watrous at gmail.com (Daniel) Date: Fri, 17 Oct 2008 09:48:25 -0700 (PDT) Subject: Python logging and ThreadingTCPServer Message-ID: <4926667c-05a9-483d-8181-bbe207a129f0@w24g2000prd.googlegroups.com> Hello, I building an application that consists of several sockets components. I would like to use logging in them, but I've noticed some issues with the logs getting mangled. This mangling seems to happen when different threads attempt to access the same log file. For example, if a client and a server component are running on the same box and both try to write to the same physical log file, the first will write fine, but when the second thread (or process) writes to the log file it mangles the first part of the log file including deleting some of the information and adding various strange characters and space. Sometimes it seems that the first process never is able to write to the log file after the second process starts writing. Is this a known issue/bug? Are there any known workarounds? Thanks, Daniel From max at alcyone.com Thu Oct 2 03:11:37 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 02 Oct 2008 00:11:37 -0700 Subject: Add vs in-place add of str to list In-Reply-To: <9f0bb5d8-ea6b-405c-b1f2-383a92275a7d@j68g2000hsf.googlegroups.com> References: <9f0bb5d8-ea6b-405c-b1f2-383a92275a7d@j68g2000hsf.googlegroups.com> Message-ID: rs387 wrote: > I'm trying to understand why it is that I can do > >>>> a = [] >>>> a += 'stuff' >>>> a > ['s', 't', 'u', 'f', 'f'] > > but not > >>>> a = [] >>>> a = a + 'stuff' > Traceback (most recent call last): > File "", line 1, in > TypeError: can only concatenate list (not "str") to list > > Can someone explain the logic? Why is the in-place add not a type > error but the usual add is? (This applies to both Python 2.6rc1 and > 3.0b2) It's because the `+=` operator is doing the equivalent of calling the `extend` method, which treats its argument as a generic sequence, and doesn't enforce type. The same thing happens with any other sequence type as the right-hand operand; for instance, tuples: >>> a = [] >>> a += (1, 2, 3) >>> a [1, 2, 3] >>> a = [] >>> a = a + (1, 2, 3) Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "tuple") to list -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Man is a hating rather than a loving animal. -- Rebecca West From python.list at tim.thechases.com Wed Oct 15 15:13:13 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 15 Oct 2008 14:13:13 -0500 Subject: read zipfile sequentially? In-Reply-To: References: Message-ID: <48F640C9.7030406@tim.thechases.com> > I have a large ASCII data set that is zipped to a reasonable size. > Can I access the data without decompressing the whole file first? > I would like to run through the data to produce a much smaller > extract and some summary statistics, but without unzipping > it (if that is even possible). Yes, if you're willing to slightly hack your install if you're running pre-2.6 Python. I had the same question, and Gabriel suggested[2] I try dropping the 2.6 version of zipfile.py in my $PYTHONPATH so it's found before the existing version. Once available, you can use the ZipFile.open() method which has an iterator you can use rather than reading the entire content into memory. You can read through the thread for further details. Works on My Machine(tm)[3] -tkc [1] http://mail.python.org/pipermail/python-list/2007-December/469254.html [2] http://mail.python.org/pipermail/python-list/2007-December/469320.html [3] http://www.codinghorror.com/blog/archives/000818.html From google at mrabarnett.plus.com Sun Oct 19 18:37:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 19 Oct 2008 15:37:24 -0700 (PDT) Subject: regexp in Python (from Perl) References: <48fb8083$0$6976$426a74cc@news.free.fr> Message-ID: <927089ec-9a9c-4b5b-b0c5-429022c698fa@d70g2000hsc.googlegroups.com> On Oct 19, 5:47?pm, Bruno Desthuilliers wrote: > Pat a ?crit : > > > I have a regexp in Perl that converts the last digit of an ip address to > > ?'9'. ?This is a very particular case so I don't want to go off on a > > tangent of IP octets. > > > ?( my $s = $str ) =~ s/((\d+\.){3})\d+/${1}9/ ; > > > While I can do this in Python which accomplishes the same thing: > > > ip = ip[ :-1 ] > > ip =+ '9' > > or: > > ip = ip[:-1]+"9" > > > I'm more interested, for my own edification in non-trivial cases, in how > > one would convert the Perl RE to a Python RE that use groups. ?I am > > somewhat familiar using the group method from the re package but I > > wanted to know if there was a one-line solution. > > Is that what you want ? > > ?>>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.1") > '192.168.1.9' > > >>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.100") > > '192.168.1.9' The regular expression changes the last sequence of digits to "9" ("192.168.1.100" => "192.168.1.9") but the other code replaces the last digit ("192.168.1.100" => "192.168.1.109"). From python at rcn.com Sun Oct 19 00:28:42 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 18 Oct 2008 21:28:42 -0700 (PDT) Subject: __metaclass__ and deepcopy issue References: Message-ID: <794cb786-87d2-4c2f-a129-804a21cda857@c22g2000prc.googlegroups.com> On Oct 17, 1:00?am, Wouter DW wrote: > I read the article onhttp://www.python.org/download/releases/2.2/descrintro/#metaclasses > and started using autoprop. > But now I have a problem I can't seem to solve myself. > > class autoprop(type): > ? def __init__(cls, name, bases, dict): > ? ? super(autoprop, cls).__init__(name, bases, dict) > ? ? props = {} > ? ? for name in dict.keys(): > ? ? ? if name.startswith("_get_") or name.startswith("_set_"): > ? ? ? ? props[name[5:]] = 1 > ? ? for name in props.keys(): > ? ? ? fget = getattr(cls, "_get_%s" % name, None) > ? ? ? fset = getattr(cls, "_set_%s" % name, None) > ? ? ? setattr(cls, name, property(fget, fset)) > class InvertedX: > ? __metaclass__ = autoprop > ? def _get_x(self): > ? ? return -self.__x > ? def _set_x(self, x): > ? ? self.__x = -x > > a = InvertedX() > from copy import deepcopy > b = deepcopy(a) > > The deepcopy gives an error inside copy.py of the python lib. Hmm, your code works just fine for me in Py2.6. If I add "a.x = 10" before the deepcopy and "print b.x" after the deepcopy, it also shows the desired result. > > TypeError: descriptor '__reduce__' of 'object' object needs an > argument > > Does anybody know how to solve this issue? Usually, when you get errors of this kind with copy, deepcopy, or pickle, it means that the copier can't figure out how to extract the relevant components and then re-assemble them into a new instance. This means that you need to define some combination of __copy__, __deepcopy__, __reduce__, __getstate__, __setstate__, __getinitargs__, and/or __getnewargs__. See the pickle module and copy module for all the gory details. One other thought, class decorators can be much easier to use and understand than an equivalent metaclass: def autoprop(cls): for name in cls.__dict__.keys(): if name.startswith("_get_") or name.startswith("_set_"): name = name[5:] fget = getattr(cls, "_get_%s" % name, None) fset = getattr(cls, "_set_%s" % name, None) setattr(cls, name, property(fget, fset)) return cls @autoprop class InvertedX: def _get_x(self): return -self.__x def _set_x(self, x): self.__x = -x a = InvertedX() a.x = 10 print a.x from copy import deepcopy b = deepcopy(a) print b.x Raymond P.S. Minor nits in the original code. When you use a dict like "props" but care only about the key, not the value, that usually means that you're better-off with a set() than a dict(). Also, you don't even need to build-up "props" since the values can be used immediately (like in my example code). But the most important part is that whenever you're using metaclasses for registration, validation, or simple transformation (as in your example), then a simple class decorator is often a better choice. If you don't have Py2.6 yet, then you can get the same effect by defining the class and *then* writing, "Inverted = autoprop(Inverted). From andy55 at gmail.com Sun Oct 26 20:57:02 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Sun, 26 Oct 2008 17:57:02 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <6md7p0Fg6oraU1@mid.individual.net> <2dd0ff36-5f12-4699-94f8-583e18cb2835@y21g2000hsf.googlegroups.com> <6mfr23Ffk1khU1@mid.individual.net> Message-ID: <2a5b4896-4602-4d13-9bdb-05db7bb9ab60@u65g2000hsc.googlegroups.com> Grrr... I posted a ton of lengthy replies to you and other recent posts here using Google and none of them made it, argh. Poof. There's nothing that fires more up more than lost work, so I'll have to revert short and simple answers for the time being. Argh, damn. On Oct 25, 1:26 am, greg wrote: > Andy O'Meara wrote: > > I would definitely agree if there was a context (i.e. environment) > > object passed around then perhaps we'd have the best of all worlds. > > Moreover, I think this is probably the *only* way that > totally independent interpreters could be realized. > > Converting the whole C API to use this strategy would be > a very big project. Also, on the face of it, it seems like > it would render all existing C extension code obsolete, > although it might be possible to do something clever with > macros to create a compatibility layer. > > Another thing to consider is that passing all these extra > pointers around everywhere is bound to have some effect > on performance. I'm with you on all counts, so no disagreement there. On the "passing a ptr everywhere" issue, perhaps one idea is that all objects could have an additional field that would point back to their parent context (ie. their interpreter). So the only prototypes that would have to be modified to contain the context ptr would be the ones that don't inherently operate on objects (e.g. importing a module). On Oct 25, 1:54?am, greg wrote: > Andy O'Meara wrote: > > - each worker thread makes its own interpreter, pops scripts off a > > work queue, and manages exporting (and then importing) result data to > > other parts of the app. > > I hope you realize that starting up one of these interpreters > is going to be fairly expensive. It will have to create its > own versions of all the builtin constants and type objects, > and import its own copy of all the modules it uses. > Yeah, for sure. And I'd say that's a pretty well established convention already out there for any industry package. The pattern I'd expect to see is where the app starts worker threads, starts interpreters in one or more of each, and throws jobs to different ones (and the interpreter would persist to move on to subsequent jobs). > One wonders if it wouldn't be cheaper just to fork the > process. Shared memory can be used to transfer large lumps > of data if needed. > As I mentioned, wen you're talking about intricate data structures, OS opaque objects (ie. that have their own internal allocators), or huge data sets, even a shared memory region unfortunately can't fit the bill. Andy From lepto.python at gmail.com Mon Oct 20 01:56:49 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 20 Oct 2008 13:56:49 +0800 Subject: a question about Chinese characters in a Python Program Message-ID: <6a4f17690810192256k541977bcgd148e160254fd526@mail.gmail.com> I believe that is the problem with encode/code. you can find more @ http://groups.google.com/group/python-cn From steve at holdenweb.com Sun Oct 19 12:44:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 19 Oct 2008 12:44:57 -0400 Subject: keyword in package name. In-Reply-To: <32d86ca5-8488-4b8c-94c0-090f86e92689@o40g2000prn.googlegroups.com> References: <32d86ca5-8488-4b8c-94c0-090f86e92689@o40g2000prn.googlegroups.com> Message-ID: <48FB6409.4030805@holdenweb.com> Abhishek Mishra wrote: > On Oct 19, 12:11 pm, Tino Wildenhain wrote: >> Abhishek Mishra wrote: >>> Hello Everyone, >>> I have the habit of using domain names (of either the application or >>> company) in reverse in package names. >>> for e.g. com.spam.app1 >> While this seemed a good idea for java, I don't think it makes >> sense for python - the reason: in python you have an import >> mechanism, where in java you just have namespaces. >> >> Therefore you can always avoid namespace clashes at import time. >> > Hi, > > Thanks for your reply on a Sunday! > > Here's my 2 cents on why I prefer this mechanism - > > I would like not to worry about namespace clashes at import time. > Using a toplevel package which isolates your namespace from all > others, is a good idea in my opinion. > This could be a product name (like MoinMoin in MoinMoin), company name > (like google in google app engine - which is just one short of > com.google btw), or your DNS. > Therefore I use a domain name lots of times. (I admit that I picked up > this habit from programming a lot in java). > > Although it looks like in this case I would have to use just the > project name. > That will work fine until one of your top-level domains is also a package or module on some other element of sys.path. I can see why the convenience of a familiar naming convention might be appealing, but you shouldn't try to stretch it beyond its natural boundaries. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From philip at semanchuk.com Sat Oct 25 13:55:03 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 25 Oct 2008 13:55:03 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> Message-ID: <8E04D9EC-A132-4BE9-8F23-76AB90C5D985@semanchuk.com> On Oct 25, 2008, at 7:53 AM, Michael Sparks wrote: > Glenn Linderman wrote: > >> In the module multiprocessing environment could you not use shared >> memory, then, for the large shared data items? > > If the poshmodule had a bit of TLC, it would be extremely useful for > this, > since it does (surprisingly) still work with python 2.5, but does > need a > bit of TLC to make it usable. > > http://poshmodule.sourceforge.net/ Last time I checked that was Windows-only. Has that changed? The only IPC modules for Unix that I'm aware of are one which I adopted (for System V semaphores & shared memory) and one which I wrote (for POSIX semaphores & shared memory). http://NikitaTheSpider.com/python/shm/ http://semanchuk.com/philip/posix_ipc/ If anyone wants to wrap POSH cleverness around them, go for it! If not, maybe I'll make the time someday. Cheers Philip From bdesth.quelquechose at free.quelquepart.fr Sun Oct 5 10:30:51 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 05 Oct 2008 16:30:51 +0200 Subject: One class per file? In-Reply-To: <6kqk84F98rlsU1@mid.individual.net> References: <48e347af$0$19545$426a74cc@news.free.fr> <6km17kF8kemdU1@mid.individual.net> <48e685b2$0$10441$426a34cc@news.free.fr> <6kqk84F98rlsU1@mid.individual.net> Message-ID: <48e8eb84$0$1125$426a74cc@news.free.fr> greg a ?crit : > Bruno Desthuilliers wrote: > >> Nope. But IIRC, one-class-per-file helps saving on compile/link time. >> A problem we don't have with dynamic languages !-) > > That's mostly true. Although I've noticed that if I have > a very large .py file, it can take a noticeable number > of moments to regenerate the .pyc after I've changed > something. Indeed - and "very large" files are a maintainance nightmare anyway. The point was that with C++, when you edit a file, you not only have to recompile this file, you *also* have to relink *everything* depending on what's defined in this file. So the saving is mostly on on (re)linking time. From prologic at shortcircuit.net.au Fri Oct 24 01:10:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 24 Oct 2008 15:10:35 +1000 Subject: How to get the actual address of a object In-Reply-To: <18ed3e54-4f9f-4ca6-af69-a684f73851ef@v13g2000pro.googlegroups.com> References: <39964422-a965-4dc0-8018-81e1c2e373a0@a29g2000pra.googlegroups.com> <18ed3e54-4f9f-4ca6-af69-a684f73851ef@v13g2000pro.googlegroups.com> Message-ID: On Fri, Oct 24, 2008 at 2:58 PM, wrote: > maybe id(x) can get it ,but how to cast it back into a object You can't. Python is NOT C/C++/Java or whatever. If you have a variable, x, and you want to "copy" it to another variable, y. Use assignment. Most (if not all) objects in python a referenced. A lot of types are also immutable. Describe your problem, perhaps we may be able to provide you a "better" solution ? Can I statically re-cast an object into a different type by getting the address of another object .... is not a very good problem. If you're after, coercing one type into another, for example: >>> x = 2 >>> y = "2" >>> z = int(y) >>> x 2 >>> y '2' >>> z 2 >>> cheers James -- -- -- "Problems are solved by method" From wgheath at gmail.com Mon Oct 6 20:31:18 2008 From: wgheath at gmail.com (William Heath) Date: Mon, 6 Oct 2008 17:31:18 -0700 Subject: self signing a py2exe windows executable In-Reply-To: References: Message-ID: Hi Roger, I managed to get the dll and register it. I am now getting this error: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\blech\My Documents\qb_bridge_client_easy\dist\sign_exe.py", line 4, in s.Sign(None) File "C:\Python25\lib\site-packages\win32com\gen_py\BD26B198-EE42-4725-9B23-AFA912434229x0x2x1.py", line 2067, in Sign return self._oleobj_.InvokeTypes(6, LCID, 1, (24, 0), ((9, 49),),pISigner2 com_error: (-2147352567, 'Exception occurred.', (0, None, u'The certificate store does not contain any certificate.\r\n', None, 0, -2138570191), None) Line 4 is this: s.Sign(None) I don't think this can be none can it? -Tim P.S. Thanks for your help! On Sat, Oct 4, 2008 at 12:30 PM, Roger Upole wrote: > William Heath wrote: > > Hi All, > > I thought I sent an email to the list regarding a need I have to self > sign > > a > > py2exe windows executable. Does anyone know how to do that? > > > > -Tim > > > > You can use capicom to sign an executable (or even a .pyd): > > import win32com.client > s=win32com.client.Dispatch('capicom.signedcode') > s.FileName='yourexecutable.exe' > s.Sign(None) > s.Timestamp('http://timestamp.verisign.com/scripts/timstamp.dll') > > Roger > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Thu Oct 30 17:38:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Oct 2008 21:38:56 +0000 Subject: Printing with interspersed element In-Reply-To: <11b141710810301410l15556dbsc0b320cccb114f56@mail.gmail.com> References: <11b141710810301410l15556dbsc0b320cccb114f56@mail.gmail.com> Message-ID: <040B8642-17EB-443B-B901-F524617791D0@googlemail.com> On 30 Oct 2008, at 21:10, Paulo J. Matos wrote: > On Thu, Oct 30, 2008 at 8:42 PM, Arnaud Delobelle > wrote: >> On Oct 30, 8:07 pm, "Paulo J. Matos" wrote: >>> Hi all, >>> >>> I guess this is a recurring issue for someone who doesn't really >>> know >>> the python lib inside out. There must be a simple way to do this. >>> I have a list of objects [x1, x2, x3, ..., xn] and I have defined a >>> print method for them print_obj(). Now I want to print them >>> intersepersed by an element. >>> If I print [x1, x2, x3] interspersed by the element 10: >>> x1.print_obj() 10 x2.print_obj() 10 x3.print_obj() >>> >>> Now, the question is, what's the best way to do this? >> >> Defining a print_obj() method is probably a bad idea. What if you >> want to print to a file for example? Instead you can define a >> __str__() method for your objects and then use the join() method of >> strings like this: >> >> print ' 10 '.join(str(x) for x in lst) >> > > Thanks for the tip but that has an issue when dealing with potentially > millions of objects. You are creating a string in memory to then dump > to a file [or screen] while you could dump to the file [or screen] as > you go through the original string. Right? Why would you want to print millions of objects on the screen? As for writing to a file, a million objects will probably mean a few tens of million bytes which is not that much. Your proposed method would not work as the python call stack would explode first. Here is one that may meet your approval (it still requires a __str__ method on your objects but you can adapt it easily): def print_with_sep(sep, iterable, file=sys.stdout): iterator = iter(iterable) try: file.write(str(iterator.next())) for item in iterator: file.write(sep) file.write(str(item)) except StopIteration: pass # Use like this: >>> print_with_sep(' 10 ', [obj1, obj2, obj3]) -- Arnaud From kurdayon at yahoo.com Wed Oct 22 17:38:17 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Wed, 22 Oct 2008 14:38:17 -0700 (PDT) Subject: How to import from a file which is not in the current directory? Message-ID: <8b8d3b12-a4c7-459d-abad-de97394ba86e@k7g2000hsd.googlegroups.com> Hi, I would like to import a function from a file which is located not in the same directory as the main program (from which the function needed to be imported). Could anybody pleas tell me how to do that? Thank you in advance. From bearophileHUGS at lycos.com Fri Oct 10 09:20:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 10 Oct 2008 06:20:35 -0700 (PDT) Subject: default value in __init__ References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <3fe70d4b-0dfe-4c60-8b16-1bc70ce96d25@j68g2000hsf.googlegroups.com> Message-ID: <80b69331-e241-4c05-8df9-03f8bdbfe0bb@y21g2000hsf.googlegroups.com> Duncan Booth: > You can't just copy the default values on every call: you would still get > people confused by the semantics whether you did a shallow or deep copy or > as now no copy. I think I agree. > I don't think simply re-executing the default argument > expression on each call works either: that would confuse at least as many > people as the current system. May I ask you why? I think I don't agree, but I am not sure. > It would be possible, but extremely annoying to limit default arguments to > being literal constants, This is a possible solution, beside re-executing the default argument expression on each call. > unless you invent some kind of scheme for declaring that > a type is safe to use as a default argument. Well, it seems functional-style programming may become more common in the future, and seeing languages like Scala, etc, maybe it can be useful to add to Python some way to define immutable classes (in an explicit way). Maybe subclasses of Immutable? > Another option might just be to generate a warning the first time a program > uses a not obviously immutable default. I don't like this solution much. > Even if you could change the behaviour of default arguments we > would still get equivalent regular questions from the people who initialise > class attributes with lists or dictionaries. I have seen professional programmers too use class attributes instead of instance ones... Well, you can't create a fool-proof language that is useful too, but in a language that is designed for new programmers too, like Python, and that doesn't put the running speed as its most important feature, then I think patching the most known and common pitfalls/traps is useful, even if you can't patch them all (without turning the language into something useless). Bye, bearophile From bj_666 at gmx.net Wed Oct 22 17:12:57 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Oct 2008 21:12:57 GMT Subject: Append a new value to dict References: <48F33AC3.80505@wu-wien.ac.at> <48ff3d36$1@news.uni-ulm.de> <8631a56f-5719-42af-adea-f6ba70bee2e3@j68g2000hsf.googlegroups.com> Message-ID: <6m9japFfin81U2@mid.uni-berlin.de> On Wed, 22 Oct 2008 10:12:56 -0700, bearophileHUGS wrote: > Frank Niemeyer: >> There's simply no >> way to increment a non-existent value - not without performing some >> obscure implict behind-the-scenes stuff. > > Like importing and using a defaultdict(int). > > >> > So you >> > either have to use a workaround: >> >> > ?>>> try: >> > ... ? counter['B'] += 1 >> > ... except KeyError: >> > ... ? counter['B'] = 1 >> >> Or you could simply use >> >> if counter.has_key('B'): >> ? ? counter['B'] += 1 >> else: >> ? ? counter['B'] = 1 > > Both those are slow. Better to use: > > if 'B' in counter: > counter['B'] += 1 > else: > counter['B'] = 1 > > Or with a defaultdict: > > counter = defauldict(int) > counter['B'] += 1 Or: counter['B'] = counter.get('B', 0) + 1 Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Sun Oct 5 10:15:41 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 05 Oct 2008 16:15:41 +0200 Subject: del and sets proposal In-Reply-To: <00f80c6a$0$20633$c3e8da3@news.astraweb.com> References: <48e7b775$0$1120$426a34cc@news.free.fr> <00f80c6a$0$20633$c3e8da3@news.astraweb.com> Message-ID: <48e8e7f5$0$30951$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Sat, 04 Oct 2008 18:36:28 +0200, Bruno Desthuilliers wrote: > >>> Yes I know that sets have a remove method (like lists), but since >>> dictionaries don't have a remove method, shouldn't sets behave like >>> more like dictionaries and less like lists? IMHO del for sets is quite >>> intuitive. >> For lists, del a[x] means 'remove item at index x'. For dicts, del a[x] >> means 'remove key:value pair which key is x'. In both cases, del a[x] is >> meaningful because a[x] is meaningful. Sets are neither ordered nor >> indexed, and can't be subscripted. So "del aset[x]" is IMHO as >> meaningless as 'aset[x]' is. Using this syntax for an operation which >> semantic is the same as alist.remove(x) would be at best inconsistent >> and confusing. > > Consider the mutable built-in collections set, dict and list, and how > they remove elements: > > aset.remove(x) > alist.remove(x) > del adict[x] This last one doesn't remove the key,value pair(s) where *the value* is x, it removes the key,value pair where the *key* is x - which is semantically very different, just like alist.remove(x) is very different from del alist[x]. > Would it really be "confusing" if sets used the same interface as dicts > use? I don't think so. I do. In both dict.__delitem__ and list.__delitem__, the argument is an index (whether arbitrary key or positional index), not the value of the element to remove. wrt/ consistency, i'd rather have dict growing a remove(value) method with same semantic as list.remove and set.remove than abuse subscript syntax to duplicate an existing API which has a very different semantic. > What else could "del aset[x]" mean As far as I'm concerned, since sets are not subscriptables, del aset[x] just can't have any meaning. > other than > "delete element x"? Going this way, 'del adict[x]' should mean 'remove key,value pair(s) where value is x' and 'del alist[x]' should be an alias for alist.remove(x). > Lists are the odd one out, because del alist[x] is used to remove the > element at position x, rather than removing an element x. Nope. It's perfectly consistent with dicts, where del adict[x] is used to remove element associated to key x, not to remove element with value x. Lists and dicts are both indexed collections, list being indexed by position and dicts by key. sets are not indexed. (snip remaining - I could only keep on repeating the same thing). From stefan_ml at behnel.de Fri Oct 3 12:11:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 03 Oct 2008 18:11:12 +0200 Subject: lxml and schema validation In-Reply-To: References: Message-ID: <48e64420$0$28904$9b4e6d93@newsspool1.arcor-online.net> hrishy wrote: > I am validating a xmlfile against a xsd (My.xsd) but i notice that the xsd has a include which includes another xsd (My1.xsd) > > I have written a simple program that to validate this > > from lxml import etree > xmlschemadoc=etree.parse("My.xsd") > xmlschema=etree.XMLSchema(xmlschemadoc) Includes/Imports will be resolved at this point. > xmldoc=etree.parse("My.XML") > xmlschema.assertValid(xmldoc) > > will my program validate against My.xsd and My1.xsd both ? It will be validated against My.xsd, which (as you said), includes My1.xsd. So, yes, both schemas will participate in the validation. > I also would like my program to continue validation against the xsd and not stope at the first failure. You want to get a list of all validation errors, instead of bailing out after the first failure, right? libxml2 doesn't support that. All you get is the list of errors in the error log of the validator, but when libxml2 decides to bail out from the validation, that's it. Stefan From tjreedy at udel.edu Mon Oct 20 14:25:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Oct 2008 14:25:17 -0400 Subject: indentation In-Reply-To: References: <48fc48df$0$12027$426a74cc@news.free.fr> <48fc7069$0$20770$426a74cc@news.free.fr> Message-ID: Ross Ridge wrote: > Bruno Desthuilliers wrote: >> I can't remember having seen any other "standard" so far. >> > Ross Ridge a ?crit : >> I've seen various indentation styles used in examples on this newsgroup. > > Bruno Desthuilliers wrote: >> I meant: in a real-life project. > > So? There's no reason to assume the styles people use on this newsgroup > don't reflect those they use in "real-life" projects. Yes there is. If I type *hypothetical* code for a post, *I* have to type all the spaces, and I often use 2 per indent level. If I type in IDLE, *it* adds the spaces (4 per indent) automatically. From pavlovevidence at gmail.com Fri Oct 3 05:09:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 3 Oct 2008 02:09:09 -0700 (PDT) Subject: del and sets proposal References: <6kl5o4F8jbc3U1@mid.uni-berlin.de> Message-ID: <0286c792-8677-400c-af60-2970bc593f70@59g2000hsb.googlegroups.com> On Oct 2, 8:02?pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 02 Oct 2008 15:39:55 -0700, Chris Rebert wrote: > > On Thu, Oct 2, 2008 at 3:20 PM, Larry Bates > > wrote: > >> a = set([1,2,3,4,5]) > >> del a[1] > > > Sets don't support subscripting, so if you can't go 'a_set[something]', > > why would you expect to be able to be able to 'del' such an expression? > > What would the subscription even mean without the 'del'? It doesn't make > > sense and would just be inconsistent. > > Then add subscription access too. ?By aliasing `__getitem__()` to > `__contains__()`. ?And `__setitem__()` could be implemented to add or > remove objects by assigning truth values. ?So hypothetically: > > >>> a = set([1, 2, 3]) > >>> a[1] > True > >>> a[4] > False > >>> a[2] = False > >>> a > set([1, 3]) > >>> a[4] = True > >>> a > set([1, 3, 4]) > >>> del a[1] > >>> a > > set([3, 4]) > > I wouldn't want that addition to `set`\s but at least it can be > implemented without introducing inconsistencies. If set behaved that way then "del a[1]" wouldn't behave like del anymore. Normally, "del whatever" means that you can no longer use "whatever"; in this proposal you can. Carl Banks From bruno.42.desthuilliers at websiteburo.invalid Wed Oct 15 10:40:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 15 Oct 2008 16:40:35 +0200 Subject: recommendations for a web CMS (content management system)? In-Reply-To: References: Message-ID: <48f600d5$0$17384$426a34cc@news.free.fr> Joe Strout a ?crit : > We need to set up a content management system that allows nontechnical > users to manage the content of their web site. Rather than starting > from scratch, I'd prefer to start with an existing CMS that we can > extend as needed. So, I'd prefer something with nice clean, > easy-to-follow code over something that includes everything but the > kitchen sink. > > Any suggestions? You may find something - at least a starting point - in the couple CMS built with Django... And by all means avoid Plone - great CMS but certainly falls in your second category !-) From google at mrabarnett.plus.com Thu Oct 23 07:34:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2008 04:34:02 -0700 (PDT) Subject: Python 2.6, multiprocessing module and BSD References: <72a04310-63d3-44fc-941f-d53e8a80ab94@p58g2000hsb.googlegroups.com> <4222a8490810220711j2b66568dwb0ffa37992e315f2@mail.gmail.com> <63663698-F40D-4E3B-9FD5-3FFC59D1D100@semanchuk.com> <4222a8490810220837i60c58e1an87e79a01e0df6f3b@mail.gmail.com> Message-ID: On Oct 22, 5:14?pm, Philip Semanchuk wrote: > On Oct 22, 2008, at 11:37 AM, Jesse Noller wrote: > > > On Wed, Oct 22, 2008 at 11:06 AM, Philip Semanchuk > > wrote: > >>> One oversight I noticed the multiprocessing module docs is that a > >> semaphore's acquire() method shouldn't have a timeout on OS X as > >> sem_timedwait() isn't supported on that platform. (You note OS X's ? > >> lack of > >> support for sem_getvalue() elsewhere.) > > > Please file a ticket or updatehttp://bugs.python.org/issue4012so I > > don't loose it, my memory is increasingly lossy. Good catch. > > I updated issue4012. > > >> A question - how do you handle the difference in error messages on ? > >> various > >> platforms? For instance, sem_trywait() raises error 35, "Resource > >> temporarily unavailable" under OS X but error 11 under Ubuntu. ? > >> Right now I'm > >> just passing these up to the (Python) caller as OSErrors. This ? > >> makes it > >> really hard for the Python programmer to write cross-platform code. > > > If you look at the code, we're pretty much raising OSError - it's > > possible we could enhance this in later versions, but given MP is > > supposed to be a cross-platform as possible and protect the user from > > the seedy underbelly of semaphores/pipes/etc - when an OSError does > > occur, it's generally a bug in our code, not the users. > > Gotcha. I had a look at the code, and you're testing for errno == ? > EAGAIN when sem_trywait() fails. This is correct for OS X and Ubuntu ? > (the platforms I mentioned above) and probably most other Unices. I ? > just don't have confidence that it will be true across all platforms, ? > esp. ones to which I don't have access like AIX and big-iron systems ? > that support POSIX. Maybe I am just taking defensive programming too ? > far. > > > > >> The only solution I can think of (which I haven't coded yet) is to ? > >> compile & > >> run a series of small C programs during setup.py that test things ? > >> like > >> sem_trywait() to see what errors occur, and provide those constants ? > >> to my > >> main .c module so that it can detect those errors exactly and wrap ? > >> them into > >> a specific, custom error for the Python caller. > > >> Any thoughts on this? > > > That's actually (while feeling hacky) a possibly sensible idea, the > > problem is is that you'd need to maintain documentation to tell users > > the exceptions for their platform. > > If I pass all errors up as OSError, yes, that will be true. But that's ? > actually the situation I was trying to avoid. > > By generating the error at install time, I can see exactly what ? > platform X returns in that situation (e.g. 11). Then I can create a ? > #define something like this: > #define ERRNO_WHEN_CALLING_SEM_TRYWAIT_ON_A_LOCKED_SEMAPHORE ?11 > > My main .c module can then test for errno == ? > ERRNO_WHEN_CALLING_SEM_TRYWAIT_ON_A_LOCKED_SEMAPHORE and wrap that in ? > a custom error, like posix_ipc.SemaphoreBusyError. > > Again, maybe I'm just taking defensive programming too far. I've been ? > bitten by other cross-platform inconsistencies at the C API level and ? > I'm trying to get the jump on them here. > Re the error codes, the OS-specific code can be mapped to an OS- agnostic(?) code. On Windows there's a Windows-specific subclass of OSError, WindowsError, containing the Windows error code winerror as well as errno which is inherited from OSError. From bearophileHUGS at lycos.com Thu Oct 23 09:57:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 23 Oct 2008 06:57:54 -0700 (PDT) Subject: Slow comparison between two lists References: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> <874p33cxm9.fsf@mulj.homelinux.net> <02c90b8b-126d-47b3-99ec-9c0117a916ab@c60g2000hsf.googlegroups.com> <87zlkvbg0h.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic: > You're right. ?The OP states he implements __eq__, so he also needs a > matching __hash__, such as: > > ? ? def __hash__(self, other): > ? ? ? ? return (hash(self.xcoord) ^ hash(self.ycoord) ^ > ? ? ? ? ? ? ? ? hash(self.streetname) ^ hash(self.streetno)) The hash function by Otten is better because it considers the order of the items too (while I think the xor doesn't): return hash((self.xcoord, self.yccord, self.streetname, self.streetno)) Bye, bearophile From goldnery at gmail.com Sat Oct 18 05:26:53 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 18 Oct 2008 02:26:53 -0700 (PDT) Subject: loops Message-ID: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> how can I do width python a normal for loop width tree conditions like for example : for x=1;x<=100;x+x: print x thanks From exarkun at divmod.com Wed Oct 8 10:06:35 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 8 Oct 2008 10:06:35 -0400 Subject: How to calculate two time? In-Reply-To: <3d16f21a-c131-4801-ad10-0c6b3d189f6e@s9g2000prg.googlegroups.com> Message-ID: <20081008140635.29191.1836616074.divmod.quotient.35666@ohm> On Wed, 8 Oct 2008 06:49:10 -0700 (PDT), lookon wrote: >I have two string like "2007-03-27T08:54:43+08:00 " >how do I get the hours between these two time(string format)? That's ISO 8601 datetime format. You might use epsilon.extime: >>> from epsilon.extime import Time >>> Time.fromISO8601TimeAndDate("2008-10-08T14:05:16.029246+00:00") - Time.fromISO8601TimeAndDate("2007-03-27T08:54:43+08:00") datetime.timedelta(561, 47433, 29246) Jean-Paul From james.kirin39 at gmail.com Wed Oct 1 12:53:48 2008 From: james.kirin39 at gmail.com (james.kirin39 at gmail.com) Date: Wed, 1 Oct 2008 09:53:48 -0700 (PDT) Subject: decent interactive python shell on MS Windows? Message-ID: Hi everyone, After having used Python on Linux for some time, I now have to do Python coding on Windows. I am big fan of the interactive Python shell to test, eg, regexps. Is there an interactive Python shell on Windows that supports: - easy copy-pasting to/from an editor? (as opposed to the cumbersome "mark", "copy" and then "paste" sequence that any terminal on Windows seems forced to adopt) - readline-like command history (up/down for previous/next command, Ctr-R for searching, etc) ? I have tried the python.org shell (difficult copy-pasting), ActiveState's (no readline command history) and iPython (difficult copy-pasting). Do you know of any decent interactive python shell on Windows that comes close to the friendliness of the standard one on Linux? Thanks in advance James From steve at REMOVE-THIS-cybersource.com.au Sun Oct 12 01:35:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Oct 2008 05:35:54 GMT Subject: Most compact "X if X else Y" idiom References: <010184ce$0$20657$c3e8da3@news.astraweb.com> Message-ID: <0101860f$0$20657$c3e8da3@news.astraweb.com> On Sun, 12 Oct 2008 05:30:33 +0000, Steven D'Aprano wrote: > Use short-circuit Booleans: > > y = x or "blah" Except of course you don't use x, you use the complex expression. y = (some complex expression) or "blah" Sorry for the itchy posting finger. -- Steven From mcnallyconfusiontg at googlemail.com Sun Oct 5 18:17:44 2008 From: mcnallyconfusiontg at googlemail.com (eqweqwe) Date: Sun, 5 Oct 2008 15:17:44 -0700 (PDT) Subject: Buy carisoprodol online Message-ID: buy cheap carisoprodol online . . . Enough to seek Carisoprodol! You've already found the best site where you can purchase Carisoprodol for lowest price! To order Carisoprodol without prescription visit link below! ************************************ http://med247.us/?p=Carisoprodol ************************************ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uy cheap carisoprodol online by cheap carisoprodol online bu cheap carisoprodol online buy heap carisoprodol online buy ceap carisoprodol online buy chap carisoprodol online buy chep carisoprodol online buy chea carisoprodol online buy cheap arisoprodol online buy cheap crisoprodol online buy cheap caisoprodol online buy cheap carsoprodol online buy cheap carioprodol online buy cheap carisprodol online buy cheap carisorodol online buy cheap carisopodol online buy cheap carisoprdol online buy cheap carisoprool online buy cheap carisoprodl online buy cheap carisoprodo online buy cheap carisoprodol nline buy cheap carisoprodol oline buy cheap carisoprodol onine buy cheap carisoprodol onlne buy cheap carisoprodol onlie buy cheap carisoprodol onlin bbuy cheap carisoprodol online buuy cheap carisoprodol online buyy cheap carisoprodol online buy ccheap carisoprodol online buy chheap carisoprodol online buy cheeap carisoprodol online buy cheaap carisoprodol online buy cheapp carisoprodol online buy cheap ccarisoprodol online buy cheap caarisoprodol online buy cheap carrisoprodol online buy cheap cariisoprodol online buy cheap carissoprodol online buy cheap carisooprodol online buy cheap carisopprodol online buy cheap carisoprrodol online buy cheap carisoproodol online buy cheap carisoproddol online buy cheap carisoprodool online buy cheap carisoprodoll online buy cheap carisoprodol oonline buy cheap carisoprodol onnline buy cheap carisoprodol onlline buy cheap carisoprodol onliine buy cheap carisoprodol onlinne buy cheap carisoprodol onlinee uby cheap carisoprodol online byu cheap carisoprodol online buy cheap carisoprodol online buy hceap carisoprodol online buy cehap carisoprodol online buy chaep carisoprodol online buy chepa carisoprodol online buy cheap carisoprodol online buy cheap acrisoprodol online buy cheap craisoprodol online buy cheap cairsoprodol online buy cheap carsioprodol online buy cheap cariosprodol online buy cheap carisporodol online buy cheap carisorpodol online buy cheap carisopordol online buy cheap carisoprdool online buy cheap carisoproodl online buy cheap carisoprodlo online buy cheap carisoprodol online buy cheap carisoprodol noline buy cheap carisoprodol olnine buy cheap carisoprodol onilne buy cheap carisoprodol onlnie buy cheap carisoprodol onlien buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online buy cheap carisoprodol online From duncan.booth at invalid.invalid Mon Oct 20 06:20:06 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Oct 2008 10:20:06 GMT Subject: What's the perfect (OS independent) way of storing filepaths ? References: <010b4bb3$0$20653$c3e8da3@news.astraweb.com> <010bad29$0$20653$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 19 Oct 2008 15:40:32 +0000, Duncan Booth wrote: > >> Steven D'Aprano wrote: >> >>> In Linux, config files should go into: >>> >>> ~/./ or /etc// >>> >>> In Windows (which versions?) then should go into the Documents And >>> Settings folder, where ever that is. >>> >>> There's no single string which can represent both of these >>> conventions! >> >> The first of those should do nicely for both Linux and Windows: >> >>>>> os.path.normpath(os.path.expanduser('~/.appname')) >> 'C:\\Documents and Settings\\Duncan\\.appname' > > > Except Windows users will be wondering why they have a directory > starting with '.' in their home directory. Dot to make files hidden is > not AFAIK supported by Windows. > The leading dot doesn't make the files hidden on Windows, but there's no reason why you can't create files/folders with a leading dot and many programs do just that. On the machine I'm on right now, 'dir .*' shows me: Directory of C:\Documents and Settings\Duncan 18/10/2008 15:48 . 18/10/2008 15:48 .. 22/09/2008 20:28 45 .appcfg_nag 30/07/2004 09:28 244 .bashrc 18/01/2007 10:50 6,783 .bash_history 11/06/2006 12:30 .borland 06/04/2004 15:43 365 .emacs-places 11/03/2004 12:34 .emacs.d 08/01/2007 19:35 30,390 .fonts.cache-1 03/05/2008 18:07 .gimp-2.0 14/01/2005 14:34 .idlerc 11/06/2006 12:36 .jbuilder2005 27/06/2005 12:44 3 .leoID.txt 11/06/2006 12:43 .Nokia 11/06/2006 12:36 .primetime2005 11/06/2006 12:13 .qualitycentral 04/02/2004 12:24 .ssh 12/08/2004 14:30 .thumbnails 30/07/2004 14:11 49 .Xauthority 29/07/2004 16:25 12 .Xdefaults 29/07/2004 14:36 .xemacs 17/08/2006 09:19 2,869 .XWinrc not to mention the thousands of .svn folders scattered across the rest of the system. From tjreedy at udel.edu Sat Oct 25 12:54:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Oct 2008 12:54:43 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <49029A1B.50503@g.nevcal.com> References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <3919088a-9d8c-40b8-87fd-6ef39ed69f76@d10g2000pra.googlegroups.com> <49025C58.7040607@g.nevcal.com> <49029A1B.50503@g.nevcal.com> Message-ID: Glenn Linderman wrote: > On approximately 10/24/2008 8:39 PM, came the following characters from > the keyboard of Terry Reedy: >> Glenn Linderman wrote: >> >>> For example, Python presently has a rather stupid algorithm for >>> string concatenation. Yes, CPython2.x, x<=5 did. >> Python the language has syntax and semantics. Python implementations >> have algorithms that fulfill the defined semantics. > > I can buy that, but when Python is not qualified, CPython should be > assumed, as it predominates. People do that, and it sometimes leads to unnecessary confusion. As to the present discussion, is it about * changing Python, the language * changing all Python implementations * changing CPython, the leading implementation * branching CPython with a compiler switch, much as there was one for including Unicode or not. * forking CPython * modifying an existing module * adding a new module * making better use of the existing facilities * some combination of the above > Of course, the latest official release > should probably also be assumed, but that is so recent, People do that, and it sometimes leads to unnecessary confusion. People routine posted version specific problems and questions without specifying the version (or platform when relevant). In a month or so, there will be *2* latest official releases. There will be more confusion without qualification. > few have likely > upgraded as yet... I should have qualified the statement. * Is the target of this discussion 2.7 or 3.1 (some changes would be 3.1 only). [diversion to the side topic] >> If there is more than one reference to a guaranteed immutable object, >> such as a string, the 'stupid' algorithm seem necessary to me. >> In-place modification of a shared immutable would violate semantics. > > Absolutely. But after the first iteration, there is only one reference > to string. Which is to say, 'string' is the only reference to its object it refers too. You are right, so I presume that the optimization described would then kick in. But I have not read the code, and CPython optimizations are not part of the *language* reference. [back to the main topic] There is some discussion/debate/confusion about how much of the stdlib is 'standard Python library' versus 'standard CPython library'. [And there is some feeling that standard Python modules should have a default Python implementation that any implementation can use until it optionally replaces it with a faster compiled version.] Hence my question about the target of this discussion and the first three options listed above. Terry Jan Reedy From malaclypse2 at gmail.com Fri Oct 24 14:18:49 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 24 Oct 2008 14:18:49 -0400 Subject: portable python In-Reply-To: References: Message-ID: <16651e80810241118l3c91ec8aqfd166d7827e69ea6@mail.gmail.com> On Fri, Oct 24, 2008 at 1:42 PM, asit wrote: > I code in both windows and Linux. As python is portable, the o/p > should be same in both cases. But why the following code is perfect in > windows but error one in Linux ??? What error message do you get in linux? How are you running your code in linux? Your code seems to generally work on my Ubuntu linux box, so you need to give us more information. -- Jerry From thomascribbs at gmail.com Thu Oct 2 12:46:42 2008 From: thomascribbs at gmail.com (thomascribbs at gmail.com) Date: Thu, 2 Oct 2008 09:46:42 -0700 (PDT) Subject: IDLE doesn't run on OSX 10.3.9 References: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> <48E26CB7.8060207@codebykevin.com> <48E387B0.8070908@codebykevin.com> Message-ID: <7da671a5-42fc-4ff1-b839-142f60e098cd@e17g2000hsg.googlegroups.com> Looks like installing TclTkAqua-8.4.10.dmg fixed it...IDLE runs now! -Tom On Oct 1, 9:22 am, Kevin Walzer wrote: > thomascri... at gmail.com wrote: > > Just did a new install of Tcl/tk from activestate.com and IDLE still > > not working... > > > -Tom > > Did you install Tcl/Tk 8.5? It won't work with the build of Python from > python.org (it looks for 8.4). > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com From ttboy86 at gmail.com Tue Oct 28 15:58:56 2008 From: ttboy86 at gmail.com (Felipe De Bene) Date: Tue, 28 Oct 2008 12:58:56 -0700 (PDT) Subject: HTML File Parsing Message-ID: I'm having problems parsing an HTML file with the following syntax :
User IDName > BGCOLOR='#c0c0c0'>Date
and so on.... whenever I feed the parser with such file I get the error : Traceback (most recent call last): File "C:\Documents and Settings\Administrator\My Documents\workspace \thread\src\parser.py", line 91, in p.parse(thechange) File "C:\Documents and Settings\Administrator\My Documents\workspace \thread\src\parser.py", line 16, in parse self.feed(s) File "C:\Python25\lib\HTMLParser.py", line 110, in feed self.goahead(0) File "C:\Python25\lib\HTMLParser.py", line 152, in goahead k = self.parse_endtag(i) File "C:\Python25\lib\HTMLParser.py", line 316, in parse_endtag self.error("bad end tag: %r" % (rawdata[i:j],)) File "C:\Python25\lib\HTMLParser.py", line 117, in error raise HTMLParseError(message, self.getpos()) HTMLParser.HTMLParseError: bad end tag: "", at line 515, column 45 Googling around I've found a solution to a similar situation, over and over again : http://64.233.169.104/search?q=cache:zOmjwM_sGBcJ:coding.derkeiler.com/pdf/Archive/Python/comp.lang.python/2006-02/msg00026.pdf+CDATA_CONTENT_ELEMENTS&hl=pt-BR&ct=clnk&cd=5&gl=br&client=firefox-a but coding : you can disable proper parsing by setting the CDATA_CONTENT_ELEMENTS attribute on the parser instance, before you start parsing. by default, it is set to CDATA_CONTENT_ELEMENTS = ("script", "style") setting it to an empty tuple disables HTML-compliant handling for these elements: p = HTMLParser() p.CDATA_CONTENT_ELEMENTS = () p.feed(f.read()) didn't solve my problem. I've made a little modification then to HTMLParser.py instead that solved the problem, as follows: original: endtagfind = re.compile('') my version : endtagfind = re.compile('') it worked ok for all the files I needed and also for a different file I also parse using the same library. I know it might sound stupid but I was just wondering if there's a better way of solving that problem than just modifying the standard library. Any clue ? thx in advance, Felipe. From gherron at islandtraining.com Mon Oct 20 13:28:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 20 Oct 2008 10:28:15 -0700 Subject: Python equivalent for C module In-Reply-To: <20081020171903.GB20797@dragontoe.org> References: <20081020171903.GB20797@dragontoe.org> Message-ID: <48FCBFAF.9000905@islandtraining.com> Derek Martin wrote: > I'd like to know if it's possible to code something in Python which > would be equivalent to the following C: > > [Assume bool is typedef'd to int, and TRUE and FALSE are #defined to 1 > and 0, respectively] > > ---- debug.c ---- > #include > > bool DEBUG; > > void dprint(char *msg) > { > if (DEBUG){ > printf("DEBUG: %s", msg); > } > } > > ---- end of debug.c ---- > > The idea being that all modules of the program would "import" this > code via the header file: > > ---- debug.h ---- > extern bool DEBUG; > void dprint(char *msg); > ---- end of debug.h ---- > > I'm specifically trying to avoid having to create a debug object and > pass it around... All modules should have visibility into the state of > whether DEBUG is turned on or off, and be able to use dprint(). Can > Python do this? > > I tried creating debug.py as such: > > ---- debug.py ---- > DEBUG = True > def dprint(msg): > if DEBUG: > print("DEBUG: %s" % msg) > ---- end ---- > > Then in the modules that wanted to use it, I did: > > from debug import DEBUG, dprint > So don't import it that way. Instead, do it this way: import debug Then us like this: debug.DEBUG = True and debug.dprint(...) Lots of other possibilities exist -- but this solves your specific first question. > But I got some weird behavior. The imported copy of DEBUG is > read-only; if you update it, the name DEBUG points to a different > object which the other modules can't see. After doing some reading of > the docs, this behavior is explained and understood (though obviously > not what I want). It just occured to me that I might be able to get > around that by using a setter function in the module itself... I'll > try this later. > > The other weird behavior was, once I changed the value of DEBUG, > dprint() started to behave oddly. No matter what I passed as an > argument (and no matter what I set the value of DEBUG to be), it > started printing the exact literal string: > > DEBUG: %s > > whenever it was called. It was as if the function couldn't see the > parameter msg, which was passed via the call. Most unexpected, and > definitely undesirable. > I don't believe it -- send your *actual* code, and we'll all have a look. Gary Herron > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > From dotancohen at gmail.com Wed Oct 8 16:14:40 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 8 Oct 2008 22:14:40 +0200 Subject: Porn Addiction Solutions? In-Reply-To: <1D5F3E52E13A42AF97DB3D2D5163CCAB@office.ipglobal.net> References: <963ea4ac-54e6-4911-9a15-846b86de5cea@u40g2000pru.googlegroups.com> <1D5F3E52E13A42AF97DB3D2D5163CCAB@office.ipglobal.net> Message-ID: <880dece00810081314k4eb450bi4247f0cb1225aed6@mail.gmail.com> 2008/10/8 Support Desk : > I got a solution, cutt it off, and then Kill yourself. > Cut what off? The OP is female. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From mnations at gmail.com Thu Oct 30 12:46:58 2008 From: mnations at gmail.com (Mudcat) Date: Thu, 30 Oct 2008 09:46:58 -0700 (PDT) Subject: Tkinter: How to get Label wraplength functionality in Text Box References: <471094a7-8fa0-4437-9c01-748bc8343d6d@q35g2000hsg.googlegroups.com> <9d98a2c9-62a1-497a-bd98-af72080c8aed@u46g2000hsc.googlegroups.com> Message-ID: <1b0231b8-d71a-42da-bf9f-521b879f2255@m73g2000hsh.googlegroups.com> Awesome...there it goes. I guess my main problem was trying to evaluate the box before it had been displayed (or all the frame propagations were finished). The key was getting the binding in there once I got the count functionality to work. After all that...such a simple function: def textBoxResize(self, event): widget = event.widget dispLines = widget.count("1.0", "end", "displaylines") widget.config(height=dispLines) Thanks for the help! On Oct 30, 9:19?am, "Guilherme Polo" wrote: > On 10/30/08, Mudcat wrote: > > > I'm not sure why my tkinter would not be compiled against 8.5 since I > > ?have the latest version. I assumed that Python 2.6 would have it > > ?without requiring me to do an extra compile. > > It is not really python's fault if tkinter is compiled against tcl/tk > 8.5 or not. The windows installer for python 2.6 happens to include > tcl/tk 8.5 and tkinter compiled against them, but ubuntu for example > doesn't distribute tkinter compiled against tcl/tk 8.5 at the moment. > > > > > ?However I was able to get it working using the code you gave me. > > ?Thanks for that. The only problem is that it seems to simply be > > ?counting newlines (or number of \n). When I use the following: > > > ? ? ? ? numlines = widget.count("1.0", "end", "displaylines", "lines") > > ? ? ? ? print "Number of lines is ", numlines > > > ?I get this: > > > ?Number of lines is ?(153, 1) > > The first is the number of displaylines, the second is the number of lines. > > > > > ?So that's not actually the number of lines displayed in the box, just > > ?the number of newline chars it finds. > > Not really. displaylines returns the number of lines displayed in the > text widget, and lines returns the number of newlines found. > Note that it is important to call "count" only after the text widget > is being displayed, otherwise displaylines won't work correctly (not > with tk 8.5.3 at least). > > > I couldn't find anything in the > > ?tk documentation that would give me any other options to count lines > > ?differently, or number of lines displayed after wrapping. > > Try this and check what you get: > > import Tkinter > > root = Tkinter.Tk() > text = Tkinter.Text() > text.pack() > > def test(event): > ? ? print "displaylines:", text.count("1.0", "end", "displaylines") > ? ? print "lines:", text.count("1.0", "end", "lines") > > text.insert("1.0", "a" * 81) > text.insert("2.0", "b\n") > text.bind('', test) > > root.mainloop() > > You should have 3 lines displayed but only 2 "real" lines. > > -- > -- Guilherme H. Polo Goncalves From enleverlesX.XmcX at XmclaveauX.com Wed Oct 15 12:25:10 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 15 Oct 2008 18:25:10 +0200 Subject: [ANN] Data Plotting Library DISLIN 9.4 References: Message-ID: <48f61a3f$0$925$ba4acef3@news.orange.fr> Hello! > version 9.4 of DISLIN Thanks! I like Dislin. But... I don't found the release (binary/win) for Python 2.6... -- Michel Claveau From steve at REMOVE-THIS-cybersource.com.au Fri Oct 17 07:36:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Oct 2008 11:36:54 GMT Subject: xor: how come so slow? References: <48f5d1a5$0$40310$4fafbaef@reader5.news.tin.it> <010845d8$0$20638$c3e8da3@news.astraweb.com> Message-ID: <01087204$0$20638$c3e8da3@news.astraweb.com> On Fri, 17 Oct 2008 22:45:19 +1300, Lawrence D'Oliveiro wrote: > In message <010845d8$0$20638$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Fri, 17 Oct 2008 20:51:37 +1300, Lawrence D'Oliveiro wrote: >> >>> ... why do you say that xoring random data with other random data >> produces less randomness than you started with? > > blocksize <= number_of_blocks * blocksize I must be thick, because that looks like a non sequitor to me. I don't see the relevance. Of course, that's just another way of saying that: 1 <= number_of_blocks and I don't see how this relates to whether xoring random data with other random data decreases the randomness available. >>> c1 = os.urandom(1) >>> c2 = os.urandom(1) >>> c3 = chr( ord(c1)^ord(c2) ) Is it your contention that c3 is more predictable than c1 or c2? If so, why? -- Steven From werner.bruhin at free.fr Thu Oct 23 10:58:41 2008 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Thu, 23 Oct 2008 16:58:41 +0200 Subject: logging module Message-ID: <49009121.6060606@free.fr> I am starting to use the logging module. Simple log to file and/or console work very nicely. Even managed to get TimedRotatingFileHandler to work. The problem I am trying to solve. 1. I would like to have a "log viewer" a wxPython based app to be able to look at a log generated by another script. Did a little test for this. - log_testing.py attached is generating the log entries - log_viewerConsole.py is trying to attach to the same logger (would convert/change this to a wxPython app) The log_viewerConsole script only sees the logs it generates. Does this script have to be started by the first one to get the same logger? Any hints on how to solve my problem would be very appreciated. Werner -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pyg_log.cfg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: log_testing.py Type: text/x-python Size: 571 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: log_viewerConsole.py Type: text/x-python Size: 466 bytes Desc: not available URL: From luca.ciciriello at email.it Fri Oct 3 02:26:24 2008 From: luca.ciciriello at email.it (luca.ciciriello at email.it) Date: Fri, 3 Oct 2008 08:26:24 +0200 Subject: python-2.6 Message-ID: <4919c541232513455c9175dc454a61f1@85.18.140.153> Strange things happens. I've download the installer package for Mac of Python 2.6 and I've launched it. When finished, I've launched from a terminal the command "Python" and all worked fine The response was "Python 2.6 etc...". Now I've launched IDLE. Nothing. IDLE icon blinked a couple of time in dock and then disapeared. I've disabled any firewall in the system but the behavior was the same. I've repared the privilege and restarted the system. A disaster. The system was dramatically slow and IDLE was still not starting. Then I've reinstalled Python 2.5.2 an all was working fine again (included IDLE and System speed). What is wrong with Python 2.6 on my system (MacOS X 10.4.11 PPC)? --------- Original Message -------- Da: Terry Reedy To: python-list at python.org Oggetto: Re: python-2.6 Data: 03/10/08 03:41 > > > > luca.ciciriello at email.it wrote: > > Hi all. > > > > I've installed on may MacOS X 10.4.11 (PPC) Python-2.5.2, numpy and scipy. > > Now I'm interested to insall Python-2.6. My question is: What will happen to > > may scientific modules if now I jump fro 2.5.2 to 2.6? I've to reinstall > > numpy and scipy? > > Keep your 2.5.2 install intact until you have everything you need and > want in a 2.6 install. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- Email.it, the professional e-mail, gratis per te: http://www.email.it/f Sponsor: CheBanca! La prima banca che ti d? gli interessi in anticipo. Fino al 4,70% sul Conto Deposito, zero spese e interessi subito. Aprilo! Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7919&d=20081003 From daniel.watrous at gmail.com Thu Oct 2 12:18:17 2008 From: daniel.watrous at gmail.com (Daniel) Date: Thu, 2 Oct 2008 09:18:17 -0700 (PDT) Subject: Sample code required to validate a xml file against XSD References: Message-ID: <9b85172e-83e0-407f-9980-4c4a8e59cb74@64g2000hsm.googlegroups.com> On Oct 2, 7:32?am, hrishy wrote: > Hi > > Does anybody have a python xample program to validate a xml file against a XSD. > > regards > Hrisy I just googled "python validate a xml file against XSD" and found this: http://mail.python.org/pipermail/xml-sig/2003-March/009244.html hope it helps. Daniel From jason.scheirer at gmail.com Thu Oct 9 14:44:01 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 9 Oct 2008 11:44:01 -0700 (PDT) Subject: Safe eval of insecure strings containing Python data structures? References: <896B75251BA19745A529B1B867893FA50677D6@planet.delsci.local> <7x7i8hvjur.fsf@ruckus.brouhaha.com> Message-ID: On Oct 9, 9:01?am, Paul Rubin wrote: > Lie Ryan writes: > > in python 2.6, ast.literal_eval may be used to replace eval() for > > literals. > > What happens on literal_eval('[1]*999999999') ? The documentation clearly states that it will fail to evaluate and raise a ValueError because there is an operation in the statement. 5*5 is NOT the literal 25, it is the equivalent to operator.mul(5, 5), and the same is true to []*x From steve at holdenweb.com Tue Oct 7 20:43:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Oct 2008 20:43:58 -0400 Subject: Race condition when generating .pyc files In-Reply-To: References: Message-ID: yogamatt1970 at gmail.com wrote: > I have a large body of Python code which runs on many different (Unix) > machines concurrently. Part of the code lives in one place, but most > of it lives in directories which I find at runtime. I only have one > copy of each Python source file and I think I'm hitting a race > condition where two hosts attempt to import the same module at the > same time. My import fails on one of the machines and the following > exception is thrown: > EOFError: EOF read where object expected > My hypothesis is that there's contention between the two (or more) > hosts when the module's .pyc file is generated. > > Possible solutions I see: > 1) Running a cron job before my code executes which compiles all the > python source first. > 2) Making separate copies of all the .py files for each host running > the code - I'd rather not do this, it seems like a big pain. > 3) Inhibiting the generation of .pyc files altogether if that's even > possible - I saw a PEP for a possible -R flag (http://www.python.org/ > dev/peps/pep-0304/) but I don't think it has been added to a released > version of Python yet plus I am stuck with Python 2.4 for the time > being. > > Any and all help appreciated. Are you using the same version of Python on all the hosts that are using the code? If not, the different versions will be forever arguing about whether the .pyc files need recompiling. Just a thought ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From vincehofmeister at gmail.com Wed Oct 22 18:34:39 2008 From: vincehofmeister at gmail.com (vincehofmeister at gmail.com) Date: Wed, 22 Oct 2008 15:34:39 -0700 (PDT) Subject: Py2exe and Module Error... Message-ID: Hey everyone: I am using py2exe and everything is working fine except one module, ClientCookie, found here: http://wwwsearch.sourceforge.net/ClientCookie/ Keeps coming up as not found no matter what I do. I have tried all these combinations from the command line: python run.py py2exe - Results in "following modules appear to be missing" [ClientCookie] python run.py py2exe -p ClientCookie - Results in "No module named ClientCookie" python run.py py2exe -i ClientCookie - Results in "No module named ClientCookie" Ok, so that wasn't the problem I guess so now I try two different combinations of the run.py file... they look like this: #!/usr/bin/env python from distutils.core import setup import py2exe #setup(windows=['C:\\exe\\new_pound.py']); setup(windows=[{"script" : "C:\\exe\\pos_final2.py"}], options={"py2exe" : {"includes" : ["sip"]}}) ^this just gives me the standard "following modules appear to be missing" [ClientCookie] #!/usr/bin/env python from distutils.core import setup import py2exe #setup(windows=['C:\\exe\\new_pound.py']); setup(windows=[{"script" : "C:\\exe\\pos_final2.py"}], options={"py2exe" : {"includes" : ["sip", "ClientCookie"]}}) ^this gives the error "No module named ClientCookie Ok so I am really in a crunch and have no idea what to do. Any help would be GREATLY appreciated. Vince P.S. I know ClientCookie is a branch of mechanize, but I don't understand how it runs fine on my machine using import ClientCookie and then when using py2exe it doesn't find it. I have tried from mechanize import ClientCookie and many alternatives but none of those work on importing the ClientCookie module normally without py2exe. From bruno.42.desthuilliers at websiteburo.invalid Tue Oct 28 12:30:17 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 28 Oct 2008 17:30:17 +0100 Subject: explanation of values, references, assignment, and method calls In-Reply-To: References: Message-ID: <49073e11$0$4533$426a34cc@news.free.fr> Joe Strout a ?crit : > I've tried to write up this topic in a clear, step-by-step manner, with > the help of diagrams and short examples from several different OOP > languages. I hope it will help clear up the confusion that seems to be > pervading the Python community May I suggest http://effbot.org/zone/call-by-object.htm ? From bdesth.quelquechose at free.quelquepart.fr Mon Oct 20 13:07:34 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 19:07:34 +0200 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: References: <48FAE71B.2080205@gmail.com> <880dece00810190123n1aaffabfrd5e89178f7bee0d4@mail.gmail.com> Message-ID: <48fcd6b6$0$21327$426a74cc@news.free.fr> Stef Mientki a ?crit : (snip) > I'm very satisfied with Python, and must say it's much more beautiful > language than Delphi, seen over the full width of programming. > Although both languages are Object Oriented, I think you can lowercase those two last words - it's not a religion, you know ?-) > for some (unknown) reason it's 10 times easier to maintain and extend > libraries in Python than in Delphi. > I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! Err... Dynamism ?-) From castironpi at gmail.com Fri Oct 10 12:33:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 10 Oct 2008 09:33:44 -0700 (PDT) Subject: extracting null pointer address from PyCObject with ctypes References: Message-ID: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> On Oct 10, 5:24?am, Gordon Allott wrote: > Hello :) > > The result of various incompatibilities has left me needing to somehow > extract the address that a null pointer is pointing to with the null > pointer being exposed to python via PyCObject_FromVoidPtr > > the code that creates the PyCObject is as follows: > ? ? tmp = PyCObject_FromVoidPtr (info.info.x11.display, NULL); > ? ? PyDict_SetItemString (dict, "display", tmp); > ? ? Py_DECREF (tmp); > Did you try: tmp= PyLong_FromLong( ( long ) info.info.x11.display ); PyDict_SetItemString (dict, "display", tmp); Py_DECREF (tmp); Or also try: PyCObject_AsVoidPtr( tmp ); From http Sun Oct 19 01:57:54 2008 From: http (Paul Rubin) Date: 18 Oct 2008 22:57:54 -0700 Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> <7d4ef244-39bd-4c4b-a412-3cb0a23e507e@e2g2000hsh.googlegroups.com> <010aa307$0$20653$c3e8da3@news.astraweb.com> Message-ID: <7xod1hxh25.fsf@ruckus.brouhaha.com> "James Mills" writes: > > for x in (2**i for i in xrange(10)): > > print x > This is by far the most concise solution I've seen so far. print '\n'.join(str(2**i) for i in xrange(10)) From half.italian at gmail.com Wed Oct 8 14:54:12 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 8 Oct 2008 11:54:12 -0700 (PDT) Subject: Using subprocess module to launch a shell shell script that itself forks a process References: <55ad9b25-96f2-40d9-8eb9-f7ddb95e135e@u29g2000pro.googlegroups.com> Message-ID: <13218efb-2506-4e92-857d-2daf65b8ff22@b38g2000prf.googlegroups.com> On Oct 8, 11:24?am, "Samuel A. Falvo II" wrote: > On Oct 7, 6:23?pm, "Gabriel Genellina" wrote: > > > Is your shell script doing something else, apart from invoking the java ? > > process? > > Obviously, yes. ?The script is some 150 lines long. ?But the hang-up > occurs because of the forked Java process, not the other lines. > > > If not, you could just invoke java directly from Python. Also, ? > > you set stdin=PIPE - is your java process expecting some input? you're not ? > > writing anything to stdin. > > It does not expect input from stdin. ?However, this does not affect > any OTHER scripts or commands I run. > > Let's remember to look at the objective facts: for shell scripts that > launch child processes of their own, Python hangs. ?For all other > types of commands, it works 100% as expected. > > > Anyway, it's better to use the communicate method instead (it uses select ? > > to read from both stdout and stderr): > > That doesn't help me. > > > See ?http://docs.python.org/library/subprocess.html#subprocess.Popen.commu... > > I have. You should be nicer to Gabriel. He is a guru. From vlastimil.brom at gmail.com Thu Oct 2 17:54:19 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 2 Oct 2008 23:54:19 +0200 Subject: Regular expressions question In-Reply-To: <73045cca0810021338q1bff8129l64733435d192f987@mail.gmail.com> References: <73045cca0810021338q1bff8129l64733435d192f987@mail.gmail.com> Message-ID: <9fdb569a0810021454jbbe1999p47a440a0c2751e1c@mail.gmail.com> 2008/10/2 aditya shukla > Hello folks , > > I trying to match a pattern in a string , i am new in using re .This is > what is happening > > When i do this > > p = re.compile('(\[&&NHX:)') > >>> m = p.match("[&&NHX:C=0.195.0]") > >>> print m > <_sre.SRE_Match object at 0x013FE1E0> > --- thus i am able to find the match > but when i use the string > > m = p.match("-bin-ulockmgr_server:0.99[&&NHX:") > >>> print m > None > -i am not able to find the match . > > Can someone help me here. > > Thanks > > Aditya > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, You may want to check the re documantation - chapter Matching vs Searching http://docs.python.org/library/re.html#matching-vs-searching "... match checks for a match only at the beginning of the string ..." >>> import re >>> p = re.compile('(\[&&NHX:)') >>> p.match("[&&NHX:C=0.195.0]") <_sre.SRE_Match object at 0x01C2FEA0> >>> p.match("-bin-ulockmgr_server:0.99[&&NHX:") >>> p.search("-bin-ulockmgr_server:0.99[&&NHX:") <_sre.SRE_Match object at 0x01C2FF60> >>> p.findall("-bin-ulockmgr_server:0.99[&&NHX:") ['[&&NHX:'] >>> hth vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From andy55 at gmail.com Fri Oct 24 10:58:52 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Fri, 24 Oct 2008 07:58:52 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <6m974kFfs9nlU1@mid.individual.net> <51fb3c73-278c-4919-a330-9cdaa9a6a50d@e2g2000hsh.googlegroups.com> <940ffec5-8294-4dbb-a773-df110594344e@79g2000hsk.googlegroups.com> <4ebbfbf7-e474-4e93-b5b0-1a1d5b0df704@a70g2000hsh.googlegroups.com> Message-ID: > That aside, the fundamental problem is what I perceive a fundamental > design flaw in Python's C API. In Java JNI, each function takes a > JNIEnv* pointer as their first argument. There ?is nothing the > prevents you from embedding several JVMs in a process. Python can > create embedded subinterpreters, but it works differently. It swaps > subinterpreters like a finite state machine: only one is concurrently > active, and the GIL is shared. Bingo, it seems that you've hit it right on the head there. Sadly, that's why I regard this thread largely futile (but I'm an optimist when it comes to cool software communities so here I am). I've been afraid to say it for fear of getting mauled by everyone here, but I would definitely agree if there was a context (i.e. environment) object passed around then perhaps we'd have the best of all worlds. *winces* > > > This is discussed earlier in the thread--they're unfortunately all > > out. > > It occurs to me that tcl is doing what you want. Have you ever thought > of not using Python? Bingo again. Our research says that the options are tcl, perl (although it's generally untested and not recommended by the community--definitely dealbreakers for a commercial user like us), and lua. Also, I'd rather saw off my own right arm than adopt perl, so that's out. :^) As I mentioned, we're looking to either (1) support a python dev community effort, (2) make our own high-performance python interpreter (that uses an env object as you described), or (3) drop python and go to lua. I'm favoring them in the order I list them, but the more I discuss the issue with folks here, the more people seem to be unfortunately very divided on (1). Andy From AlcariTheMad at gmail.com Sun Oct 26 21:53:50 2008 From: AlcariTheMad at gmail.com (Alcari The Mad) Date: Sun, 26 Oct 2008 17:53:50 -0800 Subject: Immutable object thread-safety In-Reply-To: References: <4f19db70-1c2a-41d1-97ae-f8b19f303ce1@34g2000hsh.googlegroups.com> Message-ID: Laszlo Nagy wrote: > >> Also, the other question is the operation st = 'ThreadBWasHere' is >> atomic? > I think this is the same question. And I believe it is not atomic, > because it is actually rebinding a name. Consider this: > > a,b = b,a > > This will rebind both a and b. In order to be correct, it MUST happen in > two phases: first calculate the right side, then do the rebind to the > names on the left side. The expression on the right side can be anything > that executes for a long time, and can even rebind 'a' and 'b' several > times, and will probably be paused by other threads etc. So the > assignment above cannot be atomic. You are correct. a,b = b,a yields the bytecode: 1 0 LOAD_NAME 0 (b) 3 LOAD_NAME 1 (a) 6 ROT_TWO 7 STORE_NAME 1 (a) 10 STORE_NAME 0 (b) Which is most definitely not atomic. > > I strongly feel that if such an assignment is not atomic for "a,b = b,a" > then int wont be atomic for "a+=b" or eveb "a=b" or any other > assignment. However, I can be completely wrong. :-) 'a = b' requires two bytecodes: 1 0 LOAD_NAME 0 (b) 3 STORE_NAME 1 (a) >> I mean, if Python does not guarantee if an immutable object >> assignment is atomic, then how can we say that the object is thread- >> safe? > An assigment rebinds name to an object. It is assignment to a name. > Assigning immutable and mutable objects to names are not specially > distinguished. >> So, if it is an atomic operation, which operators are atomic, >> means only assignment'='? > I don't think that '=' operator is atomic, see above. >> I am confused about which data structure to rely on thread-safety, or >> operator in Python? >> > The immutable object itself will never change state, so it is thread > safe. The problem is not with the object, but the dictionary which holds > the name 'b' and 'a' and 'st' in your example. It is mutable, and so > must be protected in a threaded application. I would suggest reading up on using the 'with' statement and thread.allocate_lock(). > > Best, > > Laszlo > From ccronan at mixcom.com Thu Oct 23 02:14:15 2008 From: ccronan at mixcom.com (Chuck Cronan) Date: Thu, 23 Oct 2008 01:14:15 -0500 Subject: "Music Theory Programming" Google Group Message-ID: Outstretched (Omar?) Today I answered a query you presented two years ago about programming music at VBAX, "Using Arrays and Indexes To Manipulate Variables ( A Music Project )". I don't know if you solved it but I realized that the notes and MIDI codes actually follow a base 12 (duodecimal) system. My response is at: http://www.vbaexpress.com/forum/showthread.php?t=10065 A little confusing (I confused myself) and tried to clear it with a reply to my own note. Using base 12 makes it easy to add key numbers and change the music key. Sorry it was two years too late, but I just joined VBAX today (I hope someone will answer my question but it seems no one is interested). I am not a musician (but I have a piano I want to sell). Chuck Charles L. Cronan, PhD 4239 N. Larkin St Shorewood, WI 53211-1558 414-962-1627 ccronan at mixcom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From incomecash123 at gmail.com Wed Oct 22 20:13:58 2008 From: incomecash123 at gmail.com (jaggu) Date: Wed, 22 Oct 2008 17:13:58 -0700 (PDT) Subject: YOUR INBOX EMAILS WILL GIVE U INCOME-- Message-ID: YOUR INBOX EMAILS WILL GIVE U INCOME-- http://www.youmint.com/network-jagguzwx2 YOUR INCOMMING SMS PAY'S U INCOME-- EARN BY JUST READING SMS ON UR MOBILE http://www.mGinger.com/index.jsp?inviteId=623396 http://www.paisa4sms.com/Index.aspx?Inviteid=134129 IMPORTANT THINGS TO REMEMBER 1. EMAIL VERIFICATION 2. MOBILE VERIFICATION 3. PROFILE COMPLETING. { HEART SURGERY FREE OF COST FOR CHILDRENS, "SRI SATYA SAI INSTITUTE" "BANGLORE" PH: 08028411500 } PLEASE PASS THIS MESSAGE TO ALL IT MAY BE HELPFUL TO SOMEONE...... ADD YOUR NAME PLSSSS JAGADISH, IBRAHIM, DHARNIDHAR, DAYAKAR RAO, SAMIKSHYA DUGGAL RAMI REDDY, SUMALATHA, VENA, RANJIT, PETER, PASURAM, LAKSHMI, NAROTHAM RAO VENKAT, PERMASH, RAMESH, RATHI , SUSHANT SAI, DEVISREE,GOPI, DIVYASHREE, SRINIVAS,HARI BABU,PADMAJA RANI, SAVITRI, JAWHAR, if u have any quries pls contact me at clickit1137 at gmail.com From grante at visi.com Mon Oct 20 21:12:00 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 20 Oct 2008 20:12:00 -0500 Subject: Porting VB apps to Python for Window / Linux use References: <48fcd5c3$0$8723$426a34cc@news.free.fr> <87d4huq3rr.fsf@asus-190829777.TeleWell.gateway> Message-ID: On 2008-10-20, Stef Mientki wrote: >> I don't think I'm feeding the troll, but - ever took a look at >> PyQt? > > I wanted to go from Delphi to a free / open source > environment, for both open source and commercial applications. > > So the Qt license stopped me from looking any further. The Qt license is still free/open-source for commercial applications as long as you license your app under the GPL. Did you mean to say for both open source and closed source applications? -- Grant From alessio211734 at yahoo.it Tue Oct 21 10:44:36 2008 From: alessio211734 at yahoo.it (alessio211734) Date: Tue, 21 Oct 2008 07:44:36 -0700 (PDT) Subject: p2exe for python 2.6 Message-ID: <8746cfb1-af94-4ddd-92a2-ff559e468f94@v72g2000hsv.googlegroups.com> Hi! How can convert my python script in exe for the python version 2.6? Thanks in adavance. Ale. From prologic at shortcircuit.net.au Mon Oct 27 03:31:52 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 27 Oct 2008 17:31:52 +1000 Subject: Improving interpreter startup speed In-Reply-To: References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> <5b8d13220810262215k16991346w9153bd37c31c409a@mail.gmail.com> Message-ID: On Mon, Oct 27, 2008 at 3:36 PM, Terry Reedy wrote: > It this a theoretical problem or an actual one, that we might have other > suggestions for? Heaven knows! I hardly think invoking hundreds and possibly thousands of short-lived python interpreters to be an optimal solution that may have spawned this particular thread. --JamesMills -- -- -- "Problems are solved by method" From mccredie at gmail.com Mon Oct 27 12:55:31 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 27 Oct 2008 09:55:31 -0700 (PDT) Subject: Limit between 0 and 100 References: Message-ID: On Oct 25, 1:42?pm, chemicalcloth... at temple.edu wrote: > Hi. I'm very new to Python, and so this is probably a pretty basic > question, but I'm lost. I am looking to limit a float value to a > number between 0 and 100 (the input is a percentage). > > I currently have: > > integer = int() > running = True > > while running: > ? try: > ? ? per_period_interest_rate = float(raw_input("Enter per-period > interest rate, in percent: ")) > ? ? break > ? except ValueError: > ? ? print "Please re-enter the per-period interest rate as a number > between 0 and 100." > > I also have to make sure it is a number and not letters or anything. > > Thanks for the help. > > James > > P.S. I don't understand a lot of what I have there, I got most of it > from the beginning tutorials and help sections. I have never > programmed before, but this is for a school assignment. You aren't very far off. You are going to need to use 'if' and '<' or '>' to check for range though. As in: if x > 10: print "x is greater than 10" OR: if 10 < x < 20: print "x is between 10 and 20" If you describe exactly what it is that you don't understand, people here will be willing to help you to understand it. However, you will find that people here are very unwilling to do your homework for you. Matt From p.f.moore at gmail.com Thu Oct 2 18:45:56 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 2 Oct 2008 23:45:56 +0100 Subject: Suppressing Python wanings globally In-Reply-To: <20081002224214.29191.2129673222.divmod.quotient.33018@ohm> References: <79990c6b0810021539r687ef9d0hd98b7e322497a021@mail.gmail.com> <20081002224214.29191.2129673222.divmod.quotient.33018@ohm> Message-ID: <79990c6b0810021545t3d7f4934ocfde2ac84b840f79@mail.gmail.com> 2008/10/2 Jean-Paul Calderone : > On Thu, 2 Oct 2008 23:39:29 +0100, Paul Moore wrote: >> >> How can I suppress a Python warning globally (i.e., for all instances >> of Python I run)? I have a test suite that runs Python via >> sys.executable, so the -W flag won't work. A wrapper script doesn't >> work, as sys.executable doesn't point to that. And PYTHONSTARTUP is >> only for interactive use, so that's no good... >> >> Is there an obvious way I've missed? Surely this is a common issue? > > Site-wide configuration is what site customization modules are for. > Check out sitecustomize.py in /usr/lib/python/ or the equivalent > for your platform/installation. Wow, that was quick! Thanks, that will do. In fact, I only want to do this for one session, so an environment variable would be more suitable in theory, but as it's a personal build I can tweak sitecustomize.py for now and get the result I want. Thanks, Paul. From pydecker at gmail.com Thu Oct 2 13:41:18 2008 From: pydecker at gmail.com (Peter Decker) Date: Thu, 2 Oct 2008 12:41:18 -0500 Subject: Database GUI generation from schema In-Reply-To: <92da89760810020924v1991a82bl29fb8d0471a3e84d@mail.gmail.com> References: <48e4877a$0$21313$426a74cc@news.free.fr> <92da89760810020924v1991a82bl29fb8d0471a3e84d@mail.gmail.com> Message-ID: On Thu, Oct 2, 2008 at 11:24 AM, Eric Wertman wrote: >> Perhaps are you talking about dabo ? >> http://www.dabodev.com > > Yes, that was it. Thanks! I was a little dissapointed to see that > the wikipedia entry for that software was deleted. Is dabo not widely > used? Depends on your definition of 'widely'. :) I know that there are several hundred subscribers to the dabo-users list. Perhaps if you asked there you might get a better idea of just how many people use Dabo. I'm curious about the Wikipedia entry. I read the deletion page arguments, but I don't know enough about how the editors decide these things to comment. I wonder what it would take to get it restored? -- p.d. From malaclypse2 at gmail.com Thu Oct 9 19:54:04 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 9 Oct 2008 19:54:04 -0400 Subject: Python HTML parser chokes on UTF-8 input In-Reply-To: <4m72s5xlgn.ln2@joeserver.homelan.net> References: <4m72s5xlgn.ln2@joeserver.homelan.net> Message-ID: <16651e80810091654m1af0b6ebq359782e8e2309e8d@mail.gmail.com> On Thu, Oct 9, 2008 at 4:54 PM, Johannes Bauer wrote: > Hello group, > > Now when I take "website" directly from the parser, everything is fine. > However I want to do some modifications before I parse it, namely UTF-8 > modifications in the style: > > website = website.replace(u"f??", u"b?r") That's not utf-8, that's unicode. Even if your file is saved as utf-8, you're telling python to convert those from utf-8 encoded bytes to unicode characters, by prefixing them with 'u'. > Therefore, after fetching the web site content, I have to convert it to > UTF-8 first, modify it and convert it back: You have to convert it to unicode if and only if you are doing manipulation with unicode stings. > website = website.decode("latin1") > website = website.replace(u"f??", u"b?r") > website = website.encode("latin1") > > This is incredibly ugly IMHO, as I would really like the parser to just > accept UTF-8 input. However when I omit the reecoding to latin1: You could just use the precise Latin-1 byte strings you'd like to replace: website = website.replace("f\xf6\xf6", "b\xe4r") Or, you could set the encoding of your source file to Latin-1, by putting the following on the first or second line of your source file: # -*- coding: Latin-1 -*- Then use the appropriate literals in your source code, making sure that you save it as Latin-1 in your editor of choice. Truthfully, though, I think your current approach really is the right one. Decode to unicode character strings as soon as they come into your program, manipulate them as unicode, then select your preferred encoding when you write them back out. It's explicit, and only takes two lines of code. -- Jerry From eckhardt at satorlaser.com Thu Oct 30 05:02:35 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 30 Oct 2008 10:02:35 +0100 Subject: Ascii codec can't encode References: Message-ID: luca72 wrote: > hello i have this problem: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 8: ordinal not in range(128) This is the result of transcoding a Unicode string to ASCII, where the Unicode string contains a character that is not representable in ASCII. This happens to me when I try to print such a character because my console is set to ASCII. > Generally i solve the problem inserting : > # -*- coding: ISO-8859-1 -*- > at the top of the file but now he don't work can you help me This only tells Python that your sourcecode uses Latin 1 as encoding. It doesn't affect other files or any input or output streams. What code exactly triggers the error? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From storey.craig at gmail.com Mon Oct 6 14:20:24 2008 From: storey.craig at gmail.com (cstorey) Date: Mon, 6 Oct 2008 11:20:24 -0700 (PDT) Subject: When Python should not be used? References: Message-ID: <7184b461-52e1-468f-bf83-e47c5b52213d@d45g2000hsc.googlegroups.com> On Oct 6, 2:07?pm, Stef Mientki wrote: > and I'm working on a large application, > which should be open source replacement for MatLab + LabView. > > cheers, > Stef An Open Source Labview replacement would be really useful! Any preview of the project? Craig From ewertman at gmail.com Thu Oct 2 12:24:25 2008 From: ewertman at gmail.com (Eric Wertman) Date: Thu, 2 Oct 2008 12:24:25 -0400 Subject: Database GUI generation from schema In-Reply-To: <48e4877a$0$21313$426a74cc@news.free.fr> References: <48e4877a$0$21313$426a74cc@news.free.fr> Message-ID: <92da89760810020924v1991a82bl29fb8d0471a3e84d@mail.gmail.com> > Perhaps are you talking about dabo ? > http://www.dabodev.com Yes, that was it. Thanks! I was a little dissapointed to see that the wikipedia entry for that software was deleted. Is dabo not widely used? From castironpi at gmail.com Sun Oct 5 22:23:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 5 Oct 2008 19:23:41 -0700 (PDT) Subject: lint for Python? References: <3f8bef54-ab51-4e93-bc68-bcb35e8afc61@v30g2000hsa.googlegroups.com> Message-ID: On Oct 5, 8:53?am, Pat wrote: > Miki wrote: > > Hello, > > >> In module one, I have a function: > > >> def foo( host, userid, password ): > >> ? ? ?pass > > >> In module two, I call that function: > > >> foo( userid, password) > > >> lint doesn't find that error and it won't be caught until it's called > >> while the program is running. > > pychecker does find these kind of errors. > > Before posting my original question, I tried pychecker and it didn't > catch that error. Sorry for the multiple posting earlier (you heard me right, not 2 but 3 identical). The basic checker of walking a parse tree, doing imports by hand, and checking call signatures isn't awful. 60 lines. /File: from ng23mod1 import foo as foo userid, password= 'abc', '123' import random foo( 'localhost', userid, password) if random.uniform( 0, 1 )< .01: # 1 out of 100 times foo( userid, password) /Checker output: foo ['Str', 'Name', 'Name'] found 3 expected random ['Num', 'Num'] found 2 expected foo ['Name', 'Name'] found 3 expected But it's extremely delicate and at 60 lines only checks fixed-length call signatures and functions, not even methods. If you have a statement: x= y.z() Then 'y' has to be defined somewhere, so you could make some educated guesses that way. From rtw at freenet.co.uk Tue Oct 14 07:43:01 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 14 Oct 2008 06:43:01 -0500 Subject: Reading from stdin (in windows) References: Message-ID: durumdara at gmail.com wrote in news:mailman.2448.1223974725.3487.python- list at python.org in comp.lang.python: > Hi! > > I wanna write a file processor in python (Windows XP). > I wanna use pipe, and not parameters. > > When I write this: > > ... > l = [] > while 1: > t = sys.stdin.read(1) > if t == '': > break > l.append(t) > > t = "".join(l) > ... > > and use code this: > process.py > I got: > "Bad file descriptor" > > What I do wrong? I need to call this module in another format? > Or I read in wrong way? > The problem appear to be that MS-Windows doesn't make pipe's for programs it opens via its file type association mechanism. Essentially MS-Windows is treating the .py file as a document and using python to "open" the document. Try running you program as: python process.py <92da89760810191049s7d0fa4e5p675ae584d7b7bfbc@mail.gmail.com> <010c6145$0$20670$c3e8da3@news.astraweb.com> Message-ID: <010fefe5$0$20657$c3e8da3@news.astraweb.com> On Tue, 21 Oct 2008 10:00:35 -0500, Grant Edwards wrote: >> It is true that all kinds of programs will create .app files in your >> home dir which is not very polite. > > It _is_ polite. Polite means following the established rules and doing > what's expected of you. That's exactly what is expected of applications > under Unix. In medieval Russia, the Rus vikings (from whom modern Russia gets its name) used to live in communal log huts. In the morning, a slave would bring along a great big steaming bowl of water for the Rus to wash their faces in. *One* bowl. The first person would wash his face, blow his nose and spit in the bowl, then pass it on to the next person, who would repeat all down the line. This was the established social rules and everybody did what was expected of them. It was also as rude as hell, and not just because "rude" also means "unpolished, uncultured". Putting preferences files in the user's top level directory is horribly inconvenient for the user. It clutters their home directory. The old-time Unix people recognised this, and made the files hidden so that their mess wasn't visible. It certainly wasn't to protect the user from themselves, because their users were other old-time Unix geeks who not only were comfortable editing config files but expected to be able to. No, the only reason for hiding the config files was because otherwise the user's home directory would be too messy. But of course all that means is that you avoid the mess so long as you don't look at it. I have 125 dot files in my home directory. They include "temporary" files from programs I haven't run in months, settings from applications I haven't even heard of (where the hell did ".parallelrealities" come from?), log files, lock files and other dross that has no place scattered across my home directory. Half of these files contain important data which users will invariably miss when making backups, and half of them are junk that don't need to be copied when making backups (e.g. .thumbnails, .Trash), but there's no easy way to include some while excluding others. It may be expected, but it is still inconsiderate and just plain *stupid*. A thirty year old stupidity is still a stupidity. It would have been easy to avoid this: just copy the relevant bits of the / directory hierarchy in the user's home directory. Global settings go in /etc and per user settings go in ~/etc. Global temp files go into / tmp and per user temp files go into ~/tmp. And so forth. Nice, neat and perfectly easy to implement and easy to deal with. -- Steven From Eric_Dexter at msn.com Fri Oct 3 09:44:08 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 3 Oct 2008 06:44:08 -0700 (PDT) Subject: tkinter question Message-ID: <538f4349-02a1-4c2b-b892-a01f1f48cb5b@l64g2000hse.googlegroups.com> I saw this (close to this anyway) lieing around on the internet and was wanting to use it to define a start point exc but I need the graphics to stay within a set y coords and I am not realy sure how to do that. I have no idea on how to bind a min/max y to it. (the concept is inspired by the java csound blue). #!/usr/bin/python from Tkinter import * import csoundroutines as cs root = Tk() global canv xx = {} def makeFrame(root): global canv test = cs.csdInstrumentlist3('bay-at-night.csd') canv = Canvas (root, height = 200, width = 350) for i in range (0, len(test.instr_number)): canv.create_text(10, i *10, text=str(test.instr_number[i]) + '...', tags=('movable')) xx[i] = canv.tag_bind('movable', '', slide) #B1-motion is a drag with left button down canv.pack() def slide (event): ''' triggered when something is dragged on the canvas - move thing under mouse ('current') to new position ''' newx = event.x if event.y < 10 and event.y > 0: newy = event.y canv.coords('current', newx, newy) makeFrame(root) root.mainloop() From Pat at junk.com Mon Oct 20 10:20:03 2008 From: Pat at junk.com (Pat) Date: Mon, 20 Oct 2008 10:20:03 -0400 Subject: question regarding list comprehensions Message-ID: I have written chunks of Python code that look this: new_array = [] for a in array: if not len( a ): continue new_array.append( a ) and... string = "" for r in results: if not r.startswith( '#' ): string =+ r It seems that a list comprehension could clean up the code, but I seem to have a mental block on list comprehensions. I've read up a lot on this subject in my books and on the Internet and for whatever reason, I'm having problems with this idiom (if that's the correct expression). I've made a number of attempts to solve this on my own but I keep getting errors. Could someone please tell me how I could convert the above code to something more elegant but readily understandable? Finally, if someone could point me to a good tutorial or explain list compressions I would be forever in your debt. From clp at rebertia.com Sun Oct 19 05:42:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 19 Oct 2008 02:42:25 -0700 Subject: default value in __init__ In-Reply-To: <256f2adc-184c-4e18-993e-b8e031febcd0@v72g2000hsv.googlegroups.com> References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <256f2adc-184c-4e18-993e-b8e031febcd0@v72g2000hsv.googlegroups.com> Message-ID: <47c890dc0810190242p64796149tfa9d018b3659e6fb@mail.gmail.com> On Sun, Oct 19, 2008 at 12:56 AM, Paul McGuire wrote: > On Oct 14, 1:36 pm, "David C. Ullrich" wrote: >> > Well... How to say.. Is there any chance these people will read anything >> > *at all* ? >> >> No. That's exactly the point! Basic Python is so transparent that >> you can start using it without reading anything, just looking at >> a few examples. _Because_ of that it's their responsibility to >> ensure that if you look at a few examples you then have a complete >> understanding of the language. >> > I agree, Python really does strive to be intuitive and easy-to-learn. > So the oddity of the behavior of "optional_list_arg=[]" is a recurring > surprise to those who jump first and read documentation later. > Besides the tutorials, reference docs, and FAQs, there are also some > web pages with titles like "Python Gotchas" and "Common Mistakes in > Python" that usually tread this ground too. Specifically: http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html?page=2 http://www.ferg.org/projects/python_gotchas.html#contents_item_6 http://zephyrfalcon.org/labs/python_pitfalls.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > >> In particular default parameters should work the way the user >> expects! The fact that different users will expect different >> things here is no excuse... >> > Are you being sarcastic? Short of "import mindreading", I don't know > how Python would know which behavior a given user would expect. Maybe > instead of a "code smell", this particular Python wart is a "design > smell". > > What is surprising is that Python cannot discriminate between this: > y = 100 > def f(a,x=y): > print a+x >>>> f(1) > 101 >>>> y=200 >>>> f(1) > 101 > > and this: > > def f(a,x=[]): > print a+len(x) > x.append(a) >>>> f(1) > 1 >>>> f(1) > 2 >>>> f(1,[1,2,3]) > 4 >>>> > > Is x supposed to be a default arg or a "static" arg (in the sense of a > static var within a function as one finds in C)? > > -- Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Wed Oct 29 08:55:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 29 Oct 2008 05:55:12 -0700 (PDT) Subject: Improving interpreter startup speed References: <740c3aec0810251823q17f61011l442bb1b69a45f17e@mail.gmail.com> <740c3aec0810261045wc2e155fm18c906c58abab649@mail.gmail.com> Message-ID: <4c1287ad-50d8-456a-a6cc-90d8a43a68e9@d70g2000hsc.googlegroups.com> Terry Reedy: > The current developers, most of whom use Python daily, [...] Thank you for bringing some light in this thread so filled with worse than useless comments. Bye, bearophile From birarai at gmail.com Fri Oct 31 14:40:02 2008 From: birarai at gmail.com (BiraRai) Date: Fri, 31 Oct 2008 11:40:02 -0700 (PDT) Subject: convert string literal to object attribute Message-ID: <6f5a1bb7-e89d-4062-b23d-7db45de58b95@c22g2000prc.googlegroups.com> def getAttributeForProperty(self,rollnumber,attribute): # attribute have the value _ward ''' If year is null then use current year. Returns the value of the attribute for the given roll number ''' print 'Searching for attribute', attribute for index, i in enumerate(self._aa): if (rollnumber == i._roll_number) and ( hasattr(i,attribute) ) : print index,i.attribute (COMPILER ERROR HERE) return i.attribute return print "\n" return i want i.attribute to be treated as i._ward I get a compile error "instance has no attribute 'attribute' " which i understand. how do i fix this HELP From andy55 at gmail.com Sat Oct 25 16:43:58 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Sat, 25 Oct 2008 13:43:58 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <63d8aa77-f863-4d8c-b135-2088d0b68760@a70g2000hsh.googlegroups.com> Message-ID: On Oct 24, 10:24?pm, Glenn Linderman wrote: > > > And in the case of hundreds of megs of data > > ... and I would be surprised at someone that would embed hundreds of > megs of data into an object such that it had to be serialized... seems > like the proper design is to point at the data, or a subset of it, in a > big buffer. ?Then data transfers would just transfer the offset/length > and the reference to the buffer. > > > and/or thousands of data structure instances, > > ... and this is another surprise! ?You have thousands of objects (data > structure instances) to move from one thread to another? Heh, no, we're actually in agreement here. I'm saying that in the case where the data sets are large and/or intricate, a single top- level pointer changing hands is *always* the way to go rather than serialization. For example, suppose you had some nifty python code and C procs that were doing lots of image analysis, outputting tons of intricate and rich data structures. Once the thread is done with that job, all that output is trivially transferred back to the appropriate thread by a pointer changing hands. > > Of course, I know that data get large, but typical multimedia streams > are large, binary blobs. ?I was under the impression that processing > them usually proceeds along the lines of keeping offsets into the blobs, > and interpreting, etc. ?Editing is usually done by making a copy of a > blob, transforming it or a subset in some manner during the copy > process, resulting in a new, possibly different-sized blob. No, you're definitely right-on, with the the additional point that the representation of multimedia usually employs intricate and diverse data structures (imagine the data structure representation of a movie encoded in modern codec, such as H.264, complete with paths, regions, pixel flow, geometry, transformations, and textures). As we both agree, that's something that you *definitely* want to move around via a single pointer (and not in a serialized form). Hence, my position that apps that use python can't be forced to go through IPC or else: (a) there's a performance/resource waste to serialize and unserialize large or intricate data sets, and (b) they're required to write and maintain serialization code that otherwise doesn't serve any other purpose. Andy From mailtobas_2004 at hotmail.com Sat Oct 11 02:44:59 2008 From: mailtobas_2004 at hotmail.com (Basha J P M) Date: Fri, 10 Oct 2008 23:44:59 -0700 (PDT) Subject: Trouble importing module using swig and python Message-ID: <19930052.post@talk.nabble.com> I am beginner in python. I am working through the tutorial examples from http://www.swig.org/ and have run into some problems. I took the following command instructions from the tutorial on swig.org: http://www.swig.org/tutorial.html I have written example.c and example.i as described in the above tutorial. My first attempt at compiling the libraries was this: $ swig -python example.i it should produce example.py and example_wrap.c files . But i am not getting example.py file in the folder where i am executing swig -python example.i But with example_wrap.c file i can able to produce _example.so shared object like gcc -c example.c example_wrap.c \ -I/vobs/tsp/tools/PYTHON/include/python2.5 gcc -shared example.o example_wrap.o -o _example.so and doing ld -shared example.o example_wrap.o -o _example.so and when iam trying to import from python like import example it is saying no module named example. My first Question is that should i get example.py in folder and second Question is that if it is not neccessary then where i am going wrong ?? Please help me in this regard. regards, basha. -- View this message in context: http://www.nabble.com/Trouble-importing-module-using-swig-and-python-tp19930052p19930052.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Tue Oct 28 12:48:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 28 Oct 2008 09:48:06 -0700 (PDT) Subject: Database specialized in storing directed graphs? References: <829ee8a7-5956-49d7-9465-a83a06537c41@m32g2000hsf.googlegroups.com> Message-ID: <9dedc367-bbb5-4601-aada-9b1995889e18@c22g2000prc.googlegroups.com> Sorry Carl Banks for the answering delay, there are problems in Google Groups. > This is not to study graph theory; I'm using the graph to represent a > problem domain. The graphs could be arbitrarily large, and could > easily have millions of nodes, and most nodes have a substantial > amount of data associated with them. Obviously I don't want a whole > such graph in memory at once, so libraries the just deal with in- > memory graphs are out. It doesn't sound a problem for modern PCs. I think you can keep the whole graph topology in RAM, and the node data on disk (for example in a file or in DB). The topology is represented by the arcs (you have said nothing regarding arc data, so I assume it's absent) and the nodes (in RAM you just need a 32 bit unsigned integer to represent the index of the node that is stored on disk. If memory becomes tight you can use just 3 bytes (2 ^ 24 = 16 millions different nodes) for the nodes, but generally the memory required for the nodes is very little compared to the memory necessary to store the arcs). You haven't said how many arcs there are, total or average for node, and if such arcs are directed or undirected. Anyway, using my Graph class (that stores each arc twice), this takes about 1 minute and 1.3 GB of RAM (1 million nodes, 10 arcs for node): from graph import Graph from random import randrange g = Graph() N = 1000000 g.addNodes(xrange(N)) for i in xrange(N * 10): g.addArc(randrange(N), randrange(N)) You have said "could easily have millions of nodes", and every arc may have tens of arcs or more. ("arbitrarily large" is an unsolvable problem because there are always limits in your program, there's no program that's able to work on an "arbitrarily large" dataset), so Python data structures become too much costly for the RAM. With a lower level language like D/C/C++ you can manage a bigger graph. You can use Boost Graph, but a homemade graph structure may suffice too for your purposes. For the problem you have explained I think a very simple graph representation may suffice: an array of integer pairs (starting_index, len) (starting_index can be a pointer too), where len is the number of outbound arcs of the node n, plus an array of indexes/pointers that list the outbound arcs. If memory gets tight you can split this second array in two, and use an array of bytes for the lengths (if you have more than 256 outbound arcs you may need a short). Note that if you use indexes then a Python array.array (or Numpy) suffices. In this situation if nnodes = 10_000_000 and narcs/node = 40 (total nodes = 40 * 10_000_000): nnodes * narcs * 4 + nnodes * (4 + 4) = 1_680_000_000 bytes, that is often available on modern PCs. On a 64 bit machine the indexes take the same memory, but pointers twice that. In "memory saving" mode: nnodes * narcs * 3 + nnodes * (3 + 1) = 1_240_000_000 bytes. A more handy compromise is: nnodes * narcs * 3 + nnodes * (4 + 4) = 1_280_000_000 bytes. > But then what happens if something changes elsewhere. Regarding the data structure, if you use arrays like I have explained, if your updates aren't much frequent then you can allocate small extra arrays to store more arcs coming out a node (but to do this you probably may enjoy using pointers instead of indexes). When you have a lot of updated you can save all to disk, and then regenerate the whole data structure. Bye, bearophile From eckhardt at satorlaser.com Wed Oct 29 06:11:38 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 29 Oct 2008 11:11:38 +0100 Subject: [2.5.1] "UnicodeDecodeError: 'ascii' codec can't decode byte"? References: Message-ID: Gilles Ganault wrote: > I'm getting this error while downloading and parsing web pages: > > ===== > title = m.group(1) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position > 48: ordinal not in range(128) > ===== > > From what I understand, it's because some strings are Unicode, and > hence contain characters that are illegal in ASCII. You just need to use a codec according to the encoding of the webpage. Take a look at http://wiki.python.org/moin/Python3UnicodeDecodeError It is about Python 3, but the principles apply nonetheless. In any case, throwing the error at a websearch will turn up lots of solutions. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From deets at nospam.web.de Mon Oct 6 09:29:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Oct 2008 15:29:55 +0200 Subject: Class properties and object properties References: <046937d2-fa31-43f9-81de-401fb7e5daeb@q9g2000hsb.googlegroups.com> Message-ID: <6kui6iF9kcqmU1@mid.uni-berlin.de> SuperZE wrote: > Learning python I was rewriting some of my old programs to see the > pros and cons of python when a steped in some weird (at least for me) > behavior. > > Here it is simplified > > The code: > >>>> class Test1: > myList = [4 for n in range(4)] > myInt = 4 >>>> a = Test1() >>>> b = Test1() >>>> a.myList > [4, 4, 4, 4] >>>> a.myInt > 4 >>>> b.myList > [4, 4, 4, 4] >>>> b.myInt > 4 >>>> b.myList[2] = 3 >>>> b.myInt = 3 >>>> b.myList > [4, 4, 3, 4] >>>> b.myInt > 3 >>>> a.myList > [4, 4, 3, 4] >>>> a.myInt > 4 > > > I would not expect the second a.myList to have changed as it did > since, for me, I have only changed b.myList. And also, why only the > list changed and not the integer? > > One thing i tried was: > >>>> class Test2: > myList = [] > myInt = 4 > def __init__(self): > self.myList = [4 for n in range(4)] > >>>> a = Test2() >>>> b = Test2() >>>> a.myList > [4, 4, 4, 4] >>>> b.myList > [4, 4, 4, 4] >>>> b.myList[2] = 3 >>>> b.myList > [4, 4, 3, 4] >>>> a.myList > [4, 4, 4, 4] > > > And as you see it worked as I expected. > > Now the question, why? Because you declare myList to be a *class*-level variable, which means *all* instances of that class (a and b in your case) *share* it. Python does not declare *instance* variables the way you do. Instead, do this: class Foo(object): def __init__(self): self.myList = [] And to avoid a common pitfall you are likely to hit next: default arguments in functions (and methods) are evaluated only *once*, when defined - not later! So def foo(some_arg=[]): some_arg.append("a") print some_arg foo() foo() will result in ['a'] ['a', 'a'] being printed out. Diez From i.am at i.be Wed Oct 8 23:39:26 2008 From: i.am at i.be (mattmatical) Date: Thu, 09 Oct 2008 05:39:26 +0200 Subject: Porn Addiction Solutions? References: <963ea4ac-54e6-4911-9a15-846b86de5cea@u40g2000pru.googlegroups.com> Message-ID: On Wed, 8 Oct 2008 12:30:09 -0700 (PDT), mikejanse at yahoo.com wrote: >You can conquer this thing. Let us know how you make out. > >Regards, > >Mike Now I finally know why this thing is called usenet. Most useful post ever. Matt From steve at holdenweb.com Tue Oct 14 15:59:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Oct 2008 15:59:29 -0400 Subject: Upgrading from 2.5 to 2.6 In-Reply-To: <48f4e9b6$0$16343$9b622d9e@news.freenet.de> References: <9gt4f4934btvoh6cdc1lql61moi0409lmm@4ax.com> <48F2CD0D.2070406@v.loewis.de> <27b3bff1-8388-45d9-af00-8ea6972a0e53@a18g2000pra.googlegroups.com> <48F42D9A.7000601@v.loewis.de> <48f4e9b6$0$16343$9b622d9e@news.freenet.de> Message-ID: <48F4FA21.2010000@holdenweb.com> Martin v. L?wis wrote: >> I'd say the wording in the installer is unfortunate. The option is >> labeled "Register extensions" and for some time I thought it was related >> to .pyd/.dll files ("C extensions"), not "Associate .py files to this >> Python installation" > > Unfortunately, I think this is too long for the available space. > How about "Make default Python"? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From darcymason at gmail.com Wed Oct 22 20:46:51 2008 From: darcymason at gmail.com (Darcy Mason) Date: Wed, 22 Oct 2008 17:46:51 -0700 (PDT) Subject: Dummy explanation to win32com needed References: <563079e6-9458-4ec7-8545-473765899bb3@u28g2000hsc.googlegroups.com> Message-ID: <48338ecc-d948-41f0-9307-a3a4b1cf8b1c@c60g2000hsf.googlegroups.com> On Oct 22, 3:43?pm, korean_dave wrote: > Hi. I need a dummy's explanation to utilizing the win32com component > to access Microsoft Excel. > > So far, I have this code. > > ? ? import win32com.client > ? ? xl = win32com.client.Dispatch("Excel.Application") > ? ? xl.Visible = 1 > > ? ? workbook = xl.Workbooks.Open("C:\test.xls") > > Now, my question is, where do I find the snytax I can use to access > such functions like workbook.ActiveSheet.Cells(1,1).Value etc... > > I need a reference to the API I can utilize. > > Where can I find this? > > Thanks guys, > -Dave I haven't used this in quite some time, but if I recall correctly, it simply follows the object model as found in Excel Help | Visual Basic Reference, or go into the Excel code editor (alt-F11)and use the object browser. One thing to be aware of, IIRC, is that in VB you can leave out some default names (like .Value, .Item for collections) but these must be explicitly referenced when called using win32com. From pavements01 at yahoo.com Wed Oct 8 15:07:34 2008 From: pavements01 at yahoo.com (pavements01 at yahoo.com) Date: Wed, 8 Oct 2008 12:07:34 -0700 (PDT) Subject: Porn Addiction Solutions? Message-ID: Help, I'm addicted to porn. I've been spending a lot of time downloading hardcore porn and masturbating to it. It's ruining my life. I just found out that one of these sites somehow hacked my card and rang up $5K in charges which they won't even refund me. Even with that I haven't stopped my habit and it's only getting worse. How can I end this addiction? Any suggestions? From paul at boddie.org.uk Thu Oct 16 10:17:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 16 Oct 2008 07:17:54 -0700 (PDT) Subject: Best way to spawn process on back end computer References: <1e5e14be-4d24-44c9-8867-76b46dd47573@t41g2000hsc.googlegroups.com> Message-ID: On 16 Okt, 15:51, Robin Becker wrote: > sophie_newbie wrote: > > I'm running a python cgi script on a frontend web server and I want it > > to spawn another script (that takes a long time to run) on a backend > > number crunching server thats connected to the same network. What do > > you think is the best way to do this? I have a few ideas but I'm sure > > there is a "best" way to go about this. > > The main problem here is that you'll probably need to detach the job to allow > the current cgi request to return a response to the client. I've added support for background processes to the pprocess library; this attempts to address the problems around detaching from worker processes and re-attaching to them later in order to collect the results: http://www.boddie.org.uk/python/pprocess/tutorial.html#BackgroundCallable Arguably, this is more complicated than the most basic approach, which would involve having separate, spawned processes just writing to files whose contents would then be passed back to the user or processed in the CGI script, but it's the notification that's the most difficult part, not the data transfer: efficiently getting a notification event, rather than polling stuff frequently, is the main problem. > The implication of that is that the job either has to be anonymous and requires > no further attention or you need to provide some means of making the job > responsive to requests about its status so that a periodic request can be made > by the web page. That implies that the job can be identified and the creation > reponse returns the identity. One of the major problems is that the normal www > user has few privileges and cannot normally write to disk. I've used UNIX sockets as the means of communication between creating/ collecting processes (the CGI script in this case) and the created/ worker processes. Someone suggested an alternative method of binding to kernel-managed namespaces, if I recall the nature of the suggestion correctly, but I haven't looked into this yet. More details here: http://www.boddie.org.uk/python/pprocess.html And for the impatient, a repository is here: https://hg.boddie.org.uk/pprocess Paul From rafesacks at gmail.com Sat Oct 25 23:59:29 2008 From: rafesacks at gmail.com (Rafe) Date: Sat, 25 Oct 2008 20:59:29 -0700 (PDT) Subject: @property decorator doesn't raise exceptions References: Message-ID: <064af395-e6b8-42e8-84d8-dfa1feb384f2@v22g2000pro.googlegroups.com> On Oct 24, 1:47?am, Rafe wrote: > Hi, > > I've encountered a problem which is making debugging less obvious than > it should be. The @property decorator doesn't always raise exceptions. > It seems like it is bound to the class but ignored when called. I can > see the attribute using dir(self.__class__) on an instance, but when > called, python enters __getattr__. If I correct the bug, the attribute > calls work as expected and do not call __getattr__. > > I can't seem to make a simple repro. Can anyone offer any clues as to > what might cause this so I can try to prove it? > > Cheers, > > - Rafe Peter Oten pointed me in the right direction. I tried to reply to his post 2 times and in spite of GoogleGroups reporting the post was successful, it never showed up. Here is the repro: The expected behavior... >>> class A(object): ... @property ... def attribute(self): ... raise AttributeError("Correct Error.") >>> A().attribute Traceback (most recent call last): File "", line 0, in File "", line 0, in attribute AttributeError: Correct Error. The misleading/unexpected behavior... >>> class A(object): ... @property ... def attribute(self): ... raise AttributeError("Correct Error.") ... def __getattr__(self, name): ... cls_name = self.__class__.__name__ ... msg = "%s has no attribute '%s'." % (cls_name, name) ... raise AttributeError(msg) >>> A().attribute Traceback (most recent call last): File "", line 0, in File "", line 0, in __getattr__ AttributeError: A has no attribute 'attribute'. Removing @property works as expected... >>> class A(object): ... def attribute(self): ... raise AttributeError("Correct Error.") ... def __getattr__(self, name): ... cls_name = self.__class__.__name__ ... msg = "%s has no attribute '%s'." % (cls_name, name) ... raise AttributeError(msg) >>> A().attribute() # Note the '()' Traceback (most recent call last): File "", line 0, in File "", line 0, in attribute AttributeError: Correct Error. I never suspected __getattr__ was the cause and not just a symptom. The docs seem to indicate __gettattr__ should never be called when the attribute exisits in the class: "Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception." Is this a bug? Any idea why this happens? I can write a hack in to __getattr__ in my class which will detect this, but I'm not sure how to raise the expected exception. Cheers, - Rafe From badmuthahubbard at gmail.com Thu Oct 30 14:50:22 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Thu, 30 Oct 2008 20:50:22 +0200 Subject: Python suitable for Midi ? In-Reply-To: <878ws73zxt.fsf@agentultra.com> References: <8200bab70810280954l79e0f1a1icfc0308ebdc5c61@mail.gmail.com> <878ws73zxt.fsf@agentultra.com> Message-ID: <8200bab70810301150g2f2cf59dg54cf553be355daa6@mail.gmail.com> On Wed, Oct 29, 2008 at 10:32 PM, J Kenneth King wrote: > > One also has access to nice-levels on unix systems. True enough, but it's not so much a problem for me, as I'm pretty okay at tuning my own system, but I believe most of the people who'd be interested in my app (if any) are not *nix users. At any rate, it's one option for those who are, and thanks for reminding me. -Chuckk -- http://www.badmuthahubbard.com From caseyrodarmor at gmail.com Wed Oct 29 15:46:50 2008 From: caseyrodarmor at gmail.com (Casey Rodarmor) Date: Wed, 29 Oct 2008 20:46:50 +0100 Subject: Dot operator magic has me stymied... Message-ID: <165076d20810291246q3951404di801e951bf4c12b81@mail.gmail.com> Hi All, I'm trying to use a class as a decorator for another class method, but it's giving me a lot of grief. Basically, my problem is with the example below: >>> class decorator: ... def __init__(self, function): ... self.function = function ... ... def __call__(self, *args, **kwargs): ... self.function(*args, **kwargs) ... >>> class Foo: ... def __init__(self): ... self.msg = "Hello," ... ... @decorator ... def greet(self, name): ... print self.msg, name ... >>> foo = Foo() >>> foo.greet("Bob") Traceback (most recent call last): File "", line 1, in File "decorate.py", line 6, in __call__ self.function(*args, **kwargs) TypeError: greet() takes exactly 2 arguments (1 given) I'm guessing that using a decorator that returns a class instance instead of a function instance has messed up the magic of the dot operator, causing it not to bind the foo instance to the self argument. Can anybody shed some light on what's happening here? Also, I really do like using classes as decorators. Are there any workarounds to get it to work with methods? Thanks a bunch! Best regards, Casey Rodarmor From bignose+hates-spam at benfinney.id.au Sun Oct 26 21:31:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2008 12:31:06 +1100 Subject: Porting VB apps to Python for Window / Linux use References: <48fcd5c3$0$8723$426a34cc@news.free.fr> <87d4huq3rr.fsf@asus-190829777.TeleWell.gateway> Message-ID: <874p2y3jtx.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > Software has no market value. Business models that try to assign it > one are doomed to fight an uphill battle against market forces. +1 QOTW. -- \ ?Yesterday I told a chicken to cross the road. It said, ?What | `\ for??? ?Steven Wright | _o__) | Ben Finney From mail at microcorp.co.za Wed Oct 8 00:48:25 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 8 Oct 2008 06:48:25 +0200 Subject: do something in time interval Message-ID: <004e01c92906$1da401c0$0d00a8c0@hendrik> "Petr Jake??" wrote: >"Leon Zhang" wrote: > >> >> I am not an expert, but why not to use time.sleep(5)? >> If you are using wxPython, you may also try wx.Timer, in which you could >> set its interval. >> >> >Thanks for your reply. >During the 5s period my script has to do some stuff instead of sleeping. >Thats why it runs in the loop and once in 5s period it has to trigger some >other stuff(function, method, action) to do. import time while True: end_time = time.time() + 5 while time.time() < end_time: do_the_in_between_stuff() do_the_every_five_second_stuff() HTH - Hendrik -- Real programmers disdain structured programming. Structured programming is for compulsive neurotics who were prematurely toilet-trained. They wear neckties and carefully line up pencils on otherwise clear desks. From bruno.42.desthuilliers at websiteburo.invalid Wed Oct 1 11:49:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 01 Oct 2008 17:49:53 +0200 Subject: indirectly addressing vars in Python In-Reply-To: References: <6bb1$48e38ed8$d1d96e63$28976@PRIMUS.CA> Message-ID: <48e39bfc$0$29409$426a74cc@news.free.fr> Chris Rebert a ?crit : > On Wed, Oct 1, 2008 at 7:53 AM, Ross wrote: >> Forgive my newbieness - I want to refer to some variables and indirectly >> alter them. Not sure if this is as easy in Python as it is in C. >> >> Say I have three vars: oats, corn, barley >> >> I add them to a list: myList[{oats}, {peas}, {barley}] > > You mean: > myList = [oats, peas, barley] > > And you're not adding *variables* to a list, you're adding *values* s/values/references to objects/, actually (snip) From pavlovevidence at gmail.com Thu Oct 16 14:45:38 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 16 Oct 2008 11:45:38 -0700 (PDT) Subject: Emacs users: feedback on diffs between python-mode.el and python.el? References: <48f4ed4b$0$6127$426a74cc@news.free.fr> <48f785f5$0$6537$426a74cc@news.free.fr> Message-ID: On Oct 16, 12:21?pm, Bruno Desthuilliers wrote: > Carl Banks a ?crit : > > > On Oct 14, 1:05 pm, Bruno Desthuilliers > > wrote: > >> - a slightly less but still annoying problem (I wouldn't > > call it a bug) > >> is the handling of indentation for nested litteral dicts/lists/tuples. > > > The python-mode.el on Subversion (python-mode's Subversion on source > > forge, not the ancient version of python-mode in the Python > > repository) has a fix for this issue. > > Great !-) > > > ?It doesn't look like there's > > any way to browse the subversion any more, though. > > Doh :( > > Is there any way to get this version then ??? You could download and apply the patch yourself: https://sourceforge.net/tracker/index.php?func=detail&aid=1588272&group_id=86916&atid=581351 http://tinyurl.com/4x3uvh Carl Banks From st1999 at gmail.com Sat Oct 4 18:48:33 2008 From: st1999 at gmail.com (robean) Date: Sat, 4 Oct 2008 15:48:33 -0700 (PDT) Subject: Professional quality scripts/code References: <50809a11-6f20-45fa-b2f4-128456ce1ce6@m74g2000hsh.googlegroups.com> <48e5d70a$0$1572$426a74cc@news.free.fr> Message-ID: <54c26866-1e6b-48f5-afde-95d0cde7ab75@a3g2000prm.googlegroups.com> On Oct 3, 1:26?am, Bruno Desthuilliers wrote: > robean a crit : > > > I have been learning Python for the last 3 months or so and I have a > > working (but somewhat patchy) sense of the the language. I've been > > using a couple of the more popular Python books as well as online > > resources. > > > A question for experienced Python programmers: can you recommend > > resources where I can look at high quality Python code and scripts? > > Well... Not everything is 'high quality' in it[1], but why not start > with the stdlib ? Most of it is pure Python, opensource code and is > already installed on your machine, isn't it ?-) > > [1] IIRC, last time I had a look at the zipfile module's code, it was > more of a Q&D hack than anything else - now as long as it works fine for > what I do with it and I don't have to maintain it, well, that's fine. > > > I've spent some time athttp://code.activestate.com/recipes/but am > > concerned that the quality of what is posted there can be somewhat hit > > and miss. > > Indeed. > > > ?What I have in mind is a site like cpan, where one can look > > at the actual source code of many of the modules and learn a thing or > > two about idiomatic Perl programming from studying the better ones. > > Any sites like that for Python? > > Lurking here is probably a good way to see a lot of code reviews. And > even possibly to submit snippets of your own code to review. Some (if > not most) of us here like to show how good we are at improving the poor > newbies code !-) Many thanks, Mike and Bruno, The resources you mention are exactly the kind of stuff I was looking for. Soon enough I hope to give all of you many chances to improve this poor newbie's code...! - Robean From luong8201 at hotmail.com Thu Oct 30 14:48:57 2008 From: luong8201 at hotmail.com (fx5900) Date: Thu, 30 Oct 2008 11:48:57 -0700 (PDT) Subject: Code not work - DESPERATE HELP :( Message-ID: <20253039.post@talk.nabble.com> Hi, i am trying to convert an .osm (openstreetmap) file into gml format and finally to shapefile given this wiki info http://wiki.openstreetmap.org/index.php/GML. I'm using windows and when i entered the following commands osm2gml.py < map_01_data.osm > map_01_data.gml on my dos prompt i get a number of errors, some of which are bellow: Traceback : File "C:\osm2gml.py, line 86, in xml.sax.parse IOError : [Errono 9] bad discriptor i did manage to convert it to gml format but was clearly unsuccesful because of the error and it was 1kb. Another point i would like to add is that ran the file using PythonWin (ActiveState) with map_01_data.osm as the argument and after hitting ok, then cancel i got Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\osm2gml.py", line 86, in xml.sax.parse( sys.stdin, osmParser ) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 211, in feed self._err_handler.fatalError(exc) File "C:\Python25\lib\xml\sax\handler.py", line 38, in fatalError raise exception SAXParseException: :1:0: syntax error Please would somebody mind telling how i can covert my osm file into the .gml format using the python file on the dos command or using pythonwin. Cheers -- View this message in context: http://www.nabble.com/Code-not-work---DESPERATE-HELP-%3A%28-tp20253039p20253039.html Sent from the Python - python-list mailing list archive at Nabble.com. From marco.bartolini at gmail.com Tue Oct 28 14:59:50 2008 From: marco.bartolini at gmail.com (flyingfrog) Date: Tue, 28 Oct 2008 11:59:50 -0700 (PDT) Subject: Database specialized in storing directed graphs? References: <829ee8a7-5956-49d7-9465-a83a06537c41@m32g2000hsf.googlegroups.com> Message-ID: Don't really know if this will be useful but i'd try pytables: http://www.pytables.org/moin it deals very well with every kind of hierarchical data sets, doesn't matter the size. It will let you load only significant data, and you'll be able to query your data. It's built on top of HDF5 libraries but exposes a very friendly pythonic interface. Surely you'll still have to implement all of the graph logic yourself but this could be a good starting point. Hope it helps Marco From s.payandeh at gmail.com Wed Oct 22 07:29:57 2008 From: s.payandeh at gmail.com (sa6113) Date: Wed, 22 Oct 2008 04:29:57 -0700 (PDT) Subject: which program I need for sftp using paramiko?? Message-ID: <20108822.post@talk.nabble.com> which program I have to install for using paramiko for sftp between a two windows machine in local network?? I have installed freeSSHd for server machine but I got an Authentication failed erro when try to connect to server using this code : sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait() if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "Authentication failed" output: SSH negotiation successful Authentication failed May I install any program on client computer such as openssh ? please help me. Thanks -- View this message in context: http://www.nabble.com/which-program-I-need-for-sftp-using-paramiko---tp20108822p20108822.html Sent from the Python - python-list mailing list archive at Nabble.com. From M8R-yfto6h at mailinator.com Wed Oct 1 22:51:21 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Wed, 1 Oct 2008 19:51:21 -0700 Subject: Socket Question References: Message-ID: <4vOdncn-Avy6qnnVnZ2dnUVZ_gudnZ2d@comcast.com> "Ali Hamad" wrote in message news:mailman.1858.1222894062.3487.python-list at python.org... > Hello All : > > A socket question from a networking newbie. I need to create > a server that: > > 1) receive a message from client. > 2) check that message and response to it. > 3) the client get the server message and send another message. > 4) finally, the server receive the message and close the connection. > > I have successfully done this. However, I couldn't use the same socket > to send the second message > to the server. I have googled but all the examples are only for sending > one message and receiving the response. > > in my client code, I have : > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("1st message") > response = s.recv(1024) > validate(response) > s.send("2nd message") > response2 = s.recv(1024) > s.close() > > However, I got the first response just fine from the server but the > second message didn't get to the server. > > So, the solution I came up with is to send the 1st message, close the > socket, create new socket, > and send the 2nd message. > > I came up with something like : > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("1st message") > response = s.recv(1024) > s.close() > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('127.0.0.1', 1888)) > s.send("2nd message") > response = s.recv(1024) > s.close() > > and it works ! > > My Question : > > is it possible to send/receive from the same socket more than one message > ? > > Thank you for your assistance in advance, Yes, you can send more than one message on a socket. The problem is likely in the server code. What does it look like? Also TCP is a streaming protocol. It has no concept of a start and end of message unless you implement something you can recognize as a complete message in the protocol. -Mark From dr.lozy at googlemail.com Sat Oct 11 08:40:17 2008 From: dr.lozy at googlemail.com (dr.lozy) Date: Sat, 11 Oct 2008 05:40:17 -0700 (PDT) Subject: How To Get Laser Hair Removal Information Message-ID: <988b76da-12a6-47dc-90d4-bb4785218ed7@y79g2000hsa.googlegroups.com> How To Get Laser Hair Removal Information http://super-free6.com/free/?p=39 Plastic Surgery - Buttock Augmentation http://super-free6.com/free/?p=151 Cosmetic Surgery Tips http://super-free6.com/free/?p=150 How to choose your esthetic surgeon? http://super-free6.com/free/?p=149 The MedLite laser - the choice for tattoo removal? http://super-free6.com/free/?p=148 How to Get Younger Every Day? http://super-free6.com/free/?p=146 How to Quit Smoking? The easy way http://super-free6.com/free/?p=147 Sweet tooth. Here is some practical advice http://super-free6.com/free/?p=145 Laser Skin Treatment ? A Popular Way Of Curing Various Skin Problems http://super-free6.com/free/?p=40 My Best Advice On Skin Care For Sensitive Skin http://super-free6.com/free/?p=36 When You Should Buy Cosmetics Online http://super-free6.com/free/?p=32 Bikini Line Hair Removal The Easy Way http://super-free6.com/free/?p=31 Cosmetic Surgery Tips http://super-free6.com/free/?p=30 How to choose your esthetic surgeon? http://super-free6.com/free/?p=29 Genital Hair Removal http://super-free6.com/free/?p=28 Laser Hair Removal Parlors In The City Of Toronto http://super-free6.com/free/?p=27 Laser Hair Removal - What You Need To Know http://super-free6.com/free/?p=26 Uncover The Best Anti Wrinkle Eye Cream http://super-free6.com/free/?p=25 New Professional Makeup Tricks http://super-free6.com/free/?p=12 Bigger Breast - How To Get Bigger Breast Without Surgery http://super-free6.com/free/?p=159 What Are Genital Warts? http://super-free6.com/free/?p=156 Vaginal Odours - A Rose Smelling Vagina Is Not Healthy http://super-free6.com/free/?p=155 Cosmetic Surgery Treatment For Massive Weight Loss Effects http://super-free6.com/free/?p=154 A Healthy Diet Plan ? How To Choose? http://super-free6.com/free/?p=167 Bikini Line Hair Removal The Easy Way http://super-free6.com/free/?p=165 Must Do Thigh Exercises For Sexy Butt And Legs http://super-free6.com/free/?p=166 Laser Hair Removal Parlors In The City Of Toronto http://super-free6.com/free/?p=164 Laser Hair Removal - What You Need To Know http://super-free6.com/free/?p=163 Anti Wrinkle Firming Cream: What You Need To Know Before Spending Your Money! http://super-free6.com/free/?p=162 Anti Wrinkle Eye Cream: See What The Hollywood Stars And Celebrities Are Now Using http://super-free6.com/free/?p=161 Laser Treatments Herald Enhancements In Personal Appearance http://super-free6.com/free/?p=160 Remergent Skin Care Products Restore Dna And Promote Healthy Skin http://super-free6.com/free/?p=56 Skin Care Keep those wrinkles away http://super-free6.com/free/?p=55 Weight Loss Energy Drink: Friend Or Foe? http://super-free6.com/free/?p=54 Fat Loss Diet ? How To Get Yourself Motivated To Start Losing Weight http://super-free6.com/free/?p=51 4 Tips To Maximize Your Weight Loss http://super-free6.com/free/?p=50 Fast Weight Loss; Some Tips http://super-free6.com/free/?p=49 How to Get a Beautiful and Healthy Skin http://super-free6.com/free/?p=46 Laser Resurfacing For Age Spots And Brown Spots http://super-free6.com/free/?p=45 Herbal Skin Care Provides Natural Protection http://super-free6.com/free/?p=44 How To Stop Hair Loss http://super-free6.com/free/?p=43 Hair Loss For Men And Women 101 http://super-free6.com/free/?p=42 I Quit Smoking With Low Level Laser Therapy http://super-free6.com/free/?p=41 From lepto.python at gmail.com Tue Oct 21 02:48:48 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 21 Oct 2008 14:48:48 +0800 Subject: Creating single .exe file without py2exe and pyinstaller Message-ID: <6a4f17690810202348i2811bfd4v96449b9984f88cd4@mail.gmail.com> you can try jungle ( http://www.suda-chen.biz/?page_id=21 ) also > ---------- ????? ---------- > From: MRAB > To: python-list at python.org > Date: Mon, 20 Oct 2008 15:47:55 -0700 (PDT) > Subject: Re: Creating single .exe file without py2exe and pyinstaller > On Oct 20, 4:48 pm, Larry Bates wrote: > > Tino Wildenhain wrote: > > > Abah Joseph wrote: > > > 2) use a python to C(++) compiler and compile the result to .exe, > > > works pretty well for simple applications: > > > http://shed-skin.blogspot.com/ From __peter__ at web.de Thu Oct 2 16:11:05 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Oct 2008 22:11:05 +0200 Subject: Regular expressions and Unicode References: Message-ID: Jeffrey Barish wrote: > I have a regular expression that I use to extract the surname: > > surname = r'(?u).+ (\w+)' > > However, when I apply it to this Unicode string, I get only the first 3 > letters of the surname: > > name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' That's a byte string. You can either modify the literal name = u'Anton\xedn Dvo\u0159\xe1k' or decode it with the proper encoding name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' name = name.decode("utf-8") > surname_re = re.compile(surname) > m = surname_re.search(name) > m.groups() > ('Dvo\xc5',) > > I suppose that there is an encoding problem, but I don't understand > Unicode well enough to know what to do to digest properly the Unicode > characters in the surname. >>> name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' >>> re.compile(r"(?u).+ (\w+)").search(name.decode("utf-8")).groups() (u'Dvo\u0159\xe1k',) >>> print _[0] Dvo??k Peter From dblubaugh at belcan.com Wed Oct 8 15:19:48 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Wed, 8 Oct 2008 15:19:48 -0400 Subject: Python syntax question In-Reply-To: <985dc1ee-e950-43a7-9a83-c851c74908f0@u29g2000pro.googlegroups.com> References: <4b32a20a-666b-4b1a-ac79-8b2802071bcd@n1g2000prb.googlegroups.com><6l4b6fFakp4rU2@mid.uni-berlin.de> <985dc1ee-e950-43a7-9a83-c851c74908f0@u29g2000pro.googlegroups.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38055C8725@AWMAIL04.belcan.com> Sir, I was just wondering that the module that you are utilizing (Rpyc) is a remote process call module for python? Is this what you are developing with at this time? Thanks, David Blubaugh -----Original Message----- From: Daniel [mailto:daniel.watrous at gmail.com] Sent: Wednesday, October 08, 2008 3:11 PM To: python-list at python.org Subject: Re: Python syntax question On Oct 8, 12:07?pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 08 Oct 2008 11:02:49 -0700, Daniel wrote: > > Here is one error I get when I try to import it: > > >>>> import Rpyc > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Python25\lib\site-packages\Rpyc\__init__.py", line 7, in > > > > ? ? from Rpyc.Lib import rpyc_excepthook > > ? File "C:\Python25\lib\site-packages\Rpyc\Lib.py", line 65 > > ? ? print("======= Remote traceback =======", file=stderr) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > > SyntaxError: invalid syntax > > > The little carrot points to the equal sign ('=') in 'file=stderr' > > > What's the syntax problem? > > That's Python?3.0 syntax where ``print`` is not a keyword anymore but > a function. ?Won't work with Python?2.5. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks! With that I was able to find a solution. This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From fuzzyman at gmail.com Mon Oct 13 08:25:43 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 13 Oct 2008 05:25:43 -0700 (PDT) Subject: Making class attributes non-case-sensitive? References: <640ad8cf-2bac-4907-accd-6ba92bac2219@a3g2000prm.googlegroups.com> Message-ID: <8ad90c16-17b8-467f-90c5-8b8ecdd6f6bc@d31g2000hsg.googlegroups.com> On Oct 13, 10:11 am, Rafe wrote: > Hi, > > I'm working within an application (making a lot of wrappers), but the > application is not case sensitive. For example, Typing obj.name, > obj.Name, or even object.naMe is all fine (as far as the app is > concerned). The problem is, If someone makes a typo, they may get an > unexpected error due accidentally calling the original attribute > instead of the wrapped version. Does anyone have a simple solution for > this? > > I can protect against some cases just by making an 'alias': > class AClass(object): > def name(self): > print "hello" > > Name = name > > ...but this doesn't protect against typos, it gets more complicated > with multi-word attribute names, and it makes my epydocs confusing to > read since all spelling versions are shown (I AM concerned about my > docs being clear, but not as much as stopping typo related errors). > > I thought about using my wrapper's __getattr__ and __setattr__, but I > I am concerned about the overhead of every delegated attribute call > running a search and compare (.lower() based compare?). > > Any ideas or precedence? If you define '__getattr__' then it will only be called for attribute names that don't exist. So only explicitly define the names you want in the lowercase variant and then have something like the following: def __getattr__(self, name): return object.__getattr__(self, name.lower()) That way each name only appears once and you only get the extra '__getattr__' in your epydoc docs. Michael > > Cheers, > > - Rafe -- http://www.ironpythoninaction.com/ From mail at timgolden.me.uk Mon Oct 20 15:22:17 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 20 Oct 2008 20:22:17 +0100 Subject: Abnormal Interpreter Shutdown In-Reply-To: References: Message-ID: <48FCDA69.9020400@timgolden.me.uk> k3xji wrote: > Hi all, > > Is there anyway to detect abnormal interpreter shutdown like (closing > from task manager, power shutdown of the PC..etc)? "Task Manager" suggests you're using Windows, on which basis you've got a few options open to you, but fundamentally if someone pulls the plug on the PC you're not going to spot it. Look at the SetConsoleCtrlHandler API[1], which is available in the pywin32 package, and the WMI power events[2]. I don't know exactly how far each one will go if someone stomps on your process, but they're definitely worth looking at. TJG [1] http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx [2] http://msdn.microsoft.com/en-us/library/aa394362(VS.85).aspx From ldo at geek-central.gen.new_zealand Tue Oct 7 05:12:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 07 Oct 2008 22:12:10 +1300 Subject: how to start thread by group? References: Message-ID: In message , Gabriel Genellina wrote: > Usually it's more efficient to create all the MAX_THREADS at once, and > continuously feed them with tasks to be done. Given that the bottleneck is most likely to be the internet connection, I'd say the "premature optimization is the root of all evil" adage applies here. From areyoulookon at gmail.com Sun Oct 12 09:03:10 2008 From: areyoulookon at gmail.com (lookon) Date: Sun, 12 Oct 2008 06:03:10 -0700 (PDT) Subject: How to detect Chinese in a string? References: <5c0d3394-c562-4cf6-8067-fe5cb5d1fb3e@c22g2000prc.googlegroups.com> Message-ID: <90a74869-0aac-4001-a963-72d42ffed37f@e38g2000prn.googlegroups.com> Get it. Thanks Peter Otten wrote: > lookon wrote: > > > I have a string a(for example, a='??Chinese'), and I want to know > > whether there are some Chinese in the string. > > > > Can someone tell me how to do it? Thanks! > > See > > http://mail.python.org/pipermail/python-list/2008-September/509738.html > > Instead of re.findall(...) > > you may use > > if re.search(...): > print "There are Chinese chars" > > Remember to decode the string with the proper encoding first, e. g. > > a = a.decode("utf-8") > > Peter From lists at cheimes.de Tue Oct 28 14:42:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 28 Oct 2008 19:42:37 +0100 Subject: 404 not found on for Python 2.6 Itanium In-Reply-To: <3fe83250-0a7f-441d-a763-9761290ad272@d36g2000prf.googlegroups.com> References: <3fe83250-0a7f-441d-a763-9761290ad272@d36g2000prf.googlegroups.com> Message-ID: csgrimes1 at gmail.com wrote: > Anyone know where else I can download 2.6 for x64 windows? x64 is AMD64 aka X64_86 and not the Itanium version. Itanium is IA64. We don't build Python for IA64 anymore. Christian From __peter__ at web.de Thu Oct 23 08:24:25 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Oct 2008 14:24:25 +0200 Subject: Slow comparison between two lists References: <3c247dbf-7801-4d25-b70b-a91a6db58f46@79g2000hsk.googlegroups.com> Message-ID: Jani Tiainen wrote: > I have rather simple 'Address' object that contains streetname, > number, my own status and x,y coordinates for it. I have two lists > both containing approximately 30000 addresses. > > I've defined __eq__ method in my class like this: > > def __eq__(self, other): > return self.xcoord == other.xcoord and \ > self.ycoord == other.ycoord and \ > self.streetname == other.streetname and \ > self.streetno == other.streetno > > But it turns out to be very, very slow. > > Then I setup two lists: > > list_external = getexternal() > list_internal = getinternal() > > Now I need get all all addresses from 'list_external' that are not in > 'list_internal', and mark them as "new". > > I did it like this: > > for addr in list_external: > if addr not in list_internal: > addr.status = 1 # New address > > But in my case running that loop takes about 10 minutes. What I am > doing wrong? Even if list_external and list_internal contain the same items you need about len(list_external)*(len(list_internal)/2), or 45 million comparisons. You can bring that down to 30000*some_small_factor if you make your addresses hashable and put the internal ones into a dict or set def __hash__(self): return hash((self.xcoord, self.yccord, self.streetname, self.streetno)) def __eq__(self, other): # as above Then set_internal = set(list_internal) for addr in list_external: if addr not in set_internal: addr.status = 1 Note that the attributes relevant for hash and equality must not change during this process. Peter From castironpi at gmail.com Fri Oct 10 20:23:03 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 10 Oct 2008 17:23:03 -0700 (PDT) Subject: extracting null pointer address from PyCObject with ctypes References: <63633db0-44d4-4c45-85af-4024af9cc584@l77g2000hse.googlegroups.com> Message-ID: On Oct 10, 4:16?pm, Gordon Allott wrote: > Aaron "Castironpi" Brady wrote: > > I see. ?If I understand, you have a PyCObject in a dictionary. > > > Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr. ?Its > > return type should be 'c_void_p', and you can use 'result.value' to > > get the original pointer. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I have a hard time following that, if using ctypes you used PyDLL to > call PyCObject_AsVoidPtr on the PyCObject I already have surely it would > ?give me back a pointer (void for sake of simplicity) but it would be a > pointer to a new PyCObject and thus calling result.value on it would > only return the memory address of the new PyCObject? > -- > Gord Allott (gordall... at gmail.com) > > ?signature.asc > < 1KViewDownload Yes, well said. But no, not true, not necessarily. You can choose/ change return types with your code. If the call is defined already and you can't change the return, just define a new one that returns long. From prologic at shortcircuit.net.au Thu Oct 30 18:55:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 31 Oct 2008 08:55:26 +1000 Subject: Python 2.5: wrong number of arguments given in TypeError for function argument aggregation (dictionary input vs the norm) In-Reply-To: <28efa6970810301549u5d01d4e3t5feacf775f7a6075@mail.gmail.com> References: <28efa6970810301549u5d01d4e3t5feacf775f7a6075@mail.gmail.com> Message-ID: On Fri, Oct 31, 2008 at 8:49 AM, mark floyd wrote: > I was doing some testing with the different ways to pass arguments into > functions and ran into what looks like a bug. > > Given function, > > def foo(a,b,c): > print a > print b > print c > > # Call function with named parameter list, leaving 'b' out > foo(a=1, c=3) > > Traceback (most recent call last): > File "aggregate.py", line 13, in > foo(a=1, c=3) > TypeError: foo() takes exactly 3 arguments (2 given) > > # Call function with dictionary for parameter list... leaving 'c' out of the > dictionary > yarg = {'a': 111, 'b': 222} > foo(**yarg) > > Traceback (most recent call last): > File "aggregate.py", line 17, in > foo(**yarg) > TypeError: foo() takes exactly 3 non-keyword arguments (2 given) > > > # Call function with dictionary for parameter list... leaving 'b' out of the > dictionary > > yarg = {'a': 111, 'c': 333} > foo(**yarg) > > Traceback (most recent call last): > File "aggregate.py", line 17, in > foo(**yarg) > TypeError: foo() takes exactly 3 non-keyword arguments (1 given) > > It seems like the interpreter craps out too early when you leave 'b' out of > the input dictionary... and it reports the incorrect number of arguments > given (I would expect to see '2 given') > > We've tested this locally using Python 2.5, Debian Etch 32-bit installation Mark, this is correct behavior. You have 3 positional arguments in the function definition. You _must_ aupply _all_ 3 of them. If you wish for b to be optional, then you must give it a default value. def foo(a, b=None, c=None): print a print b print c Note, that c must also be a default argument as you cannot have a non-default argument following a default argument. A more useful approach is this common pattern: def foo(*args, **kwargs): ... What you have discovered is not a bug :) cheers James -- -- -- "Problems are solved by method" From luke.leighton at googlemail.com Tue Oct 14 07:45:41 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 14 Oct 2008 04:45:41 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <43633737-6425-42d4-a228-43be36b0feb0@v15g2000hsa.googlegroups.com> Message-ID: > Although using browser technologies for desktop applications is > interesting (and not new by any means), there are a few things with > regard to layouts which are very difficult with Web technologies (and > aren't getting any easier, either) but which are almost trivial with > classic graphical user interface toolkits, and of course there are > cases where the roles are reversed. if it wasn't for luis pamirez's brilliant work, porting pygtk to pyjamas, i would be absolutely agreeing with you, 100%. see this: http://code.google.com/p/pyjamas/wiki/GsocLlpamies luis has demonstrated that it's possible to have your cake and eat it. effectively - incredibly - he's ported pygtk ... to the browser! so your python pygtk application gets compiled, along with his reimplementation of gtk.py, gdk.py etc., into javascript (using the pyjamas compiler) and - unmodified - your pygtk app gets to run in every major web browser. that's just... stunning. regarding what you say about web technologies being more difficult to do layouts than traditional desktop apps - i'm really sorry to say that, from my experience with using the pyjamas widget set API, i couldn't agree less. HOWEVER - if this were pure HTML and CSS, i would utterly, utterly be agreeing with you - 100%. the first paragraph of my talk for ukuug 2009 says it best: http://ukuug.org/events/linux2008/programme/abstract-LKCLeighton-2.shtml it was _such_ an abortion trying to do a simple centred layout. and it's for exactly this reason that GWT was created (and then pyjamas ported from GWT). when you're using javascript to manipulate the DOM model (or, in the case of pyjamas-desktop, manipulating the DOM model directly) then it's an _entirely_ different matter. then, when you put "standard"- like widgets which include layout manager on top of _that_, which have identical functions and functionality to those of Desktop Widgets... ... the distinction between "web" and "desktop" suddenly becomes... moot. especially in the context of luiz's work. there isn't a _single_ thing that pyjamas can't do that pygtk2, wxWidgets or pyqt4 can do. there are _lots_ of things that pyjamas can do that pygtk2, wxWidgets and pyqt4 can't do (as they stand. without extra work and/or extensions e.g. derivative customised classes based on QAbstractLayout) ok - i'm exaggerating a little :) you can't access standard python modules from pyjamas apps in a web browser, because javascript is a restricted execution environment, so you have to make do (and you can make do _extremely_ well with what's available) with the provided implementation of builtins. so, if you don't mind using XMLHTTPRequest to communicate with the rest of the world - even if it's on http loopback - _then_ you're ok :) and yes, XMLHTTPRequest is supported in pyjamas-desktop (it has to be). also, writing new layouts and new widgets, which _happen_ to operate underneath on the DOM model of a browser (or a browser-kit-library such as PyKDE or PyWebKitGTK) is trivial. _really_ trivial. i've outlined how to write your own widget, here: http://pyjd.sourceforge.net/controls_tutorial.html and it's interesting to compare that to writing one for pygtk (there's a "stars" example which is easy to find "python gtk tutorial" i think it's hit number 3). the only thing i _can_ say, for definite, is that because pyjamas is missing an equivalent of glade, the UI-generator, and those GUI-based UI editors / designers, it _is_ at the moment a bit more... hard work doing the UI design manually, if you're used to using a GUI tool to design your UI. but i'm sure that will change. l. From deets at nospam.web.de Wed Oct 15 08:00:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 15 Oct 2008 14:00:33 +0200 Subject: Using variable in storbinary function of ftpilb module References: Message-ID: <6lm4apFd4ve3U1@mid.uni-berlin.de> Arya, Manish Kumar wrote: > Hi, > > I am new to python. > > I have written a simple code to upload a file via ftp to remote server > > ------------- > import sys > import ftplib > host=sys.argv[1] > username=sys.argv[2] > passwd=sys.argv[3] > filename=sys.argv[4] > > print host,username,passwd > > ftp = ftplib.FTP(host,username,passwd) > fd=open(filename,'rb') > ftp.storbinary('STOR filename',fd) > ------------------- > > I am passing file name in cmd line arg. but I have no idea how to use > "filename" variable value in ftp.storbinary('STOR filename',fd) ? ftp.storbinary("STOR %s" % filename, fd) Diez From bieffe62 at gmail.com Mon Oct 6 08:28:53 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 6 Oct 2008 05:28:53 -0700 (PDT) Subject: If an OS was to be written in Python, how'w it look? References: Message-ID: <67d3d350-42a9-429d-951c-f430bf069b29@m73g2000hsh.googlegroups.com> On 6 Ott, 06:16, process wrote: > If an OS was to be written in Python and the hardware optimized for > it, what changes would be made to the hardware to accomodate Python > strenghs and weaknesses? > > Some tagged architecture like in Lisp machines?http://en.wikipedia.org/wiki/Tagged_architecture > > What else? I would say that a python-processor should have dictionary lookup (hash tables), garbage collection and dynamic lists implemented by hardware/firmware. Maybe in another twenty years ... Ciao ---- FB From lie.1296 at gmail.com Thu Oct 9 13:39:14 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 9 Oct 2008 17:39:14 +0000 (UTC) Subject: Pr. Euler 18, recursion problem References: <48e9ac7e@dnews.tpgi.com.au> Message-ID: On Mon, 06 Oct 2008 00:14:37 -0700, process wrote: > On Oct 6, 8:13?am, Aidan wrote: >> process wrote: >> > I am trying to solve project euler problem 18 with brute force(I will >> > move on to a better solution after I have done that for problem 67). >> >http://projecteuler.net/index.php?section=problems&id=18 >> >> > However I can't get the recursive function right. >> >> > I always have to use return right? Unless I am printing? So I can?t >> > stack to diffferent recursive calls after each other like so: >> > recur_left(t, p) >> > recur_right(t,p+1) >> >> > Some stuff I have tried: >> >> > def recur(tree, pos): >> > ? ? if not tree: >> > ? ? ? ? return [] >> > ? ? else: >> > ? ? ? ? return [[tree[0][pos]] + recur(tree[1:], pos)] + \ >> > ? ? ? ? ? ? ? ?[[tree[0][pos]] + recur(tree[1:], pos+1)] >> >> >>>> recur([[1],[2,3],[4,5,6]],0) >> > [[1, [2, [4], [4]], [2, [5], [5]]], [1, [3, [5], [5]], [3, [6], >> > [6]]]] >> >> > SO it is kind of working, just not exactly like I want. A more easily >> > parseable/readable result would be nice, I want to be able to sum() >> > over each path preferrably. >> >> > So the result should be: >> > [[1,2,4],[1,2,5],[1,3,5],[1,3,6]] >> >> > I know conceptually what has to be done. Base case: empty tree, >> > return [] >> > Else: recur to the left and to the right. >> >> This is just my opinion, but I felt the non-brute force solution to >> this problem was actually simpler than trying to define a brute force >> recursive solution.... I tried to implement a brute force algorithm at >> first, until I had an epiphany with regard to how simple the problem >> actually was. ?Then I faced palmed. > > > > But let's say you have [[1],[1,10],[1,2,300],[100000,1,1,1]]. > > you must check all solutions right? there is no pattern. if you start > from the bottom and eliminate paths that seem to be losing can you > regain that later up in the pyramid if it turns out one side gets bigg > again? A Wise Man once says: "When you're hopelessly stuck with a problem, reverse the problem" From robinvaiya at gmail.com Sat Oct 11 11:03:43 2008 From: robinvaiya at gmail.com (robin) Date: Sat, 11 Oct 2008 08:03:43 -0700 (PDT) Subject: I can't get the scanner to work on my mp160. Message-ID: <0929bd58-e6a8-43c7-b121-59aa89144442@h2g2000hsg.googlegroups.com> PROBLEM I have tried everything but I am unable to get the scanner to work . I have reinstalled drivers checked connections I have windows 2000 and all other requirements. There is a windows error code 31 that pops up. This says check connections and make sure scanner is turned on. find solution here http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer From stef.mientki at gmail.com Mon Oct 20 19:03:38 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 21 Oct 2008 01:03:38 +0200 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: <87d4huq3rr.fsf@asus-190829777.TeleWell.gateway> References: <48fcd5c3$0$8723$426a34cc@news.free.fr> <87d4huq3rr.fsf@asus-190829777.TeleWell.gateway> Message-ID: <48FD0E4A.3070206@gmail.com> Ville M. Vainio wrote: > Stef Mientki writes: > > > >>>> Sorry but for GUI design, Python is pre-historic ;-) >>>> >>> Time to show the "don't feed the troll" sign, I guess. >>> >> Even without the smiley, I'm convinced of my statement. >> cheers, >> > > I don't think I'm feeding the troll, but - ever took a look at PyQt? > I wanted to go from Delphi to a free / open source environment, for both open source and commercial applications. So the Qt license stopped me from looking any further. cheers, stef > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Thu Oct 23 00:24:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Oct 2008 04:24:58 GMT Subject: Possible read()/readline() bug? References: <380b01dc-eaef-425d-bb93-dbb838c20175@u28g2000hsc.googlegroups.com> Message-ID: <010ff59d$0$20657$c3e8da3@news.astraweb.com> On Wed, 22 Oct 2008 16:59:45 -0400, Terry Reedy wrote: > Mike Kent wrote: >> Before I file a bug report against Python 2.5.2, I want to run this by >> the newsgroup to make sure I'm not [missing something]. > > Good idea ;-). What you are missing is a rereading of the fine manual > to see what you missed the first time. I recommend this *whenever* you > are having a vexing problem. With respect Terry, I think what you have missed is the reason why the OP thinks this is a bug. He's not surprised that buffering is going on: "This indicates some sort of buffering and caching is going on." but he thinks that the buffering should be discarded when you seek: "It seems pretty clear to me that this is wrong. If there is any caching going on, it should clearly be discarded if I do a seek. Note that it's not just readline() that's returning me the wrong, cached data, as I've also tried this with read(), and I get the same results. It's not acceptable that I have to close and reopen the file before every read when I'm doing random record access." I think Mike has a point: if a cache is out of sync with the actual data, then the cache needs to be thrown away. A bad cache is worse than no cache at all. Surely dealing with files that are being actively changed by other processes is hard. I'm not sure that the solution is anything other than "well, don't do that then". How do other programming languages and Unix tools behave? (Windows generally only allows a single process to read or write to a file at once.) Additionally, I wonder whether what Mike is seeing is some side-effect of file-system caching. Perhaps the bytes written to the file by echo are only written to disk when the file is closed? I don't know, I'm just hypothesizing. -- Steven From bnayler at gmail.com Thu Oct 9 15:08:00 2008 From: bnayler at gmail.com (Barry) Date: Thu, 9 Oct 2008 12:08:00 -0700 (PDT) Subject: Problem with cPickle and cElementTree Message-ID: <753515d6-f15e-42c1-90ce-c3fac2789dcc@y21g2000hsf.googlegroups.com> I recently tried switching from ElementTree to cElementTree. My application parses a collection of large XML files and creates indexes based on certain attributes. This entire collection is saved as an instance of my Database class. Using ElementTree and cPickle has allowed me to save these instances and use them later. Using cElementTree significantly reduces parse time (~50%) and memory ~(15%) but cPickle refuses to pickle the database object. I receive: TypeError: expecting string or Unicode object, NoneType found The offending line of code simple shows my invocation of cPickle, which is not helpful. Doing exactly the same thing with ElementTree works fine. It appears that the objects returned by cElementTree do not pickle correctly. Is this a know issue? I was unable to find any reports of this problem. Any info would be appreciated! Barry From dan at remember.this.name Fri Oct 17 13:37:43 2008 From: dan at remember.this.name (Dan Ellis) Date: Fri, 17 Oct 2008 10:37:43 -0700 (PDT) Subject: Normalizing arguments References: Message-ID: On Oct 17, 6:17?pm, "Chris Rebert" wrote: > Why do you want/need this magical g() function considering that, as > you yourself point out, Python already performs this normalization for > you? A caching idea I'm playing around with. @cache def some_query(arg1, arg2): # Maybe do SQL query or something return result cache returns a function that does: - Make a key from its arguments - If key is in the cache: - Return result from cache - If it isn't: - Call some_query with the same arguments - Cache and return the result From godson.g at gmail.com Sun Oct 12 00:11:14 2008 From: godson.g at gmail.com (Godson Gera) Date: Sun, 12 Oct 2008 09:41:14 +0530 Subject: ANN: starpy-1.0.0a13 Message-ID: Hi All, I am happy to announce new release of starpy (Asterisk protocols for Twisted http://starpy.sf.net ) on behalf of starpy team. starpy-1.0.0a13 can be downloaded from here https://sourceforge.net/project/showfiles.php?group_id=164040 This release contains addition of many manager commands to manager API. Following is a list of newly added commands. 1. agentLogoff 2. dbGet 3. dbPut 4. extensionState 5. getConfig 6. meetmeMute 7. meetmeUnmute 8. park 9. pauseMonitor 10. playDTMF 11. queuePause 12. sipShowPeers 13. unpauseMonitor 14. updateConfig (read AMI documentation before using this ) 15. userEvent 16. waitEvent 17. zapDNDoff 18. zapDNDon 19. zapDialOffhook 20. zapHangup 21. zapRestart 22. zapShowChannels 23. zapTransfer - Those are all the new manager Actions that were added. Queues action is there but it won't work cause AMI returns improperly formatted lines, same case with IAXPeers action, as AgentCallbackLogin is deprecated and is not functioning properly it was not included. - Bug fix in queueStatus manager API, in collectDeferred argument 'QueueStatusEnd' is changed to 'QueueStatusComplete'. Now the deferred fires properly. - Bug fix in fastagi playback (not a standard AGI command, was created by Mike as a workaround for buggy streamFile command back in Asterisk 1.2 days. Now streamFile is working properly so you might not be using this playback ). Those are all the changes that are involved in this release if you find any bugs or hope for any new features let me know. Have fun with starpy, Godson Gera -------------- next part -------------- An HTML attachment was scrubbed... URL: From tokauf at web.de Sat Oct 4 05:44:08 2008 From: tokauf at web.de (TK) Date: Sat, 04 Oct 2008 11:44:08 +0200 Subject: newbie question: apply() In-Reply-To: References: <48e73753$0$28911$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <48e73bad$0$28916$9b4e6d93@newsspool1.arcor-online.net> > pos_args = ["spam", 1, [3]] > kwd_args = {"b":7, "c":9} > result = some_function(*pos_args, **kwd_args) > > Which is equivalent to: > result = some_function("spam", 1, [3], b=7, c=9) > > Which was equivalent to: > result = apply(some_function, pos_args, kwd_args) Thanks a lot. o-o Thomas From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 20 10:04:21 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 16:04:21 +0200 Subject: indentation In-Reply-To: References: <48fc48df$0$12027$426a74cc@news.free.fr> <48fc7069$0$20770$426a74cc@news.free.fr> Message-ID: <48fc8fe5$0$28482$426a74cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> I can't remember having seen any other "standard" so far. >> > Ross Ridge a ?crit : >> I've seen various indentation styles used in examples on this newsgroup. > > Bruno Desthuilliers wrote: >> I meant: in a real-life project. > > So? There's no reason to assume the styles people use on this newsgroup > don't reflect those they use in "real-life" projects. Yes there are. I can give you two: 1/ code editor are usually configured to insert X spaces when hitting 'tab' - which is not necessarily the case for newsreaders. Guess what happens when someone writes a code snippet directly in his newsreader ? 2/ I sometimes use 2-spaces when posting here to avoid linewraps !-) From electronixtar at gmail.com Thu Oct 2 06:06:38 2008 From: electronixtar at gmail.com (est) Date: Thu, 2 Oct 2008 03:06:38 -0700 (PDT) Subject: TypeError: can't pickle HASH objects? References: <90876c28-070e-44bf-87d2-b2f6629c9dcc@d31g2000hsg.googlegroups.com> Message-ID: <2ead517f-8994-490b-b0af-86308eb98a09@59g2000hsb.googlegroups.com> On Oct 2, 5:07?pm, "Gabriel Genellina" wrote: > En Wed, 01 Oct 2008 16:50:05 -0300, est escribi?: > > > > > > >>>> import md5 > >>>> a=md5.md5() > >>>> import pickle > >>>> pickle.dumps(a) > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Python25\lib\pickle.py", line 1366, in dumps > > ? ? Pickler(file, protocol).dump(obj) > > ? File "C:\Python25\lib\pickle.py", line 224, in dump > > ? ? self.save(obj) > > ? File "C:\Python25\lib\pickle.py", line 306, in save > > ? ? rv = reduce(self.proto) > > ? File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex > > ? ? raise TypeError, "can't pickle %s objects" % base.__name__ > > TypeError: can't pickle HASH objects > > > Why can't I pickle a md5 object? Is it because md5 algorithm needs to > > read 512-bits at a time? > > > I need to md5() some stream, pause(python.exe quits), and resume > > later. ?It seems that the md5 and hashlib in ?std module could not be > > serialized? > > Yep, they're implemented in C and have no provision for serializing. > If you can use the old _md5 module, it is far simpler to serialize; a ? > md5object just contains a small struct with 6 integers and 64 chars, no ? > pointers. > > With some help from ctypes (and a lot of black magic!) one can extract the ? > desired state, and restore it afterwards: > > --- begin code --- > import _md5 > import ctypes > > assert _md5.MD5Type.__basicsize__==96 > > def get_md5_state(m): > ? ? ?if type(m) is not _md5.MD5Type: > ? ? ? ? ?raise TypeError, 'not a _md5.MD5Type instance' > ? ? ?return ctypes.string_at(id(m)+8, 88) > > def set_md5_state(m, state): > ? ? ?if type(m) is not _md5.MD5Type: > ? ? ? ? ?raise TypeError, 'not a _md5.MD5Type instance' > ? ? ?if not isinstance(state,str): > ? ? ? ? ?raise TypeError, 'state must be str' > ? ? ?if len(state)!=88: > ? ? ? ? ?raise ValueError, 'len(state) must be 88' > ? ? ?a88 = ctypes.c_char*88 > ? ? ?pstate = a88(*list(state)) > ? ? ?ctypes.memmove(id(m)+8, ctypes.byref(pstate), 88) > > --- end code --- > > py> m1 = _md5.new() > py> m1.update("this is a ") > py> s = get_md5_state(m1) > py> del m1 > py> > py> m2 = _md5.new() > py> set_md5_state(m2, s) > py> m2.update("short test") > py> print m2.hexdigest() > 95ad1986e9a9f19615cea00b7a44b912 > py> print _md5.new("this is a short test").hexdigest() > 95ad1986e9a9f19615cea00b7a44b912 > > The code above was only tested with Python 2.5.2 on Windows, not more than ? > you can see. It might or might not work with other versions or platforms. ? > It may even create a (small) black hole and eat your whole town. Use at ? > your own risk. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - WOW! I never expected python could be coded like that! Thanks a lot! On Oct 2, 5:19 pm, "Aaron \"Castironpi\" Brady" wrote: > On Oct 2, 4:03 am, est wrote: > > > > > > > On Oct 2, 4:22 pm, "Aaron \"Castironpi\" Brady" > > wrote: > > > > On Oct 2, 2:44 am, est wrote: > > > > > On Oct 2, 1:51 pm, "James Mills" wrote: > > > > > > On Thu, Oct 2, 2008 at 3:34 PM, est wrote: > > > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > > > > break for a while. > > > > > > So use generators and consume the stream ? > > > > > > --JamesMills > > > > > > -- > > > > > -- > > > > > -- "Problems are solved by method" > > > > > no, I need to serialize half-finished digest, not file stream. > > > > > Anyone got solution? > > > > I am looking at '_hashopenssl.c'. If you can find the implementation > > > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes > > > hack to store and write its state.- Hide quoted text - > > > > - Show quoted text - > > >http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c > > > int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, > > size_t count) > > { > > #ifdef OPENSSL_FIPS > > FIPS_selftest_check(); > > #endif > > return ctx->digest->update(ctx,data,count); > > } > > > is this one? > > Oops, I needed 'EVP_MD_CTX'. I went Googling and found it. > > http://www.google.com/codesearch?hl=en&q=struct+EVP_MD_CTX+show:mV3VB... > > But does Gabriel's work for you?- Hide quoted text - > > - Show quoted text - Still need some hack with py2.5 on linux. Maybe I just need soft link / usr/lib/python2.4/lib-dynload/md5.so to py2.5 :-) py2.4 is pre-installed on most of the servers, I think. From adityashukla1983 at gmail.com Mon Oct 13 17:29:49 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Mon, 13 Oct 2008 16:29:49 -0500 Subject: Selecting random elements from a list. Message-ID: <73045cca0810131429y65d98979ifdc721ad9b4090cd@mail.gmail.com> Hello folks, i have a list say list1=[a,b,c,...z] ie 26 elements i have to take 5 elements from it randomly and save in another list.Please explain how to do this? Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Oct 21 01:43:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Oct 2008 01:43:51 -0400 Subject: indentation In-Reply-To: <010cfa46$0$20660$c3e8da3@news.astraweb.com> References: <48fc48df$0$12027$426a74cc@news.free.fr> <48fc7069$0$20770$426a74cc@news.free.fr> <010cfa46$0$20660$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 20 Oct 2008 14:25:17 -0400, Terry Reedy wrote: > >> If I type *hypothetical* code for a post, *I* have to >> type all the spaces, and I often use 2 per indent level. If I type in >> IDLE, *it* adds the spaces (4 per indent) automatically. > > But of course you would never post code without testing it first, right? > That would an Abomination Unto Nuggan. > > *wink* I have learned at least three times to either test or specify *untested*, except when testing is impossible, as when discussing unimplemented syntax or answering questions based on unposted input. I have learned much from posting *tested* code snippets. From gagsl-py2 at yahoo.com.ar Mon Oct 20 21:26:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Oct 2008 23:26:23 -0200 Subject: (relative) import trouble, sometimes it works, sometimes it doesn't ... References: <48F9A3B4.60804@gmail.com> Message-ID: En Sat, 18 Oct 2008 05:52:04 -0300, Stef Mientki escribi?: > I'm running Python 2.5 and want my programs to run at least under > Windows and Linux (preferable also Mac). > So I guess I should always use relative paths. > > From most modules I can call a global function, > that should import a dictionary from path deeper than the module itself. > The import is done in the global function. > In that global function, I get the modules path by > > SourceFile = sys._getframe(1).f_code.co_filename Why don't you let the caller tell you its own location, using __file__? The above code is too much magic for me. > now to be sure to succeed the import (at least I was thinking this would > always be successful :-( > I need to > 1- add the path of the module to be imported to sys.path > (or do a dot import) Yes. > 2- keep track of already done imports, to give a reload the next time > (or maybe always do an import followed by an reload ?) A reload is only required if the module was changed on disk and you want to get the later version. > Now what I don't understand is what relative path should I use in 1: > - relative to the main application > - relative to the working directory were I started the application > - relative to the current working directory > - relative to the module that is doing the import > - relative to the module that called the global function Relative imports assume you are inside a *package*, and they're relative to the current module location, each dot being one level above. See http://www.python.org/dev/peps/pep-0328/ > I would be pleased if someone could enlighten me, > because this information is hard to find. Yes. How import works is very poorly documented, unfortunately. You'll have to dig into the various PEPs and the bug tracker. -- Gabriel Genellina From pythonlarry at gmail.com Sun Oct 26 15:16:09 2008 From: pythonlarry at gmail.com (Larry Hale) Date: Sun, 26 Oct 2008 12:16:09 -0700 (PDT) Subject: Module python-magic on/for Windows - UPDATE: WORKING & HowTo!!! Message-ID: Thank you, again, Michael, for all your help many months ago. I *FINALLY* got a HowTo done up; please see http://wiki.python.org/moin/HowTo/FileMagic I've also emailed Mr. Hupp to see if he'll re-post the SWIG version; he's working on a newer binding (forget... ctypes??) and once that one's working... :) But for now... Cheers, Larry REF: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4c60ec1599056df8/3eff4049a7bfdfc0?hl=en%E3%AD%82a54360c4d26&lnk=gst&q=python-magic#3eff4049a7bfdfc0 From gagsl-py2 at yahoo.com.ar Wed Oct 22 02:46:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Oct 2008 04:46:37 -0200 Subject: Could anyone give a working example using asynchat in Python3.0? References: <81f2badd0810211929k513802a0x83650a73e812ab14@mail.gmail.com> Message-ID: En Wed, 22 Oct 2008 00:29:04 -0200, davy zhang escribi?: > I tried to use them but the terminator option seems no effect > > I search the google but all the code is Python2.x format, I modified > them but I get no luck..... The original package by Sam Rushing (available at http://www.nightmare.com/software.html) comes with some examples. I think they should work fine (just routinely convert the syntax to 3.0, perhaps using 2to3) There are a few other examples at Fredrik Lundh's site http://effbot.org/zone/ -- Gabriel Genellina From castironpi at gmail.com Sun Oct 19 23:20:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 19 Oct 2008 20:20:46 -0700 (PDT) Subject: Help with Iteration References: <000901c9322b$da435c80$0d00a8c0@hendrik> <1f0ee791-e8c1-4053-bf7f-89cf1f63f784@v39g2000pro.googlegroups.com> Message-ID: <461ddea3-12d0-4d73-b256-16111517ce65@2g2000hsn.googlegroups.com> On Oct 19, 8:47?pm, Asun Friere wrote: > On Oct 20, 6:10 am, Aaron Brady wrote: > > [snip] > > > If customers are stupid, should you sell stupid software? > > That's a hypothetical question with which we need never concern > ourselves. ?After all, by definition customers are not stupid, but > "always right." Only for the purposes of profit, and not even then necessarily. They can be wrong about what they would buy, wrong about what their fellow customers would buy, wrong about the product, wrong about the competition, etc. Regardless, I was asking about managers' priorities. I don't think we'd always agree on what constituted a good interface, for example, and he/she has final say over my job. I just don't want to reinvent the wheel all the time. From nagle at animats.com Fri Oct 17 11:55:03 2008 From: nagle at animats.com (John Nagle) Date: Fri, 17 Oct 2008 08:55:03 -0700 Subject: Python HTML parser chokes on UTF-8 input In-Reply-To: <4m72s5xlgn.ln2@joeserver.homelan.net> References: <4m72s5xlgn.ln2@joeserver.homelan.net> Message-ID: <48f8af9e$0$33583$742ec2ed@news.sonic.net> Johannes Bauer wrote: > Hello group, > > I'm trying to use a htmllib.HTMLParser derivate class to parse a website > which I fetched via > httplib.HTTPConnection().request().getresponse().read(). Now the problem > is: As soon as I pass the htmllib.HTMLParser UTF-8 code, it chokes. The > code is something like this: Try BeautifulSoup. It actually understands how to detect the encoding of an HTML file (there are three different ways that information can be expressed), and will shift modes accordingly. This is an ugly problem. Sometimes, it's necessary to parse part of the file, discover that the rest of the file has a non-ASCII encoding, and restart the parse from the beginning. BeautifulSoup has the machinery for that. John Nagle From dotancohen at gmail.com Sun Oct 19 05:29:35 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 19 Oct 2008 11:29:35 +0200 Subject: Porting VB apps to Python for Window / Linux use In-Reply-To: <48FAF10F.3060707@gmail.com> References: <48FAE71B.2080205@gmail.com> <880dece00810190123n1aaffabfrd5e89178f7bee0d4@mail.gmail.com> <48FAF10F.3060707@gmail.com> Message-ID: <880dece00810190229o300396bx9610c27ca4e218d@mail.gmail.com> 2008/10/19 Stef Mientki : > Dotan Cohen wrote: >> >> 2008/10/19 Stef Mientki : >> >>> >>> Sorry but for GUI design, Python is pre-historic ;-) >>> Stef >>> >> >> Really, even with the cross-platform Qt bindings? >> > > I skipped Qt because of the weird license > (I make both commercial and free-open software) >> >> Can you recommend a better language? (not java no please not java) >> >> > > As said VB or even much better Delphi ! > > But to be honest, > wanting the same language for commercial and open software, > I'm very satisfied with Python, and must say it's much more beautiful > language than Delphi, seen over the full width of programming. > Although both languages are Object Oriented, > for some (unknown) reason it's 10 times easier to maintain and extend > libraries in Python than in Delphi. > I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! > And with wxPython and some tools I made, I almost have the same environment > as Delphi. > Really, you recommend that VB apps destined for migration be recoded in Delphi, as opposed to Python? I will look further into that language. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From bdesth.quelquechose at free.quelquepart.fr Mon Oct 6 14:44:10 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Oct 2008 20:44:10 +0200 Subject: lint for Python? In-Reply-To: References: Message-ID: <48ea5c8d$0$22971$426a74cc@news.free.fr> Pat a ?crit : > I've been searching for a good multi-module lint checker for Python and > I haven't found one yet. > > Pylint does a decent job at checking for errors only within a single > module. > > Here's one of my problems. I have two modules. > > In module one, I have a function: > > def foo( host, userid, password ): > pass > > In module two, I call that function: > > foo( userid, password) > > lint doesn't find that error Nope, but even the most simple manual test should find it pretty quick. > and it won't be caught until it's called > while the program is running. I don't want that error found at 3AM. Don't you ever test your code ??? > I've never used a language that didn't catch that type of error. It does. Just try to run your code, and you'll have a nice traceback. Unless of course 'foo' is rebound in module two to another callable expecting only two parameters... > I'm > quite surprised that Python is being used by a number of major > companies. Perhaps do they rely more on testing and less on the compiler ? FWIW, I've seen my share of bugs in declarativly statically typed languages, and most of them were way nastier (and way less obvious) than the above one. > How you catch these types of errors? Just like any other type of errors : testing, testing, and then add some more tests. From nobody at nospam.noway Fri Oct 10 09:49:46 2008 From: nobody at nospam.noway (RossRGK) Date: Fri, 10 Oct 2008 09:49:46 -0400 Subject: FLexible formatted text involving nested lists? In-Reply-To: References: Message-ID: <31426$48ef5d80$d1d94b81$12971@PRIMUS.CA> Kerri Reno wrote: > Ross, > > I'm no expert in python, so excuse me if this is inane. > > What I would do is have fmts be a dictionary where > fmts = { 3 = 'oats %0d kilos over %0d days with %0d workers', > 2 = 'barley %0d lbs for %0d hours', > 1 = 'apples %0d baskets'} > > then something like > for x in bigList: > print fmts[len(x)] % x > > I didn't test this, but in theory it should work. > > Hope this helps, > Kerri Thx for the suggestion - i think that would match the number of fields to the number of parameters in the specific example but not the general case. ie fmts[3] could have 3fields this time, but might be 2 another time or something else. Plus I don't think print will accept a list 'x' in the %x part of it. From bruno.42.desthuilliers at websiteburo.invalid Fri Oct 3 04:26:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 03 Oct 2008 10:26:33 +0200 Subject: Professional quality scripts/code In-Reply-To: <50809a11-6f20-45fa-b2f4-128456ce1ce6@m74g2000hsh.googlegroups.com> References: <50809a11-6f20-45fa-b2f4-128456ce1ce6@m74g2000hsh.googlegroups.com> Message-ID: <48e5d70a$0$1572$426a74cc@news.free.fr> robean a ?crit : > I have been learning Python for the last 3 months or so and I have a > working (but somewhat patchy) sense of the the language. I've been > using a couple of the more popular Python books as well as online > resources. > > A question for experienced Python programmers: can you recommend > resources where I can look at high quality Python code and scripts? Well... Not everything is 'high quality' in it[1], but why not start with the stdlib ? Most of it is pure Python, opensource code and is already installed on your machine, isn't it ?-) [1] IIRC, last time I had a look at the zipfile module's code, it was more of a Q&D hack than anything else - now as long as it works fine for what I do with it and I don't have to maintain it, well, that's fine. > I've spent some time at http://code.activestate.com/recipes/ but am > concerned that the quality of what is posted there can be somewhat hit > and miss. Indeed. > What I have in mind is a site like cpan, where one can look > at the actual source code of many of the modules and learn a thing or > two about idiomatic Perl programming from studying the better ones. > Any sites like that for Python? Lurking here is probably a good way to see a lot of code reviews. And even possibly to submit snippets of your own code to review. Some (if not most) of us here like to show how good we are at improving the poor newbies code !-) From andy55 at gmail.com Fri Oct 24 09:58:06 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Fri, 24 Oct 2008 06:58:06 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <6m974kFfs9nlU1@mid.individual.net> <51fb3c73-278c-4919-a330-9cdaa9a6a50d@e2g2000hsh.googlegroups.com> Message-ID: <940ffec5-8294-4dbb-a773-df110594344e@79g2000hsk.googlegroups.com> On Oct 24, 9:35?am, sturlamolden wrote: > Instead of "appdomains" (one interpreter per thread), or free > threading, you could use multiple processes. Take a look at the new > multiprocessing module in Python 2.6. That's mentioned earlier in the thread. > > There is a fundamental problem with using homebrew loading of multiple > (but renamed) copies of PythonXX.dll that is easily overlooked. That > is, extension modules (.pyd) are DLLs as well. Tell me about it--there's all kinds of problems and maintenance liabilities with our approach. That's why I'm here talking about this stuff. > There are other options as well: > > - Use IronPython. It does not have a GIL. > > - Use Jython. It does not have a GIL. > > - Use pywin32 to create isolated outproc COM servers in Python. (I'm > not sure what the effect of inproc servers would be.) > > - Use os.fork() if your platform supports it (Linux, Unix, Apple, > Cygwin, Windows Vista SUA). This is the standard posix way of doing > multiprocessing. It is almost unbeatable if you have a fast copy-on- > write implementation of fork (that is, all platforms except Cygwin). This is discussed earlier in the thread--they're unfortunately all out. From lipun4u at gmail.com Fri Oct 24 05:46:00 2008 From: lipun4u at gmail.com (asit) Date: Fri, 24 Oct 2008 02:46:00 -0700 (PDT) Subject: dictionary Message-ID: what the wrong with the following code ???? >>> d={"server":"mpilgrim","database":"master", ... "uid":"sa", ... "pwd":"secret"} >>> d {'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'} >>> ["%s="%s" % (k,v) for k,v in d.items()] File "", line 1 ["%s="%s" % (k,v) for k,v in d.items()] ^ SyntaxError: EOL while scanning single-quoted string From kay.schluehr at gmx.net Sun Oct 19 00:34:13 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 18 Oct 2008 21:34:13 -0700 (PDT) Subject: Linux.com: Python 3 makes a big break References: Message-ID: On 18 Okt., 22:01, Jean-Paul Calderone wrote: > Perhaps it also omitted the fact that nothing prevents you from defining a > function to write things to stdout (or elsewhere) in Python 2.5, making the > Python 3.x change largely a non-feature. ;) > > Jean-Paul Even more. If someone had solved the hard problem of finding a less cumbersome way of writing sys.stdout.write(...) the request for multiline lambdas ( multi expression lambdas actually ) could have been decreased about 75-80%. From mail at timgolden.me.uk Thu Oct 23 03:53:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 23 Oct 2008 08:53:52 +0100 Subject: Dummy explanation to win32com needed In-Reply-To: <563079e6-9458-4ec7-8545-473765899bb3@u28g2000hsc.googlegroups.com> References: <563079e6-9458-4ec7-8545-473765899bb3@u28g2000hsc.googlegroups.com> Message-ID: <49002D90.2060906@timgolden.me.uk> korean_dave wrote: > Hi. I need a dummy's explanation to utilizing the win32com component > to access Microsoft Excel. > > So far, I have this code. > > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > xl.Visible = 1 > > workbook = xl.Workbooks.Open("C:\test.xls") Well, for a start, you want to be raw-stringing that filename. (And, possibly, putting it somewhere other than the root of your c: drive ;) ) > Now, my question is, where do I find the snytax I can use to access > such functions like workbook.ActiveSheet.Cells(1,1).Value etc... All the pywin32 / win32com stuff is doing is wrapping the Microsoft Excel Object Model. So, if you want to drive Excel you have two tools: the Macro Recorder in Excel itself; and Google: http://www.google.co.uk/search?q=site%3Amicrosoft.com+excel%20object%20model TJG From quentel.pierre at wanadoo.fr Fri Oct 31 17:19:31 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Fri, 31 Oct 2008 14:19:31 -0700 (PDT) Subject: brackets content regular expression References: <405e1745-2b3e-4ab7-812d-f9dbba2dad45@o40g2000prn.googlegroups.com> <461dc81d-e71f-4c72-ac5f-74afab74af28@o40g2000prn.googlegroups.com> <90409f7e-22e3-4f95-af3a-e2ad419ae608@c36g2000prc.googlegroups.com> Message-ID: <38fd462d-830d-4e9d-846e-be592deb96d8@c36g2000prc.googlegroups.com> On 31 oct, 20:38, netimen wrote: > there may be different levels of nesting: > > "a < b < ? > d > here starts a new group: < 1 < e < f ?> g > 2 > > another group: < 3 >" > > On 31 ???, 21:57, netimen wrote: > > > Thank's but if i have several top-level groups and want them match one > > by one: > > > text = "a < b < ? > d > here starts a new group: ?< e < f ?> g >" > > > I want to match first " b < ? > d " and then " e < f ?> g " but not " > > b < ? > d > here starts a new group: ?< e < f ?> g " > > On 31 ???, 20:53, Matimus wrote: > > > > On Oct 31, 10:25?am, netimen wrote: > > > > > I have a text containing brackets (or what is the correct term for > > > > '>'?). I'd like to match text in the uppermost level of brackets. > > > > > So, I have sth like: 'aaaa 123 < 1 aaa < t bbb < a ff > > 2 > > > > > bbbbb'. How to match text between the uppermost brackets ( 1 aaa < t > > > > bbb < a ff > > 2 )? > > > > > P.S. sorry for my english. > > > > I think most people call them "angle brackets". Anyway it should be > > > easy to just match the outer most brackets: > > > > >>> import re > > > >>> text = "aaaa 123 < 1 aaa < t bbb < a ff > > 2 >" > > > >>> r = re.compile("<(.+)>") > > > >>> m = r.search(text) > > > >>> m.group(1) > > > > ' 1 aaa < t bbb < a ff > > 2 ' > > > > In this case the regular expression is automatically greedy, matching > > > the largest area possible. Note however that it won't work if you have > > > something like this: " ". > > > > Matt > > Hi, Regular expressions or pyparsing might be overkill for this problem ; you can use a simple algorithm to read each character, increment a counter when you find a < and decrement when you find a > ; when the counter goes back to its initial value you have the end of a top level group Something like : def top_level(txt): level = 0 start = None groups = [] for i,car in enumerate(txt): if car == "<": level += 1 if not start: start = i elif car == ">": level -= 1 if start and level == 0: groups.append(txt[start+1:i]) start = None return groups print top_level("a < b < 0 > d > < 1 < e < f > g > 2 > < 3 >") >> [' b < 0 > d ', ' 1 < e < f > g > 2 ', ' 3 '] Best, Pierre From tjreedy at udel.edu Wed Oct 1 16:14:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 01 Oct 2008 16:14:09 -0400 Subject: Peek inside iterator (is there a PEP about this?) In-Reply-To: <200810011046.33309.kyrie@uh.cu> References: <200810011046.33309.kyrie@uh.cu> Message-ID: Luis Zarrabeitia wrote: > Hi there. > > For most use cases I think about, the iterator protocol is more than enough. > However, on a few cases, I've needed some ugly hacks. > > Ex 1: > > a = iter([1,2,3,4,5]) # assume you got the iterator from a function and > b = iter([1,2,3]) # these two are just examples. > > then, > > zip(a,b) > > has a different side effect from > > zip(b,a) > > After the excecution, in the first case, iterator a contains just [5], on the > second, it contains [4,5]. I think the second one is correct (the 5 was never > used, after all). I tried to implement my 'own' zip, but there is no way to > know the length of the iterator (obviously), and there is also no way > to 'rewind' a value after calling 'next'. Interesting observation. Iterators are intended for 'iterate through once and discard' usages. To zip a long sequence with several short sequences, either use itertools.chain(short sequences) or put the short sequences as the first zip arg. > Ex 2: > > Will this iterator yield any value? Like with most iterables, a construct > > if iterator: > # do something > > would be a very convenient thing to have, instead of wrapping a 'next' call on > a try...except and consuming the first item. To test without consuming, wrap the iterator in a trivial-to-write one_ahead or peek class such as has been posted before. > Ex 3: > > if any(iterator): > # do something ... but the first true value was already consumed and > # cannot be reused. "Any" cannot peek inside the iterator without > # consuming the value. If you are going to do something with the true value, use a for loop and break. If you just want to peek inside, use a sequence (list(iterator)). > Instead, > > i1, i2 = tee(iterator) > if any(i1): > # do something with i2 This effectively makes two partial lists and tosses one. That may or may not be a better idea. > Question/Proposal: > > Has there been any PEP regarding the problem of 'peeking' inside an iterator? Iterators are not sequences and, in general, cannot be made to act like them. The iterator protocol is a bare-minimum, least-common-denominator requirement for inter-operability. You can, of course, add methods to iterators that you write for the cases where one-ahead or random access *is* possible. > Knowing if the iteration will end or not, and/or accessing the next value, > without consuming it? Is there any (simple, elegant) way around it? That much is trivial. As suggested above, write a wrapper with the exact behavior you want. A sample (untested) class one_ahead(): "Self.peek is the next item or undefined" def __init__(self, iterator): try: self.peek = next(iterator) self._it = iterator except StopIteration: pass def __bool__(self): return hasattr(self, 'peek') def __next__(self): # 3.0, 2.6? try: next = self.peek try: self.peek = next(self._it) except StopIteration: del self.peek return next except AttrError: raise StopIteration Terry Jan Reedy From sthembilengidi at gmail.com Wed Oct 22 06:21:21 2008 From: sthembilengidi at gmail.com (Amie) Date: Wed, 22 Oct 2008 03:21:21 -0700 (PDT) Subject: Create a message Message-ID: Hi, I would like to know if it's possible to display a message using python, if so can you show me an example. I saw something like:" from twisted.python import log log.msg" in some programs but am not too sure how it works Or provide me with the link that has info regarding that Thanks Amie From rhamph at gmail.com Tue Oct 28 16:03:56 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 28 Oct 2008 13:03:56 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <49024ADC.4080600@g.nevcal.com> Message-ID: <777f7a0f-3061-4881-a5e9-b3e19422dca4@q26g2000prq.googlegroups.com> On Oct 28, 9:30?am, "Andy O'Meara" wrote: > On Oct 25, 9:46?am, "M.-A. Lemburg" wrote: > > > These discussion pop up every year or so and I think that most of them > > are not really all that necessary, since the GIL isn't all that bad. > > Thing is, if the topic keeps coming up, then that may be an indicator > that change is truly needed. ?Someone much wiser than me once shared > that a measure of the usefulness and quality of a package (or API) is > how easily it can be added to an application--of any flavors--without > the application needing to change. > > So in the rising world of idle cores and worker threads, I do see an > increasing concern over the GIL. ?Although I recognize that the debate > is lengthy, heated, and has strong arguments on both sides, my reading > on the issue makes me feel like there's a bias for the pro-GIL side > because of the volume of design and coding work associated with > considering various alternatives (such as Glenn's "Py*" concepts). > And I DO respect and appreciate where the pro-GIL people come from: > who the heck wants to do all that work and recoding so that a tiny > percent of developers can benefit? ?And my best response is that as > unfortunate as it is, python needs to be more multi-threaded app- > friendly if we hope to attract the next generation of app developers > that want to just drop python into their app (and not have to change > their app around python). ?For example, Lua has that property, as > evidenced by its rapidly growing presence in commercial software > (Blizzard uses it heavily, for example). > > > > > Furthermore, there are lots of ways to tune the CPython VM to make > > it more or less responsive to thread switches via the various sys.set*() > > functions in the sys module. > > > Most computing or I/O intense C extensions, built-in modules and object > > implementations already release the GIL for you, so it usually doesn't > > get in the way all that often. > > The main issue I take there is that it's often highly useful for C > modules to make subsequent calls back into the interpreter. I suppose > the response to that is to call the GIL before reentry, but it just > seems to be more code and responsibility in scenarios where it's no > necessary. ?Although that code and protocol may come easy to veteran > CPython developers, let's not forget that an important goal is to > attract new developers and companies to the scene, where they get > their thread-independent code up and running using python without any > unexpected reengineering. ?Again, why are companies choosing Lua over > Python when it comes to an easy and flexible drop-in interpreter? ?And > please take my points here to be exploratory, and not hostile or > accusatory, in nature. > > Andy Okay, here's the bottom line: * This is not about the GIL. This is about *completely* isolated interpreters; most of the time when we want to remove the GIL we want a single interpreter with lots of shared data. * Your use case, although not common, is not extraordinarily rare either. It'd be nice to support. * If CPython had supported it all along we would continue to maintain it. * However, since it's not supported today, it's not worth the time invested, API incompatibility, and general breakage it would imply. * Although it's far more work than just solving your problem, if I were to remove the GIL I'd go all the way and allow shared objects. So there's really only two options here: * get a short-term bodge that works, like hacking the 3rd party library to use your shared-memory allocator. Should be far less work than hacking all of CPython. * invest yourself in solving the *entire* problem (GIL removal with shared python objects). From rhamph at gmail.com Wed Oct 22 18:06:10 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 22 Oct 2008 15:06:10 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: Message-ID: <99c79637-e56b-4d73-9a3d-debb9a1140be@k36g2000pri.googlegroups.com> On Oct 22, 10:32?am, Andy wrote: > Dear Python dev community, > > I'm CTO at a small software company that makes music visualization > software (you can check us out atwww.soundspectrum.com). ?About two > years ago we went with decision to use embedded python in a couple of > our new products, given all the great things about python. ?We were > close to using lua but for various reasons we decided to go with > python. ?However, over the last two years, there's been one area of > grief that sometimes makes me think twice about our decision to go > with python... > > Some background first... ? Our software is used for entertainment and > centers around real time, high-performance graphics, so python's > performance, embedded flexibility, and stability are the most > important issues for us. ?Our software targets a large cross section > of hardware and we currently ship products for Win32, OS X, and the > iPhone and since our customers are end users, our products have to be > robust, have a tidy install footprint, and be foolproof. ?Basically, > we use embedded python and use it to wrap our high performance C++ > class set which wraps OpenGL, DirectX and our own software renderer. > In addition to wrapping our C++ frameworks, we use python to perform > various "worker" tasks on worker thread (e.g. image loading andprocessing). ?However, we require *true* thread/interpreter > independence so python 2 has been frustrating at time, to say the > least. ?Please don't start with "but really, python supports multiple > interpreters" because I've been there many many times with people. > And, yes, I'm aware of the multiprocessing module added in 2.6, but > that stuff isn't lightweight and isn't suitable at all for many > environments (including ours). ?The bottom line is that if you want to > perform independentprocessing (in python) on different threads, using > the machine's multiple cores to the fullest, then you're out of luck > under python 2. > > Sadly, the only way we could get truly independent interpreters was to > put python in a dynamic library, have our installer make a *duplicate* > copy of it during the installationprocess(e.g. python.dll/.bundle -> > python2.dll/.bundle) and load each one explicitly in our app, so we > can get truly independent interpreters. ?In other words, we load a > fresh dynamic lib for each thread-independent interpreter (you can't > reuse the same dynamic library because the OS will just reference the > already-loaded one). > > From what I gather from the python community, the basis for not > offering "real" muti-threaded support is that it'd add to much > internal overhead--and I couldn't agree more. ?As a high performance C > and C++ guy, I fully agree that thread safety should be at the high > level, not at the low level. ?BUT, the lack of truly independent > interpreters is what ultimately prevents using python in cool, > powerful ways. ?This shortcoming alone has caused game developers-- > both large and small--to choose other embedded interpreters over > python (e.g. Blizzard chose lua over python). ?For example, Apple's > QuickTime API is powerful in that high-level instance objects can > leverage performance gains associated with multi-threadedprocessing. > Meanwhile, the QuickTime API simply lists the responsibilities of the > caller regarding thread safety and that's all its needs to do. ?In > other words, CPython doesn't need to step in an provide a threadsafe > environment; it just needs to establish the rules and make sure that > its own implementation supports those rules. > > More than once, I had actually considered expending company resources > to develop a high performance, truly independent interpreter > implementation of the python core language and modules but in the end > estimated that the size of that project would just be too much, given > our company's current resources. ?Should such an implementation ever > be developed, it would be very attractive for companies to support, > fund, and/or license. ?The truth is, we just love python as a > language, but it's lack of true interpreter independence (in a > interpreter as well as in a thread sense) remains a *huge* liability. > > So, my question becomes: is python 3 ready for true multithreaded > support?? ?Can we finally abandon our Frankenstein approach of loading > multiple identical dynamic libs to achieve truly independent > interpreters?? I've reviewed all the new python 3 C API module stuff, > and all I have to say is: whew--better late then never!! ?So, although > that solves modules offering truly independent interpreter support, > the following questions remain: > > - In python 3, the C module API now supports true interpreter > independence, but have all the modules in the python codebase been > converted over? ?Are they all now truly compliant? ?It will only take > a single static/global state variable in a module to potentially cause > no end of pain in a multiple interpreter environment! ?Yikes! > > - How close is python 3 really to true multithreaded use? ?The > assumption here is that caller ensures safety (e.g. ensuring that > neither interpreter is in use when serializing data from one to > another). > > I believe that true python independent thread/interpreter support is > paramount and should become the top priority because this is the key > consideration used by developers when they're deciding which > interpreter to embed in their app. Until there's a hello world that > demonstrates running independent python interpreters on multiple app > threads, lua will remain the clear choice over python. ?Python 3 needs > true interpreter independence and multi-threaded support! What you describe, truly independent interpreters, is not threading at all: it is processes, emulated at the application level, with all the memory cost and none of the OS protections. True threading would involve sharing most objects. Your solution depends on what you need: * Killable "threads" -> OS processes * multicore usage (GIL removal) -> OS processes or alternative Python implementations (PyPy/Jython/IronPython) * Sane shared objects -> safethread From rridge at csclub.uwaterloo.ca Tue Oct 21 08:13:44 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 21 Oct 2008 08:13:44 -0400 Subject: What's the perfect (OS independent) way of storing filepaths ? References: <010c6145$0$20670$c3e8da3@news.astraweb.com> Message-ID: Ross Ridge wrote: > However, the normal place to store settings on Windows is in the registry. Lawrence D'Oliveiro wrote: > Which becomes a single point of failure for the whole system. As opposed to the file system being the single point failure? Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From pommereau at univ-paris12.fr Mon Oct 6 08:00:31 2008 From: pommereau at univ-paris12.fr (franck) Date: Mon, 6 Oct 2008 05:00:31 -0700 (PDT) Subject: What AugStore and AugLoad AST nodes are? Message-ID: Dear all, I'm experimenting with new ast module. I'd like to have pieces of code that can generate AugLoad and AugStore AST nodes. Indeed, I actually do not know what they correspond to. Thanks for any help! Franck From castironpi at gmail.com Fri Oct 17 13:47:42 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 17 Oct 2008 10:47:42 -0700 (PDT) Subject: How to transfer data structure or class from Python to C/C++? References: <7085c400-94ef-441f-b727-48ec7b66051d@p10g2000prf.googlegroups.com> <4b2c771b-7be0-47a6-8c64-346f97a3fefb@v39g2000pro.googlegroups.com> Message-ID: On Oct 16, 9:10?am, Hongtian wrote: > Not exactly. > > In my C/C++ application, I have following function or flow: > > void func1(....) > { > ? ? call PyFunc(struct Tdemo, struct &Tdemo1); > > } > > I mean I want to invoke Python function 'PyFunc' and transfer a data > structure 'Tdemo' to this function. After some process in Python, I > want it return 'Tdemo1' back to the C/C++ application. > > I research boost.python and think it is not a reasonable solution > because it make the C/C++ application too complex. > > Thanks. > > On Oct 16, 12:09?pm, "Aaron \"Castironpi\" Brady" > > wrote: > > On Oct 15, 8:08?pm, Hongtian wrote: > > > > Hi friends, > > > > I am a newer of Python. I want to ask below question: > > > > I have a C/C++ application and I want to use Python as its extension. > > > To do that, I have to transfer some data structure from C/C++ > > > application to Python and get some data structure from Python to C/C++ > > > application. I have researched Python document, but the example only > > > describes how to transfer some simple data, such as integer,char, > > > etc. > > > > Could you please guide me to do that? or tell me some document to have > > > a research? > > > > Thanks. Did you have any luck? From gagsl-py2 at yahoo.com.ar Wed Oct 1 05:10:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 01 Oct 2008 06:10:50 -0300 Subject: list to tuple conversion References: Message-ID: En Wed, 01 Oct 2008 04:51:33 -0300, sc escribi?: > Thanx to a recent thread I am able to have a print string > with a variable number of formatters -- what I now lack for > the creation of an elegant print statement is a tuple -- > following is the code, the last line of which does not work: > > for i in range(1, len(h.m)): > k = "r%06d" % i > col = len(h.m[k]) > if col > 2 and h.m[k][0] > " ": > print (col * '%-30s') % h.m[k] > Another alternative would be: print ''.join('%-30s' % item for item in h.m[k]) You may need to add square brackets [ ] inside the parenthesis () if your Python version is older than 2.5 -- Gabriel Genellina From jtownsen at adobe.com Thu Oct 16 17:05:16 2008 From: jtownsen at adobe.com (John Townsend) Date: Thu, 16 Oct 2008 14:05:16 -0700 Subject: Dictionary of Dicts question In-Reply-To: <59077563-2BFE-4DA6-853F-79965F1017C2@strout.net> References: <59077563-2BFE-4DA6-853F-79965F1017C2@strout.net> Message-ID: Joe had a good point! Let me describe what problem I'm trying to solve and the list can recommend some suggestions. I have two text files. Each file contains data like this: Test file 1234 4567 8975 I want to compare the numbers in each text file. The data set (i.e. the numbers) has a unique identifier: the "test" + the "file". The text files are similar, but may not be exactly the same. My initial idea was to read the text files and turn each line into a dictionary entry. A dict for each text file. Then walk through the dicts and compare the numbers. If anyone has a better idea, I'd love to hear it. -----Original Message----- From: Joe Strout [mailto:joe at strout.net] Sent: Thursday, October 16, 2008 1:49 PM To: John Townsend Subject: Re: Dictionary of Dicts question On Oct 16, 2008, at 1:19 PM, John Townsend wrote: > Accessing values is pretty straightforward (nice change from my Perl > days). For example: > > myDict['TestName']['FileName']['ct_shutdown'] > > in Python interpreter yields > > 9021 FWIW, I'd recommend you scrap this dict-of-dicts structure and instead define a class (or three). You'll know you have it right when instead of the above, you're typing something like: myDict['TestName'].FileName.ct_shutdown (The division might be a little different -- it's not entirely clear to me what in your sample code is just place-holder names, and what is meant literally.) > However, when I try to add, let's say, a new FileName entry, I end > up replacing the previous FileName entry. > > In Python interpreter, I try: > > myDict['TestName'] = {'NewFileName': {}, } Well, yes, this code says "stuff the new dictionary {'NewFileName':{}} into myDict under 'TestName', replacing whatever was under 'TestName' before." If that's not what you want, then don't do that -- assign to myDict['TestName2'] or some such. > So, how do I add a new entry without replacing the old entry? You don't; that's the whole point of dictionaries. A dictionary maps keys to values. You can't have two values for the same key. You could have a key map to a list, but I suspect we're straying a bit far now from whatever it is you're trying to accomplish. If you can explain what it is you're actually trying to accomplish (without reference to implementation details like dictionaries and entries), maybe we can suggest a suitable approach. Best, - Joe From frank.niemeyer at uni-ulm.de Wed Oct 22 10:48:25 2008 From: frank.niemeyer at uni-ulm.de (Frank Niemeyer) Date: Wed, 22 Oct 2008 16:48:25 +0200 Subject: Append a new value to dict In-Reply-To: <48F33AC3.80505@wu-wien.ac.at> References: <48F33AC3.80505@wu-wien.ac.at> Message-ID: <48ff3d36$1@news.uni-ulm.de> > However incrementing a non-existing key throws an exception. Right. And that's exactly what I would expect, according to the "principle of least surprise" Python tries to obey. There's simply no way to increment a non-existent value - not without performing some obscure implict behind-the-scenes stuff. > So you > either have to use a workaround: > > >>> try: > ... counter['B'] += 1 > ... except KeyError: > ... counter['B'] = 1 Or you could simply use if counter.has_key('B'): counter['B'] += 1 else: counter['B'] = 1 Regards, Frank From skip at pobox.com Wed Oct 8 11:59:44 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 8 Oct 2008 10:59:44 -0500 Subject: distributing apps without the Python source? In-Reply-To: <6l41pbFaj22eU1@mid.uni-berlin.de> References: <6l41pbFaj22eU1@mid.uni-berlin.de> Message-ID: <18668.55536.60851.944896@montanaro-dyndns-org.local> Marc> On Wed, 08 Oct 2008 09:18:47 -0600, Joe Strout wrote: >> We have a client who's paranoid about distributing the Python source >> to his commercial app. Is there some way I can distribute and use >> just the .pyc files, so as to not give away the source? Marc> Yes. Just use the *.pyc files. Though of course there is decompyle to consider, assuming Joe's client is truly paranoid. Skip From phillip.oldham at gmail.com Thu Oct 23 16:14:00 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 23 Oct 2008 13:14:00 -0700 (PDT) Subject: Will Python 3 be "stackless"? Message-ID: <2c0b3d73-0a4b-432a-b188-dd0b381cbe34@f40g2000pri.googlegroups.com> Will Python 3 be "stackless"? Or, rather, will it have any features similar to stackless' microthreads and channels? From george.sakkis at gmail.com Mon Oct 6 15:53:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 6 Oct 2008 12:53:55 -0700 (PDT) Subject: lint for Python? References: <48ea5c8d$0$22971$426a74cc@news.free.fr> Message-ID: On Oct 6, 3:49 pm, Pat wrote: > I'll come back with more intelligent questions after I've actually > learned some Python. That's a wise self-advice ;-) From rtw at freenet.co.uk Thu Oct 23 15:36:33 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 23 Oct 2008 14:36:33 -0500 Subject: Perl/Python regular expressions vs. Boost.regex? References: Message-ID: wrote in news:mailman.2906.1224773327.3487.python-list at python.org in comp.lang.python: > A colleague wrote a C++ library here at work which uses the > Boost.regex library. I quickly discovered an apparent problem with > how it searches. Unlike re.match the regex_match function in that > library effectively anchors the match at both the start and the end. > Can other people confirm this? > > Thx, > > Skip Montanaro > Quoting from : Important Note that the result is true only if the expression matches the whole of the input sequence. If you want to search for an expression somewhere within the sequence then use regex_search. If you want to match a prefix of the character string then use regex_search with the flag match_continuous set. So yes it does. Rob. -- http://www.victim-prime.dsl.pipex.com/ From alan.isaac at gmail.com Wed Oct 15 17:12:30 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Wed, 15 Oct 2008 21:12:30 GMT Subject: read zipfile sequentially? In-Reply-To: References: Message-ID: <21tJk.1264$Rx2.9@nwrddc01.gnilink.net> On 10/15/2008 3:13 PM Tim Chase apparently wrote: > http://mail.python.org/pipermail/python-list/2007-December/469320.html Ask and ye shall receive... Thank you! Alan Isaac From fabiofz at gmail.com Wed Oct 15 15:47:42 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 15 Oct 2008 16:47:42 -0300 Subject: IDE Question In-Reply-To: <5695f4bb-cc2a-4faf-b643-44e34434a97b@d70g2000hsc.googlegroups.com> References: <7069e0d8-ec46-44a9-8604-d2fa5b33c26c@m36g2000hse.googlegroups.com> <5695f4bb-cc2a-4faf-b643-44e34434a97b@d70g2000hsc.googlegroups.com> Message-ID: >> Now, following that route, many people call Eclipse is the 21st >> century Emacs... ;-) >> > > I don't want to kick off an editor war or anything, but I don't think > that Eclipse is anywhere near being a 21st century emacs, Peace! I'm far from starting any war too (I don't usually try to convince anyone about choosing a tool, as I believe that there's no such thing as the correct choice there, only different points of view and experiences -- the right thing is trying for yourself and deciding what you like better -- but at least I'm going to answer to some of your comments to try to be informative here). > unless > there's been a whole lot of progress with it since the last time I > used it. With emacs, I can have multiple files open in one window, > with the window split (I don't remember eclipse being able to do this, > although it allowed multiple files in their own tabs), You should be able to have it.... having multiple views for the same file: although it does that by doing a new editor, and then you can place that new editor as you want -- below some existing, to the right, etc -- or you can use an external plugin for something more closer to what emacs has: http://wiki.eclipse.org/Implement_Split_File_Editor_Functionality_for_the_Eclipse_IDE -- note: I don't personally use that -- usually I try to keep the modules small ;-) > and I can > customize the actions of the editor on the fly, without restarting it, > in a variant of LISP. That may be possible in Eclipse, I don't really > know. Depends on what you want: http://fabioz.com/pydev/manual_articles_scripting.html (but that's just one of lots of ways to customize it) > I used to use Eclipse and pydev, but once I learned my way around > emacs, I haven't gone back to it for anything. I probably would if I > did any coding in Java - but I don't. I'm exponentially more > productive with emacs while writing python code than I ever was with > Eclipse. I must say that I'm totally the other way around... even being productive in emacs, there's really no comparison there for me (disclaimer: I'm the author of Pydev, so, that's expected, but I know many people that changed to it and say the same thing) > Add to that the degree to which emacs is customizable (just about > everything that the editor does can be customized, you can jump > quickly to the source of the functions you're running while editing, > you can easily patch behavior in before or after specific function > calls, you can easily define keyboard macros and bind them to > keystrokes, and / or save them for future use, you can easily create > keystrokes that correspond to interactive filling out of templates - > "skeletons", etc), and I really don't see how someone could think that > Eclipse is anywhere near being a replacement for emacs. The one thing I miss in Eclipse (for which I use notepad++) is the macros, but that's about it... Everything else is highly customizable for me in Eclipse / Pydev... everything else is there (templates, keybindings, jumping through code: going fast to any file/definition you want in your project, hyperlinking in console, etc) Also, I don't think outside of Eclipse there's anything close to what Mylyn gives you in terms of knowing what code is really important when working on a task ( http://www.eclipse.org/mylyn/ ). > Not to mention that I don't need to have X installed to run emacs if I > don't need it. > > I may be wrong about the capabilities of Eclipse, as I haven't used it > in about a year, and emacs certainly has it's own set of quirks and > annoyances - one of which being the very steep learning curve. Eclipse also has that -- And I'm pretty sure that the more you use a tool the more you get productive in it. > Watching the screencasts linked in the blog post you linked to, I > might prefer Eclipse to emacs if I wasn't very used to never touching > a mouse, or if I was developing under windows. With my editing mindset > the way it is right now, when I see that, I just see a lot of wasted > screen space, and a lot of wasted time doing things like intellisense. > Also, the blog post didn't really give any reasons as to _why_ the > person switched over, other than that they were impressed with > Eclipse. I (almost) never do touch my mouse inside eclipse too ;-) And yes, it's very subjective. > Meh, I'm not talking trash on Eclipse - it's a fine tool if it fits > how you work with text / code. It's just not for me, and I would feel > crippled while using it if I switched back to it. I used IDEs like > that for a few years, but after about a month and a half of using > emacs, I haven't looked back. I even use it as my IRC client when I > jump on IRC. Yeap, having lots of plugins is something both emacs and eclipse have -- and until now, living within Eclipse has been a pleasant journey to me ;-) Also, as I said in the other post, choosing where you'll develop it's a highly subjective thing, so, the right thing to do is look the options, try them and decide for yourself. > I do think that people should try a variety of styles of editors to > find what works best for them though - although it does take a lot of > time to learn your way around 3 or 4 different editors, once you find > what fits with you, you will probably get a huge boost in productivity. Totally agree with that. Cheers, Fabio From ldo at geek-central.gen.new_zealand Mon Oct 20 21:07:29 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 21 Oct 2008 14:07:29 +1300 Subject: What's the perfect (OS independent) way of storing filepaths ? References: <010b4bb3$0$20653$c3e8da3@news.astraweb.com> <010bad29$0$20653$c3e8da3@news.astraweb.com> <010c838b$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <010c838b$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > And 75% [1] of average Windows users will either delete the file, move it > to a more convenient[2] location, or edit the file name to remove the dot. Doesn't seem very likely to me. Experienced Dimdows users would well know that stuffing around with files they don't understand is liable to break some application or another, so they shouldn't do it. > [2] And they are right to do so. Programs that dump config files and > directories, hidden or not, in the top level of the user's home directory > are incredibly rude. It may have been a Unix standard for as long as > there has been a Unix, but it's still the programming equivalent of > coming into somebody's house and throwing your tools all over their > living room floor. Hmm, actually you have a point there. There's also the security issue, in that other users can tell what apps you've been using based on the dotfiles present in your home directory. From gagsl-py2 at yahoo.com.ar Tue Oct 14 15:02:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 14 Oct 2008 16:02:10 -0300 Subject: Question References: <608380240810132325sf398ec8x765780937c99baf7@mail.gmail.com> <608380240810132327s4b0f941bl7f37b3b9e50aaa24@mail.gmail.com> Message-ID: En Tue, 14 Oct 2008 03:27:37 -0300, Aditi Meher escribi?: > I am using ubuntu operating system,i am using python and self app for > DB storage. > > I hv already mentioned in my question that i want to display 10 > records out of 100,how to create buffer to store remaining records > which i am not displaying. > > I know the logic,but my language of sytax is not good so i want actual > code please can u mail it to me. > > I have created DB using self app and after that created table using > python into DB, i hv also inserted the records into it using python. Maybe you're making things more complicated that they should be. You don't have to create a "buffer" to store records. If you only want to move forward (that is, you don't have to show previous records) just keep the cursor, and use cursor.fetchmany(10) to fetch the next 10 rows to show. If you have to move back and forth, just use cursor.fetchall and store the result (this is your "buffer", a list of records). For 100 records that's all you need. If you expect it to grow to 100000 records, or have many users concurrently updating the database, this might not be the right answer. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Oct 15 15:54:58 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 15 Oct 2008 21:54:58 +0200 Subject: Emacs users: feedback on diffs between python-mode.el and python.el? In-Reply-To: <7xvdvug7pn.fsf@ruckus.brouhaha.com> References: <7xvdvug7pn.fsf@ruckus.brouhaha.com> Message-ID: <48f66676$0$8018$426a74cc@news.free.fr> Paul Rubin a ?crit : > skip at pobox.com writes: >> If you're an Emacs user who has used both python-mode.el (the python mode >> code distributed with Python and XEmacs) and python.el (the python mode code >> distributed with GNU Emacs), I'd like to get your impressions on how they >> compare and where you feel the bugs lie. > > I'm not sure which is which--there is one that I'm used to from older > systems, and one on newer systems (Ubuntu Hardy) that gratutiously > broke features that I'm used to. I haven't gotten around to > investigating but will try to do so. Main thing I know is that C-c ! > used to make a new Python subwindow and now it doesn't, which is bad. The first one is python-mode.el, the second one is python.el From steve at REMOVE-THIS-cybersource.com.au Sat Oct 4 20:16:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Oct 2008 00:16:50 GMT Subject: Tuple parameter unpacking in 3.x References: <871vyyy8mb.fsf@hbox.dyndns.org> <87fxnco0v1.fsf@hbox.dyndns.org> Message-ID: <00f800fd$0$20633$c3e8da3@news.astraweb.com> On Sat, 04 Oct 2008 17:07:14 +0200, Martin Geisler wrote: > A somewhat related question: do I pay a performance penalty when I let a > function define an inner function like this: > > def foo(): > > def bar() > ... > > bar() > > compared to just defining it once outside: > > def bar(): > ... > > def foo(): > ... > bar() > > I'm thinking that each execution of the first foo could spend a little > time defining a new bar each time, or is that not how things work? > > I realize that defining bar as an inner function has the advantage of > being able to see variables in the namespace of foo. That is the main advantage, followed by reducing namespace pollution, but yes there is a very small performance penalty. >>> def outer(x): ... return x+1 ... >>> def func(x): ... return outer(x+1) ... >>> >>> def func2(x): ... def inner(x): ... return x+1 ... return inner(x+1) ... >>> assert func(37) == func2(37) >>> from timeit import Timer >>> t1 = Timer('func(23)', 'from __main__ import func') >>> t2 = Timer('func2(23)', 'from __main__ import func2') >>> t1.repeat() [1.5711719989776611, 0.82663798332214355, 0.82708191871643066] >>> t2.repeat() [1.8273210525512695, 1.1913230419158936, 1.1786220073699951] -- Steven From eckhardt at satorlaser.com Thu Oct 30 04:28:39 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 30 Oct 2008 09:28:39 +0100 Subject: Unicode Problem References: Message-ID: Seid Mohammed wrote: > I am new to python. Welcome! :) >>>> abebe = '??? ?? ??' >>>> abebe > '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 \xe1\x89\xa0\xe1\x88\xb6 > \xe1\x89\xa0\xe1\x88\x8b' >>>> print abebe > ??? ?? ?? >>>> abeba = ['???','??','??'] >>>> abeba > ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', > '\xe1\x89\xa0\xe1\x88\x8b'] >>>> print abeba > ['\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0', '\xe1\x89\xa0\xe1\x88\xb6', > '\xe1\x89\xa0\xe1\x88\x8b'] >>>> len(abebe) > 23 > ======================== > so my question is > 1)why >>> abebe prints '\xe1\x8a\xa0\xe1\x89\xa0\xe1\x89\xa0 > \xe1\x89\xa0\xe1\x88\xb6 \xe1\x89\xa0\xe1\x88\x8b' instead of ??? ?? > ?? > 2) why >>> print abeba don't print the expected ??? ?? ?? string When you just type an identifier X on the commandline, Python outputs the result of calling repr(X). This typically gives you something that you could enter in any Python program. Note that e.g. the string '??? ?? ??' is not suitable in any Python program, it requires an encoding where those characters are supported like e.g. UTF-8. Now, if you type "print X" on the commandline, it will output the thing as a string instead, giving you the original contents. If, like for a list, no string representation exists, it will fall back to using repr() instead. Disclaimer: I'm not a pro yet myself, but I think this covers the background a bit. Maybe someone will correct me if I'm horribly wrong. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From mycoffe13 at gmail.com Sat Oct 11 10:33:57 2008 From: mycoffe13 at gmail.com (mycoffe13 at gmail.com) Date: Sat, 11 Oct 2008 07:33:57 -0700 (PDT) Subject: Real Story USA Message-ID: <3b2352c5-11bf-4e8b-b157-a4002a5763ab@m73g2000hsh.googlegroups.com> REAL STORY of USA?? HEY friend?s please read this...this is a real story happened Recently for a Student in AMERICA....one guy was studying his under graduation in one of american university....he was studying hard. he was one among the best in the school..the problem with him was, he was BADLY POOR...he didn?t had money, to pay for his next semester...one day he, while Browsing the internet saw an advertisement about frenzin.com ?..it is a social networking site...he saw some basic things in that like join frenzin.com , Invite your friends through BULK InViTiES, Add Photos and Music...share it with your friends.. Add your own community in GROUPS... Comment on Music and Photos and Rate it... Send Messages to your friends.... and "win Free Gifts".... Suddenly the student had joined frenzin.com and invited about 313 people..added 87 photos and 22 music...he commented on allmost all photos and music...and rated it...he joined groups and created his own groups....Suddenly on one day the student got a Message on his frenzin Mailbox sent by frenzin company..it said? ?we are happy to announce that, you won Three Gifts. one for inviting many people to join our network, two for sharing good photos..and three for messaging to your frenz??? . . . . hey frenz you believe it or not this student had got $3000 as cash check...and $500 as gift check...he got hard money from frenzin...how he got money ??? ok ?..frenzin, when contacted him again for his bank details and address (to send him gifts)...student replied them saying... ? Iam very poor, I need money rather than Gifts, To pay my semester fee?. frenzin saw his hard work on their site, understood the situation and gave him CASH CHECK...its Really hard to believe,..iam so shocked when i heard this news....but iam happy, that this student continued his education...we must thank frenzin team for this great support..In todays world with so many BAD people around us, there is still some good people like frenzin team...which is really great... So I am Requesting all of you to Join frenzin.com click the below link....or copy paste if it doesn?t work?? http://www.frenzin.com/join_form.php From http Fri Oct 31 14:33:04 2008 From: http (Paul Rubin) Date: 31 Oct 2008 11:33:04 -0700 Subject: Testing dictionary results with doctest References: Message-ID: <7xr65wobrz.fsf@ruckus.brouhaha.com> Joe Strout writes: > >>> t.match( "The rain in Spain falls mainly on the train." ) > {'object': 'rain', 'location': 'Spain', 'subloc': 'train'} You can compare dictionaries for equality: >>> t.match( "The rain in Spain falls mainly on the train." ) == \ {'object': 'rain', 'location': 'Spain', 'subloc': 'train'} True From skip at pobox.com Sat Oct 25 15:04:08 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 25 Oct 2008 14:04:08 -0500 Subject: Perl/Python regular expressions vs. Boost.regex? In-Reply-To: References: Message-ID: <18691.28072.925254.267222@montanaro-dyndns-org.local> Rob> Quoting from : Rob> Rob> Important Rob> Note that the result is true only if the expression matches the Rob> whole of the input sequence. If you want to search for an Rob> expression somewhere within the sequence then use regex_search. If Rob> you want to match a prefix of the character string then use Rob> regex_search with the flag match_continuous set. Rob> Rob> So yes it does. Thanks. I'll try and convince my colleague to use regex_search instead of regex_match. Skip From gdyren at gmail.com Fri Oct 17 06:32:59 2008 From: gdyren at gmail.com (gdyren at gmail.com) Date: Fri, 17 Oct 2008 03:32:59 -0700 (PDT) Subject: no mistake but i didnt get what i want (with python module pymssql send information to the mssql) Message-ID: <4bff370e-7f72-4adc-a042-2823fdc9365e@u27g2000pro.googlegroups.com> the code is below: import pymssql conn = pymssql.connect(host = "121.198.126.233",user = "xxxx",password = "xxxx",database = "test") print "connecting success" cursor = conn.cursor() cursor.execute("insert into bbs_test values(%s,%s,%s,%s,%s)", ("1","nju","9:13","ustc","test")) cursor.close() conn.close() in the idle: connecting success then i get into the database :test and find that there is nothing in the table bbs_test. i don't know why From hrishys at yahoo.co.uk Thu Oct 2 09:32:22 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 2 Oct 2008 13:32:22 +0000 (GMT) Subject: Sample code required to validate a xml file against XSD Message-ID: <219519.10441.qm@web27401.mail.ukl.yahoo.com> Hi Does anybody have a python xample program to validate a xml file against a XSD. regards Hrisy From bearophileHUGS at lycos.com Mon Oct 13 09:11:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 13 Oct 2008 06:11:28 -0700 (PDT) Subject: strip module bug References: Message-ID: Poppy: > var = "detail.xml" > print var.strip(".xml") ### expect to see 'detail', but get 'detai' > var = "overview.xml" > print var.strip(".xml") ### expect and get 'overview' Python V.2.5 is not flawless, but you can't find bugs so easily. I've found only two bugs in about three years of continuous usage (while I have found about 27 new different bugs in the DMD compiler in about one year of usage). str.strip() isn't a module, and generally in Python it's called "method", in this case a method of str (or unicode). str.strip() as optional argument doesn't take the string you want to remove, but a string that represent the set of chars you want to strip away from both ends, so: >>> "detail.xml".strip("lmx.") 'detai' >>> "detail.xml".strip("abcdlz") 'etail.xm' To strip the ending ".xml" you can use the str.partition() method, or an alternative solution: >>> var = "detail.xml" >>> suffix = ".xml" >>> if var.endswith(suffix): ... var2 = var[: -len(suffix)] ... >>> var2 'detail' Bye, bearophile From homeshop18.grouping at gmail.com Tue Oct 7 07:37:27 2008 From: homeshop18.grouping at gmail.com (Online Shopping) Date: Tue, 7 Oct 2008 04:37:27 -0700 (PDT) Subject: Acer Laptops 4520NWXMi Athlon LX.AHS0C.032 Message-ID: Buy low price Acer Acer Laptops 4520NWXMi Athlon LX.AHS0C.032 - buy best Acer Aspire Laptops 4520NWXMi Athlon LX.AHS0C.032 online at lowest price at homeshop18 laptops shop. For more information visit: http://www.homeshop18.com/shop/u/y/p-Computers-Q-and-Q-Peripherals-S-Laptops-S-Acer-Q-Aspire-Q-4520NWXMi-Q-Athlon-Q-LX.AHS0C.032-Q-Notebook/Home_Online-pI_20266-clI_2-cI_920-pCI_909- From steve at holdenweb.com Tue Oct 14 10:49:20 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Oct 2008 10:49:20 -0400 Subject: Installing Python 2.4 over 2.4? In-Reply-To: References: Message-ID: W. eWatson wrote: > I suspect something has been corrupted in Python 2.4. Can I just > re-install on top of it, and still expect to have scipy and other pkgs > I've installed? On Windows, certainly - you can even uninstall and reinstall and retain your installed libraries. On Linux I am pretty sure the same is true, but caveat emptor. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From manu3d at gmail.com Fri Oct 31 12:04:14 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Fri, 31 Oct 2008 09:04:14 -0700 (PDT) Subject: Exec and Scope References: Message-ID: On Oct 31, 4:38?am, Rafe wrote: > If you are just looking to execute an attribute (be it a property, > module-level function, instance or class method, or anything else > which is an attribute of an object), just use getattr(). I must check this out. My understanding is that getAttr returns a function object that happens to be a method of that object. I can then invoke that function as if I was invoking the method of that object. What I don't know is: will the function work in a scope where the object is not defined? And even if it does, what happens to the names that refer to the containeR or containeD objects? I've read what I could in the manual about the data model, scope and namespaces but as you can probably see there still are things I do not fully comprehend. I feel a bit like seeing the dots but not quite being able to make the connections between them just yet. Thanks for your help though! This is providing me with a few ideas for some more tests to do. Manu From alan.isaac at gmail.com Fri Oct 17 19:43:11 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 17 Oct 2008 23:43:11 GMT Subject: bibtex parsing In-Reply-To: <7ca3a627-5a28-49c6-9c74-33258c484c03@a70g2000hsh.googlegroups.com> References: <7ca3a627-5a28-49c6-9c74-33258c484c03@a70g2000hsh.googlegroups.com> Message-ID: On 10/17/2008 6:14 PM Paul McGuire apparently wrote: > Visit the pyparsing wiki for all sorts of applications. Here is > a BibTeX parser submitted by pyparsing wiki user ero-sennin: > http://pyparsing.wikispaces.com/WhosUsingPyparsing#pybtex > I don't know what the license is. GPL unfortunately. Thanks! Alan From Kevin.Smith at sas.com Mon Oct 27 11:02:05 2008 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Mon, 27 Oct 2008 10:02:05 -0500 Subject: PIL: Getting a two color difference between images References: Message-ID: On 2008-10-25 12:41:51 -0500, bearophileHUGS at lycos.com said: > Kevin D. Smith: >> What I want is a two color output image: black where the image wasn't >> different, and white where it was different.< > > There are several ways to do that. If speed isn't essential, then you > can create a third blank image of the right size, and then use the > method that iterates on the pixels of an image, and assign p1 != p2 at > every pixel of the third image. > > If speed is important you can copy the images into numpy arrays and > then your operation becomes easy. > > Maybe there are built-in ways in PIL too, I don't know. You can also > find an intermediate solution, like computing the difference image > with PIL and then binarize it manually. This last method is what I ended up doing for now. I use the PIL differencing function, then walk through the result of getdata() to binarize it. I was hoping there might be a way to run a filter or something that might be faster, but I haven't figured it out. -- Kevin D. Smith From da.martian at gmail.com Tue Oct 21 04:14:56 2008 From: da.martian at gmail.com (ChaosKCW) Date: Tue, 21 Oct 2008 01:14:56 -0700 (PDT) Subject: pymssql - execute loads all results into memory! References: <767a6cf1-4968-4e95-8a0b-62adf871d399@s1g2000prg.googlegroups.com> <92da89760810200732p733977dfu1ac1f44ec44ee436@mail.gmail.com> Message-ID: On Oct 20, 3:38?pm, Tim Golden wrote: > Eric Wertman wrote: > >> I am trying to use pymssql, and have an issue where by the execute > >> (not the fetch) is appearing to load all records into memory. > > >> if I execute > > >> con = pymssql.connect(...) > >> cur = con.cursor() > >> cur.execute(sql) > >> rec ?= cur.fetchone() > > >> if I put in a query which returns a lot of records into "sql" then the > >> execute never returns, pythons memory usage slowly ballons till the > >> machine cant give anymore. If I put a sql query returning only few > >> rows, then it works fine. > > >> So I am not sure why an execute would feel the need to load all rows, > >> but its seriously crippling. Does anyone know if this is a bug or > >> something I can "turn off" > > > I ran into this myself. ?After some digging I discovered that what you > > are after is a server-side cursor that isn't implemented yet in > > pymssql. ?There is one in MySQLdb, but it's not the default behavior. > > Regardless of your usage (fetchone vs fetchmany), the result set is > > held client side. ?AFAIK the only workaround is to keep your result > > set small (enough). ?If you use fetchmany and iterate over it > > directly, it may keep your memory usage down, ?I can't remember if > > that worked. ?I definitely tried making a generator with it, that did > > not help. > > ... or just switch to pyodbc, for example, which behaves > perfectly well with this snippet against a table of >24 million > rows: > > > import pyodbc > > conn = [ > ? "Driver={SQL Server}", > ? "Server=SVR17", > ? "Database=TDI", > ? "TrustedConnection=Yes" > ] > db = pyodbc.connect (";".join (conn)) > q = db.cursor () > q.execute ("SELECT * FROM revenue") # 24 million rows > q.fetchone () > q.close () > > > > TJG Thanks for the responses, I am astounded any db api tool doesnt support cursors! pymssql is mostly useless, I will switch to an odbc interface. From bearophileHUGS at lycos.com Fri Oct 3 06:22:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 3 Oct 2008 03:22:28 -0700 (PDT) Subject: Fun with reverse sorts References: Message-ID: Chris Rebert: > So the improved code is: > your_list.sort(key=lambda elem: (elem[3], elem[2]), reverse=True) Better (untested): from operator import itemgetter ... your_list.sort(key=itemgetter(3, 2), reverse=True) Bye, bearophile From ms at cerenity.org Wed Oct 22 20:04:24 2008 From: ms at cerenity.org (Michael Sparks) Date: Thu, 23 Oct 2008 01:04:24 +0100 Subject: Best way to spawn process on back end computer References: <1e5e14be-4d24-44c9-8867-76b46dd47573@t41g2000hsc.googlegroups.com> Message-ID: sophie_newbie wrote: > Hi, > > I'm running a python cgi script on a frontend web server and I want it > to spawn another script (that takes a long time to run) on a backend > number crunching server thats connected to the same network. What do > you think is the best way to do this? I have a few ideas but I'm sure > there is a "best" way to go about this. Best is always subjective - what sort of interaction are you after? Web request to trigger an activity (fire and forget) Web request to trigger an activity, which produces output suitable for something else? Web request to trigger an activity, which produces output after a while that you want to send back over a later web request? Web request to trigger an activity, which produces output after a while that you want to send back over a later web request, and you want to easily tie the two things together? Web request to trigger an activity, which produces output after a while that you want to send back over a later web request, and you want those two events to look like part of one operation? Picking a concrete example... Or something a bit more like: * User uploads an image * Gets converted to a bunch of standard sizes, and placed into a queue for moderation and then later use? Or perhaps: * User uploads a video * That gets transcoded to a different video format ? (eg video contribution transcoded to flash video?) In the latter two cases, this is something I've needed to do, so I created a simple WSGI filter that dumps the uploaded images/videos into a standard file location, and then had a script that watches that standard location for new images & videos, and does those conversions and transcodes. Strictly speaking to be "clean" about it, you need to dump the file to a temporary location whilst you're grabbing it from the network and when it's been written to disk rename it. I've no idea if this maps to your problem at all. (since I can think of a few scenarios that match your description). If it does match, then this code may be handy: http://code.google.com/p/kamaelia/source/browse/branches/private_MPS_Participate/Apps/FileProcessor/App/BatchFileProcessor.py If you want to use that code, let me know and I'll package it up. There's an older version here: * http://www.kamaelia.org/release/Kamaelia-FileProcessor-0.1.0.tar.gz Regards, Michael. -- http://www.kamaelia.org/Home From ssharkey at linuxunlimited.com Thu Oct 30 10:28:00 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 30 Oct 2008 10:28:00 -0400 Subject: Single string vs list of strings Message-ID: <4909C470.1030309@linuxunlimited.com> Hi All, I have a need to determine whether a passed variable is a single string, or a list of strings. What is the most pythonic way to do this? Thanks. -Scott From martin at v.loewis.de Tue Oct 14 14:49:26 2008 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 14 Oct 2008 20:49:26 +0200 Subject: Upgrading from 2.5 to 2.6 In-Reply-To: References: <9gt4f4934btvoh6cdc1lql61moi0409lmm@4ax.com> <48F2CD0D.2070406@v.loewis.de> <27b3bff1-8388-45d9-af00-8ea6972a0e53@a18g2000pra.googlegroups.com> <48F42D9A.7000601@v.loewis.de> Message-ID: <48f4e9b6$0$16343$9b622d9e@news.freenet.de> > I'd say the wording in the installer is unfortunate. The option is > labeled "Register extensions" and for some time I thought it was related > to .pyd/.dll files ("C extensions"), not "Associate .py files to this > Python installation" Unfortunately, I think this is too long for the available space. Regards, Martin From mseagoe at gmail.com Mon Oct 27 16:29:25 2008 From: mseagoe at gmail.com (Mark) Date: Mon, 27 Oct 2008 13:29:25 -0700 (PDT) Subject: Unpacking byte strings from a file of unknown size Message-ID: <5adcb40f-3b97-4fb7-b534-ab323bdb7636@s1g2000prg.googlegroups.com> Hi; I'm trying to use the struct.unpack to extract an int, int, char struct info from a file. I'm more accustomed to the file.readlines which works well in a 'for' construct (ending loop after reaching EOF). # This does OK at fetching one 10-byte string at a time: # (4, 4, 2 ascii chars representing hex) info1, info2, info3 = struct.unpack(' References: Message-ID: <48e645a7$0$28904$9b4e6d93@newsspool1.arcor-online.net> Sean Davis wrote: > I have an xml document and simply need to add an xml-stylesheet to > it. I am using lxml to parse the xml document and then would like to > insert the xml-stylesheet tag using the etree api. Any suggestions? I assume you are talking about a processing instruction here, not a tag. Use the .addprevious() method on the root Element with a PI object. Stefan From electronixtar at gmail.com Mon Oct 20 09:30:09 2008 From: electronixtar at gmail.com (est) Date: Mon, 20 Oct 2008 06:30:09 -0700 (PDT) Subject: a question about Chinese characters in a Python Program References: <31544011-a013-42b6-acfc-586261cc33f5@r36g2000prf.googlegroups.com> <88023378-be29-4533-951d-3c7c3d3f6827@64g2000hsu.googlegroups.com> Message-ID: On Oct 20, 6:47?pm, Paul Boddie wrote: > On 20 Okt, 07:32, est wrote: > > > > > Personally I call it a serious bug in python > > Normally I'd entertain the possibility of bugs in Python, but your > reasoning is a bit thin (inhttp://bugs.python.org/issue3648):"Why > cann't Python just define ascii to range(256)" > > I do accept that it can be awkward to output text to the console, for > example, but you have to consider that the console might not be > configured to display any character you can throw at it. My console is > configured for ISO-8859-15 (something like your magical "ascii to > range(256)" only where someone has to decide what those 256 characters > actually are), but that isn't going to help me display CJK characters. > A solution might be to generate UTF-8 and then get the user to display > the output in an appropriately configured application, but even then > someone has to say that it's UTF-8 and not some other encoding that's > being used. As discussed in another recent thread, Python 2.x does > make some reasonable guesses about such matters to the extent that > it's possible automatically (without magical knowledge). > > There is also the problem about use of the "str" built-in function or > any operation where some Unicode object may be converted to a plain > string. It is now recommended that you only convert to plain strings > when you need to produce a sequence of bytes (for output, for > example), and that you indicate how the Unicode values are encoded as > bytes (by specifying an encoding). Python 3.x doesn't really change > this: it just makes the Unicode/text vs. bytes distinction more > obvious. > > Paul Thanks for the long comment Paul, but it didn't help massive errors in Python encoding. IMHO it's even better to output wrong encodings rather than halt the WHOLE damn program by an exception When debugging encoding problems, the solution is simple. If characters display wrong, switch to another encoding, one of them must be right. But it's tiring in python to deal with encodings, you have to wrap EVERY SINGLE character expression with try ... except ... just imagine what pain it is. Just like the example I gave in Google Groups, u'\ue863' can NEVER be encoded into '\xfe\x9f'. Not a chance, because python REFUSE to handle a byte that is greater than range(128). Strangely the 'mbcs' encoding system can. Does 'mbcs' have magic or something? But it's Windows-specific Dealing with character encodings is really simple. AFAIK early encoding before Unicode, although they have many names, are all based on hacks. Take Chinese characters as an example. They are called GB2312 encoding, in fact it is totally compatible with range(256) ANSI. (There are minor issues like display half of a wide-character in a question mark ? but at least it's readable) If you just output serials of byte array, it IS GB2312. The same is true with BIG5, JIS, etc. Like I said, str() should NOT throw an exception BY DESIGN, it's a basic language standard. str() is not only a convert to string function, but also a serialization in most cases.(e.g. socket) My simple suggestion is: If it's a unicode character, output as UTF-8; other wise just ouput byte array, please do not encode it with really stupid range(128) ASCII. It's not guessing, it's totally wrong. From deets at nospam.web.de Wed Oct 15 10:24:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 15 Oct 2008 16:24:58 +0200 Subject: urllib accept-language doesn't have any effect References: Message-ID: <6lmcpiFd08p7U1@mid.uni-berlin.de> Martin Bachwerk wrote: > Hello, > > I'm trying to load a couple of pages using the urllib2 module. The > problem is that I live in Germany and some sites seem to look at the IP > of the client and forward him to a localized page.. Here's an example of > the code, how I want to access google.com main english page, but get > German instead. (For those of you who live in US, you will probably get > correct results.. try emulating with 'fr' in accepted languages or > something) > > opener = urllib2.build_opener() > opener.addheaders = [('Host', 'www.google.com'), > ('Accept-Language','en-gb,en;q=0.5'), ('User-agent', 'Mozilla/5.0 > (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.1) Gecko/2008070208 > Firefox/3.0.1')] > webfile = opener.open(url) > > Any help would be greatly appreciated! What is your actual problem - does it work with *other* requests you somehow produce (browser or some such)? In the end, it's up to the site you query to return you whatever they see fit. Nothing urllib or python in general can change. Diez From vincehofmeister at gmail.com Fri Oct 10 18:12:31 2008 From: vincehofmeister at gmail.com (vincehofmeister at gmail.com) Date: Fri, 10 Oct 2008 15:12:31 -0700 (PDT) Subject: Modification of a urllib2 object ? References: <67360ab7-2679-4cac-9841-767f797778ad@8g2000hse.googlegroups.com> <355b358b-6a35-4cae-a7dc-5c22016cd959@l62g2000hse.googlegroups.com> Message-ID: <3b4392ae-fd35-4748-9456-8376b429b0de@34g2000hsh.googlegroups.com> On Oct 10, 1:02 pm, George Sakkis wrote: > On Oct 10, 2:32 pm, vincehofmeis... at gmail.com wrote: > > > > > I have several ways to the following problem. > > > This is what I have: > > > ... > > import ClientForm > > import BeautifulSoup from BeautifulSoup > > > request = urllib2.Request('http://form.com/) > > > self.first_object = urllib2.open(request) > > > soup = BeautifulSoup(self.first_object) > > > forms = ClienForm.ParseResponse(self.first_object) > > > Now, when I do this, forms returns an index errror because no forms > > are returned, but the BeautifulSoup registers fine. > > First off, please copy and paste working code; the above has several > syntax errors, so it can't raise IndexError (or anything else for that > matter). > > > > > Now, when I switch the order to this: > > > import ClientForm > > import BeautifulSoup from BeautifulSoup > > > request = urllib2.Request('http://form.com/) > > > self.first_object = urllib2.open(request) > > > forms = ClienForm.ParseResponse(self.first_object) > > > soup = BeautifulSoup(self.first_object) > > > Now, the form is returned correctly, but the BeautifulSoup objects > > returns empty. > > > So what I can draw from this is both methods erase the properties of > > the object, > > No, that's not the case. What happens is that the http response object > returned by urllib2.open() is read by the ClienForm.ParseResponse or > BeautifulSoup - whatever happens first - and the second call has > nothing to read. > > The easiest solution is to save the request object and call > urllib2.open twice. Alternatively check if ClientForm has a parse > method that accepts strings instead of urllib2 requests and then read > and save the html text explicitly: > > >>> text = urllib2.open(request).read() > >>> soup = BeautifulSoup(text) > >>> forms = ClientForm.ParseString(text) > > HTH, > George request = urllib2.Request(settings.register_page) self.url_obj = urllib2.urlopen(request).read() soup = BeautifulSoup(self.url_obj); forms = ClientForm.ParseResponse(self.url_obj, backwards_compat=False) print forms images = HtmlHelper.getCaptchaImages(soup) self.webView.setHtml(str(soup)) #here we generate the popup dialog Dialog = QtGui.QDialog() ui = captcha_popup.Ui_Dialog() ui.setupUi(Dialog, self) ui.webView.setHtml(str(images[0])); ui.webView_2.setHtml(str(images[1])); Dialog.raise_() Dialog.activateWindow() Dialog.exec_() Dialog.show() Now I am getting this error: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\PyQt4\POS Pounder\Oct7\oct.py", line 1251, in createAccounts forms = ClientForm.ParseResponse(self.url_obj, backwards_compat=False) File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg \ClientForm.py", line 1054, in ParseResponse AttributeError: 'str' object has no attribute 'geturl' From martin at v.loewis.de Sat Oct 25 15:27:57 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 25 Oct 2008 21:27:57 +0200 Subject: sqlite version for python 2.6 In-Reply-To: References: Message-ID: <4903733d$0$8562$9b622d9e@news.freenet.de> > I'd like to know which version of sqlite the python 2.6 sqlite3 module > supports. When you compile Python, you can chose any version of sqlite that you want to. Regards, Martin From 20080915.20.wmcclain at spamgourmet.com Fri Oct 31 10:50:59 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 31 Oct 2008 14:50:59 GMT Subject: Windows DOS box redirection References: <20253039.post@talk.nabble.com> Message-ID: On 2008-10-31, Tim Golden wrote: > You've got a few options. Ok, thanks! It is a small hobbyist community. I'll just document it and tell them "life is hard for Windows users." -Bill -- Sattre Press The King in Yellow http://sattre-press.com/ by Robert W. Chambers info at sattre-press.com http://sattre-press.com/kiy.html From robin at alldunn.com Wed Oct 8 22:01:32 2008 From: robin at alldunn.com (Robin Dunn) Date: Wed, 08 Oct 2008 19:01:32 -0700 Subject: wxPython binaries for Python 2.6 Message-ID: <48ED65FC.5030504@alldunn.com> Hi All, A set of wxPython binaries for Python 2.6 on Win32, Win64 and Mac OS X are now available at http://wxpython.org/download.php What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From tino at wildenhain.de Mon Oct 27 09:41:47 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 27 Oct 2008 14:41:47 +0100 Subject: xchat In-Reply-To: References: Message-ID: <4905C51B.7000609@wildenhain.de> Hi, luca72 wrote: > Hello > > i have installed xchat on suse11 i see that there is the possibility > to use python for make some script, i see also that the python > interface is loaded, but when in python i type import xchat i get that > the module don't exist. > where is the module? > I try also to ask in the xchat forum but i get no reply so i try here try it again from within xchat. See the documentation for the python console (like a chat to python interpreter) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From apardon at forel.vub.ac.be Wed Oct 29 06:38:54 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Oct 2008 10:38:54 GMT Subject: Finding the instance reference of an object References: <0107e3de$0$20638$c3e8da3@news.astraweb.com> <168EBF3C-9299-4AF3-A86F-8A16B7130A91@strout.net> Message-ID: On 2008-10-17, Joe Strout wrote: >> Python's assignment semantics (as opposed to its "object handling, a >> term for which I have no referent) are not the same as those of, say >> C. > > They are, though. The only difference you've pointed out is that > *numbers* are different in Python vs. C, and that's an internal > implementation detail I was blissfully unaware of until this > discussion. (I'm grateful to know it, but it really doesn't matter in > day-to-day coding.) No they are not. An assignment in Python is like making an (new) alias/reference, while an asignment in C is copying the content of one variable into another. -- Antoon Pardon From steve at REMOVE-THIS-cybersource.com.au Thu Oct 23 18:17:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Oct 2008 22:17:36 GMT Subject: Question about scope References: <4900a518$0$12849$426a34cc@news.free.fr> Message-ID: <0110f0fd$0$20657$c3e8da3@news.astraweb.com> On Thu, 23 Oct 2008 21:08:12 -0400, Pat wrote: > Stripping out the extra variables and definitions, this is all that > there is. > Whether or not this technique is *correct* programming is irrelevant. Oh rly? Well, sure, you can write bad code if you like, and make your actual job much harder. No skin off our nose, except when you come along asking for free debugging out of the goodness of our hearts. > I simply want to know why scoping doesn't work like I thought it would. > > > ---> myGlobals.py file: > > class myGlobals(): > remote_device_enabled = bool Creates a class myGlobals with a class attribute called "remote_device_enabled" which is equal to the class bool. Why not just initialise it to True here? Why is it a class attribute instead of an instance attribute? > ---> my initialize.py file: > > from myGlobals import * Creates a name called "myGlobals" which is local to this module. It is bound to the same myGlobals class as defined by myGlobals.py module. > def initialize(): > myGlobals.remote_device_enabled = True Sets the class attribute remote_device_enabled to a useful value at last. > ---> my main.py file: > > import from myGlobals import * Gives a Syntax error. If you're not going to be bothered to test the code before you send it, I'm not sure I can be bothered to debug it for you. > RDE = myGlobals.remote_device_enabled Creates a local name RDE which takes its initial value from the class attribute remote_device_enabled. This could be more easily written as: RDE = bool since initialize() hasn't been called yet. > def main(): > if RDE: # this will not give me the correct value > process_device() Obvious something else is happening in your real code, because following the program logic you've shown (ignoring the SyntaxError), it should give the correct value: RDE is bool. By a lucky accident, "if bool" evaluates as True and process_device() will be called. I suggest that your spaghetti code is far more complicated and you haven't successfully teased out a minimal thread that demonstrates the problem. -- Steven From userprogoogle-139 at yahoo.co.uk Sun Oct 12 05:48:29 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Sun, 12 Oct 2008 02:48:29 -0700 (PDT) Subject: Download CGI Message-ID: <9894f25f-e89c-4674-8189-b7440fe18630@m32g2000hsf.googlegroups.com> Hi, I am trying to figure out how to create a Python script which will open a file from a folder outwith the public_html path and serve it directly to the user for downloading. The aim being so that the users cannot see where the file is served from. Is there an easy way to do this, or an HTML header I am missing or an easy way in Python? Best, rod From hv at tbz-pariv.de Thu Oct 30 03:56:58 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Thu, 30 Oct 2008 08:56:58 +0100 Subject: urlencode() doseq and Python 3.0 Message-ID: <6mt7maFhtdvkU1@mid.individual.net> Hi, I think the default of urlencode doseq being false is just there to preserve the old behavior. http://svn.python.org/view/python/branches/py3k/Lib/urllib/parse.py?rev=66199&sortby=date&view=markup {{{ ... if not doseq: # preserve old behavior }}} I guess no one want really wants this: >>> urllib.urlencode({'key': ['value1', 'value2']}) 'key=%5B%27value1%27%2C+%27value2%27%5D' I think this is what most people want: >>> urllib.urlencode({'key': ['value1', 'value2']}, doseq=True) 'key=value1&key=value2' Should I open a bug against 3.0? Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From martin at v.loewis.de Fri Oct 10 02:36:14 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 10 Oct 2008 08:36:14 +0200 Subject: Python 2.6, GUI not working on vista? In-Reply-To: References: <9f426393-cb5d-463a-8f84-8f541b84b1b5@d31g2000hsg.googlegroups.com> <8b30411a-3963-4f70-8977-1818f57b250f@h2g2000hsg.googlegroups.com> <48e75d94$0$25303$426a74cc@news.free.fr> <48EE7A98.5090300@v.loewis.de> Message-ID: <48EEF7DE.5070501@v.loewis.de> >> I know for a fact that the implementation is incomplete. In Windows >> Installer, there is no way (that I know of) to create an MSI file >> that conditionally turns on UAC, only when the installation actually >> needs privilege elevation. > > You cannot turn on (or turn off) UAC for a single application or > operation. That's the whole point of UAC. The installer runs in two phases: the UI phase, and the actual installation phase. They are separate processes, and UAC is invoked only in the middle (when it switches to the "server" phase). It would well be possible to invoke UAC conditionally, depending on what the UI phase learned. > Are you sure it worked with UAC enabled and a non-privileged account? > Anyway, here are some links regarding UAC: > > * http://www.codeproject.com/KB/vista-security/MakingAppsUACAware.aspx > * http://en.wikipedia.org/wiki/User_Account_Control#Requesting_elevation Unfortunately, these are irrelevant, since they talk about UAC wrt. applications. However, an MSI file is not an application, so all these settings and APIs don't apply. Regards, Martin From eckhardt at satorlaser.com Thu Oct 30 05:43:18 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 30 Oct 2008 10:43:18 +0100 Subject: Ascii codec can't encode References: <7a61ad70-bc83-4df3-b9f7-b6b6ff741056@r66g2000hsg.googlegroups.com> Message-ID: luca72 wrote: > Hy the code is this: > > Pok\xe9mon That's not what I meant, I meant a piece of Python source code. This piece has to be large enough to demonstrate the problem but with everything else removed. The point is that guessing what is wrong in your program is just futile; In order to help, people need information. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From tjreedy at udel.edu Wed Oct 1 16:21:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 01 Oct 2008 16:21:21 -0400 Subject: How to give a global variable to a function which is in a module? In-Reply-To: <8e0eceeb-6a58-4ffb-a521-6ff63b5856c6@m44g2000hsc.googlegroups.com> References: <8e0eceeb-6a58-4ffb-a521-6ff63b5856c6@m44g2000hsc.googlegroups.com> Message-ID: Kurda Yon wrote: > Hi, > > I would like to declare a global variable, which is seen to a > particular function. If I do as the following it works: > > x = 1 > def test(): > global x > print x > return 1 If you are just reading x, the global statement does nothing and is not needed. > However, it does not helps since my function is in a separate file. In > other words I have a main program which has the following structure: > > from test import test > x = 1 > y = test() > > and I have a test.py file which contains the "test" function: > def test(): > global x > print x > return 1 > > In this case the test does not see the global variable x. How can I > make the x to be visible? 'Global' means 'global to the current module in which the global statement appears. Yes this is confusing. 'Modular' would be more exact, but 'global' goes back to before Python when there were no separate modules connected together. Either pass x to the function (probably best) or put x into the imported module with 'test.x = 1". Terry Jan Reedy From duncan.booth at invalid.invalid Sat Oct 18 06:39:46 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Oct 2008 10:39:46 GMT Subject: loops References: <34025ed7-7807-4fa6-b921-2ddc16f2ef02@h60g2000hsg.googlegroups.com> Message-ID: Gandalf wrote: > how can I do width python a normal for loop width tree conditions like > for example : > > for x=1;x<=100;x+x: > print x > What you wrote would appear to be an infinite loop so I'll assume you meant to assign something to x each time round the loop as well. The simple Python translation of what I think you meant would be: x = 1 while x <= 100: print x x += x If you really insist on doing it with a for loop: def doubling(start, limit): x = start while x <= limit: yield x x += x ... for x in doubling(1, 100): print x From gagsl-py2 at yahoo.com.ar Mon Oct 27 03:21:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Oct 2008 05:21:40 -0200 Subject: Immutable object thread-safety References: <4f19db70-1c2a-41d1-97ae-f8b19f303ce1@34g2000hsh.googlegroups.com> <8M8Nk.3344$hc1.518@flpi150.ffdc.sbc.com> Message-ID: En Sun, 26 Oct 2008 23:25:09 -0200, Alcari The Mad escribi?: >> I am confused about which data structure to rely on thread-safety, or >> operator in Python? > All of the builtin functions(which are implemented in C, like len()) are > atomic(but assigning their output to a value may not be). You can't count on the builtins being atomic. len(x) executes type(x).__len__ if such method exists, which may execute arbitrary Python code, even trigger the garbage collector and run absolutely unrelated things. See this effbot page for discussion [1] - but in general, since the language reference doesn't specify whether an operation is atomic or not, you should not count on it. Use a lock when required. [1] http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm -- Gabriel Genellina From bernhard.voigt at gmail.com Thu Oct 30 09:40:51 2008 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Thu, 30 Oct 2008 06:40:51 -0700 (PDT) Subject: open a shell prompt froma python program References: <64876a2a-4078-48bc-8f77-d4e8dfff1aca@u18g2000pro.googlegroups.com> <22ea3426-83ca-4365-9688-49b87077b88f@z18g2000prn.googlegroups.com> <6mtgq8Fiqg88U1@mid.uni-berlin.de> <8aef8ae0-5b65-4e4b-a65a-f7b0c0676a31@c2g2000pra.googlegroups.com> Message-ID: <4ceb2a48-f93f-4427-9eef-2eef57efea4d@m73g2000hsh.googlegroups.com> On Oct 30, 11:53?am, gaurav kashyap wrote: > HI, > I am getting the following error: > > konsole: cannot connect to X server > > do i need to install the related files. Do you have an x-server running? I assume so, because you have a terminal window opened. If you became root using su, you need to allow connections to x- server, which is started by the regular user. you can do this for local access using $ xhost local: Best wishes! Bernhard From gagsl-py2 at yahoo.com.ar Thu Oct 2 01:43:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Oct 2008 02:43:56 -0300 Subject: what does "python -i" use as input stream (stdin)? References: Message-ID: En Wed, 01 Oct 2008 14:48:52 -0300, Almar Klein escribi?: > I wanted to give your solution a try, but got stuck. > The file that I want to replace the "standard input" with is a pseudo > file > object with a custom read method. I have a hard time finding out how > to have a file descriptor (or fileno) associated with it. > > I tried inheriting from the "file" class (using a dummy file on disk), > and > then > overriding the read() and __init__() method. To test I used > os.read(my_file_no,1), > but it reads the contents of my dummy file rather than using my read > method. > So obviously it does some low level stuff there... I did not understand completely what you want, and rereading previous posts I got even more confused... Could you provide a complete description of what you want to do? Is it a single process, or two separate processes? Running on the same machine or remotely? All python or there is another program involved? -- Gabriel Genellina From nospam at spamhaters.com Wed Oct 1 03:51:33 2008 From: nospam at spamhaters.com (sc) Date: Wed, 01 Oct 2008 02:51:33 -0500 Subject: list to tuple conversion Message-ID: clp: Thanx to a recent thread I am able to have a print string with a variable number of formatters -- what I now lack for the creation of an elegant print statement is a tuple -- following is the code, the last line of which does not work: #!/usr/bin/python import xml.sax import eaddyhandler parser = xml.sax.make_parser() h = eaddyhandler.EAddyHandler() parser.setContentHandler(h) parser.parse(".ea.xml") for i in range(1, len(h.m)): k = "r%06d" % i col = len(h.m[k]) if col > 2 and h.m[k][0] > " ": print (col * '%-30s') % h.m[k] What's going on is I have an oocalc spreadsheet for e-addresses -- column 1 has the name, and then I keep adding e-addresses for ppl when they get new ones, as successive entries on their row, meaning each row has a variable number of e-address columns. I have an xml extractor that runs before this script using odf.opendocument, which works famously. My class, EAddyHandler, also works, and builds its dictionary of rows in 'm', forgive me, no flames please, I needed a short name for the dictionary I have to type it so many times. The key to 'm' is an 'r' + row number, so I can get stuff out of it and it's still in the right order, fun with dictionaries. What I was hoping for was something that could vary the source for the print statement as cleanly as the 'col' multiplication creates the print format, but the list, 'h.m[k]' is not a tuple, it's a list, and I'm just not quite where I am trying to get with this. If there were a builtin function that took a list and returned a tuple, I'd be there, but if there is such a thing I need someone to point me at it. I can't help thinking I am missing some obvious construct, and I'll be advised to go reread the tutorial, but I'm not there, and if you can take pity on me and point me there, I'll be your friend for life. Well -- I'll be grateful... TIA, Scott From dotancohen at gmail.com Wed Oct 15 03:41:48 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 15 Oct 2008 09:41:48 +0200 Subject: Can Python fix vcard files? In-Reply-To: References: <41384953-e731-47ba-8a44-27d0124c0fe4@k37g2000hsf.googlegroups.com> <1ddce4a8-e11c-4b06-9859-32d69407e1ac@r66g2000hsg.googlegroups.com> Message-ID: <880dece00810150041n71d0a793qfeae2172736fe706@mail.gmail.com> 2008/10/15 Lawrence D'Oliveiro : >> I didn't find anything which forbids splitting quoted-printable >> character values in these specifications. > > What adds to the confusion is that quoted-printable has its own convention > for soft-wrapping long lines, using an equals sign followed by a newline. My test file has newlines not preceded by an equals sign: NOTE;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=D7=A9=D7=95=D7=A8=D7=94 =D7=A 8=D7=90=D7=A9=D7=95=D7=A0=D7=94.\n=D7=94=D7=A9=D7=95=D7=A8=D7=94 =D7=94=D7= A9=D7=A0=D7=99=D7=94 =D7=9B=D7=\n Is this not standards-compliant? It is going to be a pain writing code to work around that! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From steve at holdenweb.com Thu Oct 9 06:34:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Oct 2008 06:34:13 -0400 Subject: Python/Django hosting on "normal" hosting plans In-Reply-To: <48EC954F.1040605@tim.thechases.com> References: <4b9f23a2-75e8-4e4d-a05b-1ecd71ce3b58@t18g2000prt.googlegroups.com> <6l364gFaf29cU1@mid.uni-berlin.de> <20081008062253.uqlwejdjxcggowcw@syd-srv02.ezyreg.com> <48EC954F.1040605@tim.thechases.com> Message-ID: Tim Chase wrote: [In response t David Lyon] >> My questions are: >> >> - can most everyday vanilla linux web hosts run a django site ? >> >> - can most everyday vanilla linux web hosts run python web scripts? > > Depends on your definition of "most everyday vanilla linux web hosts". :) > > The bottom-of-the-barrel hosts will often (but not always) offer Python > CGI. Django "can" run in a CGI (google for "django cgi"[0]), but it's > an unpleasant experience because the entire Django framework gets > reloaded for *every* request. Doable/tolerable for a private > development/family page, but it will likely flounder under the slightest > load. > > This is like strapping a jet engine (Django) on a bicycle (CGI). [1] > Doable, but more for the macho-factor of "I got it working" rather than > the practical aspects. > > Your lowest-end hosting services won't offer mod_python or WSGI (either > Apache with mod_wsgi, or others like lighttpd with a wsgi interface) > though WSGI is becoming more popular. There are still some > shared-hosting solutions that facilitate using Django[2] pretty well. > They're not super-cheap, but they're affordable. The canonical catalog > of Django-friendly & Django-capable hosting services can be found at > [3]. If you're just starting out with Django, it might help to pay a > bit more for one of the click-n-go hosts, while others you'll have to do > some of the heavy lifting (installing Django, as well as possibly other > components, assembling your wsgi startup script, etc) yourself. > There's recently been a discussion about hosting on the django-users list, which I recommend you think about joining. Both WebFaction and SliceHost got high marks from many users. I personally use OpenHosting, who are very Python-friendly and mostly just let you ge on with what you want to do, which is great if you are comfortable managing your own email and web services. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From faheem at email.unc.edu Sat Oct 11 16:30:24 2008 From: faheem at email.unc.edu (Faheem Mitha) Date: Sat, 11 Oct 2008 20:30:24 +0000 (UTC) Subject: regular expression question (re module) Message-ID: Hi, I need to match a string of the form capital_letter underscore capital_letter number against a string of the form anything capital_letter underscore capital_letter number some_stuff_not_starting with a number Eg D_A1 needs to match with DUKE00001_plateD_A1.CEL, but not any of DUKE00001_plateD_A10.CEL, Duke00001_PlateD_A11v2.CEL, DUKE00001_plateD_A12.CEL. Similarly D_A10 needs to match DUKE00001_plateD_A10.CEL, but not any of DUKE00001_plateD_A1.CEL, Duke00001_PlateD_A11v2.CEL, DUKE00001_plateD_A12.CEL. Similarly D_A11 needs to match Duke00001_PlateD_A11v2.CEL, but not any of DUKE00001_plateD_A1.CEL, DUKE00001_plateD_A10.CEL, DUKE00001_plateD_A12.CEL. Thanks in advance. Please cc me with any reply. Faheem. From flaviostz at gmail.com Sun Oct 26 11:47:11 2008 From: flaviostz at gmail.com (flaviostz) Date: Sun, 26 Oct 2008 08:47:11 -0700 (PDT) Subject: Error when creating class Message-ID: <045e2b2f-f68d-43bf-810d-9df3719508e0@m74g2000hsh.googlegroups.com> Hi, I wrote this small program: class Simples: def minha_func (valor1, valor2): return valor1 - valor2 mf = Simples() x = mf.minha_func(2, 3) print x But when I try execute it, python interpreter gives me this error: >>> Traceback (most recent call last): File "/tmp/py91849hI", line 11, in x = mf.minha_func(2, 3) TypeError: minha_func() takes exactly 2 arguments (3 given) Please, help me with this issue. Thanks, Fl?vio From andy55 at gmail.com Tue Oct 28 10:23:44 2008 From: andy55 at gmail.com (Andy O'Meara) Date: Tue, 28 Oct 2008 07:23:44 -0700 (PDT) Subject: 2.6, 3.0, and truly independent intepreters References: <490026AC.6030604@cheimes.de> <2aeeb71e-885f-433b-a684-2cb2d501a508@q9g2000hsb.googlegroups.com> <63d8aa77-f863-4d8c-b135-2088d0b68760@a70g2000hsh.googlegroups.com> <0b92de73-de5a-4c1b-862a-7d52d3747def@m74g2000hsh.googlegroups.com> Message-ID: <722d2f4e-eb35-4bba-9d3e-4913e3eef4df@x1g2000prh.googlegroups.com> On Oct 26, 10:11?pm, "James Mills" wrote: > On Mon, Oct 27, 2008 at 12:03 PM, Andy O'Meara wrote: > > I think we miscommunicated there--I'm actually agreeing with you. ?I > > was trying to make the same point you were: that intricate and/or > > large structures are meant to be passed around by a top-level pointer, > > not using and serialization/messaging. ?This is what I've been trying > > to explain to others here; that IPC and shared memory unfortunately > > aren't viable options, leaving app threads (rather than child > > processes) as the solution. > > Andy, > > Why don't you just use a temporary file > system (ram disk) to store the data that > your app is manipulating. All you need to > pass around then is a file descriptor. > > --JamesMills Unfortunately, it's the penalty of serialization and unserialization. When you're talking about stuff like memory-resident images and video (complete with their intricate and complex codecs), then the only option is to be passing around a couple pointers rather then take the hit of serialization (which is huge for video, for example). I've gone into more detail in some other posts but I could have missed something. Andy From hufflehuffle at west.de Thu Oct 23 03:23:51 2008 From: hufflehuffle at west.de (=?ISO-8859-1?Q?Andreas_M=FCller?=) Date: Thu, 23 Oct 2008 00:23:51 -0700 (PDT) Subject: "Find" in list of objects Message-ID: <5816f329-67ca-4255-a1f2-bce72dbb8ae2@u46g2000hsc.googlegroups.com> Hi! (Python 2.2.3 if this is relevant :-) I have a list of objects with, lets say, the attributes "ID", "x" and "y". Now I want to find the index of list element with ID=10. Of course I can loop through the list manually, but is there a construct like list.find (10, key='ID') ? Thanks for your ideas. Best regards, Martin From tjreedy at udel.edu Fri Oct 24 12:09:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Oct 2008 12:09:21 -0400 Subject: 2.6, 3.0, and truly independent intepreters In-Reply-To: <4901d976$0$14054$9b4e6d93@newsspool3.arcor-online.net> References: <6m974kFfs9nlU1@mid.individual.net> <1e40e9df-fc39-4c8c-bbd4-05c9f9a37d67@75g2000hso.googlegroups.com> <4901d976$0$14054$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Stefan Behnel wrote: > Terry Reedy wrote: >> Everything in DLLs is compiled C extensions. I see about 15 for Windows >> 3.0. > > Ah, weren't that wonderful times back in the days of Win3.0, when DLL-hell was > inhabited by only 15 libraries? *sigh* > > ... although ... wait, didn't Win3.0 have more than that already? Maybe you > meant Windows 1.0? > > SCNR-ly, Is that the equivalent of a smilely? or did you really not understand what I wrote? From duncan.booth at invalid.invalid Wed Oct 22 14:29:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Oct 2008 18:29:45 GMT Subject: Ordering python sets References: <8f67b6f80810220522r49b0f588qf9d6001f62c080f0@mail.gmail.com> <6m92plFfp081U1@mid.individual.net> Message-ID: Peter Otten <__peter__ at web.de> wrote: > Here's another one: > >>>> set([1,9]) > set([1, 9]) >>>> set([9,1]) > set([9, 1]) > > This time I did indeed search systematically... > You missed one with smaller values: >>> set([8,0]) set([8, 0]) >>> set([0,8]) set([0, 8]) You can work some of it out quite easily instead of searching. The hash value for an integer is itself, the initial space allocated for the set is 8 slots so each value is reduced modulo 8. If the values you insert don't clash then the order of insertion doesn't matter. If there are values which coincide on the same slot then the second one inserted will go into a different slot so the order may vary. What Tim Chase has missed in his tests: > s = set(r.randint(1,1000) for _ in range(1000)) is that to get the elements out of order at least one element must be larger than the number of allocated slots. Since there are always a lot of unused slots that means the range for the integers needs to be significantly greater than the number of integers. e.g. >>> set([128]+range(84)) set([128, 0, 2, 3, 4, 5, 6, 1, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 7, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 43]) >>> set([128]+range(85)) set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 128]) the 86th element added to the set makes to total size allocated large enough that the 128 no longer conflicts with the 0. From bearophileHUGS at lycos.com Fri Oct 31 11:28:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 31 Oct 2008 08:28:46 -0700 (PDT) Subject: Testing dictionary results with doctest References: Message-ID: <5b4136a8-59a6-4022-a2ae-0831bc1d6d8f@b31g2000prb.googlegroups.com> Joe Strout: > What's the standard solution for this? I don't know of any standard solution, I generally sort the items in some ways, or add the result, that has to be equal: >>> r = foo() >>> r == {'object': 'rain', 'location': 'Spain', 'subloc': 'train'} True > Does doctest have some special way to tell it to consider the result ? > as a dictionary rather than a string? ?Or something else? A more general solution like this for sets/dics may become useful... do you have any idea regarding how to design it? Bye, bearophile From lie.1296 at gmail.com Sat Oct 25 11:24:39 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 25 Oct 2008 15:24:39 +0000 (UTC) Subject: set/dict comp in Py2.6 References: <28b0fe12-9a82-4d14-b3fa-3cd203000ba0@l77g2000hse.googlegroups.com> <0112daca$0$20624$c3e8da3@news.astraweb.com> Message-ID: On Sat, 25 Oct 2008 09:07:35 +0000, Steven D'Aprano wrote: > On Sat, 25 Oct 2008 01:13:08 -0700, bearophileHUGS wrote: > >> I'd like to know why Python 2.6 doesn't have the syntax to create sets/ >> dicts of Python 3.0, like: >> >> {x*x for x in xrange(10)} >> {x:x*x for x in xrange(10)} > > Maybe nobody asked for it? > > Personally, I don't see the advantage of set and dict comprehensions. In fact, it is a good syntax sugar for set/dict(generator-comprehension) > I > think the value of them is very marginal, not worth the additional > syntax. > > set([x*x for x in xrange(10)]) You should omit the []s as it would force python to build an internal list. I'm sure you know this would be a problem for large comprehensions. > dict((x, x*x) for x in xrange(10)) > > work perfectly well using the existing syntax. > > > -- > Steven From bruno.42.desthuilliers at websiteburo.invalid Tue Oct 14 04:09:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 14 Oct 2008 10:09:18 +0200 Subject: Deviation from object-relational mapping (pySQLFace) In-Reply-To: <28d12195-7ce3-4e07-91de-8ab3518082cb@j22g2000hsf.googlegroups.com> References: <18b290c1-afd9-49ce-9666-2fe9be1d2ba1@y29g2000hsf.googlegroups.com> <27eae129-78d5-40e8-b15b-2f1c8c145e05@64g2000hsm.googlegroups.com> <28d12195-7ce3-4e07-91de-8ab3518082cb@j22g2000hsf.googlegroups.com> Message-ID: <48f453a8$0$22804$426a74cc@news.free.fr> sulyokpeti at gmail.com a ?crit : (snip) > It is not convincing to look at an XML file alone. Let me give you an > example. Glade is a GTK+ application for creating GTK+ GUI. It > generates an XML file, that can be loaded in every programming > language that has libglade binding. > Similarly, there could be a > database design tool to create a database, and save SQL/DML > expressions into an XML config file. Why so ? What's wrong with a plain SQL file ? We already have a language for RDBMS schema description, and the schema description is itself stored in the RDBMS catalog so the SQL description can be regenerated from the RDBMS. I just don't see the point of storing all this in XML. > Then you create the RDB command > objects by loading the XML in your favourite language. > I think programming languages are intended for describing neither relational > databases nor GUIs. SQLAlchemy is an interesting attempt at integrating the relational model in a programming language. Ok, I don't mean neither of us is necessarily right and the other wrong - different POV, mostly, so I guess we can at least agree to disagree !-) From bj_666 at gmx.net Thu Oct 9 04:57:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Oct 2008 08:57:39 GMT Subject: Clever way of sorting strings containing integers? References: Message-ID: <6l5vc3Fatb4gU1@mid.uni-berlin.de> On Thu, 09 Oct 2008 00:41:27 -0700, Holger wrote: > I tried to do this elegantly, but did not come up with a good solution > > Sort strings like > foo1bar2 > foo10bar10 > foo2bar3 > foo10bar2 > > So that they come out: > foo1bar2 > foo2bar3 > foo10bar2 > foo10bar10 > > I.e. isolate integer parts and sort them according to integer value. import re def key_func(string): result = re.split(r'(\d+)', string) for i in xrange(1, len(result), 2): result[i] = int(result[i]) return result def main(): lines = ['foo1bar2', 'foo10bar10', 'foo2bar3', 'foo10bar2', 'fo', 'bar1000', '777'] lines.sort(key=key_func) print '\n'.join(lines) Ciao, Marc 'BlackJack' Rintsch From prologic at shortcircuit.net.au Fri Oct 3 00:25:40 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 3 Oct 2008 14:25:40 +1000 Subject: problem with sockets code In-Reply-To: References: Message-ID: On Fri, Oct 3, 2008 at 2:13 AM, Daniel wrote: > Hello, > > I can't seem to get my sockets code to work right. Here is what I > have inside my RequestHandler handle() function: > > total_data=[] > > data = True > logger_server.debug(self.__class__.__name__ + ' set data = > True') > while data: > logger_server.debug(self.__class__.__name__ + ' receive > first readline() of data') > data = self.rfile.readline().strip() > logger_server.debug(self.__class__.__name__ + ' first > readline() of data = %s' % data) > total_data.append(data) > receivedCommand = '\n'.join(total_data) > > And this is what I have inside my client code > > sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > sock.connect(('localhost',5001)) > > sock.sendall('Hello, world\r\n') > data = sock.recv(1024) > sock.close() > print 'Received', repr(data) > > There's a little more to it, but this is enough for me to ask my > question. The problem is that I can't get the server loop (while > data:) to stop without closing the connection, but I want to receive > something back from the server before closing the sockets connection. > My logs show that the server never leaves the loop. > > Thanks in advance. Daniel, You really should use an existing framework to help you write your application here. You're using the plain old (standard-library) sockets module. I would suggest you use either Twisted, or pymills. Twisted is more feature-rich, and a general purpose event-driven framework. It can be a little overwhelming to use. pymills is my event-driven, component architecture library that allows you to build event-driven systems very easily with a component design. You can download pymills from here: http://hg.shortcircuit.net.au/index.wsgi/pymills/archive/tip.tar.gz Or you can get the latest developmen branch by using Mercurial and cloning it: hg clone http://hg.shortcircuit.net.au/index.wsgi/pymills/ Here is a simple EchoServer that you could modify to suit your application needs: #!/usr/bin/env python from pymills import event from pymills.event import * from pymills.net.sockets import TCPServer class Echo(TCPServer): @listener("read") def onREAD(self, sock, data): self.write(sock, data) def main(): echo = Echo(8000) event.manager += echo while True: try: manager.flush() echo.poll() except KeyboardInterrupt: break if __name__ == "__main__": main() cheers James -- -- -- "Problems are solved by method" From claird at lairds.us Wed Oct 29 17:17:02 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 29 Oct 2008 21:17:02 +0000 Subject: Why gives "k = 09" a syntax error ? References: <4908B8FC.5010200@gmail.com> <6772c5db-cdcc-4f79-9a24-1da8e849c870@34g2000hsh.googlegroups.com> Message-ID: In article <6772c5db-cdcc-4f79-9a24-1da8e849c870 at 34g2000hsh.googlegroups.com>, Mensanator wrote: >On Oct 29, 2:44?pm, Stef Mientki wrote: >> Guilherme Polo wrote: >> > On 10/29/08, Stef Mientki wrote: >> >> >> hello, >> >> >> ?Why gives "k = 09" ?a syntax error ? >> >> > 09 is not a valid octal number. Instead use 011. >> >> > Ok, I guess you were not aware that prefixing a number with a '0' >> > would cause python to parse it as an octal and now you know. >> >> thanks guys, >> I didn't realize there were still people using octal notation ;-) > >Windows users don't have much need for it, but it's still >popular with the 'Nix crowd. . . . I contest that; my observation is that it's entirely an artifact of legacy software, and regarded as no better than a distraction by even the most narrow human 'Nixers, or the hardware types who might at one time have found octal natural. My own origins were in hardware, Unix, and other DEC OSs, so I consider myself as likely as anyone to think in octal--and I rarely do. While I can't accept the "popular" part, I agree with you that Unix people are at least more likely to recognize the 0-prefix. From Pat at junk.net Tue Oct 7 22:15:54 2008 From: Pat at junk.net (Pat) Date: Tue, 07 Oct 2008 22:15:54 -0400 Subject: Array of dict or lists or ....? References: Message-ID: Dennis Lee Bieber wrote: > On Mon, 06 Oct 2008 19:45:07 -0400, Pat declaimed the > following in comp.lang.python: > >> I can't figure out how to set up a Python data structure to read in data >> that looks something like this (albeit somewhat simplified and contrived): >> >> >> States >> Counties >> Schools >> Classes >> Max Allowed Students >> Current enrolled Students >> >> Nebraska, Wabash, Newville, Math, 20, 0 >> Nebraska, Wabash, Newville, Gym, 400, 0 >> Nebraska, Tingo, Newfille, Gym, 400, 0 >> Ohio, Dinger, OldSchool, English, 10, 0 > > > > The structure looks more suited to a database -- maybe SQLite since > the interface is supplied with the newer versions of Python (and > available for older versions). I don't understand why I need a database when it should just be a matter of defining the data structure. I used a fictional example to make it easier to (hopefully) convey how the data is laid out. One of the routines in the actual program checks a few thousand computers to verify that certain processes are running. I didn't want to complicate my original question by going through all of the gory details (multiple userids running many processes with some of the processes having the same name). To save time, I fork a process for each computer that I'm checking. It seems to me that banging away at a database would greatly slow down the program and make the program more complicated. The Perl routine works fine and I'd like to emulate that behavior but since I've just starting learning Python I don't know the syntax for designing the data structure. I would really appreciate it if someone could point me in the right direction. From barry at python.org Wed Oct 1 23:46:45 2008 From: barry at python.org (Barry Warsaw) Date: Wed, 1 Oct 2008 23:46:45 -0400 Subject: RELEASED Python 2.6 final Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the release of Python 2.6 final. This is the production-ready version of the latest in the Python 2 series. There are many new features and modules, improvements, bug fixes, and other changes in Python 2.6. Please see the "What's new" page for details http://docs.python.org/dev/whatsnew/2.6.html as well as PEP 361 http://www.python.org/dev/peps/pep-0361/ While Python 2.6 is backward compatible with earlier versions of Python, 2.6 has many tools and features that will help you migrate to Python 3. Wherever possible, Python 3.0 features have been added without affecting existing code. In other cases, the new features can be enabled through the use of __future__ imports and command line switches. Python 3.0 is currently in release candidate and will be available later this year. Both Python 2 and Python 3 will be supported for the foreseeable future. Source tarballs, Windows installers, and Mac disk images can be downloaded from the Python 2.6 page: http://www.python.org/download/releases/2.6/ (Please note that due to quirks in the earth's time zones, the Windows installers will be available shortly.) Bugs can be reported in the Python bug tracker: http://bugs.python.org Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSOREJ3EjvBPtnXfVAQLAigP/aEnrdvAqk7wbNQLFbmBonIr2YQbd1vEu TyTr5imYXFWGNfv1/JMeMBjMfwpHi1bgPEDTLEZdhDRNj/G1h4NqqnpfJS0lfIaU 4JBKwnsO80se/RGyupcs5f09UdKxOljhbFKEw46CHDkd9lE+cqy2yhetEwyx3c3+ AVC11sjcO54= =Oxo3 -----END PGP SIGNATURE----- From easta01 at yahoo.com Thu Oct 9 13:37:54 2008 From: easta01 at yahoo.com (easta01) Date: Thu, 9 Oct 2008 10:37:54 -0700 (PDT) Subject: Get High on Rave Pills Message-ID: Many pills in the market today like Ecstasy are popular at rave parties. These pills though effective in giving you a kick can also be risky to consume & possess. Reactions to these drugs include teeth gritting, nausea, hazy vision, chills, spasms & sweating. Increased heart rate & high BP levels also occur due to these pills. You can also suffer from sleep problems, anxiety & depression. Continued use of these drugs may eventually harm your physical & psychological functions. Apart from the effects, it's also illegal to keep such drugs with you in most countries. You will be arrested if you are found with these drugs on you in places that have banned such pills. On the other hand, Rave is the safest option available to you without the fear of nasty side-effects or a long time in jail. Rave gives you the same buzz that the illegal ones do but without any proven side- effects. It's absolutely non-addictive & is legal to possess in every country. Rave gives you the freedom to carry it anywhere you go as it also comes in a mini-pack of 10 capsules. For an Out-of-the-World & Earth-Shattering Experience, Try Rave Pills!! Only the blend in each Rave energy boosting pill can make you happy & give you an out-of-the-world high without any "come-down" effects that are seen in most other party pills. When you are on the Rave trip, your mind is detached from your body. You will experience a sensation of entering into a complete new reality. Rave is sure to have an impact even on the most zealous psychonaut. Rave is a fun and super- safe pill to enjoy all nighters no matter which place in the universe you are in. http://fhurl.com/b15490 From dan.barbus at gmail.com Thu Oct 2 01:01:32 2008 From: dan.barbus at gmail.com (Dan Barbus) Date: Wed, 1 Oct 2008 22:01:32 -0700 (PDT) Subject: index all instances by id - a memory leak? References: <74db5980-0322-41aa-bd39-3f3dfe86e3da@y71g2000hsa.googlegroups.com> Message-ID: <2ba3cd37-1869-4608-a166-0b7436f0550e@t65g2000hsf.googlegroups.com> On Oct 2, 7:54?am, Dan Barbus wrote: > > ? ? def getItemById(id): > ? ? ? ? return _itemsById[id] I just saw that this won't compile. Still, ignoring this, I thing the purpose of the code is pretty clear. Thanks for any feedback. From pruebauno at latinmail.com Mon Oct 6 10:27:46 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 6 Oct 2008 07:27:46 -0700 (PDT) Subject: Dict Comprehension ? References: Message-ID: <7cfd6944-955b-4f23-99f9-d52615abd909@75g2000hso.googlegroups.com> On Oct 6, 8:59 am, "Ernst-Ludwig Brust" wrote: > Given 2 Number-Lists say l0 and l1, > count the various positiv differences between the 2 lists > > the following part works: > > dif=[abs(x-y) for x in l0 for y in l1] > da={} > for d in dif: da[d]=da.get(d,0)+1 > > i wonder, if there is a way, to avoid the list dif > > Ernst-Ludwig Brust from collections import defaultdict da=defaultdict(int) for x in [10]: for y in [11]: da[abs(x-y)]+=1 From marcus at internetnowasp.net Fri Oct 31 00:07:59 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Fri, 31 Oct 2008 12:07:59 +0800 Subject: Malaysia python programmers In-Reply-To: <49095A93.6070505@internetnowasp.net> References: <49095A93.6070505@internetnowasp.net> Message-ID: <490A849F.402@internetnowasp.net> Hi, I apologize if this is not the place to do this. A python user group for malaysia is currently being formed , so if you are in malaysia, feel free to join us at : www.python.my Marcus.CM. From duncan.booth at invalid.invalid Mon Oct 20 13:58:27 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Oct 2008 17:58:27 GMT Subject: Idenfity numbers in variables References: <1224501408.9143.40.camel@king.imim.es> Message-ID: Lie Ryan wrote: > That's the job of regular expression: 'import re' > > numbered_atom = re.compile('[A-Z][a-z]?[0-9]+') > if numbered_atom.match('C10'): > # this is a numbered atom > if numbered_atom.match('C'): > # this WON'T match > > read more about regular expression on the web (hint: python share the > same re syntax with many other languages, php, javascript, grep, etc) > Or simply: if atom[-1].isdigit(): # this is a numbered atom else: # this isn't From martin.bachwerk at rwth-aachen.de Wed Oct 15 10:41:17 2008 From: martin.bachwerk at rwth-aachen.de (Martin Bachwerk) Date: Wed, 15 Oct 2008 16:41:17 +0200 Subject: urllib accept-language doesn't have any effect In-Reply-To: <6lmcpiFd08p7U1@mid.uni-berlin.de> References: <6lmcpiFd08p7U1@mid.uni-berlin.de> Message-ID: <48F6010D.3010407@rwth-aachen.de> Hi, yes, well my browser settings are set to display sites in following languages "en-gb" then "en". As a matter of fact, Google does indeed show me the German site first, before I click on "go to google.com" and it probably stores a cookie to remember that. But a site like gizmodo.com forwards me directly to the English site (even though they have a German version available). But the Python call returns the German version. How does that make sense? Cheers, Martin > Martin Bachwerk wrote: > > >> Hello, >> >> I'm trying to load a couple of pages using the urllib2 module. The >> problem is that I live in Germany and some sites seem to look at the IP >> of the client and forward him to a localized page.. Here's an example of >> the code, how I want to access google.com main english page, but get >> German instead. (For those of you who live in US, you will probably get >> correct results.. try emulating with 'fr' in accepted languages or >> something) >> >> opener = urllib2.build_opener() >> opener.addheaders = [('Host', 'www.google.com'), >> ('Accept-Language','en-gb,en;q=0.5'), ('User-agent', 'Mozilla/5.0 >> (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.1) Gecko/2008070208 >> Firefox/3.0.1')] >> webfile = opener.open(url) >> >> Any help would be greatly appreciated! >> > > What is your actual problem - does it work with *other* requests you somehow > produce (browser or some such)? > > In the end, it's up to the site you query to return you whatever they see > fit. Nothing urllib or python in general can change. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > > From Pat at junk.com Mon Oct 6 19:45:07 2008 From: Pat at junk.com (Pat) Date: Mon, 06 Oct 2008 19:45:07 -0400 Subject: Array of dict or lists or ....? Message-ID: I can't figure out how to set up a Python data structure to read in data that looks something like this (albeit somewhat simplified and contrived): States Counties Schools Classes Max Allowed Students Current enrolled Students Nebraska, Wabash, Newville, Math, 20, 0 Nebraska, Wabash, Newville, Gym, 400, 0 Nebraska, Tingo, Newfille, Gym, 400, 0 Ohio, Dinger, OldSchool, English, 10, 0 With each line I read in, I would create a hash entry and increment the number of enrolled students. I wrote a routine in Perl using arrays of hash tables (but the syntax was a bear) that allowed me to read in the data and with those arrays of hash tables to arrays of hash tables almost everything was dynamically assigned. I was able to fill in the hash tables and determine if any school class (e.g. Gym) had exceeded the number of max students or if no students had enrolled. No, this is not a classroom project. I really need this for my job. I'm converting my Perl program to Python and this portion has me stumped. The reason why I'm converting a perfectly working program is because no one else knows Perl or Python either (but I believe that someone new would learn Python quicker than Perl) and the Perl program has become huge and is continuously growing. From electronixtar at gmail.com Thu Oct 2 05:03:13 2008 From: electronixtar at gmail.com (est) Date: Thu, 2 Oct 2008 02:03:13 -0700 (PDT) Subject: TypeError: can't pickle HASH objects? References: <90876c28-070e-44bf-87d2-b2f6629c9dcc@d31g2000hsg.googlegroups.com> <11c7ac04-b535-4135-81a5-ec7c73638134@l62g2000hse.googlegroups.com> <0b218e99-3d57-429f-9636-031d84131a9c@64g2000hsm.googlegroups.com> <3e829db7-5339-4190-8de7-51d4d1c8c1c5@i76g2000hsf.googlegroups.com> Message-ID: <00a25dd0-eae4-4f25-bfde-b1725f893cf8@k37g2000hsf.googlegroups.com> On Oct 2, 4:22?pm, "Aaron \"Castironpi\" Brady" wrote: > On Oct 2, 2:44?am, est wrote: > > > > > > > On Oct 2, 1:51?pm, "James Mills" wrote: > > > > On Thu, Oct 2, 2008 at 3:34 PM, est wrote: > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > > break for a while. > > > > So use generators and consume the stream ? > > > > --JamesMills > > > > -- > > > -- > > > -- "Problems are solved by method" > > > no, I need to serialize half-finished digest, not file stream. > > > Anyone got solution? > > I am looking at '_hashopenssl.c'. ?If you can find the implementation > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes > hack to store and write its state.- Hide quoted text - > > - Show quoted text - http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count) { #ifdef OPENSSL_FIPS FIPS_selftest_check(); #endif return ctx->digest->update(ctx,data,count); } is this one? From ptmcg at austin.rr.com Fri Oct 31 13:51:41 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 31 Oct 2008 10:51:41 -0700 (PDT) Subject: brackets content regular expression References: <405e1745-2b3e-4ab7-812d-f9dbba2dad45@o40g2000prn.googlegroups.com> Message-ID: <752560c4-95b5-44ea-bb45-b931c344bb87@w24g2000prd.googlegroups.com> On Oct 31, 12:25?pm, netimen wrote: > I have a text containing brackets (or what is the correct term for > '>'?). I'd like to match text in the uppermost level of brackets. > > So, I have sth like: 'aaaa 123 < 1 aaa < t bbb < a ff > > 2 > > bbbbb'. How to match text between the uppermost brackets ( 1 aaa < t > bbb < a ff > > 2 )? > > P.S. sorry for my english. To match opening and closing parens, delimiters, whatever (I refer to these '<>' as "angle brackets" when talking about them in this context, otherwise they are just "less than" and "greater than"), you will need some kind of stack-based parser. You can write your own without much trouble - there are built-ins in pyparsing that do most of the work. Here is the nestedExpr method: >>> from pyparsing import nestedExpr >>> print nestedExpr('<','>').searchString('aaaa 123 < 1 aaa < t bbb < a ff > > 2 > bbbbb') [[['1', 'aaa', ['t', 'bbb', ['a', ['tt'], 'ff']], '2']]] Note that the results show not the original nested text, but the parsed words in a fully nested structure. If all you want is the highest-level text, then you can wrap your nestedExpr parser inside a call to originalTextFor: >>> from pyparsing import originalTextFor >>> print originalTextFor(nestedExpr('<','>')).searchString('aaaa 123 < 1 aaa < t bbb < a ff > > 2 > bbbbb') [['< 1 aaa < t bbb < a ff > > 2 >']] More on pyparsing at http://pyparsing.wikispaces.com. -- Paul From duncan.booth at invalid.invalid Fri Oct 31 11:27:26 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Oct 2008 15:27:26 GMT Subject: Testing dictionary results with doctest References: Message-ID: Joe Strout wrote: > What's the standard solution for this? Should I iterate over the > sorted keys and print those out instead? Is there some built-in > method somewhere that will print a dictionary in a reliable order? > Does doctest have some special way to tell it to consider the result > as a dictionary rather than a string? Or something else? pprint will sort a dictionary's keys as well as laying it out with line breaks where appropriate. >>> from pprint import pprint >>> pprint(t.match( "The rain in Spain falls mainly on the train." )) {'location': 'Spain', 'object': 'rain', 'subloc': 'train'} which leaves the question of what you do for this one: >>> pprint({1j: 'hello', 0: 'world'}) Traceback (most recent call last): File "", line 1, in pprint({1j: 'hello', 0: 'world'}) File "C:\Python25\lib\pprint.py", line 55, in pprint printer.pprint(object) File "C:\Python25\lib\pprint.py", line 106, in pprint self._format(object, self._stream, 0, 0, {}, 0) File "C:\Python25\lib\pprint.py", line 129, in _format rep = self._repr(object, context, level - 1) File "C:\Python25\lib\pprint.py", line 195, in _repr self._depth, level) File "C:\Python25\lib\pprint.py", line 207, in format return _safe_repr(object, context, maxlevels, level) File "C:\Python25\lib\pprint.py", line 249, in _safe_repr for k, v in sorted(object.items()): TypeError: no ordering relation is defined for complex numbers >>> -- Duncan Booth http://kupuguy.blogspot.com From kyosohma at gmail.com Wed Oct 29 10:11:39 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 29 Oct 2008 07:11:39 -0700 (PDT) Subject: parsing MS word docs -- tutorial request References: <504bbcdb-2ba1-4ac8-85e1-e86d693a214a@z6g2000pre.googlegroups.com> <49082dbe$0$182$e4fe514c@news.xs4all.nl> Message-ID: <611e0791-27b6-48ef-a45d-7eab55d3e156@r66g2000hsg.googlegroups.com> On Oct 29, 4:32?am, Okko Willeboordsed wrote: > Get a copy of; ?Python Programming on Win32, ISBN 1-56592-621-8 > Use Google and VBA for help > > bp.tralfamad... at gmail.com wrote: > > All, > > > I am trying to write a script that will parse and extract data from a > > MS Word document. ?Can / would anyone refer me to a tutorial on how to > > do that? ?(perhaps from tables). ?I am aware of, and have downloaded > > the pywin32 extensions, but am unsure of how to proceed -- I'm not > > familiar with the COM API for word, so help for that would also be > > welcome. > > > Any help would be appreciated. ?Thanks for your attention and > > patience. > > > ::bp:: Also check out MSDN as the win32 module is a thin wrapper so most of the syntax on MSDN or in VB examples can be directly translated to Python. There's also a PyWin32 mailing list which is quite helpful: http://mail.python.org/mailman/listinfo/python-win32 Mike From pommereau at univ-paris12.fr Tue Oct 7 02:38:45 2008 From: pommereau at univ-paris12.fr (franck) Date: Mon, 6 Oct 2008 23:38:45 -0700 (PDT) Subject: What AugStore and AugLoad AST nodes are? References: Message-ID: > They aren't used by the current implementation. OK, thanks! Franck From Henk.van.Asselt at gmail.com Thu Oct 16 16:29:44 2008 From: Henk.van.Asselt at gmail.com (Henk.van.Asselt at gmail.com) Date: Thu, 16 Oct 2008 13:29:44 -0700 (PDT) Subject: del and sets proposal References: <48e7b775$0$1120$426a34cc@news.free.fr> <00f80c6a$0$20633$c3e8da3@news.astraweb.com> <00f88c9e$0$20633$c3e8da3@news.astraweb.com> Message-ID: "Life was like a box of chocolates. You never know what you're gonna get." Regardless of how it is implemented, mathematically a set is a collection of items. The order does not matter, an item is part of a set, or is not part of a set. Period. Henk From bj_666 at gmx.net Fri Oct 3 04:57:51 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Oct 2008 08:57:51 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> <6kernnF7dmkkU3@mid.uni-berlin.de> <00f2b28e$0$20617$c3e8da3@news.astraweb.com> <6kglc3F7fcvuU1@mid.uni-berlin.de> <6kh28kF7fcvuU2@mid.uni-berlin.de> <00f4d98c$0$20640$c3e8da3@news.astraweb.com> <4600661d-4514-4538-a39b-8c50504604db@t65g2000hsf.googlegroups.com> Message-ID: <6km54fF8lr73U1@mid.uni-berlin.de> On Thu, 02 Oct 2008 18:15:59 -0700, bearophileHUGS wrote: > What's a range(n)? A function that returns a list of n items, from 0 to > n. This is easy to understand, while xrange(n) is a bit less easy to > understand (a generator or generators). `xrange()` doesn't return a generator or iterator but an object that implements the sequence protocol: In [159]: a = xrange(0, 10, 2) In [160]: len(a) Out[160]: 5 In [161]: a[0] Out[161]: 0 In [162]: a[2] Out[162]: 4 Ciao, Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at websiteburo.invalid Mon Oct 20 07:55:31 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 20 Oct 2008 13:55:31 +0200 Subject: default value in __init__ In-Reply-To: References: <5f3a6fdc-40e5-4450-b65d-066f87f27309@v53g2000hsa.googlegroups.com> <48ef37fe$0$22798$426a34cc@news.free.fr> <48f505c8$0$20216$426a74cc@news.free.fr> Message-ID: <48fc71b2$0$4643$426a74cc@news.free.fr> David C. Ullrich a ?crit : > In article <48f505c8$0$20216$426a74cc at news.free.fr>, > Bruno Desthuilliers wrote: > (snip) >>>> Well... How to say.. Is there any chance these people will read anything >>>> *at all* ? >>> No. That's exactly the point! >> Yeps. But I don't think we derive the same conclusions from that point. > > Erm, I think maybe your irony detector needs a little calibration... Possibly, yes... >>> [...] >>> In particular default parameters should work the way the user >>> expects! The fact that different users will expect different >>> things here is no excuse... > > I was worried someone might not realize I was being sarcastic, > which is why I threw in this obvious impossibility > >> If different users expect different - mostly incompatible - things, how >> would it be possible to have it working "the way the user expect" ? > > but I guess it wasn't enough. Obviously not - at least for me. OTHO, I've seen peoples very seriously asking for such obvious impossibilities. >> Should Python grow some telepathic features to guess the user's >> expectations and modifies itself to meet these expectations ?-) And the answer is, of course, 42. From sjmacdonaldjail at gmail.com Sun Oct 5 18:34:51 2008 From: sjmacdonaldjail at gmail.com (sjmacdonaldjail at gmail.com) Date: Sun, 5 Oct 2008 15:34:51 -0700 (PDT) Subject: Buy Soma online Message-ID: buy cheap soma online . . . Enough to seek Soma! You've already found the best site where you can purchase Soma for lowest price! To order Soma without prescription visit link below! ************************************ http://med247.us/?p=soma ************************************ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uy cheap soma online by cheap soma online bu cheap soma online buy heap soma online buy ceap soma online buy chap soma online buy chep soma online buy chea soma online buy cheap oma online buy cheap sma online buy cheap soa online buy cheap som online buy cheap soma nline buy cheap soma oline buy cheap soma onine buy cheap soma onlne buy cheap soma onlie buy cheap soma onlin bbuy cheap soma online buuy cheap soma online buyy cheap soma online buy ccheap soma online buy chheap soma online buy cheeap soma online buy cheaap soma online buy cheapp soma online buy cheap ssoma online buy cheap sooma online buy cheap somma online buy cheap somaa online buy cheap soma oonline buy cheap soma onnline buy cheap soma onlline buy cheap soma onliine buy cheap soma onlinne buy cheap soma onlinee uby cheap soma online byu cheap soma online buy cheap soma online buy hceap soma online buy cehap soma online buy chaep soma online buy chepa soma online buy cheap soma online buy cheap osma online buy cheap smoa online buy cheap soam online buy cheap soma online buy cheap soma noline buy cheap soma olnine buy cheap soma onilne buy cheap soma onlnie buy cheap soma onlien buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online buy cheap soma online From bj_666 at gmx.net Wed Oct 1 06:42:14 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Oct 2008 10:42:14 GMT Subject: Are there any python micro-frameworks (like ruby's Camping)? References: <609d9426-671b-488f-b170-c51ca34e857a@p25g2000hsf.googlegroups.com> Message-ID: <6kh2g6F7fcvuU3@mid.uni-berlin.de> On Wed, 01 Oct 2008 01:02:24 -0700, Phillip B Oldham wrote: > Are there any python micro-frameworks (like ruby's Camping)? Maybe `CherryPy`!? It's the heart of other frameworks that add templating, ORM and the like to it. Another consideration might be `Werkzeug`. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Oct 23 20:34:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 23 Oct 2008 22:34:07 -0200 Subject: Py2exe and Module Error... References: <5044cf25-140c-4953-805b-b1b454623df7@u75g2000hsf.googlegroups.com> Message-ID: En Thu, 23 Oct 2008 20:02:41 -0200, escribi?: > On Oct 22, 8:33 pm, "Gabriel Genellina" > wrote: >> En Wed, 22 Oct 2008 20:34:39 -0200, >> escribi?: >> >> > I am using py2exe and everything is working fine except one module, >> > ClientCookie, found here: >> >> >http://wwwsearch.sourceforge.net/ClientCookie/ >> >> > Keeps coming up as not found no matter what I do. I have tried all >> > these combinations from the command line: > Ok, thank you for your reply Gabriel. I did as you said, including > adding 'import ClientCookie' to setup.py and that worked fine when > running the script it found it. However, when actually running it > through py2exe after adding the package as you have said, it still > says 'No module named ClientCookie' > > Any help would be greatly appreciated. Sorry, I can not give further general advice. This seems to be something specific to ClientCookie - try any forum devoted to the package, or ask the author directly. -- Gabriel Genellina From castironpi at gmail.com Wed Oct 1 15:04:58 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 1 Oct 2008 12:04:58 -0700 (PDT) Subject: Peek inside iterator (is there a PEP about this?) References: Message-ID: <73f35969-87ef-4a0a-9447-a693f3a1d66b@l64g2000hse.googlegroups.com> On Oct 1, 9:46?am, Luis Zarrabeitia wrote: > Hi there. > > For most use cases I think about, the iterator protocol is more than enough. > However, on a few cases, I've needed some ugly hacks. > > Ex 1: > > a = iter([1,2,3,4,5]) # assume you got the iterator from a function and > b = iter([1,2,3]) ? ? # these two are just examples. > > then, > > zip(a,b) > > has a different side effect from > > zip(b,a) > > After the excecution, in the first case, iterator a contains just [5], on the > second, it contains [4,5]. I think the second one is correct (the 5 was never > used, after all). I tried to implement my 'own' zip, but there is no way to > know the length of the iterator (obviously), and there is also no way > to 'rewind' a value after calling 'next'. > > Ex 2: > > Will this iterator yield any value? Like with most iterables, a construct > > if iterator: > ? ?# do something > > would be a very convenient thing to have, instead of wrapping a 'next' call on > a try...except and consuming the first item. > > Ex 3: > > if any(iterator): > ? ?# do something ... but the first true value was already consumed and > ? ?# cannot be reused. "Any" cannot peek inside the iterator without > ? ?# consuming the value. > > Instead, > > i1, i2 = tee(iterator) > if any(i1): > ? ?# do something with i2 > > Question/Proposal: > > Has there been any PEP regarding the problem of 'peeking' inside an iterator? > Knowing if the iteration will end or not, and/or accessing the next value, > without consuming it? Is there any (simple, elegant) way around it? > > Cheers, > > -- > Luis Zarrabeitia (aka Kyrie) > Fac. de Matem?tica y Computaci?n, UH.http://profesores.matcom.uh.cu/~kyrie It wouldn't be that hard to make your own. a = peekingiter([1,2,3,4,5]) b = peekingiter([1,2,3]) Just don't cross it with typing and get peking duck. From ireborin at delete.this.gmail.com Thu Oct 23 18:32:53 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Fri, 24 Oct 2008 00:32:53 +0200 Subject: More efficient array processing References: <20136676.post@talk.nabble.com> <6mbuacFfv9sgU5@mid.uni-berlin.de> Message-ID: On Fri, 24 Oct 2008 00:32:11 +0200, Ivan Reborin wrote: >On Thu, 23 Oct 2008 11:44:04 -0700 (PDT), "John [H2O]" > wrote: > >> >>Thanks for the clarification. >> >>What is strange though, is that I have several Fortran programs that create >>the exact same array srtucture... wouldn't they be restricted to the 2Gb >>limit as well? > >Depends on lot of things, as Mark has hinted. *Marc* Apologies. -- Ivan From uzmanajmal at gmail.com Thu Oct 23 22:55:15 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Fri, 24 Oct 2008 07:55:15 +0500 Subject: Question about interpreter Message-ID: Assalamalaikum An interpreter which Python also uses, translates and checks for errors in code, one line at a time. Question: Does interpreter also executes the translated code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob.martin at excite.com Sun Oct 26 03:26:52 2008 From: bob.martin at excite.com (Bob Martin) Date: Sun, 26 Oct 2008 07:26:52 GMT Subject: dictionary References: Message-ID: <0ZUMk.77674$E41.38149@text.news.virginmedia.com> in 86949 20081024 205720 "Hendrik van Rooyen" wrote: >Steven D'Aprano wrote: > >>On Fri, 24 Oct 2008 14:53:19 +0000, Peter Pearson wrote: >> >>> On 24 Oct 2008 13:17:45 GMT, Steven D'Aprano wrote: >>>> >>>> What are programmers coming to these days? When I was their age, we >>>> were expected to *read* the error messages our compilers gave us, not >>>> turn to the Interwebs for help as soon there was the tiniest problem. >>> >>> Yes, and what's more, the text of the error message was "IEH208". After >>> reading it several times, one looked it up in a big fat set of books, >>> where one found the explanation: >>> >>> IEH208: Your program contains an error. Correct the error and resubmit >>> your job. >>> >>> An excellent system for purging the world of the weak and timid. >> >>You had reference books? You were lucky! When I was lad, we couldn't >>afford reference books. If we wanted to know what an error code meant, we >>had to rummage through the bins outside of compiler vendors' offices >>looking for discarded documentation. > >eee! You were Lucky! > >You had Compilers! >You had Compiler Vendors! > >When I was lad, we had nowt but raw hardware. >We had to sit in cold room, ears deafened by >whine of fan, clicking switches to load our >octal in computer. We just had error light... > >- Hendrik Computers? you had computers? From mnordhoff at mattnordhoff.com Thu Oct 9 03:40:18 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 09 Oct 2008 07:40:18 +0000 Subject: Inefficient summing In-Reply-To: <47c890dc0810081347o3c64f83at366e6a3ed65f933b@mail.gmail.com> References: <969403b6-613c-448f-a1c4-535d8a78c124@f37g2000pri.googlegroups.com> <47c890dc0810081347o3c64f83at366e6a3ed65f933b@mail.gmail.com> Message-ID: <48EDB562.50804@mattnordhoff.com> Chris Rebert wrote: > I personally would probably do: > > from collections import defaultdict > > label2sum = defaultdict(lambda: 0) FWIW, you can just use: label2sum = defaultdict(int) You don't need a lambda. > for r in rec: > for key, value in r.iteritems(): > label2sum[key] += value > > ratio = label2sum["F1"] / label2sum["F2"] > > This iterates through each 'r' only once, and (imho) is pretty > readable provided you know how defaultdicts work. Not everything has > to unnecessarily be made a one-liner. Coding is about readability > first, optimization second. And optimized code should not be > abbreviated, which would make it even harder to understand. > > I probably would have gone with your second solution if performance > was no object. > > Cheers, > Chris -- From aspersieman at gmail.com Tue Oct 21 08:48:41 2008 From: aspersieman at gmail.com (Aspersieman) Date: Tue, 21 Oct 2008 14:48:41 +0200 Subject: pymssql - execute loads all results into memory! In-Reply-To: <48FDB7BD.6040703@timgolden.me.uk> References: <767a6cf1-4968-4e95-8a0b-62adf871d399@s1g2000prg.googlegroups.com> <92da89760810200732p733977dfu1ac1f44ec44ee436@mail.gmail.com> <48FDB7BD.6040703@timgolden.me.uk> Message-ID: On Tue, 21 Oct 2008 13:06:37 +0200, Tim Golden wrote: > Aspersieman wrote: >> However, pyODBC doesn't support return variables(parameters) in stored >> procedures (at least with MS SQL). pymssql is the only db api for >> python that I've found that can reliably do this. I've tried adodbapi, >> pyodbc and one or two others (can't think of the names now... :-/). > > That's a fair point (I'm assuming you're right; I've never tried). That > tends to be a shortcoming of SQL interfaces. However, pymssql is based > on the defunct ntwdblib.dll interface which is becoming harder and harder > to find as of SQL2005. Have you tried putting a feature request in to > the pyodbc team? I've not had anything to do with them for a bit, but > they did implement the .nextset method at my request a couple of years > ago. (That's assuming it's even possible with ODBC in general, which > I also haven't checked). > > TJG > -- Oh, trust me - I've tried a *LOT*. I aggree, submitting a feature request is a good idea. I think I'll do that. :) I did read somewhere (I think on the pyodbc site) that pyodbc isn't DB API 2.0 feature complete yet - so I'll have to probably check if they haven't already planned this. Obtaining output parameters from stored procedures is something I have to do quite often, unfortunately - so maybe I can submit a patch even... :) Alternatively - I have found the adodbapi quite useful (although it also doesn't support output parameters), so I might ask them too. Thanks for the suggestion. Regards Nicol -- Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo From tgrav at mac.com Wed Oct 1 12:50:25 2008 From: tgrav at mac.com (Tommy Grav) Date: Wed, 01 Oct 2008 12:50:25 -0400 Subject: Fwd: string concatenate References: <0ACA4EAC-09DC-4FAB-A288-F51AB43B831A@me.com> Message-ID: On Oct 1, 2008, at 12:41 PM, sandric ionut wrote: > Hi: > > I have the following situation: > nameAll = [] > for i in range(1,10,1): > n = "name" + str([i]) > nameAll += n > print nameAll > > I get: > > ['n', 'a', 'm', 'e', '[', '1', ']', 'n', 'a', 'm', 'e', '[', '2', > ']', 'n', 'a', 'm', 'e', '[', '3', ']', 'n', 'a', 'm', 'e', '[', > '4', ']', 'n', 'a', 'm', 'e', '[', '5', ']', 'n', 'a', 'm', 'e', > '[', '6', ']', 'n', 'a', 'm', 'e', '[', '7', ']', 'n', 'a', 'm', > 'e', '[', '8', ']', 'n', 'a', 'm', 'e', '[', '9', ']'] > > but I would like to have it as: > > name1 name2 name3 ...name10 > > How can I do it? > > Thank you, > > Ionut > nameAll = [] > for i in xrange(1,10,1): > n = "name" + str(i) > nameAll.append(n) > print nameAll ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9'] list.append() is the right tool for adding new elements to a list. Cheers Tommy From trash at willeboordse.demon.nl Sat Oct 11 03:45:46 2008 From: trash at willeboordse.demon.nl (Okko Willeboordse) Date: Sat, 11 Oct 2008 09:45:46 +0200 Subject: Get "code object" of class In-Reply-To: References: <48ef4f8f$0$3007$e4fe514c@dreader12.news.xs4all.nl> Message-ID: <48F059AA.9090206@willeboordse.demon.nl> Thanks, "Why do you even need the classes code object anyway?" I need to instantiate and use the class in another process. This other process doesn't has access to the py or pyc file holding the m_class (source) code so I can't use pickle. Something like; In the first process (that has access to my_class (source) code) I do; c = compile(inspect.getsource(my_class), "
User ID NameDate