From knightsofspamalot-factotum at gvdnet.dk Fri Jul 16 06:25:56 2004 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 16 Jul 2004 12:25:56 +0200 Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: <4edc17eb.0407152054.10f75b4c@posting.google.com> Message-ID: <87n020l03v.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Michele" == Michele Simionato writes: Michele> Is there a way to get any info about why the Python process Michele> failed? (did I mention I am a rather poor emacs user? ;) In addition to Jacek's tips, you can also check the *Messages* buffer for clues. That's always a good place to start. Oh, and make sure that the Python executable is in your path. That bit is not entirely unimportant. :-) Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAkD3rTQACgkQYu1fMmOQldU+sQCeJET5eKVWzmo+N9KefyfxlOLv LYEAnjDQe+IEto5jYhy/5YqxvD/5bbAS =KgLH -----END PGP SIGNATURE----- From Joseph.V.Laughlin at boeing.com Thu Jul 1 21:07:16 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Thu, 1 Jul 2004 18:07:16 -0700 Subject: Converting string to argument Message-ID: <67B3A7DA6591BE439001F2736233351202DECB3D@xch-nw-28.nw.nos.boeing.com> class Foo: x = "blah" y = "blah some more" foo = Foo() x_string = "x" y_string = "y" # I want something like this to work: print foo.x_string print foo.y_string # The above should print out "blah" and "blah some more" # Any ideas? # Let me know if I need to clarify anything. Joe Laughlin NCO Simulation Labs Integrated Defense Systems The Boeing Company From meldron at meldron.org Sun Jul 4 19:45:42 2004 From: meldron at meldron.org (Bernd Kaiser) Date: Mon, 05 Jul 2004 01:45:42 +0200 Subject: Black window In-Reply-To: References: <2kr34jF5510tU1@uni-berlin.de> Message-ID: <2krj3lF5helcU5@uni-berlin.de> Gropius wrote: >> Check out py2exe >> http://starship.python.net/crew/theller/py2exe/ > > Ok, but i don't understand what to do.. > > Windows NT services You can build Windows NT services by passing a service keyword argument to the setup function, the value must be a list of Python module names containing a service class (identified by the _svc_name_ attribute): # setup.py from distutils.core import setup import py2exe setup(service=["MyService"]) The build service executable are able to install and remove themselves by calling them with certain command line flags, run the exe with the -help argument to find out more. From alanmk at hotmail.com Wed Jul 28 08:05:44 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 28 Jul 2004 13:05:44 +0100 Subject: https proxy In-Reply-To: <7xpt6h6r9k.fsf@ruckus.brouhaha.com> References: <410678ed$1@newsflash.abo.fi> <7xpt6h6r9k.fsf@ruckus.brouhaha.com> Message-ID: [Paul Sweeney] >>I wish to access an https:// site using my browser and click around >>it. I wish to see the http(s) GET urls and http(s) POST urls and >>data which are being sent to the https server. If the site were an >>http:// site I would use a tool like ethereal to see what was going >>on, but this data is sent encrypted from the browser due to the >>https connection, so I'll just see the encrypted data. So I need a >>tool to view the unencrypted form of the data which is being sent >>encrypted (sorry for being unclear about the "unecrypted data" in my >>last post, I hope this is better). [Paul Rubin] > You could do that but I don't know of already-existing Python code > that does it. Basically it would be a man-in-the-middle attack against > the browser/server pair: > > browser---(SSL)---proxy---(SSL)---server > > There'd be two separate SSL sessions and the proxy would of course > have to present its own server certificate to the browser, which you'd > configure the browser to accept. The server application could take > various measures to detect this subterfuge and stop it from happening, > but I doubt any normal server apps actually bother to do that. It's > not a true security break, since the browser user has to accept the > proxy certificate, thereby giving "permission" for the interception. Paul S, Perhaps you could achieve what you want with Apache and mod_proxy? http://httpd.apache.org/docs/mod/mod_proxy.html Use (a HTTPS-configured) Apache to decode the requests with mod_proxy, and simply forward all requests to another plain (HTTP) python proxy of your choice. The ProxyRemote or ProxyPass directives could be used for that. On looking at the ProxyRemote documentation, it states "only 'http' is supported by this module.' However, a quick search turns up the following snippet, i.e. that Apache mod_ssl provides HTTPS support for mod_proxy. From the horses mouth, i.e. Ralf Engelschall: "when you want to forward to a HTTPS target you need HTTPS support in mod_proxy. That's only possible with mod_ssl (which enhanced mod_proxy for HTTPS). Then you can do all: Accept HTTP and HTTPS and connect to HTTP and HTTPS targets, i.e. create gateways in all combinations." http://www.lists.aldigital.co.uk/apache-ssl/msg02860.html HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From sjdevnull at yahoo.com Fri Jul 16 16:05:29 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 16 Jul 2004 13:05:29 -0700 Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: <87d62xoun1.fsf@gvdnet.dk> Message-ID: <96c2e938.0407161205.4fbedb3e@posting.google.com> Martin Christensen wrote in message news:<87d62xoun1.fsf at gvdnet.dk>... > Mark> It sends the entire selected block to a new interpreter, yes. > Mark> Not each line to a different interpreter, if that's what you're > Mark> trying to say. > > I think what he was trying to say is this: for each time you send a > code snippet to the interpreter, a new interpreter is started, and > afterwards you won't have the same interpreter and its state to play > with. > > With Emacs' Python mode, you can run a so-called inferior Python > process, which is just to say that you have an interpreter running in > Emacs. You can then keep sending code to this same interpreter. [SNIP] > I should be greatly surprised if it weren't possible to do something > similar in at least Vim. http://www.vim.org/scripts/script.php?script_id=165 The vimsh package allows you to run a shell under Vim; among other things, you can run python under this shell. I do this all the time, with macros to run selected line(s) from my python code in the Python window, maintaining state in between sending lines through Python--so running "i=100", then going back to editing and later running "i=i+1", "print i" will print 101. This runs seperately from Vim's built-in Python interpreter, so you don't have to worry about namespace collisions, etc (in fact, you can easily have several vimsh python windows each running their own interpreters, just like in emacs). vimsh doesn't have smart terminal emulation (just dumb ptys), though, so you can run line-oriented programs fine this way, but you can't run e.g. curses or advanced termcap programs in any useful way. Not a big deal for me. Sumner From tim.golden at viacom-outdoor.co.uk Mon Jul 5 11:46:23 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 5 Jul 2004 16:46:23 +0100 Subject: Perform operation whenever dir is altered Message-ID: | So, for every file in the directory, I want to trigger an rsync | command whenever that file is edited. Have a look at this (not having tried it myself): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/217829 TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fumanchu at amor.org Mon Jul 19 00:28:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 18 Jul 2004 21:28:44 -0700 Subject: namespace for released packages? Message-ID: Stuart Bishop wrote: > It is pretty rare to get clashes - module authors are generally > nice enough to make sure nobody else is using their package name > before releasing things and generally package everything into > a single top-level module. Alex Hunsley replied: > Doesn't a single top level module translate into all the > source being in > one file? (please correct if I'm wrong about this!) Let's be clear about terms: Python has 'modules' and 'packages'. Each module is one file (on all platforms I can think of), whereas a package consists of multiple module files*, all contained within a single directory tree on a filesystem (the tree root == the name of the package). So the phrase "package everything into a single top-level module" is a bit misleading. Generally, you will find two kinds of Pythonistas: those who write modules and those who write packages, and they'll phrase their answers to such questions differently. Despite these differences, modules and packages compete for the same namespace at the top level. So yes, a single top-level module literally means all the source being in one file; for many Python projects, that works. For many others, that doesn't work; hence packages. Use what works for your project. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org * OK, if you want to pick nits, you *could* make a package with just one file, mypkg/__init__.py. But let's not cloud the issue. ;) From elbertlev at hotmail.com Wed Jul 7 15:59:03 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 7 Jul 2004 12:59:03 -0700 Subject: WaitForMultipleObjects in Python. Message-ID: <9418be08.0407071159.19707dae@posting.google.com> Is there any way to wait in multiple events, semaphores etc. For examole on Queue and Event? Like you can do in WIN32. From roel.wuyts at ulb.ac.be Tue Jul 6 03:58:46 2004 From: roel.wuyts at ulb.ac.be (Roel Wuyts) Date: Tue, 6 Jul 2004 09:58:46 +0200 Subject: CfC: Workshop on Revival of Dynamic Languages @ OOPSLA'04 Message-ID: <2004070609584677300%roelwuyts@ulbacbe> CALL FOR CONTRIBUTIONS International Workshop on Revival of Dynamic Languages http://pico.vub.ac.be/~wdmeuter/RDL04/index.html (at OOPSLA2004, Vancouver, British Columbia, Canada, October 24-28, 200) Organization committee: Roel Wuyts (primary contact - roel.wuyts at ulb.ac.be), Gilad Bracha, Wolfgang De Meuter, St?phane Ducasse and Oscar Nierstrasz. Important Dates --------------------- Deadline for submissions: August 16, 2004. Notification of Acceptance: September 10, 2004. Theme and Goals ------------------------ In industry, static languages (such as Java, C++ and C\#) are much more widely used than their dynamic counterparts (like CLOS, Python, Self or Smalltalk). So it appears as though dynamic language concepts were forgotten and have lost the race. But this is not the case. Java and C\#, the latest mainstream static languages, popularized to a certain extent dynamic language features such as garbage collection, portability and (limited forms of) reflection. In the near future, we expect this dynamicity to increase even further. E.g., it is getting clearer year after year that pervasive computing is becoming the rule and that concepts such as meta programming, reflection, mobility, dynamic reconfigurability and distribution are becoming increasingly popular. All of these features are the domain of dynamic languages, and hence it is only logical that more dynamic language concepts have to be taken up by static languages, or that dynamic languages can make a breakthrough. The goal of this workshop is to bring together researchers in (object-oriented) language design interested in dynamic language features and languages that do not fit into the static mainstream. Call for contributions ---------------------------- Areas of interests include, but are not limited to ? closures ? delegation ? actors, active objects ? prototype-based languages and approaches ? mixins and traits ? reflection and meta-programming ? language symbiosis and multi-paradigm languages ? ... In Brief: we welcome position statements, both about new language(s) (features) as well as about existing ones that already cover solutions for problems that are currently getting relevant in mainstream languages. We encourage brand new ideas, even though they have not been tried and proven yet. It is a workshop, not a conference, so work in progress is accepted. We expect... ? a statement to bring dynamism to an existing OOPL, or ? a proposal for completely new features/languages, or ? experience reports on dynamic features, to learn what works/does not work in current-day development, or ? killer applications making use of dynamic features, or ? descriptions of interactions between different dynamic features and/or OO concepts, or ? anything else related to dynamicity in (OO) PLs Prospective attendees are requested to submit a position statement or an essay (max 5 pages) on a topic relevant to the workshop to Roel Wuyts (Roel.Wuyts at ulb.ac.be) no later than August, 16. Submissions should be 5 pages in length and are demanded to be in .pdf format. Notification of acceptance will be on September, 10. Submissions should contain page numbers and up to 5 keywords. Important Dates ---------------------- Deadline for submissions: August 16, 2004. Notification of Acceptance: September 10, 2004. -- Roel Wuyts DeComp roel.wuyts at ulb.ac.be Universit? Libre de Bruxelles http://homepages.ulb.ac.be/~rowuyts/ Belgique From franz.steinhaeusler at utanet.at Mon Jul 5 06:20:40 2004 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Mon, 05 Jul 2004 12:20:40 +0200 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <2kltpoF40v4pU1@uni-berlin.de> Message-ID: On Sat, 03 Jul 2004 04:18:12 +0800, Jon Perez wrote: >SciTE is the editor I have been looking for all these >years. >[...] >Some of the highlights: > >* The code folding is superb - it even folds HTML! >[...] and class browser. if you have wxpython installed, there is a class browser add-on. (in german): http://python.sandtner.net/viewtopic.php?t=1048&highlight=wxpython Download: http://www-public.tu-bs.de:8080/~y0011042/scclbr/scitebrowser.zip and add to your python.properties file: command.name.2.*=Class Browser command.2.*="E:\EigDat\Python\scitebrowser\scitebrowser.pyw" "$(FileDir)" "$(WindowID)" command.subsystem.2.*=2 replace the path with your location of scite browser: command.2.*="E:\EigDat\Python\scitebrowser\scitebrowser.pyw" -- Franz Steinhaeusler From squirrel at WPI.EDU Wed Jul 14 14:13:30 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 14 Jul 2004 14:13:30 -0400 Subject: returning a value from a thread In-Reply-To: <10fatb8dknikr58@corp.supernews.com> References: <10fatb8dknikr58@corp.supernews.com> Message-ID: On Wed, 14 Jul 2004, Jeff Shannon wrote: > Christopher T King wrote: > > >Just don't forget to .join() on the thread in module1 before accessing the > >container object! (Assuming you're using threading) I just wish Python's > >.join() could return values, like pthread_join can. > > This may work if the worker thread will perform a relatively short task > and then die *before* you access the result. But lists and dictionaries > are not thread-safe -- if they are potentially accessed by multiple > threads concurrently, then the behavior will be unpredictable. That's where the .join() comes in handy (it blocks until the thread dies) ;) From sridharinfinity at gmail.com Thu Jul 22 14:17:43 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 22 Jul 2004 11:17:43 -0700 Subject: Problems with pygtk/gtk.glade In-Reply-To: <40ffed62$1_1@news.iglou.com> Message-ID: Try using the latest version of pygtk [1] - 2.3.93, I guess [1] http://www.pygtk.org From chrisccc_3k at yahoo.com Wed Jul 28 13:33:18 2004 From: chrisccc_3k at yahoo.com (Chris Connett) Date: Wed, 28 Jul 2004 13:33:18 -0400 Subject: eval() of empty string hangs In-Reply-To: References: <5uidnRYv-6DqK5rcRVn-vQ@powergate.ca> <4107c099$1@buckaroo.cs.rit.edu> Message-ID: <4107e361$1@buckaroo.cs.rit.edu> Peter Hansen wrote: > Chris Connett wrote: > >> Is it possible that the exception is propagating up the wrong stack? >> This is a separate thread, could it be on the main thread somehow? >> The creating thread has ended by the time this exception is due to be >> raised. > > > This doesn't make sense to me. What do you mean by 'creating thread'? > If it's what I think you mean, then either it's not really the > creating thread, or it hasn't really ended yet... after all, how > could a thread that has ended cause an exception to occur? I didn't mean to confuse, just throwing some ideas out, sorry. Here's the big picture: A function is called, which creates a Submission object, and then calls a sequence of methods on it. Since this is a normal everyday function, the user must wait for it to finish. So after some basic integrity checks, it creates a new thread to do the major processing, which could take a significant amount of time. Once that thread is created and started, the function the user called returns, and the user goes on their merry way. The thread from which the user originally called the first function should end shortly after that, but as always with threading, no guarantees. ... Well, I've found the problem. My own oversight, a NameError in the top level except block, I forgot to qualify the name of the Exception being caught. I should have used pychecker, I have no excuse not to have, it's installed. Sorry to have wasted the group's time, but I have learned from this greatly. Nothing like complete embarrassment in front of one's peers to make a lesson stick. ;) From squirrel at WPI.EDU Fri Jul 16 11:20:48 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 16 Jul 2004 11:20:48 -0400 Subject: Non sequitur (was: Lists, tuples and memory. In-Reply-To: References: <9418be08.0407151109.15894fe7@posting.google.com> Message-ID: On Fri, 16 Jul 2004, Dennis Lee Bieber wrote: > On Thu, 15 Jul 2004 15:52:53 -0400, Christopher T King > declaimed the following in comp.lang.python: > > > whereas the group of related items 'apple','red',3,5 (presumably > > describing an apple in some predefined manner, say, > > fruit,color,width,height) should be stored in a tuple. At least that's > > Must be a mutant red pear > > I don't think I've ever seen an apple with a 2" difference in > height vs width. Granted, a Red Delicious (being a common apple) does > have a bit of a height advantage... Let's just say spacetime is warped... ;) From irmen at -nospam-remove-this-xs4all.nl Wed Jul 14 17:30:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 14 Jul 2004 23:30:13 +0200 Subject: test_format fails (because of test__locale) In-Reply-To: References: <40eef27c$0$43451$e4fe514c@news.xs4all.nl> <40F35E2D.3030002@v.loewis.de> <40f4835a$0$65124$e4fe514c@news.xs4all.nl> Message-ID: <40f5a5e5$0$14941$e4fe514c@news.xs4all.nl> Tim Peters wrote: > [Irmen de Jong] > ,,, > >>As Michael Hudson pointed out it's probably a test that >>messes with the locale settings and forgets to set them back, >>or some such. > > > In case you don't already know it, regrtest.py's little-used -f > argument lets you specify a file, containing the names of the tests > you want to run. That was great, I quickly found out that test__locale is the cause. Not only test_format but also test_unicode fail on my Mandrake 10 box. My default locale is nl_NL. Behold: [irmen at atlantis Python-2.4a1]$ cat testcases.in test__locale test_format test_unicode [irmen at atlantis Python-2.4a1]$ ./python Lib/test/regrtest.py -f testcases.in test__locale test_format test test_format produced unexpected output: ********************************************************************** *** line 2 of actual output doesn't appear in expected output after line 1: + u'%f' % (1.0,) == u'1,000000' != '1.000000' ********************************************************************** test_unicode test test_unicode failed -- Traceback (most recent call last): File "/home/irmen/BUILD/Python-2.4a1/Lib/test/test_unicode.py", line 358, in test_formatt ing string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) File "/home/irmen/BUILD/Python-2.4a1/Lib/test/string_tests.py", line 615, in test_formatt ing self.checkequal('0042.00', '%07.2f', '__mod__', 42) File "/home/irmen/BUILD/Python-2.4a1/Lib/test/string_tests.py", line 56, in checkequal realresult AssertionError: u'0042.00' != u'0042,00' 1 test OK. 2 tests failed: test_format test_unicode [irmen at atlantis Python-2.4a1]$ --Irmen From jjl at pobox.com Wed Jul 14 18:21:38 2004 From: jjl at pobox.com (John J. Lee) Date: 14 Jul 2004 23:21:38 +0100 Subject: Collaborative Text Editor References: <-OidnYKNZa0mC2jdRVn-hQ@centurytel.net> Message-ID: <87smbuw7pp.fsf@pobox.com> Ed Suominen writes: > I'm thinking of implementing a real-time collaborative text editor in Python > using Twisted. Cool! I've wondered about this in the past. Not sure how useful it would turn out to be, but would be fun to find out. > An initial plan is to use a Twisted PB server daemon that > accepts user:password:file connections from text editor clients to make > changes to a specified file on the server, and have the text editor clients > update their local copies of the file based on local user input or input > entered from other users, relayed via the server. I wonder if client-server is the way to go here. On the surface, P2P seems more natural fit. The way I've always imagined it working is as follows. I'm sure experimentation is the way to find out what works, though, so Twisted certainly sounds like a great idea. - At any time, exactly one person has control. - The only person able to move the cursor and edit text is the one with control. - Anybody may flag up that they want control. Everybody is notified when this happens. - Control passes from one person to another by means of the person with control yielding it to a specified person. If I were doing this (which I'm not, of course), I would go out of my way to meet the following goals: - Critical: the way should be left open to implementing the protocol on any decent editor. - Important: the protocol should be efficient, so that latency is minimised. I imagine this requires pushing changes out rather than polling to check for changes, and having reasonably high-level primitive operations -- maybe insert, cut, paste, move, maybe rectangle-wise cut/paste operations too, maybe indent / dedent, plus operations on a circular clipboard stack (strange image ;-). > Jabber compatibility would be nice, as would color-coding of different > users' text, etc. Jabber certainly seems an entirely secondary thing: if it helps meet your goals, great. If not, who cares? I don't see how colour coding would work, other than to have text that has been entered since the last switch of control coloured differently. [...] > I'd appreciate pointers to any existing, simple Python-based text editors > suitable for being adapted to this purpose. "Suitable" means under an > OSI-approved license and written cleanly and modularly to facilitate > incorporation into another project. [...] I know vim is Python-scriptable, and has a fairly wide user base (especially if you count). For a number of reasons I've been meaning to learn vi properly for ages, but find it very hard to kick my emacs habit... have-the-appropriate-amount-of-fun-ly y'rs John From tim.peters at gmail.com Tue Jul 13 16:02:48 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 13 Jul 2004 16:02:48 -0400 Subject: Visual Studio not installed In-Reply-To: References: Message-ID: <1f7befae040713130221989f51@mail.gmail.com> [Darren Dale] > I have not been able to run "python setup.py install" on several > packages, receiving the following error: > > Python was built with version 6 of Visual Studio, and extensions need to > be built with the same version of the compiler, but it isnt installed. > > Could someone explain what this means? It means you're on a Windows system, you haven't installed Microsoft's C compiler ("version 6 of Visual Studio"), and you're trying to install a package that requires compiling C code. It doesn't work because it needs a C compiler. Sometimes you can get a different download of the package for Windows containing precompiled C code, though (it depends on the specific package). > I am working on windows XP at the moment, but when I move to Linux, does > this mean I will not be able to install from source? Linux systems all come with C compilers. Windows systems don't. Of course on a Linux system, the Python you use will not have been compiled with Visual Studio, so disutils won't claim that it was (it's telling you the truth on WIndows, though). I hope that answers your question, because I'm not sure what it was . From uval at rz.uni-karlsruhe.de Sun Jul 11 19:49:28 2004 From: uval at rz.uni-karlsruhe.de (Daniel =?ISO-8859-1?Q?Sch=FCle?=) Date: Mon, 12 Jul 2004 01:49:28 +0200 Subject: __getattribute__ Message-ID: Hello NG is this kind of usage possible for classes l = [1, 2, 3, 1] l.__getattribute__("count")(1) for example f = foo() def bar(t, m, p): t.__getattribute__(m)(p) regards Daniel From fumanchu at amor.org Sun Jul 18 16:19:46 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 18 Jul 2004 13:19:46 -0700 Subject: mod_python: How to make a single object available to allinstances? Message-ID: Michael Str?der wrote: > Robert Brewer wrote: > > > > mod_python won't reload modules (as long as you keep *a* > thread alive, I > > think); therefore, you can put your dict in a module: > > > > # myapp/env.py > > > > bigdict = {} > > > > On the first request to your app, start a new thread with a > reference to > > that module; subsequent imports will find env.py in sys.modules and > > won't reload, and therefore won't reinit your bigdict. > > Please enlighten me under which conditions this work. > Does that also work with Apache 1.3 and worker processes? Or > does it only > work with Apache 2.0 and threads? I'm not an expert on Apache or mod_python by any means. The above technique works on Apache 2 on my Win2k box. Y'all should probably ask Grisha on the mod_python list... Trond, are you using Apache 1 or 2? Robert Brewer MIS Amor Ministries fumanchu at amor.org From della at toglimi.linux.it Tue Jul 20 11:45:08 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Tue, 20 Jul 2004 15:45:08 GMT Subject: convert list of strings to set of regexes; convert list of strings to trie In-Reply-To: <3e96ebd7.0407190547.e805de5@posting.google.com> References: <3e96ebd7.0407190547.e805de5@posting.google.com> Message-ID: <86bLc.4092$OH4.59249@twister1.libero.it> Klaus Neuner wrote: > Hello, > > I need a function that converts a list into a set of regexes. Like so: > > string_list = ["blaa", "blab", "raaa", "rabb"] > > print string_list2regexes(string_list) > > > This should return something like: > > ["bla(a|b)", "ra(aa|bb)"] So, I guess you just want to isolate common prefixes. > I am aware of the fact that converting the list to a *trie* would almost do > the job. But I couldn't find anything about Python modules that produce tries. Maybe http://cvs.bioperl.org/cgi-bin/viewcvs/viewcvs.cgi/biopython/Bio/triefind.py?annotate=1.1&cvsroot=biopython can be of some use for you, even if I didn't have a look at it. -- Ciao, Matteo From squirrel at WPI.EDU Sat Jul 17 00:43:35 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Sat, 17 Jul 2004 00:43:35 -0400 Subject: Lists, tuples and memory. In-Reply-To: References: <9418be08.0407151109.15894fe7@posting.google.com> <9418be08.0407160626.4e5b58db@posting.google.com> Message-ID: On Fri, 16 Jul 2004, David Eppstein wrote: > In article , > Christopher T King wrote: > > > Ick. I thought part of the reason Set was created (aside from enabling > > set operations) was to improve on the dict() storage method. > > What alternative storage method did you have in mind that would be as > efficient and that would allow the same types of objects to be collected > into sets? One that didn't have to store a pointer to None for every single item :/ From tim.peters at gmail.com Thu Jul 22 13:03:56 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 22 Jul 2004 13:03:56 -0400 Subject: assertion error In-Reply-To: <40FFA3B7.6040109@optusnet.com.au> References: <40FFA3B7.6040109@optusnet.com.au> Message-ID: <1f7befae040722100365f5f6@mail.gmail.com> [benevilent at optusnet.com.au] > I'm getting an assertion error as a result of embedding python. > > "Modules/gcmodule.c:231: visit_decref: Assertion `gc->gc.gc_refs != 0' > failed." > > I only get this assertion error with Python compiled with debugging > flags, rathen than the standard library which comes with Debian. C asserts are only active in a debug build, so that's not surprising. > Using gdb I know on what type the object is, which is involved in the > assertion. It is a subclass of a built-in type which I have defined. Did you write this subclass in C or in Python? > This subclass has variables which can cause instances of the subclass to > participate in circular references (the built-in type I have defined > itself has no member variables). Removing the circular references seems > to avoid the error. > > I was under the impression that python can detect circular references, > and that this should not be a problem. Circular references aren't a problem. As the comment on that assert says, assert(gc->gc.gc_refs != 0); /* else refcount was too small */ If you wrote your subclass in C, it's almost certainly a missing Py_INCREF (or excess Py_DECREF) in your C code: there are more pointers to the object than the object's refcount believes exist. Or it's possible that you wrote a tp_traverse implementation that visits a single containee more than once (but that's rare). If you wrote your subclass in Python, then it's probably a not-reported-before bug in Python, and you should open a bug report (including a minimal test case). From nun at example.com Sat Jul 10 14:24:34 2004 From: nun at example.com (Mitja) Date: Sat, 10 Jul 2004 20:24:34 +0200 Subject: List Comprehension Syntax References: Message-ID: Moosebumps (news:j9NHc.8596$mJ3.4258 at newssvr25.news.prodigy.com) wrote: > You could do: > > result = [ > element.replace( 'blah', 'moof' ) > for element in list > if element[0:4] == 'blah' ] > > I guess, but that seems awkward to me. Looks too much > like a for loop and an if, and then the value is at the > top, which reads funny to me. (Strangely putting it on > one line doesn't read as funny, but it is less readable.) > Maybe I just have to get used to it. Which do you > prefer? Comments? I usually do result = [ element.replace( 'blah', 'moof' ) for element in list if element[0:4] == 'blah' ] It seems clean and logical enough to me - like e.g. defining big dicts. From skip at pobox.com Fri Jul 30 13:26:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 30 Jul 2004 12:26:17 -0500 Subject: what does 'for _ in range()' mean? In-Reply-To: References: <2moucmFo8dpdU1@uni-berlin.de> <41076E3E.233CE3F1@alcyone.com> <2mui6cFq81c0U1@uni-berlin.de> Message-ID: <16650.33977.470780.634065@montanaro.dyndns.org> Dave> Speaking of which, am I the only one here that sees this _() Dave> function as a total hack? It's a convention adopted by the i18n folks which got imported to Python. Preexisting tools that wander through the source and build dictionaries of string literals will work with C, Python or Perl (or whatever). The string "My dog has fleas" becomes _("My dog has fleas") That construct is a valid function call in many popular languages. There's an extra side benefit as well. To internationalize code that contains string literals you want to disturb code readability as little as possible. _(...) seems to be the least visually obtrusive function call available. So, yes it's a hack, maybe even a total hack, but it's a hack with history. Skip From skip at pobox.com Thu Jul 1 16:27:45 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 1 Jul 2004 15:27:45 -0500 Subject: [ANN] libgmail 0.0.1 -- Gmail access via Python In-Reply-To: <3c18c08f.0407011159.9243ee1@posting.google.com> References: <3c18c08f.0407011159.9243ee1@posting.google.com> Message-ID: <16612.29633.154518.517180@montanaro.dyndns.org> phil> P.S. I'm aware this may not make it through Usenet in one piece, phil> so watch out for line wrappings. Probably be safer to place it on a website somewhere and just post the url. Skip From apardon at forel.vub.ac.be Thu Jul 8 04:11:08 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Jul 2004 08:11:08 GMT Subject: Python indentation References: Message-ID: Op 2004-07-07, Brian Quinlan schreef : > Sateesh wrote: >> I surely understand the importance of indentation, but as you see there are >> beautification tools that can be used to beautiy the C code. > > I'm not sure why this is relevant. > >> Also indentation is based upon ones style of coding, and I feel somewhat >> restricted when the language itself restricts someone to code in a >> particular way. > > Which is why I asked you to name a desirable code construction that > Python denies you due to it's indentation rules. If, for example, you > find the following style compelling: Well personnaly if i have a loop with the terminating condition in the middle I now have to write it like this while True: code if condition: break code I would prefer to indent sucu code as follows: while True: code if condition: break code Why? because the loopbreaker is IME part of the loopstructure, not an ordinary if statement in the loopbody. This is why I prefer free form languages. If you need certain control structure that is not directly in the language but can be simulated, you can still indent your code according to the structure you have in mind as opposed to the structure that is forced upon you by the simulation. -- Antoon pardon From titogarcia_nospamniguarreria_ at inicia.es Thu Jul 15 18:24:43 2004 From: titogarcia_nospamniguarreria_ at inicia.es (Tito) Date: Fri, 16 Jul 2004 00:24:43 +0200 Subject: [Novice] Default argument value in function definition Message-ID: <2loejlFelu9nU1@uni-berlin.de> >From the Python's tutorial, about default argument values: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L I can't imagine how subsequent calls to f can share the same value for L. The tutorial says that a new symbol table for the variables inside of the function is created each time the function is called, and I would say the symbol table is destructed when the function finishes execution. How is the value of L conserved between funtion calls? Can someone explain the mechanism to me? Thanks, Tito From grante at visi.com Wed Jul 28 18:06:32 2004 From: grante at visi.com (Grant Edwards) Date: 28 Jul 2004 22:06:32 GMT Subject: space/tab conversion utility? References: <41081f6e$0$65607$a1866201@newsreader.visi.com> Message-ID: <41082368$0$8091$a1866201@newsreader.visi.com> On 2004-07-28, David Eppstein wrote: > In article <41081f6e$0$65607$a1866201 at newsreader.visi.com>, > Grant Edwards wrote: > >> Is there any utility to convert Python sources from space-based >> block indentation to tab-based? > > Why would you want to? So that I can submit patches to a Python application whos devloper uses tabs. My Python editor uses spaces. -- Grant Edwards grante Yow! So this is what it at feels like to be potato visi.com salad From n/a Fri Jul 23 10:37:44 2004 From: n/a (ADE) Date: Fri, 23 Jul 2004 07:37:44 -0700 Subject: File Transfer Message-ID: <10g28n8a2ajv93@corp.supernews.com> Hi I would like to create a program that a User can send large image files across the internet to my computer (only image formats) I would like to have basically a Client who sends files and a Server who recieves files Does anyone know where I can learn about this or has some code they wouldn't mind sharing Cheers From Scott.Daniels at Acm.Org Wed Jul 14 19:41:30 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 14 Jul 2004 16:41:30 -0700 Subject: Questions to the FAQ In-Reply-To: References: Message-ID: <40f5c8c3$1@nntp0.pdx.net> Josef Wolf wrote: > - FAQ entry 6.6: > > This FAQ entry makes a difference between new-style classes and classic > classes. An example is given for the new style and a hint is given how a > classic class would look like. But I can't see any difference in them: > The new-style example starts with "class Derived(Base):" and the hint for > the classic class is "class Derived(Base): ..." So what's the difference? > > What am I missing here? OK, I don't know where this comes in the FAQs (if it is there at all). First, the shorter answer: You can't have a new-style class inherit from a classic class, nor can you have a new-style inherit from a classic class. So, the "style" of a class (classic or new-style) that inherits from some other class is inherited. Here is a useful lie (lie in that there are tricky ways to avoid this): All new-style classes eventually inherit from the builtin class "object", none of the old-style classes are subclasses of object. So, for your question, after "class Derived(Base): ..." if issubclass(Base, object): Derived is new-style. if not issubclass(Base, object): Derived is classic. or (perhaps interesting, perhaps more to the point, perhaps confusing): if isinstance(Base, type): Derived is new-style. if not isinstance(Base, type): Derived is classic. Now a longer blather: The difference between "classic classes" (or old-style classes as we will eventually call them) is which "metaclass" they are built with. Don't worry too much about that, you shouldn't fiddle with (or worry about understanding) metaclasses until you know quite a lot about Python's implementation. The nickel explanation is that a metaclass controls how a class works in the same way that a class controls how an instance works. The class controls how the instance behaves, and the metaclass controls how that class does that controlling. "type" is a class for types, which is how the second pair of tests above work. object is the simplest class of type "type" -- everything below it is a new-style class. There are ways other than inheriting eventually from object to set up a metaclass to use for a class, but you should regard that as black magic for a while -- a metaclass gives you enough rope to shoot yourself in the foot. -- -Scott David Daniels Scott.Daniels at Acm.Org From dd55 at cornell.edu Wed Jul 14 10:51:28 2004 From: dd55 at cornell.edu (Darren Dale) Date: Wed, 14 Jul 2004 10:51:28 -0400 Subject: object attributes from a dictionary In-Reply-To: References: Message-ID: John Lenton wrote: > On Tue, 13 Jul 2004 18:24:49 -0400, Darren Dale wrote: > >>Is there a more direct way than this to turn a dictionary into an object? >> >>class pupa: >> def __init__(self,initDict,*args,**kwargs): >> [setattr(self,key,initDict[key]) for key in initDict.keys()] >> >>larva={'a':1,'b':2} >>moth=pupa(larva) >> >>(ok, so I'm dorking a bit here. I havent slept in two days.) > > > class pupa(dict): > def __getattr__(self, attr): > return self[attr] > def __setattr__(self, attr, val): > self[attr] = val > Maybe I'm missing a step, but this doesnt work. From jdc at uwo.ca Mon Jul 12 23:26:32 2004 From: jdc at uwo.ca (Dan Christensen) Date: Mon, 12 Jul 2004 23:26:32 -0400 Subject: Monte Carlo Method and pi References: <87llhqbbh5.fsf@uwo.ca> <3064b51d.0407120954.6e7aedf@posting.google.com> Message-ID: <87r7rg4mfr.fsf@uwo.ca> Tim Hochberg writes: > I can more than double the speed of this under psyco by replacing **2 > with x*x. I have inside information that pow is extra slow on psyco(*) Thanks for pointing this out. This change sped up all of the methods I've tried. It's too bad that Python does optimize this, but I case pow could be redefined at runtime. > (*) Psyco's support for floating point operations is considerable > slower than its support for integer operations. The latter are > optimized all the way to assembly when possible, but the latter are, > at best, optimized into C function calls that perform the > operation. That's unfortunate. > Thus there is always some function call overhead. Fixing > this would require someone who groks both the guts of Psyco and the > intracies of x86 floating point machine code to step forward. If someone volunteers, that would be great. I don't know anything about x86 floating point; is it a real mess? > If one takes into the accout the speed difference of the two CPUs this > puts the both the numarray and psyco solutions within about 50% of the > Fortran solution, which I'm impressed by. I've now run a bunch of timings of all the methods that have been proposed (except that I used C instead of Fortran) on one machine, a 2.66GHz P4. Here are the results, in seconds: Python 2.3.4 Python 2.4a1 naive loop: 0.657765 0.589741 naive loop psyco: 0.159085 naive loop weave: 0.084898 * numarray: 0.115775 ** imap lots: 1.359815 0.994505 imap fn: 0.979589 0.758308 custom gen: 0.841540 0.681277 gen expr: 0.694567 naive loop C: 0.040 * Only one of the tests used psyco. I did run the others with psyco too, but the times were about the same or slower. For me, psyco was about four times slower than C, and numarray was almost 3 times slower. I'm surprised by how close psyco and numarray were in your runs, and how slow Fortran was in beliavsky's test. My C program measures user+sys cpu time for the loop itself, but not start-up time for the program. In any case, getting within a factor of four of C, with a random number generator that is probably better, is pretty good! One really should compare the random number generators more carefully, since they could take a significant fraction of the time. The lines with one * use C's rand(). The line with ** uses numarray's random array function. Does anyone know what random number generator is used by numarray? By the way, note how well Python 2.4 performs compared with 2.3.4. (Psyco, weave, numarray not shown because I don't have them for 2.4.) I'm still curious about whether it could be possible to get really fast loops in Python using iterators and expressions like sum(1 + it1 - 2 * it2), where it1 and it2 are iterators that produce numbers. Could Python be clever enough to implement that as a for loop in C with just two or three C function calls in the loop? Dan Here's the code I used: -----pi.py----- from random import random from itertools import * from math import sqrt from operator import pow, sub, add from timeTest import * try: import weave haveWeave = True except: haveWeave = False try: import numarray import numarray.random_array haveNumarray = True except: haveNumarray = False def v1(n = 500000): "naive loop" rand = random sqr = sqrt sm = 0 for i in range(n): r = rand() sm += sqr(1-r*r) return 4*sm/n def v1weave(n = 500000): "naive loop weave" support = "#include " code = """ double sm; float rnd; srand(1); // seed random number generator sm = 0.0; for(int i=0;i #include "/home/spin/C/spin_time.h" int main() { double sm; float rnd; int i; int n = 500000; spin_time start, end; spin_time_set(start); srand(1); // seed random number generator sm = 0.0; for(i=0;i #include #include #define FACTOR (1.0/100.0) typedef struct { clock_t real; struct tms t; } spin_time; #define spin_time_set(st) st.real = times(&(st.t)) // floating point number of seconds: #define spin_time_both(st_start, st_end) \ ((st_end.t.tms_utime-st_start.t.tms_utime)*FACTOR + \ (st_end.t.tms_stime-st_start.t.tms_stime)*FACTOR) From grante at visi.com Wed Jul 28 22:10:02 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jul 2004 02:10:02 GMT Subject: space/tab conversion utility? References: <41081f6e$0$65607$a1866201@newsreader.visi.com> <410824eb$0$8091$a1866201@newsreader.visi.com> <41083376$0$65611$a1866201@newsreader.visi.com> Message-ID: <41085c7a$0$65603$a1866201@newsreader.visi.com> On 2004-07-29, Tim Peters wrote: > [Grant Edwards, wants to convert spaces to tabs] >> ... >> 2) Simply converting all leading spaces to the right number of >> tabs (unexpand knows how to do that) isn't correct. Only >> the spaces that are block-indent spaces should be converted. > ... > > reindent.py is in your Python distribution, and is the state > of the art for "intelligent" conversion of tab-infected files > to space-celebrating ones. I understand that's not the > direction you want, but it is the *code* you want to start > from. [...] That does indeed sound like the right starting point. The other option I can think of would be to hack up Jed's Python-mode so that it attempts to automatically detect whether tabs or spaces should be used. Or I could go work on my car. -- Grant Edwards grante Yow! BEEP-BEEP!! I'm a at '49 STUDEBAKER!! visi.com From tdelaney at avaya.com Fri Jul 9 02:35:19 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 9 Jul 2004 16:35:19 +1000 Subject: Why would I learn Python over other languages? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01ACB511@au3010avexu1.global.avaya.com> Charif Lakchiri wrote: > I have setup up Python on my system and played around a bit with, and > I have to admit that it's surprisingly simple and easy to get things > done with it. However, in my "quest" for interpreted oo scripting > languages, I also came across a language called Ruby. I know it's a > lot to ask, but I would really appreciate a few words, no great > detail, comparing Python to Ruby from those of you who have > experience with both. STFW http://www.google.com.au/search?q=python+ruby+comparison Tim Delaney From __peter__ at web.de Mon Jul 26 10:49:40 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Jul 2004 16:49:40 +0200 Subject: re.split() not keeping matched text References: <558Nc.1253$Mp1.1138@bignews4.bellsouth.net> Message-ID: mark at wutka.com wrote: > I don't know if this will save you any processing time, but you can just > replace the split with a findall like this: > l = re.findall("[^.?!]+[?!.]+", x) > > This should handle your example, plus it handles multiple occurances of > the punctuation at the end of the sentence. One caveat: the invariant "".join(re.findall("[^?!.]+[?!.]+", s)) == s will no longer hold as you will lose leading punctuation and trailing non-punctuation: >>> re.findall("[^?!.]+[?!.]+", "!so what! you're done? yes done") ['so what!', " you're done?"] >>> Peter From dietmar at schwertberger.de Wed Jul 28 18:09:58 2004 From: dietmar at schwertberger.de (Dietmar Schwertberger) Date: Thu, 29 Jul 2004 00:09:58 +0200 Subject: https proxy References: Message-ID: In article , Paul Sweeney wrote: > Dietmar Schwertberger wrote: > > Anyway it's available from my homepage; it's in the RISC OS additions > > archive - the name is SSLRelay. > > Thanks for posting a response Dietmar. > > It sounds like this works the same as the http proxies in my OP so it won't > unencrypt the data to make it viewable, but then it doesn't need to for your > app :-) > > In case someone else is reading this and it sounds useful to them, I > couldn't figure the url of your website, so you may want to repost with it. Oh yes, it's http://www.schwertberger.de . Regards, Dietmar From FBatista at uniFON.com.ar Wed Jul 14 15:05:22 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 14 Jul 2004 16:05:22 -0300 Subject: odd question Message-ID: [Karl Pech] #- Hi, #- #- I'm currently working on the following exercise: #- --- #- You have given the following function: #- def f2(i, j, k): #- return ((i | j) & k) | (i & j) #- #- Find a useful utilization for this function. #- --- #- #- Actually I couldn't figure out so far, what exactly is #- a "useful utilization". Can anybody of you help me? Depends on context. I find this very useful for puzzle students... :) . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Jul 3 14:06:01 2004 From: roy at panix.com (Roy Smith) Date: Sat, 03 Jul 2004 14:06:01 -0400 Subject: Testing for empty iterators? Message-ID: In the old days, if I wanted to return a sequence of items, I'd return a list, and loop over it like this: for thing in getListOfThings (): do something With iterators, I'm doing: for thing in getThingIterator (): do something. Now I need to test to see if the iterator is empty. Actually, it's a unit test where I want to assert that it is empty. In the old days, I would have done: assertEquals (getListOfThings (), []) but I don't see any clean way to do this with an iterator. The best I can come up with is something like: flag = False for thing in getThingIterator (): flag = True break assertEquals (flag, False) Is that really the only way to do it? From ville at spammers.com Sun Jul 4 14:27:10 2004 From: ville at spammers.com (Ville Vainio) Date: 04 Jul 2004 21:27:10 +0300 Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> <2kofmgF4li52U2@uni-berlin.de> Message-ID: >>>>> "Chain" == chain lube writes: Chain> You put yourself into big troubles if you miss the Chain> opportunity of Bigloo. I agree. Should I also forward this message to 10 other people to dodge the impending doom? Chain> The code is much better structured in Scheme than in Chain> Python. It is a big mistake to assume that Python displays Chain> any readability. The one So true. (set! x 10) Is so much more readable than x=10 Chain> annoying school people in introductory courses would be Chain> Python for its huge learning curve and its messy behavior. With all due respect, someone that thinks python has a huge learning curve must be a little bit on the slow side, cognition-wise. -- Ville Vainio http://tinyurl.com/2prnb From nomail at nospam.no Wed Jul 7 05:19:25 2004 From: nomail at nospam.no (Dominic) Date: Wed, 07 Jul 2004 11:19:25 +0200 Subject: Typed Python? In-Reply-To: References: <2kn746F4ci1vU1@uni-berlin.de> <2kofmgF4li52U2@uni-berlin.de> Message-ID: > What reminds me that LISP was used to write Yahoo! Store first... I read this a couple of times now. What was so great about Yahoo-Store? Did they have a better design, a better architecture? Or could they just mess around faster because they were doing it in a more dynamic language than e.g. C. What did Yahoo!-Store prove? If they had done it in BASIC or COBOL, would that justify a claim that BASIC/COBOL are great implementation languages? Obviously a implementation benefits if the implementation language fits and supports the programmer by being e.g. readable etc.. But isn't the architecure and overall design, a well documented analysis more important? As soon as the system is operating, requirements change and the system must adopt. In the future Model Driven Architecture may put even more emphasis on the activities happening before coding even starts. This SCHEME vs. Python discussion leads nowhere. Sure LISP/SCHEME are quite unique and the language is very elegant and powerful. But many do not feel comfortable with the programming style and readability (i like LISP but to me it still looks like symbolic machine code), so they chose Python or something else. Ciao, Dominic From __peter__ at web.de Thu Jul 1 03:52:39 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jul 2004 09:52:39 +0200 Subject: Time delay loop - better way? References: Message-ID: Dan Bishop wrote: > "Terry Reedy" wrote in message > news:... >> "Conrad" wrote in message >> news:pan.2004.06.30.22.48.43.405408 at nospam.com... >> > Greetings, >> > >> > Q: Is there some way to gracefully suspend a python app for a second or >> > so then resume? >> >> time.sleep(secs) >> >> >I could write the classic basic dumb >> > loop-tenzillion-times delay, but that seems inelegant, and well, >> > just wrong. >> >> I believe such loops either hog the CPU or take longer than intended. > > Or even worse, a faster CPU comes out and the loop is *shorter* than > intended. Well, you could adjust the delay to CPU speed. But avoid 16-bit counters if you expect your program to run on fast machines with more than 20 MHz :-) http://www.merlyn.demon.co.uk/pas-r200.htm#R200 Peter From jonathan.wright at gmail.com Fri Jul 23 13:00:15 2004 From: jonathan.wright at gmail.com (Jon Wright) Date: 23 Jul 2004 10:00:15 -0700 Subject: math module broken? References: <246a4e07.0407222219.23bb209b@posting.google.com> <4100BE72.1040405@igpm.rwth-aachen.de> Message-ID: <56b071ab.0407230900.30950a9a@posting.google.com> Helmut Jarausch wrote in message > Both are "correct" if you know what you have been asking for. > In standard mathematics the argument to a trigonometric function like > sin, cos, tan, ... is in radians (!) There was some discussion about this recently over in comp.lang.fortran, arising when someone queried sin/cos/tan etc for very large angles (represented in floating point, eg: sin(1.0E18)). Reduction (angle modulo 2pi) is considerably easier if you use a *rational* unit for measuring angles, as the answer can remain exact in terms of the particular number represented in floating point. Without using an irrational number, exact representations of angles can actually exist where you also have exact representations of sines and cosines. With radians you can only represent zero exactly, and below it seems not even that! Can someone supply a real concrete example where there is a reason to prefer radians when computing sin/cos/tan? (Not their derivatives!) The latter of the three examples is most disappointing: C:\>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from math import sin,asin,pi >>> sin(pi/6) # == 0.5 0.49999999999999994 >>> degrees(asin(0.5)) # == 30 30.000000000000004 >>> sin(pi) # == 0 1.2246063538223773e-016 I understand why this fails - I just think the world is wrong. Represent angles using some rational fraction of a circle and all this crap goes away. Why convert to a unit which eliminates the possibility of an exact representation of any result at all? > In the example above, Microsoft - something special as ever - seems to expect > the argument in degrees (which is quite unusual) The microsoft calculator has a checkbox for switching between degrees and radians and gets all of the analytical results above correct. We live in a mad world.... Jon From mwh at python.net Thu Jul 8 11:45:51 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 8 Jul 2004 15:45:51 GMT Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com> <87isdaf6w5.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > With new open-source library code, in the absence of a need for some > major feature introduced later, I'd probably pick 2.2 now, because of > the big changes from 2.1 to 2.2. I can see why you might choose 2.0, > 2.1 or 2.3 instead, though. All depends on the audience you hope to > reach, of course. I can't think of a good reason for choosing 2.0. Or, if you're choosing right now, 2.2, really. Cheers, mwh -- It's an especially annoying American buzzword for "business use, as opposed to consumer, research, or educational use". -- Tim Peters defines "enterprise" From tdelaney at avaya.com Tue Jul 13 18:14:06 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 14 Jul 2004 08:14:06 +1000 Subject: newbie:trying to read in stdoutput of commands under various *nixes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01B47A33@au3010avexu1.global.avaya.com> googleboy wrote: > #!/usr/bin/python > > import string, os > > name = "uname" > outName = os.popen ( name, "w" ) > print outName > > =+= > > and get output like: > > > Linux Here you are opening a pipe in "write" mode. uname writes to stdout (hence the "Linux" line) then returns a file-like object that you can write to. That's the first line. What you want is to open the process in "read" mode, then read the data from it. Untested: import os pin = os.popen("uname", "r") try: print pin.read() finally: pin.close() Tim Delaney From tjreedy at udel.edu Thu Jul 15 23:17:16 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Jul 2004 23:17:16 -0400 Subject: bugs at iter file() ? References: <10fc6kj98mkfef4@corp.supernews.com> Message-ID: "Michael Geary" wrote in message news:10fc6kj98mkfef4 at corp.supernews.com... > Terry Reedy wrote: > > To add to what Tim said: From the viewpoint of Windows in > > its default mode, there are no remaining lines. ^Z is the end > > of file and anything after that is accidental junk filling out the > > remainder of the disk block. > > Just to clarify one point... Windows itself does not have "text" or "binary" > files, and it does not treat ^Z in a file in any special way. There are no > special characters in files. Sorry, but ^Z has meant end-of-file I presume from the first version of DOS, which I suspect copied the usage from something previous. Example (Microsoft Basic manual, 1989): "When input is redirected [from terminal to a file], GW Basic continues to read from this source until a CTRL-Z is detected." Perhaps the usage has dimmed in non-DOS-based Windows, so that I should have said more carefully "from the viewpoint of DOS and perhaps DOS-based Windows and partially in modern non-DOS-based Windows ...". Still, in Windows XP, open a Command Prompt window and enter disk:\path> copy con: temp abd^Zdef where ^Z is control-Z and you get a file with 3, not 7 characters. The Windows version of the Python interactive interpreter exits on ^Z because that is, or at least was, standard behavior for interactive non-gui DOS/Windows programs > For example, if you use Notepad to open a file with embedded ^Z characters, > you will see those characters in the text (typically as right arrows, > depending on the font). The file won't be truncated at the first ^Z. This surprises me a bit. Which version of Windows? Try type'ing the same file ('type filename') in an XP Home command prompt. Even now, it should be truncated (just tested this). 07/15/2004 11:07 PM 7 temb ... C:\Documents and Settings\Terry>type temb abc I created temb as abc^Zdef with Python file.write (^Z=\032). > It's the C runtime that makes the distinction between text and binary files > and treats ^Z specially. The Microsoft Windows C runtime treats ^Z specially because that is, or at least was, the OS convention. possibly since before there was a C compiler for DOS. Terry J. Reedy From Scott.Daniels at Acm.Org Sat Jul 24 15:12:59 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 24 Jul 2004 12:12:59 -0700 Subject: Is there a reference/alias/pointer in Python? In-Reply-To: References: Message-ID: <4102b866$1@nntp0.pdx.net> Daniel Eloff wrote: > ... If I understand this correctly, mutable objects like lists and > dictionaries function in much the same way (if you assigned it to > Users['current_users_username']) but when you attempt to modify the > object through either pointer you end up modifying the underlying object > and thus the changes will be reflected in both? > > Am I close? The big trick to understanding python is to think of variables not as storage, but as names associated with values. That is often the missing link in understanding. after: s = "abcd" t = "defg" Think that your local dictionary (which is where your variables live), will have a pair of entries, one of which associates "s" with a string object, and another entry associating "t" with another string object. If you then do: s = 12345 "s" in the dictionary is now associated with the object for 12345. After: t = 12345 The "t" entry is also associated with an object representing 12345 (not necessarily the same object, but one that compares equal). The "variable" for any python object is a simple PyObject * pointer, and the only operations on that are to replace the pointer with another pointer. If you do this: s = [1, 2, 3, 4] t = [1, 2, 3, 4] There is no choice, s and t refer to different objects. The way to see this is to change each of them and check the results: s[2] = -1 t[1] = -2 Now looking at s and t, you can see they are distinct. If you do: s = [1, 2, 3, 4] t = s s[2] = -1 t[1] = -2 and then examine s and t, you can see that s and t are the same list. this can be check with the "is" comparison. s is t is True if (and only if) the PyObject*'s for s and t match. For immutable objects, no useful distinction can be made between two objects which are ==, but there is still a difference between "is" and "==". "s is t" works a lot like: "id(s) == id(t)". Hope this explanation helps. -- -Scott David Daniels Scott.Daniels at Acm.Org From richardt at edshk.demon.co.uk Wed Jul 21 06:48:04 2004 From: richardt at edshk.demon.co.uk (Richard Townsend) Date: Wed, 21 Jul 2004 11:48:04 +0100 Subject: string.encode on HP-UX Message-ID: Using Python-2.3.4 on HP-UX11i, the following code: import locale loc = locale.setlocale(locale.LC_ALL) print 'locale =', loc loc = locale.nl_langinfo(locale.CODESET) print 'locale =', loc print 'hello'.encode(loc, 'replace') produces: locale = C C C C C C locale = roman8 Traceback (most recent call last): File "test_locale.py", line 13, in ? print 'hello'.encode(loc, 'replace') LookupError: unknown encoding: roman8 [The same code on SUSE 9.1 doesn't raise an exception]. Should I be able to pass the value returned by nl_langinfo() to the string.encode call? Similar code is used by wxGlade and this exception prevents it from running. Does anybody know how to fix this on HP-UX? -- Richard Townsend From srumbalski at copper.net Thu Jul 8 22:50:35 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Thu, 08 Jul 2004 22:50:35 -0400 Subject: Short if References: <_LCdnQhjm9eluXHd4p2dnA@powergate.ca> Message-ID: <40ee07d0_3@newsfeed.slurp.net> Antoon Pardon wrote: > Op 2004-07-07, Peter Hansen schreef : >> ellisjb at my-deja.com wrote: >> >>> Reading the voting results I don't see why this was rejected. The way >>> I read it those in favor of some form of ternary operator seem to have >>> well over 50% of the vote. >> >> Answered at the top of the PEP, in the introduction: [snip] >> Clear enough? > > Not really. The question I have is whether the majority would > prefer an if-then-else expression in an other format than > there preference over not having an if-then-else expression. > As I recall from discussions at the time there were a number of people who supported only specific forms of a ternary operator while being vehemently opposed to other forms (often because of a perceived lack of readability of competing options). Therefore those in favor of a ternary operator, while appearing to constitute a majority, are more acurately described as fragmented minorities. Hence, the (unfortunate) status quo. Steven Rumbalski From paul at oz.net Fri Jul 2 20:40:00 2004 From: paul at oz.net (Paul) Date: 3 Jul 2004 00:40:00 GMT Subject: Eliminating duplicates entries from a list efficiently Message-ID: Can anyone suggest an efficient way to eliminate duplicate entries in a list? The naive approach below works fine, but is very slow with lists containing tens of thousands of entries: def uniq(list): u = [] for x in list: if x not in u: u.append(x) return u print uniq(['a','b','c','a']) ['a', 'b', 'c'] Thanks, -- Paul From jeff at ccvcorp.com Mon Jul 12 16:55:53 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 12 Jul 2004 13:55:53 -0700 Subject: Adding to VB In-Reply-To: References: Message-ID: <10f5ugonop1me8f@corp.supernews.com> F. GEIGER wrote: > *** wrote: > >> I'm looking for a simple way to add python scripting support to a VB >> project so that I can have a python script modify what the vb program >> does. A > > > Have a look into Mark Hammonds PPW32 book, Mark and Andy do this in > one of their excellent real world examples. A brief summary of the approach they use -- design your VB project as a set of COM objects. Create a set of Python classes that understand how to manipulate those COM objects. Embed a Python interpreter inside of your VB project (as yet another COM object). You now can use Python code to manipulate all (exposed) aspects of your VB app. But seriously, go buy the PPW32 book. If you're doing anything involving COM objects, it's well worth it -- and if you're scripting other applications on Windows, you *should* be doing it through COM. Jeff Shannon Technician/Programmer Credit International From no_sp at m_please.cc Fri Jul 30 07:33:22 2004 From: no_sp at m_please.cc (Mathias) Date: Fri, 30 Jul 2004 13:33:22 +0200 Subject: Problem with matplotlib Message-ID: Dear NG, I need to draw a few images in the same window and found matplotlib to be a very nice tool for my needs (thanks for the hint!). But I have trouble installing matplotlib on RedHat9 - under XP it runs just fine. I updated all the indicated packages except the agg package which I didn't really understand. So output with default setting is: [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from matplotlib.matlab import * Bad key "toolbar" on line 30 in /home/franzius/eclipse/workspace/Hierarchical SFA (moving digits)/.matplotlibrc Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/site-packages/matplotlib/matlab.py", line 143, in ? from backends import new_figure_manager, error_msg, \ File "/usr/lib/python2.3/site-packages/matplotlib/backends/__init__.py", line 26, in ? from backend_gtkagg import error_msg, draw_if_interactive, show, new_figure_manager File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_gtkagg.py", line 16, in ? from _gtkagg import agg_to_gtk_drawable ImportError: No module named _gtkagg When I change the .matplotlibrc settings to backend: GTK it works but then I can't reuse the image window as it seems. With WX I cant use imshow() Are there precompiled binaries with the agg stuff for linux as for windows? Or what do I have to install the agg sources myself (compilation seemed ok, but what then)? Sorry for my confusion and thanks for any help, Mathias From exarkun at divmod.com Tue Jul 27 16:46:43 2004 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 27 Jul 2004 16:46:43 -0400 Subject: IPC In-Reply-To: References: Message-ID: <4106BF33.5010003@divmod.com> Donn Cave wrote: > In article , > wrote: > >>There's two modules that I like to use for this kind of stuff: >>http://starship.python.net/crew/tmick/ (process.py) >>http://www.lysator.liu.se/~astrand/popen5/ (also process.py >>just to be confusing) > > > And worse yet, neither does much processing per se. > > >>I recently did a quick hack using select and popen2, but I >>doubt it's fast or even safe, but it works. >> >>#yadda yadda >>r, w, e = popen2.popen3(cmd) >>cmd = "?\n" >>w.write(cmd) >>w.flush() >>#continuely test for output to read >>while select.select([e],[],[],1)[0]:#timeout guessing game >> line=e.readline() >> #do something with line >>while select.select([r],[],[],1)[0]:#timeout guessing game >> line=r.readline() >> #do something with line >> >>If you're output is line buffered you probably shouldn't have >>many problems with this approach if you can be assured your >>program will respond within the 1 second alloted to it. If >>you're positive you'll get output, just remove the timeout. > > > Two points spring to mind: > > 1. Select's fundamental purpose, the reason you must > write select([file], ... instead of select(file, ... > is to handle multiple sources of input. > > 2. The file object's fundamental purpose is to make > sure select doesn't work. Even if output is line > buffered, that doesn't help input, which will still > confound select with process buffering. The buffer > parameters for the input file objects could do > something, but at the cost of reading input byte > by byte at considerable expense in system calls. > Use file descriptors. I was with you up until the last sentence. You seem to be implying that select([fileObj], ...) is different, at some underlying level, from select([fileObj.fileno()], ...) This is not the case. If you pass a file object to select(), Python will call fileno() for you. There is indeed buffering, but it will apply to the file descriptor just as much as it will to the file object, because it happens at or below the file descriptor level. Jp From lbates at swamisoft.com Thu Jul 15 10:54:08 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 15 Jul 2004 09:54:08 -0500 Subject: Tell if Win2000 or XP is inactive References: Message-ID: Why not just use screensaver that begins after your "unused/inactive" time period and check the On resume, password protect" box (XP). They have to log back in to do anything. Doesn't really log them "out", but if they have applications loaded, logging them out is going to be difficult (e.g. what do you do with any dialogs that may appear asking about unsaved work) and may not be what you really want. This should "protect" the unattended machine (which is what the auditors want) and your users. HTH, Larry Bates Syscon, Inc. "Bart Nessux" wrote in message news:cd63c7$1bq$1 at solaris.cc.vt.edu... > Hello, > > Auditors want us to log out a user if the computer they are logged onto > has been unused/inactive for a set period of time. It's trivial to > logout the user, but we're having trouble telling if the system is > indeed inactive. If we could learn that information, then we'd need to > measure how long it has been like this so we can all the logout > function. How might this determination and measurement be approached? > > We're using Python 2.3.x w/o Mr. Hammonds extra Windows extensions. We > do not want to install the win32 extensions. > > Thanks, > Bart From squirrel at WPI.EDU Fri Jul 16 11:30:51 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 16 Jul 2004 11:30:51 -0400 Subject: Lists, tuples and memory. In-Reply-To: <9418be08.0407160626.4e5b58db@posting.google.com> References: <9418be08.0407151109.15894fe7@posting.google.com> <9418be08.0407160626.4e5b58db@posting.google.com> Message-ID: On 16 Jul 2004, Elbert Lev wrote: > "Larry Bates" wrote in message news:... > > Any reason not to put the words into a dictionary? > > Dictionary has the almost 100 times faster access time theb bisect of > a list. Build time is about 1 second (very good). Memory consumption > almost 8 MB - 2.5 times higher then with the list (not too good). > Unless very fast access time is an imperative, I'd rather not to use > it. Try using a set instead of a dictionary. You should get the good access time of dictionaries with nearly the low memory usage of a list: from sets import Set lstdict=Set([x.lower().strip() for x in file("D:\\CommonDictionary.txt")]) if word in lstdict: Combine the above with the suggestions to use generators for best performance. Also available is sets.ImmutableSet. I'm not sure if this provides enhanced performance over Set though. From klappnase at web.de Thu Jul 1 05:38:55 2004 From: klappnase at web.de (klappnase) Date: 1 Jul 2004 02:38:55 -0700 Subject: Tkinter CheckButton variables References: Message-ID: "Elaine Jackson" wrote in message news:... > My CheckButton variables seem always to be true, whether the box is checked or > not, which makes them considerably less useful. Following is a little script > that illustrates the difficulty. Any help will be greatly appreciated. Thank > you. > > ########################################### > > from Tkinter import * > > def bCommand(): > if c['variable']: ## ALSO TRIED: if cVbl > print 'bool(cVbl)==True' > else: > print 'bool(cVbl)==False' > > root = Tk() > cVbl = IntVar() > c = Checkbutton(root,variable=cVbl) > c.pack(side=LEFT) > b = Button(root,height=1,width=10,command=bCommand) > b.pack(side=LEFT) > root.mainloop() c[variable'] returns (of course) cVb1 and therefore will always be true. You should use if cVb1.get(): (etc.) Michael From lard at tardis.ed.ac.molar.uk Sun Jul 18 14:52:59 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Sun, 18 Jul 2004 18:52:59 GMT Subject: dynamic class/module use? (like Java's forName) In-Reply-To: References: <_OdKc.29430$v7.8250@fe2.news.blueyonder.co.uk> <8glKc.31979$v7.20488@fe2.news.blueyonder.co.uk> Message-ID: Terry Reedy wrote: > "Alex Hunsley" wrote in message > news:8glKc.31979$v7.20488 at fe2.news.blueyonder.co.uk... > >> if (actionString == "blah"): >> blahThang = blah(constructor stuff) >> blahThang.doSomething() >> else if (actionString == "blah2"): >> blahThang2 = blah2(constructor stuff) >> blahThang2.doSomething() >> else if (actionString == "blah3"): >> blahThang3 = blah3(constructor stuff) >> blahThang3.doSomething() >> else if (actionString == "blah2"): >> # etc etc > > > The Python idiom for something like the above is to use a dict instead of > if/else. > It is especially useful when you want to add alternatives at runtime. > Something like > > actions = { 'blah':blah, 'blah2', blah2, 'blah3':blah3, ...} > # easily extended at runtime > ... > actions[actionString](constructor_stuff).doSomething > > Terry J. Reedy Interesting, I hadn't thought of using a dict. Using a dict would be better than 'if's, but would still require a central part of the code to know about all the actions! My way allows new classes to be presented and used without altering existing code. Also my method forces new actions to interface with 'central' code via the available official interface, rather than having new actions potentially put in the central code and hence have access to things directly (which isn't a good OO design). From russelllear at earthlink.net Sat Jul 3 19:27:23 2004 From: russelllear at earthlink.net (Russell Lear) Date: Sat, 03 Jul 2004 23:27:23 GMT Subject: Looking for minimal SQL References: Message-ID: Marco Aschwanden wrote: > I am wondering if anyone has a link / hint / book that > assembled this minimum sql. "SQL in a Nutshell" from O'Reilly documents both SQL99 and the deviations of Oracle, MS SQLServer, MySQL, and PostgreSQL (including lists of vender specific keywords). Don't know if it is quite what you're looking for, but it might help. That said, I'm not sure that trying for DB independence is really what you need to do. By doing that you not only make your life more difficult from an implementation PoV (by not taking advantages of useful utilities and extensions offered by the specific vendor), but you may not be able to provide the level of performance demanded by customers (depending on the size of your application). I recently developed an application for an Oracle database. (prototyped in Python, but moved to C#/.NET cuz that's what was wanted). The original version used pretty standard SQL and performed correctly. Only problem was that, under more extreme (but not-atypical) customer loads, it crawled. I needed to tweak the SQL to play to Oracle's quirks as well as using some of their packages. A better approach might be to provide an abstraction layer with vendor-specific plugins. Above the abstraction layer you expose a model that's important to your app. Below, you map to the DB. Just my opinion. Russell. From rtw at freenet.co.uk Sun Jul 25 14:44:45 2004 From: rtw at freenet.co.uk (Rob Williscroft) Date: 25 Jul 2004 18:44:45 GMT Subject: concatinating strings to int... or something :) References: Message-ID: WIdgeteye wrote in news:pan.2004.07.25.13.27.56.119159 at none.none in comp.lang.python: > (Simple test code below) > > What I am trying to do is print; > > you win $50 > > what I am getting is; > > you win $ 50 with the space between the $ and 50. > > I tried; print arf + barf print arf + str( barf ) > but it tells me you can't concat strings to numbers. > > mon = int(raw_input("get number")) > > barf = 2 * mon > > arf = "you win $" > > print arf, barf > print "%s%d" % (arf,barf) http://docs.python.org/lib/typesseq-strings.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From grante at visi.com Thu Jul 29 10:32:37 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jul 2004 14:32:37 GMT Subject: space/tab conversion utility? References: <41081f6e$0$65607$a1866201@newsreader.visi.com> <41082368$0$8091$a1866201@newsreader.visi.com> Message-ID: <41090a85$0$65608$a1866201@newsreader.visi.com> On 2004-07-29, Catalin Marinas wrote: >> So that I can submit patches to a Python application whos >> devloper uses tabs. My Python editor uses spaces. > > You have different options to the diff command for this: > > -E --ignore-tab-expansion Ignore changes due to tab expansion. > -b --ignore-space-change Ignore changes in the amount of white space. > -w --ignore-all-space Ignore all white space. > -B --ignore-blank-lines Ignore changes whose lines are all blank. But the lines of code I added will still be indented with spaces, and the program's author uses tabs. > Otherwise, a simple sed script might do it (convert 4 spaces > to one tab for example): > > sed -e "s/ /\t/g/" Nope, that doesn't work for reasons already discussed. Even if you restrict it to spaces at the beginning of the line (e.g. unexpand -t4 --first-only) it still breaks things. -- Grant Edwards grante Yow! I just remembered at something about a TOAD! visi.com From squirrel at WPI.EDU Wed Jul 28 09:18:30 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 28 Jul 2004 09:18:30 -0400 Subject: saving and reloading variables for interactive work In-Reply-To: References: Message-ID: On Tue, 27 Jul 2004, Darren Dale wrote: > If I am working interactively with 10 variables and wanted to pickle > them and reload them tomorrow using the same variable names, would there > be a direct way of doing it? Reminds me of my days in AppleSoft BASIC :) Unfortunately, there is no quick & easy way to do this in Python, since there is no easy way to differentiate unpicklable things (such as modules and functions) from picklable ones (your variables), nor to make Pickle gracefully ignore such objects. If you can get all your variable names into a list, however, you could use this code: >>> foo = 5 >>> bar = 6 >>> myvars = ['foo','bar'] >>> import pickle >>> pickle.dump(dict([(n,vars()[n]) for n in myvars]),open('myvars','w')) [time passes] >>> import pickle >>> vars().update(pickle.load(open('myvars'))) >>> foo 5 >>> bar 6 Pythonistas will cringe at my gratuitous use of vars(), but Python currently provides no method of using getattr()/setattr() to get/set module-level variables. getattr(__main__,...), anyone? From finite.automaton at gmail.com Thu Jul 15 11:13:16 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 15 Jul 2004 08:13:16 -0700 Subject: Lament: Import is not very smart. References: <10fbi6ll3q1v038@news.supernews.com> Message-ID: <4b39d922.0407150713.6d365e6d@posting.google.com> > you mean we should always have to say "import foo.bar.baz", even when > I'm in 'foo.bar'? PEP 328 clarifies relative/absolute imports. It should be available in the 2.4a release via "from __future__ import absolute_import" (http://www.python.org/peps/pep-0328.html) From __peter__ at web.de Thu Jul 1 07:03:34 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jul 2004 13:03:34 +0200 Subject: how to replace double backslash with one backslash in string... References: <40e3e738$0$25703$636a15ce@news.free.fr> Message-ID: Vincent Texier wrote: > I want to send 3 chars in hexa code to the serial port. > > So I type in a tkinter entry : "\x20\x01\x21" This *is* a 12-char string. > The string is set in a StringVar(). > > When I read the stringVar, I get : "\\x20\\x01\\x21" This is one way to represent above 12-char string in Python. > The length is 12 and not 3 anymore. > > How can I replace the escape character from the string with the > corresponding char, and get my 3 char string back ? You are not getting it back, your getting it for the first time: >>> "\\x20\\x01\\x21".decode("string_escape") ' \x01!' Peter From frank at chagford.com Sat Jul 24 09:23:20 2004 From: frank at chagford.com (Frank Millman) Date: 24 Jul 2004 06:23:20 -0700 Subject: math module broken? References: <246a4e07.0407222219.23bb209b@posting.google.com> Message-ID: <246a4e07.0407240523.21b73ec4@posting.google.com> Frank Millman wrote: > Hi all > > I was helping my niece with her trigonometry homework last night. Her > calculator's batteries were flat, so I thought I would use Python's > math module to calculate sin, cos, and tan. > > Can someone please explain these discrepancies? > Thank you so much for the explanations, everyone. I appreciate your patience. I agree with Timothy's suggestion about adding a note to the documentation. Obviously the math module is designed for those that know what they are doing. However, you will always get the odd guy like me that has some vague recollection of trigonometry from school days, but does not really understand it, so it should help to avoid similar confusion in the future. Frank From cpl.19.ghum at spamgourmet.com Sat Jul 3 11:55:48 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 3 Jul 2004 15:55:48 +0000 (UTC) Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> Message-ID: > Haskell is strongly typed but fully supports polymorphism > Haskell is functional rather than imperative > Haskell uses significant whitespace, like Python and it is at least 3 days behind Python. At least in Sweden, @ Chalmers ... EuroHaskell was just behind EuroPyhton From indigo at bitglue.com Sun Jul 25 11:09:47 2004 From: indigo at bitglue.com (Phil Frost) Date: Sun, 25 Jul 2004 11:09:47 -0400 Subject: capturing the output of external commands In-Reply-To: <0pg7g0tjoe0c9075kqdg7pjvlnlkqodf7k@4ax.com> References: <0pg7g0tjoe0c9075kqdg7pjvlnlkqodf7k@4ax.com> Message-ID: <20040725150947.GA6416@unununium.org> See the standard 'commands' module. If that doesn't fit your needs, you can capture the output directly with os.popen. On Sun, Jul 25, 2004 at 02:51:06PM +0000, Avi Kak wrote: > Is there a Python function in any of the > standard-distribution modules that does > what the backticks do in Perl? > > I want to run an external command and I'd > like its output to be captured directly > in my Python script in the form of a string > object. > > The function os.system() or any of the > os.exec functions do not work for what I > have in mind because they do not capture > and return in Python the output produced > by the commands supplied to them as > arguments. > > Avi Kak > kak at purdue.edu From skip at pobox.com Fri Jul 9 17:01:56 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 9 Jul 2004 16:01:56 -0500 Subject: [python-list] What am I doing wrong here? In-Reply-To: <1001523104070913042549520c@mail.gmail.com> References: <16622.59541.684345.30522@montanaro.dyndns.org> <1001523104070912155f72848e@mail.gmail.com> <1001523104070913042549520c@mail.gmail.com> Message-ID: <16623.1988.847858.922903@montanaro.dyndns.org> Paul> Works for me with this change: Paul> s = """From skip Thu Jul 8 14:50:00 -0500 2004 Paul> is mailbox.PortableUnixMailbox supposed to be able to handle Paul> ">From" ? I'm befuddled. I could have sworn I saw the bad behavior with both Python 2.3.4 and Python built from CVS. It currently works with 2.3.4 but not CVS... Hmmm... Makes me think maybe I'm not doing anything wrong after all. Thanks, Skip From jeff at ccvcorp.com Wed Jul 14 17:02:52 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 14 Jul 2004 14:02:52 -0700 Subject: returning a value from a thread In-Reply-To: References: <10fatb8dknikr58@corp.supernews.com> <10fb49dtbqk74d0@corp.supernews.com> Message-ID: <10fb7lqlil570d1@corp.supernews.com> Christopher T King wrote: >How about: > >blocking_IO_thread = threading.Thread(target=blocking_IO_func) >blocking_IO_thread.run() >somestuff() >someotherstuff() >blocking_IO_thread.join() > >or: > >workerthread = threading.Thread(target=somefunc) >workerthread.run() >do_screen_updates() >wait_for_user_request() >workerthread.join() > >Neither of those needs multiple processors to show (possibly huge) >performance gains. > Hmmm... I suppose so, although it seems to me that in most cases, you will be waiting for multiple chunks of blocking IO (in which case the worker thread should feed them through a queue for the main thread to process as they arrive), or needing to do an arbitrary number of screen updates / other user requests before the thread is finished (i.e., the "responsive UI" case I mentioned). The blocking IO case does have some merit, I'll admit -- I may be somewhat biased by the problems I've been working on, where blocking IO hasn't been an issue, so I didn't consider this. (I still have to say that I can't imagine *many* cases where one would have background processing where a specific number of UI interactions is appropriate -- if you need UI updates, then you're probably going to need an arbitrary number of them, in which case you need to check whether the thread is done rather than wait for it -- but I suppose that such cases may exist.) >Either way, I didn't make this problem up: the OP >asked how to get a value back from a thread (a reasonable thing to do), >not whether doing such a thing was the correct way to code his problem >(which I have no reason to doubt). > > You did, however, give an answer that will only work effectively in a particular subset of cases that fit the OP's description, without being specific about those limitations. It may well be that your solution will work for the OP, but since this list is archived and frequently searched, it's always good to explain *why* a given solution works or doesn't work. The OP is not the only person who'll be reading, so it is (at least IMO) beneficial to speak to a somewhat more general case, or at least to be clear about what cases one *is* speaking to. Jeff Shannon Technician/Programmer Credit International From aahz at pythoncraft.com Tue Jul 6 10:05:42 2004 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2004 10:05:42 -0400 Subject: useless destructors References: <2ktlakF6atfrU2@uni-berlin.de> Message-ID: In article <2ktlakF6atfrU2 at uni-berlin.de>, Oliver Fromme wrote: > >PS: I didn't bother to try lynx, because it is the least useful >browser anyway. :-) Actually I'm surprised that there are still people >who insist on using it, since there are better alternatives such as >links or w3m. They work better as browsers, technically, but their keyboard operations are much poorer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From tim.golden at viacom-outdoor.co.uk Mon Jul 19 11:40:37 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 19 Jul 2004 16:40:37 +0100 Subject: Printing on Windows Message-ID: [Chris Gonnerman] | >| What I want to know is, how do I specify what size paper I | >| want to print on? OK, as far as I can see, what you would ideally do is to call GetPrinter to pick up the current DEVMODE info, adjust the field you wanted, and then call SetPrinter to fix that in place before you call StartDoc to initialise the print job. Unfortunately, in pywin32 the win32print.GetPrinter explicitly returns a NULL in place of the DEVMODE pointer (from looking at the source), and even if it did return a DEVMODE structure, no corresponding SetPrinter method is exported. I'm not grumbling: if I had the wherewithal, I'd send Mark H a patch to add the functions in. It might be possible via ctypes but the DEVMODE structure is not small, so there would be a fair bit of messing about. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jbperez808 at wahoo.com Wed Jul 28 02:20:04 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 28 Jul 2004 14:20:04 +0800 Subject: what does 'for _ in range()' mean? Message-ID: <2moucmFo8dpdU1@uni-berlin.de> I saw this code snippet: sock.listen(20) for _ in range(20): newsock, client_addr = sock.accept() print "Client connected:", client_addr data[newsock] = "" why use _ for this example? Is there any optimization to be had using it? I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code? From mwh at python.net Fri Jul 9 08:15:33 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 9 Jul 2004 12:15:33 GMT Subject: bitstreams References: Message-ID: Andreas Lobinger writes: > Aloha, > > Michael Hudson wrote: > > Andreas Lobinger writes: > >>can anyone here recommend a implementation for bitstreams? > >> > >>For a project i need to extract bitfields from a file containing > >>one large bitstream (length >> 1000bit). The bitfields (1bit-24bit) > >>are not aligned to char boundaries (8bit). > > > Well, a thousand bits really isn't very many. Read the lot and slurp > > it into a long? > > Thanks to both replies by now. Two points. length>>1000bits means > that i'm talking about an implementation that runs up to 1000000bits. Oh :-) > In the moment i'm working with a string in memory and use a state > maschine to get to the first byte, use string.struct to get > the word/long containing all bits and a little bit masking. Right. > There is no real problem writing code for this, but i thought that > it could be that there are already implementations for bitstreams > f.e. mpeg-reading, a zlib implementation or other coding/decoding > things... Not to my knowledge! Such things are generally done by C libraries that are then wrapped for use by Python, in my experience. Writing a C extension to do what you need probably isn't amazingly hard (so long as you don't need bitfields wider than the machine word size I guess). Cheers, mwh -- 8. A programming language is low level when its programs require attention to the irrelevant. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From alanmk at hotmail.com Fri Jul 30 07:52:21 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 30 Jul 2004 12:52:21 +0100 Subject: Does jython depend on java class. In-Reply-To: <2mtrovFrgsp1U1@uni-berlin.de> References: <2msad9Fple9gU1@uni-berlin.de> <2mtrovFrgsp1U1@uni-berlin.de> Message-ID: <%DqOc.5812$Z14.7062@news.indigo.ie> [angel] >>>A java runtime environment includes jvm and java class (for example >>>classes.zip in sun jre). Of course jython need jvm,but does it need java >>>class. [Alan Kennedy] >>Yes, jython requires specific classes at runtime. >> >>For example, the python dictionary type is implemented by the java >>classes org.python.core.PyStringMap and org.python.core.PyDictionary. >>The .class files for these classes are stored in jython.jar, which >>always has to be loadable/in-your-classpath when your java application >>uses jython. [angel] > I still want to confirm if jython requires standard java class, for > example java.lang.* java.util.* ... > From the word "the python dictionary type is implemented by the java > classes org.python.core.PyStringMap and > org.python.core.PyDictionary" , I guess jython should depend on > java.lang.String, java.util.Hashtable ... > > So jython doesn't only compile python source code to java bytecode, > it is implemented by java language. Is it correct? Yes, jython does require java classes, e.g. java.util.*, java.lang.*, etc, at runtime. Attempting to summarise:- 1. Jython compiles all jython classes to java bytecode. 2. The java bytecode generated is layered upon a jython-specific "runtime" which implements jython semantics for data types: i.e. org.python.core.* 3. The classes in this jython specific runtime depend on java platform classes, i.e. java.util.*, java.io.*, etc. This can be seen by looking at the source for jython, i.e. $jython_home/org/python/core/*.java where you will see the jython "runtime" files containing import statements of the form import java.io.*; import java.util.*; import java.lang.ref.*; For example, the import list for org.python.core.PyList.java is import java.util.Vector; which shows that jython lists are built on java.util.Vector objects, the definition of which obviously must be available when jython programs use lists. This is true both when the code is compiled dynamically by jython, and when it is compiled statically by jythonc. HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From rparnes at megalink.net Wed Jul 14 18:38:01 2004 From: rparnes at megalink.net (Bob Parnes) Date: Wed, 14 Jul 2004 18:38:01 -0400 Subject: pyqt: multiple selections in QListView In-Reply-To: <200407130829.07198.phil@riverbankcomputing.co.uk> References: <200407130829.07198.phil@riverbankcomputing.co.uk> Message-ID: <20040714223801.GA6640@megalink.net> On Tue, Jul 13, 2004 at 08:29:07AM +0100, Phil Thompson wrote: > On Tuesday 13 July 2004 1:53 am, Bob Parnes wrote: > > I cannot find a reference on identifying multiple selections in > > QListView. Apparently one has to iterate through all the items and test > > each individually, but I don't know how to do the iteration. The qt3 > > documentation suggests QListViewItemIterator, but this does not seem to > > be available in python. > > QListViewIterator was added to PyQt v3.9 (current version is v3.12). > > Phil Thanks very much. I am using v3.8 on a debian computer. I'll try to upgrade. Bob -- Bob Parnes rparnes at megalink.net From peufeu at free.fr Mon Jul 19 13:31:07 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Mon, 19 Jul 2004 19:31:07 +0200 Subject: Alternative suggestion for conditional expressions (see PEP 308) References: <390d8a01.0407150701.7e3f9776@posting.google.com> Message-ID: Flame suit on. - add a switch-case statement : I do miss a switch-case in Python. The interpreter can't really optimize if/elif as a dictionary lookup, because what if there is a AND or OR clause, or if the object has defined a __cmp__ method with side effects ? This would be pervert... switch color: case 1: name = 'red' case 2: name = 'blue' case 3: case 4: name = 'colorblind' Could use a 'break' (like in C) or not (cleaner). - add a switch-case statement which can return a value. Problem : you need a new keyword for that, which is a bad thing... and it starts to look like lisp... I think the ternary operator is a half-baked solution to a more general problem ; it is useful as a little shortcut like " x ? 'Yes' : 'No' but doing more with it leads to obfuscation. Still, something lacks in Python... just like the break-n-levels. From DesertLinux at netscape.net Sat Jul 24 20:11:43 2004 From: DesertLinux at netscape.net (Byron) Date: Sun, 25 Jul 2004 00:11:43 GMT Subject: Problem stripping line feeds In-Reply-To: References: Message-ID: <3VCMc.13896$Qu5.855@newsread2.news.pas.earthlink.net> Hi Robert, I don't know if this will help too much, but have you tried the following: import string cleanedText = string.strip("String with carriage return goes here.") Byron --- Robert Oschler wrote: > Hello, > > I am using the following function to try and strip both carraige returns and > line feeds, ASCII 13 and 10 respectively, from a string. It doesn't seem to > be working: > > x = filter(lambda c: c not in "\012\015", string.strip(x)) # octal version > > I also tried: > > x = filter(lambda c: c not in "\r\n", string.strip(x)) # escape char. > version > > What am I doing wrong? > > Thanks From Kyler at news.Lairds.org Sun Jul 25 02:08:20 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Sun, 25 Jul 2004 06:08:20 GMT Subject: JPEG2000 support? Message-ID: <54ubt1-nrn.ln1@lairds.us> I'm getting ready to build an application around a big JPEG2000 image but I haven't found any Python support for JPEG2000. I plan to just use an external call to JasPer to handle the conversion for now but I'd prefer to have a better integrated solution. Are any Python libraries likely to have support for it soon? My searches are yielding surprisingly little. Thank you. --kyler From fperez528 at yahoo.com Sun Jul 11 20:57:29 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 11 Jul 2004 18:57:29 -0600 Subject: if/elif chain with assignment expressions References: <7xvfguflq1.fsf_-_@ruckus.brouhaha.com> <7x4qoe6vae.fsf@ruckus.brouhaha.com> Message-ID: Neil Hodgson wrote: > I hope this does not change as it makes analysis of the code easier. > Reading and understanding code is as important as writing it. Analysis of a > problem depends as much on restricting the set of possible causes ('it is > *not* the case that') as it does on generating a larger set of possible > causes ('it is the case that'). Pruning the possible cause tree is extremely > valuable and Python cooperates with a well thought out set of restrictions. > Being able to depend on the absence of assignments in if and while > statements is a benefit when fixing Python code over C/C++. Characterizing > these as "training wheels" and thus only of use to beginners is > unreasonable. Well, the problem here (and apparently others share this opinion) is that this particular restriction genuinely forces kludgy code in certain circumstances. As John Roth pointed out, the looping case is easily solved with iterators, but Paul's original one is not. I know that the if(x=0) bug in C/C++ is a potentially nasty one, having been bitten by it myself in the past. It is also true that having this particular option available allows certain kinds of code to be written in a clear and concise manner. So yes, it is a slightly dangerous feature, but one which offers true expressive power. Hence my characterization of it as 'training wheels': I don't mean to say that only beginners can fall into the trap (even Lance Armstrong can fall off a bike), but rather that experienced users will know what to watch for, and will be willing to pay the price of potentially falling for the liberty of going faster :) Cheers, f From beliavsky at aol.com Fri Jul 16 07:52:50 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 16 Jul 2004 04:52:50 -0700 Subject: class methods vs. functions References: <40f58208_1@127.0.0.1> Message-ID: <3064b51d.0407160352.4a607707@posting.google.com> Egbert Bouwman wrote in message news:... > My impression is that you can hardly call this OOO: > Object Oriented Orthodoxy. For instance, from the GOF I learned: Excuse me, but what is "GOF"? I thought of Good Old Fortran, but them I am an odd duck :). From m.bless at gmx.de Thu Jul 22 04:43:41 2004 From: m.bless at gmx.de (Martin Bless) Date: Thu, 22 Jul 2004 08:43:41 GMT Subject: datetime.fromstr() - how? References: <40fd17d2.18754421@news.versatel.de> Message-ID: <40ff7ca6.5736828@news.versatel.de> Dan Bishop <> wrote in : > >import datetime >def strToDate(ymd): > return datetime.date(*map(int, ymd.split('-'))) Yes, thanks, I like your solution better. This way I don't have to use 'time' as a second module. For those interested, here's what I'm using now. It's a pity the 'datetime' module lacks 'time.strptime()' functionality. In contrast it does provide 'strftime()' methods. mb - Martin # date,time,datetime,timestamp handling for MySQLdb # independant from mxdate class mysql_date(datetime.date): "Represent and convert 'YYYY-MM-DD'-like date values." def fromstr(Cls,s): try: return Cls(*map(int,s.split('-'))[:3]) except: return None fromstr = classmethod(fromstr) class mysql_time(datetime.time): "Represent and convert 'HH:MM:SS'-like time values." def fromstr(Cls,s): "Construct instance from string." try: return Cls(*map(int,s.split(':'))[:3]) except: return None fromstr = classmethod(fromstr) class mysql_datetime(datetime.datetime): "Represent and convert 'YYYY-MM-DD HH:MM:SS'-like datetime values." def fromstr(Cls,s): "Initialize instance from string." try: return Cls(*map(int,s.replace('-',' ').replace(':',' ').split())[:6]) except: return None fromstr = classmethod(fromstr) class mysql_timestamp(datetime.datetime): "Represent and convert 'YYYYMMDDHHMMSS'-like timestamp values." def fromstr(Cls,s,f='%Y%m%d%H%M%S'): "Initialize instance from string." try: return Cls(*map(int,[s[0:4],s[4:6],s[6:8],s[8:10],s[10:12],s[12:14]])) except: return None fromstr = classmethod(fromstr) def __str__(self): return self.strftime('%Y%m%d%H%M%S') myconv = MySQLdb.converters.conversions.copy() myconv.update({ FIELD_TYPE.TIMESTAMP : mysql_timestamp.fromstr, FIELD_TYPE.DATETIME : mysql_datetime.fromstr, FIELD_TYPE.DATE : mysql_date.fromstr, FIELD_TYPE.TIME : mysql_time.fromstr, }) From ben at transversal.com Tue Jul 13 04:19:43 2004 From: ben at transversal.com (Ben) Date: Tue, 13 Jul 2004 09:19:43 +0100 Subject: Prothon 0.1.2 is getting close to Alpha [Prothon] References: <9po0f0tkseqefiol1pcts844nfk7a7cr7o@4ax.com> <3p0Ic.350$i_3.206@fed1read04> <40f25132$0$13161$afc38c87@news.easynet.co.uk> Message-ID: <40f39b20$0$686$afc38c87@news.easynet.co.uk> Mark Hahn wrote: > Ben wrote: > >> As a user of Python who is very interested in Prothon this point is >> very important to me. Thinking about this, does Prothon have a >> mechanism similar to Pythons import hooks, so in a Prothon program >> you could do somthing like >> >> import python >> >> and then be able to import python modules natively. (With automatic >> translation of the builtin types). e.g >> >> import python >> import urllib2 >> ... >> >> >> This would greatly increase the uptake and people would be able to >> play around with prothon using libraries that already have and >> understand? > > Unfortunately Prothon objects are very different than Python's internally > so > automatic translation of libraries will probably never be possible. > Prothon > was never intended to be compatible with Python. Prothon "steals" most of > Python but is not compatible, just like Python 3 will not be. > > There will probably be library equivalents that are close enough to make > porting quite easy though. The current re library is a good example. It > is > compatible. Also the Prothon sqlite library uses the Python db protocol. Could it not be done in a similar manner to LunaticPython (https://moin.conectiva.com.br/LunaticPython), only slightly more integrated, so that method calls on prothon objects are simply forwarded to the equivalent python calls? It should be possible to write a forwarding proxy, I was just wondering about the import hooks part, so that if a .py file is found instead of a .pr, the proxying can be invoked. Anyway, its not that important. Just a suggestion I had. Cheers, Ben --- From grante at visi.com Fri Jul 23 03:55:56 2004 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2004 07:55:56 GMT Subject: math module broken? References: Message-ID: <4100c48c$0$233$a1866201@newsreader.visi.com> On 2004-07-23, Delaney, Timothy C (Timothy) wrote: > Delaney, Timothy C (Timothy) wrote: > >> The python trigonometric functions use radians. The Microsoft >> calculator (and the textbook) use degrees. > > I should note that there doesn't appear to be anything in the > documentation saying this. The closest thing is the statement "The math > module consists mostly of thin wrappers around the platform C math > library functions." And the man page for the C math libary function says: DESCRIPTION The sin() function returns the sine of x, where x is given in radians. What? Microsoft doesn't provide man pages for the C library functions?!?! -- Grant Edwards grante Yow! I hope the at "Eurythmics" practice birth visi.com control... From squirrel at WPI.EDU Thu Jul 15 09:17:51 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 15 Jul 2004 09:17:51 -0400 Subject: Ellipse fitting in python? In-Reply-To: References: <2335b39d.0407141028.2f565490@posting.google.com> <87oemiw777.fsf@pobox.com> Message-ID: On Wed, 14 Jul 2004, Fernando Perez wrote: > A quick comment in case it's not obvious: an ellipse is not a function in > Cartesian coordinates, and most standard LS solvers expect a function. So > it's probably best to convert things over to polar before feeding the data to > the LS solver. You could break both the ellipse and the data into two pieces (say, y>=K and y Does anyone (Tim?) have (ideally Python, but I can cope) code implementing the fixed-format algorithm from the Subject: named paper by Burger & Dybvig? Cheers, mwh -- #python FAQ: How do I build X? A: Wait for twisted.X. -- from Twisted.Quotes From squirrel at WPI.EDU Thu Jul 1 14:01:19 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 1 Jul 2004 14:01:19 -0400 Subject: how to find "".encodings In-Reply-To: <40E44EC1.7040007@draigBrady.com> References: <40E44EC1.7040007@draigBrady.com> Message-ID: On Thu, 1 Jul 2004 P at draigBrady.com wrote: > Christopher T King wrote: > > On Thu, 1 Jul 2004 P at draigBrady.com wrote: > >> > >>I know base64,utf8,latin,ascii work > >>and these are listed in the encodings > >>and codecs modules, but where can one > >>get a definitive list? I missed your mention of the encodings module - I didn't even know it existed! help(encodings) brings up a list too (albeit without descriptions). > Great thanks. If there was a link to that from > the appropriate entries in the following, I'd be happy. > http://docs.python.org/lib/string-methods.html Agreed (I had trouble finding it, too). From squirrel at wpi.edu Sat Jul 10 01:20:46 2004 From: squirrel at wpi.edu (Chris King) Date: Sat, 10 Jul 2004 01:20:46 -0400 Subject: Proper tail recursion In-Reply-To: References: Message-ID: <10euv59k82i7j89@corp.supernews.com> Christopher T King wrote: > I take that back. The intertwinement of C functions and Python calls on > the stack makes this nearly impossible -- there's no easy way to pop both > the C and Python stacks before calling the next function (it could be > partially done popping only the Python stack, though). Methinks tail calls > will have to wait for Stackless. Here I am, replying to myself again :) I'm trying a new implementation, making good use of a loop around the entirety of PyEval_EvalFrame(). Unfortunately, my changes cause the interpreter to segfault after a couple of tail calls. A debugger shows that 0xffffffff is getting stuck into a pool->freeblock in PyObject_Free(), and then is subsequently dereferenced in PyObject_Malloc() (causing the segfault). Could this be caused by my code Py_DECREFing an object too many times, but leaving a pointer to it somewhere? (My changes don't explicitly set anything to 0xffffffff or -1.) Or am I just in way over my head? :P From ialbert at mailblocks.com Wed Jul 28 15:42:59 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 28 Jul 2004 15:42:59 -0400 Subject: Newbie Question about Python as a language In-Reply-To: References: Message-ID: Dave Guenthner wrote: > definetly need some type if Visual Development Environment. Also, > does Python have methods or classes to access the Windows registry? > Also, I guess if was going to use an OO language, why would I choose > Python over say C# and Visual Studio? If your programs are strongly Windows specific you should stay with Microsoft products/languages. Istvan. From martin at v.loewis.de Wed Jul 28 18:10:45 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 29 Jul 2004 00:10:45 +0200 Subject: Static python compile on windows. In-Reply-To: <3c3c77dw.fsf@python.net> References: <41075068$0$26143$9b622d9e@news.freenet.de> <3c3c77dw.fsf@python.net> Message-ID: <4108245e$0$192$9b622d9e@news.freenet.de> Thomas Heller wrote: > Now I have a ~900 kB static python.exe. How can I prevent that this exe > tries to import extension modules from the file system - it always > crashes with a Fatal Python error: Interpreter not initialized (because > it tries to load the normal python23.dll which I have also installed)? See my comments to python-dev. The easiest way, as you explain, is to disable dynamic loading in the first place. Alternatively, make sure that the PE module it tries to load is the same as the one implementing dynamic loading. Regards, Martin From squirrel at WPI.EDU Thu Jul 22 10:52:32 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 22 Jul 2004 10:52:32 -0400 Subject: Basic Python Question In-Reply-To: <6ZLLc.4839$Mq3.91303@news4.e.nsc.no> References: <6ZLLc.4839$Mq3.91303@news4.e.nsc.no> Message-ID: On Thu, 22 Jul 2004, Richard Spooner wrote: > I have created a threaded class which sets up a socket and then binds to a > port. When I make a new instance I send the port number and I would like > the __init__ routine to set up the socket and then attempt to bind it to a > port. > > If I already have an instance of this class running then obviously I'll > already have a port bound. So if I try and create another instance with the > same port I'd like the program to flag this error and inform the user that > it is instead using the original instance.. To get the effect you want (return the previous instance), you'll need to do some trickery with __new__, the function which is responsible for creating a class (as opposed to initialization, which is handled by __init__): import threading import socket import struct class dataretriever(threading.Thread): __bound = {} # this holds data of the form port:class_instance __opened = False # used to stop multiple __init__s def __new__(cls,port): # try to get an existing class instance bound to port try: c = cls.__bound[port] # if that fails, make a new instance except KeyError: c = threading.Thread.__new__(cls, port) # and store it in our class variable cls.__bound[port] = c # this is executed if the try: succeeded else: print 'Port %d already bound, returning previous instance!' % port # __new__ must return an instance of cls return c def __init__(self, port): # only initialize ourselves once if self.__opened: return True self.__opened=True threading.Thread.__init__(self) self.setDaemon(1) self.resultQueue = resultsQueue self.s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) try: self.s.bind(( '', port)) except: print "Error binding worker" self.start() def run(self): while 1: pass #playing with the data I recieve >>> x = dataretriever(9999) >>> z = dataretriever(10000) >>> z is x False >>> y = dataretriever(9999) Port 9999 lready bound, returning previous instance! >>> y is x True Hope this all makes some sense :P From squirrel at WPI.EDU Mon Jul 19 21:05:27 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 19 Jul 2004 21:05:27 -0400 Subject: Question For Language Lawyers - WAS: Re: Combining colon statements on one line? In-Reply-To: <8i5us1-d7a1.ln1@eskimo.tundraware.com> References: <20040716050940.73131.qmail@web51810.mail.yahoo.com> <8i5us1-d7a1.ln1@eskimo.tundraware.com> Message-ID: On 19 Jul 2004, Tim Daneliuk wrote: > OK, this is clever, but I have a question for the Language Lawyers > here: > > It is really good style to depend upon boolean True and False > being 1 and 0? It seems to me that, especially in an OO > language, True and False ought to be treated as abstract > boolean objects. I remember reading something about this in a previous thread, and I think it was decided that int(True) will always evaluate to 1, and int(False) will similarly always evaluate to 0. So it may not be good style, but it should be guaranteed behaviour for some time. (Note: AFAICT, this isn't in the official language spec, though.) > In particular, assuming they are 1 and 0 > (it seems to me) promotes something about the language > _implementation) into the application code which is a Bad > Thing. Not necessarily -- you aren't really assuming they're 1 and 0 in Python ((1 is True) == False), but rather that they evaluate to 1 and 0 in an integer context, which is something that can be (and it seems is) as well defined as the fact that float(1) evaluates to 1.0. This does bring up the discrepancy that somelist[True] works, while somelist[1.0] doesn't. Dunno what to say about that :P > I actually resort to this sort of stuff to keep > things as abstract as possible: > > F = 1 == 0 > T = not F I used to do the same thing in C for a while: #define FALSE 0 #define TRUE !FALSE Though this came about because I had previously used VB, where -1 is the canonical true value, as opposed to the value of 1 used in C, and for some odd reason I was relying on this implementation detail. Moral: VB is hazardous to your health :) From chb_sh at hotmail.com Mon Jul 26 00:50:12 2004 From: chb_sh at hotmail.com (redguardtoo) Date: 25 Jul 2004 21:50:12 -0700 Subject: FlashIME2.0, the auto-complete software with python keyword dicitionary support Message-ID: <5b0a428e.0407252050.6bf43870@posting.google.com> http://www.d2ksoft.com It is easy to add your own keyword. online demo video(gif,flash, avi) available From mkc+dated+1090462781.ada7d5 at mathdogs.com Tue Jul 6 22:31:29 2004 From: mkc+dated+1090462781.ada7d5 at mathdogs.com (Mike Coleman) Date: 06 Jul 2004 22:31:29 -0400 Subject: can python easily be made truly 64-bit? (was Re: suse 9.1 and 64) References: <40de7dc6$0$13018$9b622d9e@news.freenet.de> <40e9c557$0$183$9b622d9e@news.freenet.de> <40e9e28d$0$13009$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > I see. Then the current limitation is in no way serious for you. You > apparently don't have the actual need, with an actual limitation in > actual data, which forces you to take work-arounds at the present > day. That's correct. I did bump into the limitation while designing a program a couple of years ago, in the sense that I discovered it and worked around it. (I don't recall exactly what the workaround was--maybe I switched to C++ for that program.) > For the specific example of large strings, you might have to > introduce a "multi-level" string, where a string wrapper has ten > strings, each 1GB of size, to achive the illusion of a 10GB string; > likewise for mmap. Yes, that would be a work-around, but apparently > none that you already had to make. This would kind of work. It doesn't seem like you could pass such a string as an argument to re.match or re.sub or as an operand to 'in', though, and expect things to work correctly. Anyway, I was just curious about the status of this. Thanks! Mike From jfabiani at yolo.com Sat Jul 31 04:23:45 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat, 31 Jul 2004 08:23:45 GMT Subject: MySQLdb select Message-ID: Hi, I'm a newbie and I'm attempting to learn howto create a select statement. When I use >>> string1='18 Tadlock Place' >>> cursor.execute("SELECT * FROM mytest where address = %s",string1) All works as expected. But >>> numb=10 >>> cursor.execute("SELECT * FROM mytest where clientID = %d",numb) Traceback (innermost last): File "", line 1, in ? File "/usr/lib64/python2.3/site-packages/MySQLdb/cursors.py", line 95, in execute return self._execute(query, args) File "/usr/lib64/python2.3/site-packages/MySQLdb/cursors.py", line 110, in _execute self.errorhandler(self, TypeError, m) File "/usr/lib64/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue TypeError: int argument required ClientID was created using "clientID int not null auto_increment primary key" What is the correct way passing the numb var to the string? Thanks John From python-listNOSPAMthankyou at lahf.org Mon Jul 5 16:31:00 2004 From: python-listNOSPAMthankyou at lahf.org (python-listNOSPAMthankyou at lahf.org) Date: Mon, 5 Jul 2004 21:31:00 +0100 Subject: Compiling nonexistent cvsignore file Message-ID: <200407052129.44831.python-listNOSPAMthankyou@NOSPAMlahf.org> Can you ?help me, can you pass me onto someone who can? Whilst compiling: rpmbuild --rebuild python2.3-2.3.4-2pydotorg.src.rpm I got an error: RPM build errors: ? ? user jafo does not exist - using root ? ? group jafo does not exist - using root ? ? user jafo does not exist - using root ? ? group jafo does not exist - using root ? ? user jafo does not exist - using root ? ? group jafo does not exist - using root File not found: /var/tmp/python2.3-2.3.4-root/usr/lib/python2.3/Tools/freeze/.cvsignore I'm not to concerned about the user and group errors (should I be?), but I am with the cvsignore file not found. Should I just head on over to the cvs, and grab myself a cutting edge version of the Python src RPM? Or what .. ? Does anyone have the links to where these solutions may be, please? -- -- No Spam solicited, from you or by you, Thanks. -- ---Virus checked by sender - There are no viruses attached to this email.--- From peter at engcorp.com Mon Jul 26 09:28:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Jul 2004 09:28:55 -0400 Subject: python bug? In-Reply-To: References: Message-ID: Anthony Petropoulos wrote: > When running this simple code: > ------- > class Dada: > a = [] This defines a class variable, of which there exists only one, effectively shared across all instances of Dada. > def __init__(self, arg): > self.a.append(arg) This (the "self.a" part) looks up the name "a" in the dictionary for the instance. It doesn't find anything there, so it looks next in the class. It finds the shared class variable. Then you append something to it. Note that as you are not "rebinding" the name "self.a" to anything, but merely modifying the contents of the list it is bound to, you don't end up with an instance variable called "self.a". > d1 = Dada("pro") > d2 = Dada("hoho") Given the above, it should be apparent that this is just appending both values to the same list. > Is this a feature? Is there something I'm missing? Yes, you are missing the following change to your code to do what you want: class Dada: def __init__(self, arg): self.a = [] self.a.append(arg) (of course, you would probably just write that as a single line "self.a = [arg]" in real code) This stuff should be covered, I believe, by the tutorial. Make sure you have gone through that carefully, and perhaps take the time to read all the FAQ entries before getting too deep into the language. -Peter From della at toglimi.linux.it Wed Jul 7 09:40:35 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 07 Jul 2004 13:40:35 GMT Subject: sets.Set doesn't honour __eq__ In-Reply-To: References: Message-ID: David Vaughan wrote: > I was expecting the class sets.Set to act like an > unordered list with no two members equal. But, while > the following code prints True, the assertion fails. > > > from sets import Set > > _base = str > class caseless_string(_base): > """Strings, but equality ignores case.""" > def __eq__(self, other): > return _base.__eq__(self.upper(), other.upper()) > [...] You just have to define __hash__ too: class caseless_string(str): """Strings, but equality ignores case.""" def __eq__(self, other): return str.__eq__(self.lower(), other.lower()) def __hash__(self): return str.__hash__(self.lower()) works fine for me. (btw, why do you do the _base trick?) -- Ciao, Matteo From newsgroups at jhrothjr.com Mon Jul 19 16:34:54 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 19 Jul 2004 16:34:54 -0400 Subject: unittest: Proposal to add failUnlessNear References: Message-ID: <10foc4c32lcfd65@news.supernews.com> "Bengt Richter" wrote in message news:cdh0mg$npj$0 at 216.39.172.122@theriver.com... > On 19 Jul 2004 11:06:47 GMT, Antoon Pardon wrote: > > >I have been working with unittests lately and found that the > >self.failUnlessAlmostEqual, isn't as usefull as it could be. > > > >My main problem is, that it is only usefull with objects > >that can be converted to floats, while there are a whole > >bunch of objects that can be almost equal but not so > >convertable. The first example coming to mind being > >complex numbers. > > > >A secondary objection is that you are limited to > >a very specific set of tolerances. If for instance > >you want to verify that two numbers differ at most > >by 0.0003 you can't specify that. > > > >So I propose to add the following > > > > > > def failUnlessNear(self, first, second, tolerance=1e-7, msg=None, norm=abs): > > """Fail if the two objects are too far appart as determined > > by the distance between them and the tolerance allowed. > > """ > > if norm(second-first) > tolerance: > > raise self.failureException, \ > > (msg or '%s != %s within %s tolerance' % (`first`, `second`, `tolerance`)) > > > > > >-- > >Antoon Pardon > > How about a more general solution? E.g., how about an optional keyword arg > cmp=comparison_function > passed to failUnlessAlmostEqual? (I'm guessing here, no time to look at it) > E.g., that way for mixed numbers including complex you could (if you thought > it made sense, which I am not necessarily arguing ;-) use e.g. > > def special_cmp(x,y): # untested! > diff = complex(x)-complex(y) > return max(cmp(abs(diff.real), tolerance), cmp(abs(diff.imag), tolerance)) > > and pass cmp=special_cmp as the kwarg. > > For special objects, you could define other kinds of nearness, and raise > appropriate informative exceptions if you get non-comparable arguments. > > (obviously tolerance has to be defined, so if you want to vary it conveniently, > you could pass it to a factory function that does the above def and returns > it with tolerance captured in a closure referred to by special_cmp). > > Or some other way. The point is you get to define the cmp= function as you please > without modifying the framework (once the optional kwarg is implemented).) I think this is overkill. I find myself using a raw assert much of the time rather than unittest's specific test methods; it works just as well and I don't have to remember the blasted syntax! The only reason for doing float and complex specially is that they are basic Python types, and while it's trivial to do the correct floating point test (assert abs(x - y) < tolerance) in each instance, it's repetitive code that isn't that easy to generalize correctly (at least without having to specify the tolerance on each call). See my other response for the general solution I used in FIT. John Roth > > gotta go... > > Regards, > Bengt Richter From sjdevnull at yahoo.com Thu Jul 22 15:12:38 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 22 Jul 2004 12:12:38 -0700 Subject: elisp -> Python (was Re: [OT] Emacs, Eclipse, Leo (was Re: IDE References: <16632.421.388512.993923@montanaro.dyndns.org> <7xn01sfqhs.fsf@ruckus.brouhaha.com> Message-ID: <96c2e938.0407221112.1a6b9859@posting.google.com> Paul Rubin wrote in message news:<7xn01sfqhs.fsf at ruckus.brouhaha.com>... > Fran?ois Pinard writes: > > Pymacs is not Emacs Lisp, and Python in Vim is not Vimscript either, > > tweaks are needed in both cases for accessing some of the underlying > > scripting facilities. Pymacs is rather elegant, Python in Vim is rather > > clean. > > What are these editors? Emacs and vi are the two most common editors for serious programmers in the Unix/Linux world; vim is the standard vi implementation used on most Linux distributions (and is widely available on other platforms, including other Unixes as well as Windows, Macintosh, Amiga, Vax, etc). GNU Emacs is the standard emacs implementation used on most Unix platforms that have any emacs implementation (and is widely available on other platforms, probably all those listed above but certainly Windows, Macintosh, and other Unixes). Other common vi implementations include nvi (used by BSD) and vile, other common emacs implementations include XEmacs (formerly Lucid Emacs) and jed. > Are they written in Python? How do they implement the editing buffer? Vim is implemented in C, and supports at least 4 scripting languages for extensions (vim, python, perl, and tcl); most larger extensions are written in Perl or Python, though some are in vim's built-in script. Emacs is a hybrid C/elisp implementation (elisp being Emacs' dialect of LISP) and normally extensions are written in elisp. Pymacs allows writing extensions in python. > How do they implement searching backwards for a regexp in the buffer? At what level? In vim, at the user or vimscript level: ?some_regex At the python level, you can use: import vim current_buffer=vim.current.buffer And then use the standard Python re to search current_buffer (a list of lines) or otherwise edit current_buffer. And you can treat current_buffer basically as you would expect: current_buffer[0]="New" # Change first line to "New" current_buffer[0:0]="New" # insert new first line "New" del current_buffer[9] # delete 10th line of buffer current_buffer.append("Last") # Append line "Last" to buffer Inside of vim, ":help python" has more info on the Python interface. Alternatively, you could execute a Vim command from the Python interface: import vim vim.command("?some_regex\n") #The search-backward command a user would run From mh at dreadnok.pixar.com Fri Jul 23 17:30:29 2004 From: mh at dreadnok.pixar.com (Mark Harrison) Date: Fri, 23 Jul 2004 21:30:29 GMT Subject: Extending and Embedding doc? References: Message-ID: Mark Harrison wrote: > Extending and Embedding the Python Interpreter > http://www.python.org/doc/current/ext/ext.html Got it, it's in the doc bundles at http://www.python.org/doc/current/download.html Thanks! From oliver.schoenborn at utoronto.ca Thu Jul 15 16:56:24 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Thu, 15 Jul 2004 16:56:24 -0400 Subject: difflib.ndiff broken? Message-ID: Can anyone try the following in their python interpreter? These give correct output: >>> print list(ndiff(['saving2 <>'])) ['- saving2 <>', '? ^^^\n'] >>> print list(ndiff(['saving2 <>'])) ['- saving2 <>', '? ^^^\n'] >>> print list(ndiff(['saving2 <>'])) ['- saving2 <>', '? ^^^^\n'] >>> print list(ndiff(['saving <>'])) ['- saving <>', '? ^^^^\n'] Now try the very slight variations: >>> print list(ndiff(['saving2 <>'])) ['- saving2 <>'] >>> print list(ndiff(['saving2 <>'])) ['- saving2 <>'] This can't be right... or is it? Where are the '? ...' lines? It does this for both Python 2.3.2 on Windows 2000 and Python 2.3.3 on SGI. If it's correct, how come??? Oliver From tjreedy at udel.edu Fri Jul 16 00:01:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Jul 2004 00:01:40 -0400 Subject: Lists, tuples and memory. References: <9418be08.0407151109.15894fe7@posting.google.com> Message-ID: "Larry Bates" wrote in message news:CLednf1kspFPeGvd4p2dnA at comcast.com... > Any reason not to put the words into a dictionary? for spell checking, I think I would... > Then your code becomes: > > lstdict=dict([(x.lower().strip(), None) for x in > file("D:\\CommonDictionary.txt")]) The list comp creates an unnecessary (and, in this case, large) intermediate list. In 2.4, removing the [] pair would result in a generator expression. In the meanwhile... >>> def lostrip(src): ... for w in src: yield w.lower().strip(), None ... >>> t = dict(lostrip(['abc ', 'DEG\n'])) >>> t {'abc': None, 'deg': None} Terry J. Reedy From guerra at tng.iac.es Fri Jul 9 21:29:52 2004 From: guerra at tng.iac.es (carlos2004) Date: Fri, 09 Jul 2004 21:29:52 -0400 Subject: looping def. Message-ID: <256c345a2b3587097ab136d923439e1a@localhost.talkaboutprogramming.com> this code is part of a program, where a button send a command to capture some images form a web cam.When the button is clicked the program will capture 100 frames in 30 seconds and freeze the actual image, after 30 seconds we can see the image live again, I?d like to repeat this 10 times pressing the button only one time and at the end send a message; END. code down.... aNY HELP.... def OnClick_500(self, evt): start_time = time.clock() filename = time.asctime(time.gmtime()).replace(' ','_').replace(':','-') dat = [] while time.clock() < start_time + 30: dat.append(cam.snap()) print len(dat) , 'frames taken in 30 seconds' dat = array(dat) fn = 'c:/PEPE_IMAGES/'+filename+'.GIF'#time.asctime(time.gmtime())+'.GIF' gIF.Write(dat, fn) From michele.simionato at gmail.com Fri Jul 16 12:44:05 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Jul 2004 09:44:05 -0700 Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: <4edc17eb.0407152054.10f75b4c@posting.google.com> Message-ID: <4edc17eb.0407160844.6263aeab@posting.google.com> Jacek Generowicz wrote in message news:... > michele.simionato at gmail.com (Michele Simionato) writes: > > > "Process Python exited abnormally with code 1" > > > Is there a way to get any info about why the Python process failed? > > You could start by looking at the python interpreter Emacs is trying > to run: > > C-h v py-python-command RET Thanks Jacek, this did the job. py-python-command was set to "/usr/bin/env python" and Mandrake was not happy about that, for some reason. I solved setting py-python-command to "/usr/bin/python". Now it works. Still, it is not as handy as in Scheme/Lisp where I can execute the block by just giving C-x C-e after the last parens (ah, how bad Python lack of parens ;) BTW, if someone needs tips for programming Scheme with emacs my suggestion is to try quack.el by Neil van Dyke (google is your friend). Michele Simionato From michele.simionato at gmail.com Sat Jul 10 04:02:21 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Jul 2004 01:02:21 -0700 Subject: Typed Python? References: <2kofmgF4li52U2@uni-berlin.de> <20040707223402.258$ii@news.newsreader.com> <20040708045519.202$tz@news.newsreader.com> Message-ID: <4edc17eb.0407100002.4929b352@posting.google.com> Ville Vainio wrote in message news:... > >>>>> "Hamilcar" == Hamilcar Barca writes: > > >> Python supports recursion, second order functions, numerical > >> programming and hundreds of other important concepts. > > Hamilcar> How about currying and deferred list evaluation? > > Deferred list evaluation: generators > Lazy evaluation in general: lambda : f(1,2) this does not work so well; missing a constructs such as Scheme "set!" and "let" anseverely limitates certain programming paradigms which are natural in Scheme. This is ok, anyway, since Python is not Scheme. But you cannot claim that Python support for certain things is as good as in other languages (say Scheme, Haskell, etc.) > Currying: lambda x,y : f(x,y,1,2) This is not currying. It is specializing arguments. Here is a reference about specializing arguments in Scheme: http://srfi.schemers.org/srfi-26/srfi-26.html Haskell does real currying. Michele Simionato From guettli at thomas-guettler.de Thu Jul 22 09:15:44 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 22 Jul 2004 15:15:44 +0200 Subject: Problem with urllib.py References: Message-ID: Am Thu, 22 Jul 2004 10:43:38 +0200 schrieb Volker M.: > Hey, > > I want to open a list of URLs with Pythons urllib and the fuction > open(URL) automatically. It is important that the program open ONLY > normal http-sites and no https-sites with user/password-request. > So exists a possibility that I could cancel all site requests with > user/password-dialogues? Hi, urllib is not interactive. If you don't send a login+password you get an "not authorized" response with the corresponding http error code. You can check this return code in your script. By the way, the user/password request (Pop-Up of browser) is HTTP Basic Authentication, it can be used with http or https. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From http Thu Jul 22 03:33:12 2004 From: http (Paul Rubin) Date: 22 Jul 2004 00:33:12 -0700 Subject: hash() algorithm References: Message-ID: <7xiscgfqdj.fsf@ruckus.brouhaha.com> Beno?t Dejean writes: > hi. Is the hash() algorithm standard ? Does hash(some_string) will always > return the same hash code on every arch ? I'd say you should not rely on that. > i need to use a ~checksum function, like md5, but i was also > thinking about hash() which is obviously simpler. So i can safely > rely on hash() behaviour so i can use it to generate ~strong and > portable identifier/checksum ? I don't know what you mean by "strong". I'm sure you can find collisions in hash() without much effort. It's much harder to do that for md5. From tdelaney at avaya.com Mon Jul 5 20:12:33 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 6 Jul 2004 10:12:33 +1000 Subject: Improved super/autosuper Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01ACAB95@au3010avexu1.global.avaya.com> OK - I've updated the recipe (though it's not available for general viewing yet). http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286195 autosuper is now a mixin class. Two properties are available - self.super and self.super_raise. Use self.super if you don't want an AttributeError to be raised if no base class has the attribute. Use self.super_raise if you do. The object returned by self.super and self.super_raise is a callable wrapper. If you call it, it will call the method on a base class with the same name as the method that self.super was called from. Alternately, you can access attributes/methods on the returned object. class A (autosuper): def __init__ (self, a, b): print 'A.__init__' print a, b self.super(a, b) def test (self, a, b): print 'A.test' print a, b self.super(a, b) class B (A): def __init__ (self): print 'B.__init__' self.super(1, 2) self.super.test(3, 4) B() produces: B.__init__ A.__init__ 1 2 A.test 3 4 Code is attached. Tim Delaney -------------- next part -------------- A non-text attachment was scrubbed... Name: super.py Type: application/octet-stream Size: 7424 bytes Desc: super.py URL: From dalcolmo at vh-s.de Thu Jul 22 11:46:34 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Thu, 22 Jul 2004 17:46:34 +0200 Subject: how can I get the name of a variable (or other object)? References: <20040722142305.0000373a@titan> Message-ID: <20040722174634.00007204@titan> on Thu, 22 Jul 2004 15:37:45 +0100 Richard Oudkerk wrote: > Try ... Thanks, actually I found all the answers so far quite helpful, even though I should have known them already. - Josef From chris.peressotti at utoronto.ca Mon Jul 19 10:25:51 2004 From: chris.peressotti at utoronto.ca (Chris P.) Date: 19 Jul 2004 07:25:51 -0700 Subject: Python 2.2 code continues running before list comprehension is completed? Message-ID: <3f233389.0407190625.4a32e753@posting.google.com> Hi. I've made a program that logs onto a telnet server, enters a command, and then creates a list of useful information out of the information that is dumped to the screen as a result of the command. Here's a generic version of the code in question: ##### # Prior code opens telnet connection "tn" and logs in. tn.read_until('> ') tn.write('THE COMMAND IS HERE\n') dump = tn.read_very_eager() dump_lines = dump.split('\n') dump_info = [x for x in dump_lines if (VARIOUS CONDITIONS ON x)] # string1 and string2 are strings that are known to # always appear in the dump. A = dump_info.index('string1\r') B = dump_info.index('string2\r') C = A - B - 1 ##### The thing is, I can step through this code in the debugger and it works fine. When run from the command line, however, I get the following error in response to my dump_info.index lines: ValueError: list.index(x): x not in list So I tried putting (for x in dump_info: print x) right after I make the list comprehension and, when I run that, it shows that the list is incomplete... so it SEEMS like Python begins to create the list comprehension and then continues to execute commands before the list comprehension is finished! Any help with a solution or workaround will be greatly appreciated, - Chris From gherzig at fmed.uba.ar Tue Jul 20 17:48:29 2004 From: gherzig at fmed.uba.ar (Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina) Date: Tue, 20 Jul 2004 18:48:29 -0300 Subject: cPickle and pgsql...damn!! Message-ID: <200407201848.29498.gherzig@fmed.uba.ar> Hi people, im having trouble when trying to UnPickle a 'pickled' field from a psql (7.3) field. I just want: >damnDict = {'foo' : 'bar'} >serializedDict = cPickle.dumps(damnDict) >print serializedDict >'}q\x01U\x03fooq\x03barq\x03s.' >pgconn.query('insert into TABLE values (%s)' % serializedDict) >result = pgconn.query('select * from TABLE').getresult()[0] >print result >'}qx01Ux03fooqx03barqx03s.' And....voila!! There is not the same piece of crap!! When i try to unpickle it (and get the original damnDict) i got 'Cant find MARK' error msg. Maybe this is a PostgreSQL issue, but if someone have a clue.... Here is the data Python 2.2 PostgreSQL 7.3 The field where i put the serialized data is a text field. Thanks! -- Gerardo Herzig Departamento de Proyectos Especiales e Internet Facultad de Medicina U.B.A. From http Mon Jul 12 15:43:09 2004 From: http (Paul Rubin) Date: 12 Jul 2004 12:43:09 -0700 Subject: Non-blocking read() in httplib? References: <2lf8joFc1kkcU1@uni-berlin.de> Message-ID: <7xn0253tbm.fsf@ruckus.brouhaha.com> Marcin Ciura writes: > I would like to defend against this by throwing an exception when the > read() lasts too long. But I cannot use select.select(), because > HTTPResponse has no fileno() method. Neither can I use signal.alarm(), > as it is for Unixes only. > > Is there any other way to break read() or make it non-blocking? I think I'd reach down into the response object and get the fileno. >From httplib.py: class HTTPResponse: # ... def __init__(self, sock, debuglevel=0, strict=0): self.fp = sock.makefile('rb', 0) self.debuglevel = debuglevel self.strict = strict so maybe you can get the fileno from response.fp. From lbates at swamisoft.com Mon Jul 26 19:32:46 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 26 Jul 2004 18:32:46 -0500 Subject: interactive graphics? References: <4egNc.115864$Mr4.37857@pd7tw1no> Message-ID: <4q2dnWvlH5QGCZjcRVn-sA@comcast.com> If your platform is Windows you might also want to take a look at: http://www.onlamp.com/pub/a/python/excerpts/chpt20/index.html HTH, Larry Bates Syscon, inc. "Elaine Jackson" wrote in message news:4egNc.115864$Mr4.37857 at pd7tw1no... > I'm intrigued by the pedagogical possibilities of those Java applets where you > can manipulate an image by mouse-dragging. Is there any prospect of doing > something similar with Python? And if so, where might one start? > > From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Mon Jul 5 04:29:51 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Mon, 5 Jul 2004 10:29:51 +0200 Subject: ANN: PySQLite 0.5.1 References: Message-ID: Hi ! But... try to manage "date" with SQLite... (it's only a sample). From stevecanfield at yahoo.com Fri Jul 9 13:27:21 2004 From: stevecanfield at yahoo.com (Steve Canfield) Date: 9 Jul 2004 10:27:21 -0700 Subject: member fns w/o args? Message-ID: <63081650.0407090927.493bd055@posting.google.com> Is fn2() accessible? class c: def fn1(self): print "in fn1()" def fn2(): print "in fn2()" Do member functions with no arguments have any meaning? -sc From justin__devine at hotmail.com Mon Jul 26 11:53:08 2004 From: justin__devine at hotmail.com (JDevine) Date: 26 Jul 2004 08:53:08 -0700 Subject: SpecTix Message-ID: I am brand new to python. I have written a windows program that I'd like to use SpecTix to design the GI for. After experimenting with Spectix, I have realized the output (.ui file) is not in python, Since there is no documentation for Spectix that I can find, can someone please tell me what language the ui file is in and the necessary process to connect that output to an already functional .py file -Justin Thanks alot to any who provide some help. From kamikaze at kuoi.asui.uidaho.edu Thu Jul 15 19:15:33 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 15 Jul 2004 23:15:33 GMT Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: <87d62xoun1.fsf@gvdnet.dk> Message-ID: Martin Christensen wrote on Thu, 15 Jul 2004 22:58:10 +0200: > I should be greatly surprised if it weren't possible to do something > similar in at least Vim. Thus `:help python`, which tells how to use the built-in interactive interpreter. Jacek took poorly to my suggestion to use Vim's help system to learn how Vim works, but there's no point in repeating information so easily available. -- Mark Hughes "The void breathed hard on my heart, turning its illusions to ice, shattering them. Was reborn, then, free to scrawl own design on this morally blank world. Was Rorschach." --Alan Moore, _Watchmen #6_, "The Abyss Gazes Also" From peter at engcorp.com Fri Jul 9 08:50:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jul 2004 08:50:01 -0400 Subject: Too many return-statements = bad style? In-Reply-To: <2l7fnvF9is81U1@uni-berlin.de> References: <2l7fnvF9is81U1@uni-berlin.de> Message-ID: <5OudnTKux_bkCXPd4p2dnA@powergate.ca> Rgemini wrote: > I do it that way too. But I put exit comments next to the returns so they > stand out more. Something like > > return foo ##### exit because foo = bar ##### Wouldn't that be redundant if the code read this way? if foo == bar: return foo -Peter From guettli at thomas-guettler.de Mon Jul 26 11:34:55 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 26 Jul 2004 17:34:55 +0200 Subject: Suggestions on Python XML. References: Message-ID: Am Fri, 23 Jul 2004 22:47:37 -0700 schrieb June Moore: > Hi, > I would like to write a script in Python that takes XML request, query > MySQL database and sends XML requests back. > Can anyone here suggest any relevant links / tutorials on the web that > are related to allow me to do this? Hi, Try to break your problem into several smaller ones. 1. Parse the request (not http, just a normal file) I suggest sax: import xml.sax 2. Learn how to handle a HTTP-Request (module cgi and cgitb) 3. Try to make queries with mysql 4. Create valid XML You can use fd.write() or a library. Good luck, Thomas From dd55 at cornell.edu Tue Jul 6 19:07:58 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 06 Jul 2004 19:07:58 -0400 Subject: reading file contents to an array (newbie) Message-ID: Hello, I am trying to learn how to read a delimited file into a numarray. I have a working strategy, but it doesnt seem very elegant: manually changing whitespace delimiters to commas, evaluating the lines to a list of tuples, creating a numarray object from that list. Could I get some suggestions on how to do this more Pythonically? I have to read pretty large files, so this approach is probably way to slow. Here is my code: from numarray import * myFile=file('test.dat',mode='rt') tempData=myFile.readlines() data=[] for line in tempData: line=line.replace(' ',',') line=line.replace('\n','') data.append(eval(line)) data=array(data) Thanks... From peter at engcorp.com Wed Jul 28 18:32:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jul 2004 18:32:54 -0400 Subject: what does 'for _ in range()' mean? In-Reply-To: References: <10gevuasrt08rae@news.supernews.com> Message-ID: David Eppstein wrote: > In that context, it's allowed multiple times, but in some other contexts > it's not: > >>>>def foo(_,_): pass > > ... > File "", line 1 > SyntaxError: duplicate argument '_' in function definition Uh, okay... and does Ocaml allow duplicating argument names in whatever it has that passes for a function definition? This is all a reach from the original point of the thread, which was to use it as a throw-away control variable in a for loop... -Peter From steve at ferg.org Mon Jul 19 14:10:35 2004 From: steve at ferg.org (Stephen Ferg) Date: 19 Jul 2004 11:10:35 -0700 Subject: Subclassing int for a revolving control number References: Message-ID: I think the simplest solution would be just to use a generator... ************************************ def rollover(argMaxNumber=20): while True: for i in range(1, argMaxNumber+1): yield i ########### test the rollover generator... r = rollover(5) for i in range(33): print i, "=", r.next() ************************************* From tim.peters at gmail.com Fri Jul 23 15:54:14 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 23 Jul 2004 15:54:14 -0400 Subject: math module broken? In-Reply-To: References: <246a4e07.0407222219.23bb209b@posting.google.com> <4100BE72.1040405@igpm.rwth-aachen.de> <56b071ab.0407230900.30950a9a@posting.google.com> Message-ID: <1f7befae04072312547d39d683@mail.gmail.com> [Christopher T King] > ... > Reduction... from 1.0e18?! Of course that doesn't work with radians, it > doesn't even works with degrees! Actually, it can. If you view a floating-point number as being exactly what it says it is, then of course there's an exact reduction of that number modulo pi. Very high-quality math libraries compute that too. I know because I wrote one . The popular fdlibm (from Netlib) does "as-if infinite precision" trig argument reduction too. The details can be excruciating. You (of course) need to know pi to greater than machine precision, but not to as much greater as you may think: across all possible 754 doubles, you can find the one closest to being an exact multiple of pi, and you only need to use enough extra precision to get the right answer (to machine precision) in that worst case. At least 3 groups have discovered that independently (I was one of them, discovered when writing a libm for Kendall Square Research in the early 90's, in collaboration with Peter Tang). IIRC, Mary Payne at DEC was the first to implement "infinite precision" trig argument reduction in a commercial math library, and she wrote a very readable paper about it I'm unable to find now. She wasn't able to put an a priori bound on the amount of precision needed, so it was less efficient than later attempts. All in all, and despite having pushed the state of the art there myself, it's a silly thng to bother with . From jacek.generowicz at cern.ch Thu Jul 15 16:52:37 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: Thu, 15 Jul 2004 22:52:37 +0200 Subject: class methods vs. functions In-Reply-To: <20040715160010.GA1767@mirk.lan> References: <40f58208_1@127.0.0.1> <20040715160010.GA1767@mirk.lan> Message-ID: On 15 Jul 2004, at 18:00, Egbert Bouwman wrote: > On Thu, Jul 15, 2004 at 02:10:06PM +0200, Jacek Generowicz wrote: > >> Why treat it as private, if it isn't marked as private? If it isn't >> marked as private, then it's part of the interface. If it's part of >> the interface, then it is intended for use by clients. If it's >> intended for use by clients, then use it. > > My impression is that you can hardly call this OOO: > Object Oriented Orthodoxy. For instance, from the GOF I learned: Aaah, the dear GOF book. You do realize that the GOF book is, to a lange extent, a book about the shortcomings of C++, don't you? For example, think about how you would implement the Decorator and the State patterns in Python. I would advise against basing your understanding of what object oriented programming is about, on the GOF book. > - the object's internal state can not be accessed directly This is blatantly false, as your code snippet below clearly demonstrates. (You probably meant "should not" rather that "can not". The "should not" is a dogma. Understand its motivation, and decide for yourself to what extent you want to buy it.) > - operations are the only way to change an object's internal state Ditto. (... "are the only way" -> "should be the only way" ...) > - requests (or messages) are the only way to get an object > to execute an operation Read up about properties in Python. Strictly speaking, it's not an object which executes an operation; rather methods carry out operations on objects. And it's certainly not true that messages are the only way to get a method to carry out an operation on objects ... put differently: generic functions exist. > It is not easy to find definitions of 'interface' in python books, How about "Anything that does not start with an underscore" ? (One can argue about the details of this proto-definition, but in terms of value per word, it's pretty good, I'd say.) > And now you suggest that everything that is accessible is part > of the interface. No. I suggest that everything that is part of the interface is part of the interface. Put in other terms, everything that is not marked as private, is part of the interface (or in some languages, everything that is marked as public, is part of the interface --- though "private" and "public" might not be the words which are used to describe a similar concept in those languages). Some languages (notably C++ and Java) consider that marking things as private is not good enough (I guess that the assumption is that people who program in those languages are too stupid to understand the importance of interfaces and to respect them), and such languages attempt to make the private parts inaccessible. Encapsulation and access restriction are orthogonal concepts, which have been conflated in Java and C++. That doesn't make them any less orthogonal, as concepts ... so don't make the (all too common mistake) of believing that they are actually one and the same. > I think I prefer the orthodoxy. Into bondage, are you ? :-) > I suppose that is what you mean when you say: >> Be careful not to let Java or C++ (or anyone strongly influenced by >> them) to shape your understanding of object oriented programming. You >> would be doing yourself a disservice. > but I need more explanations, arguments, references. Well, in terms of explanations and arguments, I was steering you towards a discussion of the generic-function OO paradigm ... but you seem not to have followed that up. In terms of references ... try looking into some languages which support OO, which predate Java and C++ (or which are otherwise not influenced by them, or, at least, look very different from them.) You could try Smalltalk, or Common Lisp, for example. > You seem to encourage the following practice: >>>> class C: pass >>>> c = C() >>>> c.x = 9 Absolutely. > the internal state of c is not private, This is not generally true, but it is true in this case. For example, I would discourage the following: class C: def __init__(self): self._x = 3 c = C() c._x = 9 Note that I would not forbid it. In fact, I would encourage it, in some situations. For example a) You are debugging your application, or investigating its behaviour b) The author of C hadn't anticipated some perfectly valid use you wish to make of C, and didn't provide you with an adequate interface From jarausch at igpm.rwth-aachen.de Wed Jul 21 06:35:25 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 21 Jul 2004 12:35:25 +0200 Subject: Python C++ In-Reply-To: References: Message-ID: <40FE46ED.7000203@igpm.rwth-aachen.de> Francois Fernandes wrote: > Hi! > > Is it possible to easyly integrate c++ classes in python? > > I don't want to use boost c++. > > Does anyone know how to start or where to find documentation for this? > I prefer PyCXX http://cxx.sourceforge.net -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From martin at v.loewis.de Wed Jul 14 16:21:38 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Jul 2004 22:21:38 +0200 Subject: How big is python24.dll? In-Reply-To: <8089854e.0407140429.6b86b2c7@posting.google.com> References: <40f3690b$0$26125$9b622d9e@news.freenet.de> <8089854e.0407140429.6b86b2c7@posting.google.com> Message-ID: <40f595d2$0$13062$9b622d9e@news.freenet.de> Fuzzyman wrote: > As a side issue David Kastan has just compiled Python 2.3.4 for the > pocketPC. He's endeavoured to keep the dll down to a minimum and > everything else in a zip - making minimum size distributions possible. > > More of an issue on a machine with 32mb ram (including storage)..... On such a system, removing unneeded modules is trivial: just don't compile them (and comment-out the relevant lines in config.c). For people who want super-small packages of Python2.4, it would be possible to create a separate python24.dll, which is plug-in compatible except that it has fewer modules built-in. If there is a real need for such a thing, somebody will provide regardless of whether the standard distribution provides it. Regards, Martin From liquid at kuht.it Sun Jul 4 11:38:56 2004 From: liquid at kuht.it (GMTaglia) Date: 4 Jul 2004 08:38:56 -0700 Subject: a bug in urllib? References: Message-ID: <8e352b1f.0407040738.f0d623d@posting.google.com> Haim Ashkenazi wrote in message news:... > Hi > > I'm writing a script that uses urllib on win98. until now I used python > 2.3.x (x < 4) and it worked ok. I re-installed windows and installed > python 2.3.4 and now I get an error when trying to open a url "no host > given": > > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 > > Type "copyright", "credits" or "license()" for more information. > > > > **************************************************************** > > Personal firewall software may warn about the connection IDLE > > makes to its subprocess using this computer's internal loopback > > interface. This connection is not visible on any external > > interface and no data is sent to or received from the Internet. > > **************************************************************** > > > > IDLE 1.0.3 > > >>> import urllib > > >>> f = urllib.URLopener() > > >>> x = f.open('http://www.python.org') > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > x = f.open('http://www.python.org') > > File "C:\PYTHON23\Lib\urllib.py", line 181, in open > > return getattr(self, name)(url) > > File "C:\PYTHON23\Lib\urllib.py", line 281, in open_http > > if not host: raise IOError, ('http error', 'no host given') > > IOError: [Errno http error] no host given > > >>> > > -------------------------------------------- > > I don't think it's a network error because I can browse to this site > without a problem. does anyone have any idea? is it a bug? can anyone tell > me where I can download an earlier version (not activestate, it's not > running well on my win98)? > > Bye I've just tried also in windows but no errors, same version as you Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import urllib >>> f = urllib.URLopener() >>> x = f.open('http://www.python.org') >>> Maybe you can reconsider a network error? ciao Mario From michael at foord.net Thu Jul 8 03:16:13 2004 From: michael at foord.net (Fuzzyman) Date: 8 Jul 2004 00:16:13 -0700 Subject: Parsing HTML - modify URLs References: <8089854e.0407071224.36d15900@posting.google.com> <87brire8n7.fsf@pobox.com> <40ec817a$0$25460$afc38c87@news.optusnet.com.au> Message-ID: <8089854e.0407072316.6ecdc334@posting.google.com> richard wrote in message news:<40ec817a$0$25460$afc38c87 at news.optusnet.com.au>... > > michael at foord.net (Fuzzyman) writes: > >> "Robert Brewer" wrote in message > >> news:... > >> > Haven't used it, but Beautiful Soup sounds like it fits the bill: > >> > > >> > http://www.crummy.com/software/BeautifulSoup/ > >> > >> It talks about 'walkin the parse tree'... which is a bit more magic > >> than I want... I just want to modify URLs in tags... which means I > >> mainly want to extract the HTML unchanged and also modify a few tags - > >> HTMLParser is quite good at this- but dies *horribly* at bad HTML... I > >> may have to try beautiful soup though :-) > > From the BeautifulSoup page: > > "You can modify a Tag or NavigableText in place. Printing it out as a > string will print the new markup text." > > And really, it handles *any* HTML, no matter how crappy - I'm using it to > deal with pages that have random and in them with no > matching end / start tags. Eugh. > > Once you've written rewrite_url(), this will do the job on the BeautifulSoup > side: > > soup = BeautifulSoup() > soup.feed(source_html) > for tag, attr in (('img', 'src'), ('a', 'href')): > for tag in soup(tag): > if tag.get(attr): > tag[attr] = rewrite_url(tag[attr]) > print soup > > > Richard Brilliant Richard. I did hack together a version that worked inside the Tag class of BeautifulSoup - but your suggestion is much more elegant. I've already written rewrite_url - twice now :-) Should work fine........ Thanks Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From squirrel at WPI.EDU Thu Jul 15 14:10:23 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 15 Jul 2004 14:10:23 -0400 Subject: class methods vs. functions In-Reply-To: References: <40f58208_1@127.0.0.1> Message-ID: On Thu, 15 Jul 2004, Egbert Bouwman wrote: > My impression is that you can hardly call this OOO: > Object Oriented Orthodoxy. For instance, from the GOF I learned: > - the object's internal state can not be accessed directly > - operations are the only way to change an object's internal state > - requests (or messages) are the only way to get an object > to execute an operation > - a signature consists of an operation's name, parameters and return value > - the interface to an object is the set of all signatures of its operations Replace .x with .getx() and .y with .gety() if it suits you, but often in the case where an object is mostly used as a container (similar to a C struct), direct access to its attributes is considered the norm: a = 3+5j a.real # --> 3.0 a.imag # --> 5.0 If you so choose, you can make .x and .y read-only with a little __setattr__ magic (there's probably an easier way to do this in new-style classes), as they are in the complex type: a.real = 4 # --> AttributeError Sure, it may not fit with "proper OO methodology", but it's a good way of making visible the fact that "this object is a container, I'm retrieving one of the variables it contains". If the interface is well-defined, it doesn't matter how you access it, so long as you follow the interface's design. From noe at netscape.net Mon Jul 19 11:57:36 2004 From: noe at netscape.net (Noe) Date: Mon, 19 Jul 2004 11:57:36 -0400 Subject: matplotlib References: Message-ID: <7fydnZ3_zKACbWbd4p2dnA@comcast.com> "John Hunter" a ?crit dans le message de news:mailman.565.1090241092.5135.python-list at python.org... > >>>>> "Noe" == Noe writes: > > Noe> Hello, I have a problem with finance_work2.py provided in the > Noe> documentation. I can't find the helpers module : ImportError: > Noe> No module named helpers > > Noe> Someone could help me? > > You need a couple other files as well - should have mentioned this in > the finance_work file... > > Save the following in the same dir as finance_work.py > > http://matplotlib.sourceforge.net/screenshots/helpers.py > > http://matplotlib.sourceforge.net/screenshots/msft_nasdaq_d.csv > > http://matplotlib.sourceforge.net/screenshots/__init__.py > > You'll also probably want to add a call to the function show at the > end of the file if you want to display the results in a GUI window. > > Good luck! > JDH > > > Hi John, thanks for your answer, but I already have a problem while launching the script : Fatal Python error: PyEval_RestoreThread: NULL tstate abnormal program termination After a lot of response from google impossible to find the problem... If you have some clue, I take ! Thanks From onurb at xiludom.gro Wed Jul 7 16:16:32 2004 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 07 Jul 2004 22:16:32 +0200 Subject: [OT] Python indentation In-Reply-To: <2l2nltF81vsgU1@uni-berlin.de> References: <2l24dvF7h0e9U1@uni-berlin.de> <2l2nltF81vsgU1@uni-berlin.de> Message-ID: <40ec5ba8$0$18114$626a14ce@news.free.fr> Reinhold Birkenfeld a ?crit : > Grant Edwards wrote: > (snip about 'why significative whitespace') >>> >>>Yes. It's about readability. >>> (snip) >>Compare C and Python: >> >>In C, we have 10 lines >> >> if (condition) >> { >> doThis(); >> doThat(); >> } >> else >> { >> doWhatever(); >> andSoOn(); >> } > > > Well, one could apply another coding style in this example: > > if (condition) { > doThis(); > doThat(); > } else { > doWhatever(); > andSoOn(); > } > > which only takes 7 lines and is not much less readable. For me it's as absolutely unreadable as the first snippet. The only truely correct layout being (of course !-) : if (condition) { doThis(); doThat(); } else { doWhatever(); andSoOn(); } > But I agree with > you! I do too. The fact is that there is no brace-and-indent-style-war with Python !-) Bruno From dvarrazzo at virgilio.it Mon Jul 19 11:09:52 2004 From: dvarrazzo at virgilio.it (Daniele Varrazzo) Date: Mon, 19 Jul 2004 17:09:52 +0200 Subject: Metaclasses for class mangling after definition. Message-ID: Hi everybody, I am writing a base class for <> stereotype classes, to implement controlled access to the state and expose some of the access logic (in order to dinamically build javascript code for client-side checks, for example). Currently the idiom needed to subclass it is something like: class Group(Entity): _interface = Entity._extend_interface( id = Direct(state_field='grp_id', filters=(ReadOnlyFilter(),), doc="The univocal database id for the group."), name = Direct( filters=( StringFilter(), MaxLenFilter(max_len=40, message="The group name can be at most " "%(max_len)s characters long."),), doc = "A descriptive name for the group."), ) _state = Entity._extend_state( grp_id=None, name=None, ) # ... class definition ... make_entity(Group) The make_entity() call compiles some dinamically generated code to produce the properties required to access the class. But adding such line after each entity definition bothers me. I don't know much about metaclasses: could they help me to automatically perform such mangling on the classes "at compile time" (or at least once in the class lifetime)? Hints about that? What make_entity does is here down. Basically each Field instance (Direct is a Field subclass) in the _interface dictionary (a class member) create a property object on the same class that will perform the access for the class instances. def make_entity(entity): """Complete the Entity subclass building its attributes.""" for (field_name, field) in entity._interface.iteritems(): if not hasattr(entity, field_name): field.field_name = field_name field.create_accessors(entity) Thank you in advance Daniele From ajsiegel at optonline.com Wed Jul 7 21:42:52 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 08 Jul 2004 01:42:52 GMT Subject: Typed Python? References: Message-ID: On 07 Jul 2004 16:45:37 +0200, Jacek Generowicz wrote: >> Another thing is whether it pays off for future students to learn a >> language that they won't need after that one course, > >What they will need in the future, depends on what they choose to do >in the future. If they want to be Java monkeys, then they should not >bother with Scheme. If they want to be highly skilled programmers, >then Scheme is a vastly superior choice to Java (and even Python). > >> unless they choose to stay in school & join academia. Some might >> say that the time would be better spent by teaching Python instead. > >Some might say that the time would be better spent teaching >accountancy. It all depends on what you want out of life. Perhaps it would. >From the point of view of an outsider to the world of professional programming: We judge a programming language with respect to its use in the "real world", with Python and Lisp and Scheme lovers feeling obliged to point to their languages use in the real world. Real world seeming to mean - more or less - the business world. By employing the highly skilled programmer, equipped with the just right tool (be it Python or Scheme or Lisp or whatever) someone is finding competitive advantage, and thereby making more than ordinary profits, perhaps building an empire or two. But it is quite unlikely that someone is the programmer. Who brings born aptitudes, years of study and experience, etc, to the table, and is probably in and out on a contract basis, having earning subsistance for a bit of time, perhaps, in fact, by accomplishing something of brilliance. In the realms where I have my experience, nobody would be boasting of being that programmer. Art From __peter__ at web.de Tue Jul 27 08:49:45 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Jul 2004 14:49:45 +0200 Subject: replace dict contents References: <41060AB3.9080600@jessikat.fsnet.co.uk> Message-ID: Tim Jarman wrote: > On 27 Jul 2004, at 08:56, Robin Becker wrote: > >> Is there a simple way to replace the contents of a dictionary entirely >> with those of another. >> >> for lists we can do >> >> L1[:] = L2 > How about: > > >>> d1 = { "spam" : "eggs" } > >>> d2 = { "gumby" : "my brain hurts!"} > >>> d1 is d2 > False > >>> d1 = dict(d2) This rebinds the name d1 to a copy of d2 and will not affect other references to the original d1. Peter From __peter__ at web.de Mon Jul 19 12:31:36 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jul 2004 18:31:36 +0200 Subject: Python 2.2 code continues running before list comprehension is completed? References: <3f233389.0407190625.4a32e753@posting.google.com> Message-ID: Heiko Wundram wrote: > IIRC, Python 2.2 didn't support list comprehensions (feature new as of > 2.3), so you'll have to work around that by creating some form of simple > for loop which does what you want, esp. considering that VARIOUS > CONDITIONS ON x seems to be a lot more than just a simple check (which > will make the code a helluvalot cleaner if spelled out). Python 2.2.1 (#1, Sep 10 2002, 17:49:17) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [c for c in "you are wrong"][-5:] ['w', 'r', 'o', 'n', 'g'] >>> (but only with regard to list comprehensions) Peter From kak at purdue.edu Thu Jul 22 23:50:55 2004 From: kak at purdue.edu (Avi Kak) Date: Fri, 23 Jul 2004 03:50:55 GMT Subject: befuddled by os.exec functions Message-ID: Hello: I'd be most grateful if someone could answer the following questions about the exec functions in the os module. 1) How does one get one of the os.exec functions in Python to execute a shell script that includes some sort of a control structure in the shell script itself? For example, I can do the following in Perl $ENV{ACK_MSG} = "You said: "; exec('while a=a; do read MYINPUT; echo $ACK_MSG $MYINPUT; done'); How can one use one of the os.exec functions in Python to do the same? All of the os.exec functions require a pathname for the first argument, followed by well-defined arguments. But the above example does not break down into pathname and argument components. 2) In the following example, I am mystified as to why the first element of the list in the second argument has to be ignored. If it is going to be ignored anyway, why does it need to be supplied at all? The following call does the same regardless of what one has in the first element of the second-arg list. os.execvp( 'ls', ['ls', '-al'] ) Thanks. Avi Kak kak at purdue.edu From r_b_lawson at yahoo.com Thu Jul 8 08:48:16 2004 From: r_b_lawson at yahoo.com (Rick Lawson) Date: 8 Jul 2004 05:48:16 -0700 Subject: Porting Java web application to Python to make it faster? References: <1inbbvrpmu1n6$.a0ikxbujiqk3$.dlg@40tude.net> Message-ID: <14460e6d.0407080448.2985143@posting.google.com> Disclaimer: I love Python but write Java webapps (mainly Struts) for a living. I don't think the problem is Java, server side it is very fast. With a good data access layer and caching (like Hibernate) I think that a Java webapp will be hard to beat. Sounds like the problem is the design decision to emulate a rich desktop app as a web based app. Since this is an internal app you may want to suggest a desktop client (either Java or Python based) communicating via Soap or xmlrpc. The nice thing about doing an rich client app in Java for a limited audience is you can Webstart it which makes for painless deployment. On the other hand, I've had good luck writing wxPython based rich clients and using Inno Setup to deliver a clickable installer. Good luck, Rick Wolfgang Keller wrote in message news:<1inbbvrpmu1n6$.a0ikxbujiqk3$.dlg at 40tude.net>... > Hello, > > as a non-developer I am currently participating in an industrial "research" > project to develop a so-called "web application". This application serves > at the same time as middleware to connect several other "conventional" > enterprise-applications such as ERP, SCADA etc. and to provide a GUI > frontend to the users. The developers are into Struts, Enterprise Java > Beans and the like, so it will be entirely implemented in Java with all the > processing on the server side and only static HTML pages on the client > side. It will have to "emulate" much of the GUI logic of a conventional > interactive application with multiple Eclipse-like collapsable panes, > XForms-like dynamic forms, lots of expandable tree views and sortable lists > everywhere, plus SOAP communication "behind the scenes" to get and put > loads of data all over the company's network. > > The developers say it will require "considerable" hardware resources in > order to allow reasonable response times, according to them >>1GByte of RAM > for a rather small workgroup (<10 concurrent users). From my own personal > experience with applications implemented in Java (such as UML and database > modeling tools etc.) I fear that this might in fact mean that the reponse > times will be Godot-like and that the application will miserably choke as > soon as we confront it with real-world amounts of data going beyond the > usual "three items" toy demonstrations. > > Now the question: If this desaster scenario (I'm working for the industrial > application partner in the project who expects to get some results that > will be actually usable for everydays' work) will actually happen (I hope > it won't, but still...), might there be a chance that by paying a cs > student for porting it to Python in his diploma thesis using such things as > Coil, Cheetah, Webware etc. it will get slimmer and faster? And if so, by > how much approximately? 10%? One order of magnitude? > > TIA, > > Best regards, > > Wolfgang Keller From anthonybaxter at gmail.com Mon Jul 5 02:46:26 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Mon, 5 Jul 2004 16:46:26 +1000 Subject: python 2.3.1 on HP-UX 11.22 In-Reply-To: References: Message-ID: On Mon, 05 Jul 2004 02:02:26 -0400, John Koller wrote: > On Fri, 02 Jul 2004 09:06:35 +0530, prabu wrote: > > > Hello all, > > I am new to Python,And this is my first post.I have installed > > "Fsh",an Opensource Product ,very similar to SSH on > > my HP-UX B.11.22 U ia64(IPF).It has Python dependency.The problem is > > ImportError: No module named select > "Python Standard Library" lists select as a standard module for 2.0. You > may have a bad installation. Can you import the other modules of the > standard library? It's fairly clear that this particular install of Python is hosed. You might want to get a pre-packaged version from a HP Porting site, for instance: http://hpux.cs.utah.edu/hppd/hpux/Languages/python-2.3.3/ From Mike at Geary.com Thu Jul 15 14:31:13 2004 From: Mike at Geary.com (Michael Geary) Date: Thu, 15 Jul 2004 11:31:13 -0700 Subject: Too many return-statements = bad style? References: <258fd9b8.0407150634.2b671ebf@posting.google.com> Message-ID: <10fdjbjguqi4h01@corp.supernews.com> > Steve Thompson wrote: > > And for those folks that actually view many exits as a > > Good Thing, I would argue that increasing the cyclomatic > > complexity of any piece of code is by definition the very > > antithesis of good software engineering. Magnus Lyck? wrote: > Agreed, but setting a variable to different values in different > if-else-branches in a function and returning that in a single > return doesn't give you a lower cyclomatic complexity than > multiple exits in the if-else-structure. I'm with you. I've had people take code I wrote that was very clean, simple, and easy to understand--and yes, used multiple returns--and rewrite it into a convoluted mess of nested if statements and state variables just to achieve the holy grail of a single return point. Very frustrating experience! I can only guess that they saw an early return as adding complexity, but didn't see nested ifs and extra state variables as adding complexity. I just want simple, maintainable code, whatever technique gets me there. -Mike From dd55 at cornell.edu Tue Jul 20 09:31:29 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 20 Jul 2004 09:31:29 -0400 Subject: installing my own module: module not recognized Message-ID: I followed the online docs on how to create and install a module. python setup.py install seems to work fine, I did python setup.py register as well (not sure what this is for). setup created a folder for me called Spec in python23/Lib/site-packages, and included my files: analysis.py/c and SpecDB.py/c. Running the interpretter, from Spec.analysis import * complains that there is no module named Spec.analysis. from Spec import * gives the same complaint. If you recognize my oversight, would you let me know what it is? Thanks, Darren From nobody at nowhere.com Tue Jul 27 14:20:19 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Tue, 27 Jul 2004 14:20:19 -0400 Subject: IPC References: Message-ID: Larry, As I said, I use FTP only to test the IPC and give here a known example. It's in fact with a custom program that I have to communicate. Any help in this regard? Yannick "Larry Bates" wrote in message news:e9OdnbY0ddteC5vcRVn-sw at comcast.com... > Python has built in support for ftp (see ftplib) > use it instead of trying to "communicate" with > external FTP program. > > http://www.python.org/doc/current/lib/module-ftplib.html > > You can catch any exceptions (like failure to connect) > by using python try:/except: blocks. > > HTH, > Larry Bates > Syscon, Inc. > > "Yannick Turgeon" wrote in message > news:Z6wNc.21572$i_2.899460 at news20.bellglobal.com... > > Hi, > > > > I'm relatively new to Python. I'm using 2.3.4 on W2K. > > > > What I want to do is to start a program and interact with it. Say my > program > > is FTP, I want to start FTP then send the commande "open x.x.x.x" then > look > > for the answer (if the connection is opened or not), then do something > > dependant of the success or error. > > > > I tried with popen3. The problem I got with this: it seems that I have to > > end the program before being able to read the output. Or maybe I'm not > using > > it correctly. I do test the communication with FTP exec. but it will be a > > custom program in real. Here is my code: > > > > > > def test(self): > > cmd = "ftp" > > r, w, e = popen2.popen3(cmd) > > > > cmd = "?\n" # A simple FTP commande > > w.write(cmd) > > w.flush() > > > > # That is what I would like but it's hanging here. I have to > remove > > this group and read at the end. > > for line in e.readlines(): > > # Do something conditionnal to the result of "line" > > pass > > for line in r.readlines(): > > # Do something conditionnal to the result of "line" > > pass > > > > > > cmd = "quit\n" > > w.write(cmd) > > w.flush() > > > > for line in e.readlines(): > > print line > > for line in r.readlines(): > > print line > > > > w.close() > > r.close() > > e.close() > > ---------------------- > > > > Anybody can help? Thanks for your time. > > > > Yannick > > > > > > From cpl.19.ghum at spamgourmet.com Thu Jul 15 03:06:40 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 15 Jul 2004 07:06:40 +0000 (UTC) Subject: odd question References: Message-ID: > --- > You have given the following function: > def f2(i, j, k): > return ((i | j) & k) | (i & j) > > Find a useful utilization for this function. That's easy. This function is a possible proof that it is possible to write pearllike (=writeonly) code in Python too. From dkuhlman at rexx.com Tue Jul 6 19:48:43 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 06 Jul 2004 16:48:43 -0700 Subject: generate LaTeX/TeX syntax highlighted code References: Message-ID: <2l0s1uF7bfreU1@uni-berlin.de> > John Hunter wrote: > >> Are there any tools that can be used to process python code and >> generate LaTeX/TeX output with syntax highlighted code? The SciTE text editor enables you to export to LaTeX (also to PDF, HTML, XML, and RTF). See: http://scintilla.sourceforge.net/SciTE.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From wxling3 at hotmail.com Wed Jul 21 10:44:50 2004 From: wxling3 at hotmail.com (Nancy) Date: 21 Jul 2004 07:44:50 -0700 Subject: How to lunch webpage without using SMTP server? Message-ID: Hi, Guys, Is there any other way to use python or mod_python writing a web page? I mean, not use "form.py/email", no SMTP server.
... Thanks a lot. Nancy W From jacek.generowicz at cern.ch Thu Jul 8 03:03:30 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jul 2004 09:03:30 +0200 Subject: Typed Python? References: <2kofmgF4li52U2@uni-berlin.de> Message-ID: Ville Vainio writes: > The only thing I learned was doing functional programming, handy ways > to use recursion etc (using set! was forbidden in the excercises). I > could have learned the same things with Python. And I don't think I > "missed" anything, got perfect score and generally considered the > course trivial. Well, there's always the possibility that the course was crap. This is not unusual, as I've suggested before. From news01 at metrak.KILLSPAM.com Tue Jul 20 05:54:48 2004 From: news01 at metrak.KILLSPAM.com (sosman) Date: Tue, 20 Jul 2004 19:54:48 +1000 Subject: default values in tuple assignment? Message-ID: <40fcec24$0$4754$afc38c87@news.optusnet.com.au> I take it python doesn't support defaults when assigning to a tuple, eg: for line in file: (parameter, value, units = 'kg') = line.split() along the lines of default parameter assignment in function calls. From thomas at it-snedkeren.BLACK_HOLE.dk Wed Jul 7 05:14:45 2004 From: thomas at it-snedkeren.BLACK_HOLE.dk (Thomas Lindgaard) Date: Wed, 07 Jul 2004 11:14:45 +0200 Subject: Short if Message-ID: Hello Does Python have a short if like C or PHP: bool = false string = 'This is ' + (( bool ) ? 'true' : 'false') ? -- Mvh. /Thomas From tim.peters at gmail.com Fri Jul 16 13:37:32 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 16 Jul 2004 13:37:32 -0400 Subject: try: finally: question In-Reply-To: References: <40eadf77@usenet01.boi.hp.com> <40eb00db@usenet01.boi.hp.com> <35-dnVL-0qrXtnbdRVn-jg@powergate.ca> <2IadnfA7t7M3vXHdRVn-ug@powergate.ca> Message-ID: <1f7befae04071610373e4ffaf5@mail.gmail.com> [Joshua Marshall] > Why is this not an argument 'finally' wasn't removed based on "an argument", it was removed based on negative feedback from real experience. What you give here certainly is "an argument", but this wasn't an argument-based decision. > for disallowing multiple except blocks, like:> > > try: > raise A() > except A: > raise B() > except B: > print 'Did we get here?' Because there's no evidence that anyone is confused by this in practice. There was ample evidence that many people were confused in practice when a 'finally' clause was allowed too. > This is legal and well-defined in Python. If try/except/finally was > removed it seems like multiple except blocks should have been removed > too--the behavior of one is as obvious as the other. So you say, but experience said otherwise. You can speculate about why if you want to, but it's a fact -- for whatever reason, Python programmers in real life are not confused by multiple 'except' blocks, but were confused about the semantics of allowing 'finally' too at the same level. No amount of argument can change that -- it was an observation, not a deduction. From PPNTWIMBXFFC at spammotel.com Thu Jul 1 06:42:28 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 01 Jul 2004 12:42:28 +0200 Subject: Looking for minimal SQL References: Message-ID: > What kind of application are you developing ? I am developing nothing right now. I still am evaluating... eventually a simple CRM (Customer Relationship Management). I might start doing something next year, but my brain started to create a framework. There are several reasons why I would like to stay "db" independent: For one I would like to run the "same" application over some rpc-server (which would have a powerful db) or as a standalone application with a "simple" db behind (which will synchronized from time to time *plan*plan*). I have already implemented a "simple" framework that allows me to reuse the same code be it as a multi-tier app be it as a standalone app. A database switch in the future is possible... hence... etc. etc. -> Python offers openess when it comes to os platforms -> db api offers a certain openness when it comes to dealing and parameterizing sql-stmts ... I want to stick to a minimal sql-language set to achieve real db openness I am aware that programming "sql-neutral" is not the most efficient, the easiest way to go. For example: If Sub-Selects are not portable than I would split up the queries and glue them together with Python. If for example one looks for the oldest customer: With sub-selects you may write: SELECT * FROM customer WHERE age = (SELECT max(age) FROM customer) Without sub-selects I would have to write two seperate statements: SELECT max(age) FROM customer --> take the "age" out of this query "SELECT * FROM customer WHERE age = ?", (age) This might not be the fastest solution but I would like to try! Hope this answers your question, Marco From squirrel at WPI.EDU Wed Jul 14 09:41:10 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 14 Jul 2004 09:41:10 -0400 Subject: Somewhat OT... Computer playing Minesweeper In-Reply-To: References: <200407132252.49595.heikowu@ceosg.de> <200407140402.26558.heikowu@ceosg.de> Message-ID: On Wed, 14 Jul 2004, Heiko Wundram wrote: > PS-ing myself: I can't see a better (in terms of finding the solution) > approach, but of course this algorithm lacks speed, as the amount of > consistent states can become quite large for a single field which has very > much scattered information, like: Rather than trying all possibilities of the mine field as a whole, why not just take it one number at a time? Not all portions of the mine field are dependent on the field as a whole; you can greatly decrease the number of patterns checked if you work in this way. IMHO Python is the wrong language to be doing this in though -- a constraint-logic language like Prolog would be much more well suited to the task (indeed, you could probably write a Minesweeper solver in a few dozen lines of Prolog). It may be a lot easier to implement a CL algorithm in Python, and then to formulate your problem using that. From peter at engcorp.com Thu Jul 15 10:13:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Jul 2004 10:13:43 -0400 Subject: speed of python 2.4 In-Reply-To: References: <87658wdgvg.fsf@blakie.riol> Message-ID: Jacek Generowicz wrote: > Peter Hansen writes: > > >>>What is the value of XX and YY ? >> >>No, "what" is a word that is used to introduce some types of >>questions. ;-) > > You need to fix your parser. Or others can fix their humour detector... which is supposed to be helped along by the friendly winky... From newsgroups at jhrothjr.com Sat Jul 3 06:59:55 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jul 2004 06:59:55 -0400 Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> Message-ID: <10ed4cticmisb36@news.supernews.com> "Thomas Reichelt" wrote in message news:2kn746F4ci1vU1 at uni-berlin.de... > Moin, > > short question: is there any language combining the syntax, flexibility and > great programming experience of Python with static typing? Is there a > project to add static typing to Python? I believe that it's on Guido's wish list, at least as an option. At one time there was a types sig that was looking into it, but I don't know of its current status. It got bogged down and didn't deliver anything. There are a couple of projects that have done some kind of type inference in Python. You might check out Bicycle Repair Man, which has a type inference engine that it uses to help in refactoring. I've also heard of another academic project that was supposed to release code sometime this summer, but the name escapes me. There are a number of places that would have to be cleaned up to make type inference work well. The .find() method is practically a poster child for a method that would give any type inference mechanism fits. It returns an integer, right? Wrong. It's supposed to return either an index into the string (a separate type) or an indication it didn't find one. However, the result sometimes evaluates to False when it found one, always evaluates to True when it didn't, and is a valid index even when it didn't find a match. A .findall() method that returned a list of all matches is much cleaner: it evalutes to false when the list is empty (no matches), it never returns something that looks like an index for a non-match, and it's compatible with the for statement. John Roth > > Thank you, > > -- > greetz tom From ally_burnett at yahoo.co.uk Mon Jul 12 10:57:40 2004 From: ally_burnett at yahoo.co.uk (alastair) Date: 12 Jul 2004 07:57:40 -0700 Subject: TIFF Image conversion Message-ID: <23ae7099.0407120657.2110b42c@posting.google.com> Hi, I need to convert a 24-bit RGB TIFF image to an 8-bit RGB TIFF image. I've tried using PIL and the convert() method - this allowed me to convert to an 8-bit grayscale image, close but not exactly what I need :( >From what I've read, it doesn't look like I can do what I need in PIL. Does anyone know of another method ? Thanks, Alastair. From schwupdidu at web.de Tue Jul 27 10:55:53 2004 From: schwupdidu at web.de (Steffen Kunze) Date: 27 Jul 2004 07:55:53 -0700 Subject: C++ SWIG Pyton - problems to create interface file Message-ID: <2103e28b.0407270655.2de6eaa0@posting.google.com> Hello I am from Germany and I study Information-Technology (2nd semester). Every three month I have a internship at the DLR (German Aerospace Center) and in the moment I try to use Python and especially SWIG. My problem is to write the interface file. I have big problems to write my own interface file. I know that I have to write the headers and the functions in there, but I haven`t really found out how. (it?s a cpp and a header file, where class, a datatype and different functions are defined.) Maybe you have time to give me some tips to make an interface file out of the files on --> http://cruncher.ba-mannheim.de/~s0312424/timedepFlowVis.h and http://cruncher.ba-mannheim.de/~s0312424/timedepFlowVis.cpp Thank you!!! From joewong at mango.cc Tue Jul 27 00:20:58 2004 From: joewong at mango.cc (Joe Wong) Date: Tue, 27 Jul 2004 12:20:58 +0800 Subject: MySQL library Message-ID: <0e8801c47391$1eabbc40$7f00a8c0@scl01.siliconcreation.com> Hi, I am now looking at the MySQL cluster solution. May I know beforehand that the MySQL python library can work with the MySQL cluster or not? Regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhuening at zedat.fu-berlin.de Thu Jul 8 08:34:12 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 8 Jul 2004 12:34:12 GMT Subject: os.startfile / webbrowser + Firefox References: Message-ID: SBrunning at trisystems.co.uk wrote in news:mailman.116.1089288257.5135.python-list at python.org: > A Firefox problem, I think, in that the file type association doesn't > seem to get set up properly. Bill Simoni told me how to fix this: > . > Yes, this solves the problem. Thank you, Simon! Matthias From jjl at pobox.com Mon Jul 26 16:31:42 2004 From: jjl at pobox.com (John J. Lee) Date: 26 Jul 2004 21:31:42 +0100 Subject: File upload using httplib References: <23ae7099.0407260514.63f41232@posting.google.com> Message-ID: <87iscatsr5.fsf@pobox.com> ally_burnett at yahoo.co.uk (alastair) writes: > I'm attempting to test out some functionality of the Apache http > server. What I'd like to do is send a file to the server - eg. a text > file or binary file (I will be testing gzipped transfers eventually > ...). This is called 'HTTP file upload'. Use Google Groups to see lots of posts about it in this newsgroup. Eg: http://groups.google.com/groups?&threadm=10fojr85tvg4i28%40corp.supernews.com If you haven't done already, install a sniffer or a proxy. Ethereal works for me. [...] > headers = {"Content-type": "application/x-www-form-urlencoded", > "Accept": "text/plain"} > > conn = httplib.HTTPConnection("127.0.0.1:8080") > conn.request("POST", "/test/test.py") [...] As Peter said, you're failing to send the headers you think you are. If you did send those headers, though, you would be asking the server to believe you're POSTing application/x-www-form-urlencoded data (stuff like foo=bar&spam=eggs), but sending it a Python file. John From grante at visi.com Wed Jul 21 16:15:34 2004 From: grante at visi.com (Grant Edwards) Date: 21 Jul 2004 20:15:34 GMT Subject: How to lunch webpage without using SMTP server? References: <40febe1a$0$8082$a1866201@newsreader.visi.com> Message-ID: <40fecee6$0$241$a1866201@newsreader.visi.com> On 2004-07-21, David Bolen wrote: >>>> Again, we've been through all this before. She doesn't have >>>> access to an SMTP server, apparently. >> >> If that's true, then she can't send e-mail to non-local >> addresses -- regardless of whether she's running a local SMTP >> server or not. > > She can if said local server talks to the final delivery SMTP > agents/servers. They have to be listening or the e-mail addresses > specifying their use for mail delivery won't work at all. I assumed that somebody who "doesn't have access to an SMTP" doesn't have access to any SMTP servers. If "an SMTP server" means "a local SMTP" or "a relaying SMTP server", then that's a different story. -- Grant Edwards grante Yow! PARDON me, am I at speaking ENGLISH? visi.com From apardon at vub.ac.be Thu Jul 22 13:52:16 2004 From: apardon at vub.ac.be (Antoon Pardon) Date: 22 Jul 2004 17:52:16 GMT Subject: unittest: Proposal to add failUnlessNear References: <10fobkud5fvgr9b@news.supernews.com> <10fr2qrka5o575a@news.supernews.com> Message-ID: John Roth wrote: > "Antoon Pardon" wrote in message > news:slrncfpk65.m9.apardon at trout.vub.ac.be... > > Op 2004-07-19, John Roth schreef : > > > "Antoon Pardon" wrote in message > > > news:slrncfnaq7.kj.apardon at trout.vub.ac.be... > > >> I have been working with unittests lately and found that the > > >> self.failUnlessAlmostEqual, isn't as usefull as it could be. > > >> > > >> My main problem is, that it is only usefull with objects > > >> that can be converted to floats, while there are a whole > > >> bunch of objects that can be almost equal but not so > > >> convertable. The first example coming to mind being > > >> complex numbers. > > >> > > >> A secondary objection is that you are limited to > > >> a very specific set of tolerances. If for instance > > >> you want to verify that two numbers differ at most > > >> by 0.0003 you can't specify that. > > > > > > Float and complex have two very different issues. > > > > Only if you want them to be. Floats are a subset > > of complex and as such can be treated exactly > > the same. > Floats are not a subset of complex. I concur > with Roy Smith's comments on that issue. There's Yes they are. > no reason why complex numbers cannot be > represented by a pair of integers, or rationals, > or the new floating decimal type, or whatever. I think this is getting sidetracked. This started with a request for a better test to check whether something is near enough something else. Since all your alternatives give exact results you don't need to test for nearness you test for equality. So within this contexts where you can't calculate things exactly floats are a subset of complex. > In addition, you're going to have to do significant > type checking if you want to combine floats and > complex in the same method call. That's just > poor design. No you don't. Please explain why something like abs(a - b) < tolerance needs typechecking when a and b can be complex numbers as well as floats > > > Since I'm maintaining the Python port of FIT, I > > > had to deal with them. What I did for float was > > > use the character form of the float to determine > > > the precision. The default routine appends a > > > character 5 and then uses this to calculate the > > > bounds within which the other value must be found. > > > > > > An example may help. Let's say I want to > > > test against '6.23e14'. This method would > > > establish bounds of 6.235e14 and 6.225e14 > > > and then test whether the other number was > > > within those bounds. (Note that the '5' is > > > appended before the numbers are converted > > > to float, however the second bound is calculated > > > after the conversion.) > > > > Why don't you just test whether the second > > number lies within a fault tolerance of > > 5e11 of 6.23e14 > I take it you've never worked with FIT. It's intended > to be used by non-technical people on a project, such > as the on-site customer, business analysts and so forth. > If I did something as silly as requiring them to insert > a tolerance that is blatently obvious to anyone looking > at the number involved, I'd get a change request so fast > that the edges would char from the friction. A tolerance is never blatantly obvious from looking at the number involved. On a number like 6.23e14 the tolreance could be 5e11 or 3e12 in fact from just looking at the number I would guess at a tolerace of 1e12, in other words bounds between 6.22e14 and 6.24e14. Besides you are mixing user interface and implementation. There is nothing stopping you from inferring this obvious tolerance and using it in your program. The fact that the user just insered 6.23e14, doesn't stop you the programmer to test whether a second number lies within a fault tolerance of 5e11 of 6.23e14 -- Antoon Pardon From jjl at pobox.com Mon Jul 19 19:31:49 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jul 2004 00:31:49 +0100 Subject: Scripting HTTP POST - multipart/form-data References: <10fojr85tvg4i28@corp.supernews.com> Message-ID: <87k6wz60be.fsf@pobox.com> Jeff Shannon writes: > I'm looking to script a routine file-upload through an HTTP server > (which I don't have access to). I've got specs on the CGI app that > receives this upload (i.e. field names and expected contents). > > However, it looks like urllib/urllib2 won't handle multipart/form-data > POSTs. Neither should have any problem with multipart/form-data. They don't actually provide and specific support for it either, though. [...] > Is there another (preferably all-python) library that will work for > this? [...] Yes, one that works on top of urllib2: http://wwwsearch.sf.net/ClientForm Search for .add_file on that page for an example of file upload. IIRC I've posted examples of that here in the past, too. John From fakeaddress at nowhere.org Sat Jul 10 13:49:33 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 10 Jul 2004 17:49:33 GMT Subject: Does my RE rock, or suck? In-Reply-To: References: Message-ID: Thanks for responses Gustavo. That's most of what I need to know. Gustavo Niemeyer wrote: [...] > Given the context (person names), your worst case will probably be > failing every name. The names were just for demo. The actual application is to match resource paths with the most-specific handler. [...] > It looks like a sane use of regular expressions. Since it's not obviously insane, I'll include the code below, in case anyone else wants to use it or QA it for free. --Bryan """ The Problem: We're given a set of "start strings". Later we'll be called (many times) with a "path string", and we need to find the longest of the start strings that is a prefix of the given path string. Method: Build a Python regular expression (RE) from the start strings, such that re.search(path) will match the desired prefix. The RE has no loop-like things, and never has two branches beginning with the same character. Searching should be fast in all cases. """ import re def build_prefix_re(str_list): """ Given a sequence of strings, return a compiled RE such that build_prefix_re(str_list).search(x) will match the longest string in str_list that is a prefix of x. """ def trie_insert(map, str): if str: submap = map.setdefault(str[0], {}) trie_insert(submap, str[1:]) else: map[""] = {} def sequentialize(map, lst): if map: keys = map.keys() # Order so that longer matches are first keys.sort() keys.reverse() lst.append('(?:') seperator = '' for key in keys: lst.append(seperator + re.escape(key)) submap = map[key] while len(submap) == 1: # While follow-set is singleton, condense. key = submap.keys()[0] submap = submap[key] lst.append(re.escape(key)) sequentialize(submap, lst) seperator = '|' lst.append(')') map = {} for str in str_list: trie_insert(map, str) lst = ['^'] sequentialize(map, lst) re_str = "".join(lst) # print "Prefix finding RE is: '%s'\n" % re_str return re.compile(re_str) if __name__ == '__main__': slist = ["a.b/cde/fg", "bchij", "bivwd", "cdj", "cdjwv", "cdjxi"] prematcher = build_prefix_re(slist) for str in slist: match = prematcher.search(str) assert(match.group(0) == str) s = str + 'extraneous' match = prematcher.search(s) assert(match.group(0) == str) for str in ('', 'cd', 'bb', 'cdi', 'xbchij', 'bchiij'): match = prematcher.search(str) assert not match, "BAD, found '%s'" % str From ville at spammers.com Mon Jul 26 04:54:47 2004 From: ville at spammers.com (Ville Vainio) Date: 26 Jul 2004 11:54:47 +0300 Subject: Static Typing References: <4104C664.7441435B@alcyone.com> Message-ID: >>>>> "Erik" == Erik Max Francis writes: Erik> Ville Vainio wrote: >> We do need to have to wait a bit more to get a statically typed >> CPython, unfortunately. Somehow I feel it's not going to get in >> during the 2.4 alpha/beta cycle ;-). Erik> It's interesting, though. I had missed it the first time Erik> around, I find it intriguing. It is - but the slides don't describe type inference, and that's definitely what I would like to see in the future typing system. -- Ville Vainio http://tinyurl.com/2prnb From squirrel at WPI.EDU Thu Jul 29 12:03:56 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 29 Jul 2004 12:03:56 -0400 Subject: A goto-like usage of a function In-Reply-To: References: Message-ID: On Thu, 29 Jul 2004, Bart Nessux wrote: > I understand recursion to be a loop or a loop to > be recursion... however you prefer to look at it. > Whether it's a function calling itself until the > user gets the input right or a while statement w/i > a function waiting for correct input... IMO, it's > the same thing. With that said, there may be > performance issues that I'm unaware of that make > your approach better or worse than mine... > outside that, I think either approach is worthwhile. The 'performance issue' at stake is that the stack is being slowly but surely eaten up using the recusive call... it's possible for a user to crash your program by repeatedly providing incorrect input. This programming style is enabled, however, by tail recursion elimination, as seen in Scheme, where such recursion would be the natural way to write your code. Not so in Python though -- a while loop is the one true way to go (as recently prounounced by Guido ;)). From tzot at sil-tec.gr Mon Jul 12 11:39:02 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 12 Jul 2004 18:39:02 +0300 Subject: datetime.iterdate References: Message-ID: <7pb5f0pbst3mistd1ju3q8qk4mcqbct1o6@4ax.com> On Mon, 12 Jul 2004 09:20:38 -0400, rumours say that Christopher T King might have written: [snip of a<=x<=b proposition to replace xrange] >To work perfectly, my >proposal needs only a slight change in the parser (to compile a(aaffect existing code though. A lot of code is based on "x and y" evaluating y only if x is true... -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From della at toglimi.linux.it Wed Jul 28 05:08:14 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 28 Jul 2004 09:08:14 GMT Subject: Question on lists In-Reply-To: References: <41071cfe$0$60648$d5a6236f@newsreader.cybernetik.net> Message-ID: <22KNc.17055$1V3.394355@twister2.libero.it> Andrew Bennetts wrote: > Nothing builtin that I know of, but it's trivial to write: Using 2.4, looks like the logic is in itertools.groupby: >>> from itertools import groupby >>> l = ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e'] >>> list(x for x, _ in itertools.groupby(l)) ['a', 'b', 'c', 'd', 'e'] -- Ciao, Matteo From nick at nick8325.freeserve.co.uk Fri Jul 23 08:03:45 2004 From: nick at nick8325.freeserve.co.uk (Nick Smallbone) Date: Fri, 23 Jul 2004 13:03:45 +0100 Subject: dynamic import References: Message-ID: <4100fe9f$0$7120$db0fefd9@news.zen.co.uk> wrote in message news:mailman.750.1090583812.5135.python-list at python.org... > Hi, > I'm trying to do a dynamic import of a file that has no problems with it, that > is to say I can import it normally, my sys.path is set to the right folder etc. > but my dynamic import code is not working, this is the problem code: > > try: > import f[0] > except: > print "not importable" > > f[0] returns the name of the file I'm importing, so I suppose this is a typing > problem, should I change f[0] to be some other type? > > I've also tried > t = "import " + f[0] > try: > eval(t) > except: > print "not importable" > > but I always get "not importable" > That's because eval evaluates an expression and returns the result. To execute a statement you need to use exec(t) instead. Nick From andre at andrenobre.com.br Fri Jul 16 16:22:37 2004 From: andre at andrenobre.com.br (=?ISO-8859-1?Q?Andr=E9_Nobre?=) Date: Fri, 16 Jul 2004 17:22:37 -0300 Subject: Run as service Message-ID: <40F8390D.1080404@andrenobre.com.br> Hello, i?m starting with python and i made this little piece of code, to know if i have new mails to receive. import poplib, getpass arquivo = 'mails.txt' info = file(arquivo).read().split('\n') d = {} for e in info: a = e.split('\t') print "Verificando e-mail de %s" % (a[1],) p = poplib.POP3(a[0]) p.user(a[1]) p.pass_(getpass.getpass()) print "\n%s mensagens em seu mailbox.\n" % p.stat()[0] p = None print "Final" it gets some information from mails.txt* file and watch new mails. I want to know how to leave this code running as service under windows and send a warning message (like that windows popup messages) when a there is a new e-mail. * my file is like this (simple text) mailserver \t maillogin \n Tkz and sorry about my english.... -- Andr? From jdhunter at ace.bsd.uchicago.edu Wed Jul 7 09:46:42 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 07 Jul 2004 08:46:42 -0500 Subject: generate LaTeX/TeX syntax highlighted code In-Reply-To: (David Eppstein's message of "Tue, 06 Jul 2004 11:47:43 -0700") References: Message-ID: >>>>> "David" == David Eppstein writes: >> Are there any tools that can be used to process python code and >> generate LaTeX/TeX output with syntax highlighted code? David> \usepackage{listings} David> http://www.ctan.org/tex-archive/macros/latex/contrib/listings/ ... beyond my wildest dreams... JDH From finite.automaton at gmail.com Tue Jul 20 19:09:37 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 20 Jul 2004 16:09:37 -0700 Subject: distutils alternatives? Message-ID: <4b39d922.0407201509.12c9d43b@posting.google.com> I'm in a situation where I need to distribute several interdependent Python packages. There are good reasons not to combine them all into one package. Distutils doesn't seem to be able to bundle a heterogeneous mix of multiple packages and modules, and so I've currently got people launching three installers in the proper sequence in order to get software installed, which seems needlessly complicated and confusing. There must be a better way. What I really want is a way for the installer to automatically download and install dependencies... First, does anyone know of an alternative to distutils that does this? Second, this is exactly what Gentoo's Portage software does, except for Gentoo ebuilds instead of Python packages. It also happens to be written in Python. Can anyone more familiar with Portage's internals comment on the feasibility of harnessing emerge to work as a Python package installer/distributer for systems which aren't running Gentoo? It is also foreseeable that something like this could be linked to PyPI, etc. From miki.tebeka at zoran.com Mon Jul 5 17:15:13 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 5 Jul 2004 23:15:13 +0200 Subject: Embedded Python application don't work if Python is installed Message-ID: <20040705211513.GA2760@zoran.com> Hello All, I have a funny problem: An embedded python application is working fine on a "clean" computer. When it runs on a computer with python installed (the very same computer used to produce the application) it has a import error: ---------- can't import SACD module (sacd.py) Error in sys.exitfunc: Traceback (most recent call last): File "atexit.pyc", line 20, in _run_exitfuncs File "threading.pyc", line 566, in __exitfunc File "threading.pyc", line 578, in _pickSomeNonDaemonThread File "c:\ADP86Tools\bin\sacd.py", line 44, in ? filterwarnings("ignore", category=FutureWarning) File "warnings.pyc", line 140, in filterwarnings File "re.pyc", line 5, in ? File "sre.pyc", line 97, in ? File "sre_compile.pyc", line 13, in ? File "_sre.pyc", line 9, in ? File "_sre.pyc", line 7, in __load ImportError: DLL load failed: The specified module could not be found. ---------- (The traceback is printed from the embedding application) All the required modules are in a library (python23.zip) and placed the needed dll's in the same directory as the application (it's in sys.path). The script itself is a regular python file (.py), dependencies were found using py2exe. OS is win2k and Python is 2.3.4. I've tried editing sys.path to contain only the application directory and the library zip and also to add the application directory to PATH environment variables. Nothing helps. The offending module is re. Writing import re re.compile("\s+") will cause the same problem. Any ideas? Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys From chris.irish at libertydistribution.com Fri Jul 9 13:08:49 2004 From: chris.irish at libertydistribution.com (Chris Irish) Date: Fri, 09 Jul 2004 10:08:49 -0700 Subject: I am new to this In-Reply-To: <56cfb0e3.0407061626.50ba3904@posting.google.com> References: <56cfb0e3.0407061626.50ba3904@posting.google.com> Message-ID: <40EED121.4050102@libertydistribution.com> Porky Pig Jr wrote: > >there are lots of on-line courses available, as other responders have >pointed out. Yet having looked at most of them, I still think the >proper way to start is to go through the book 'Learning Python' by >Lutz and Ascher (which is what I'm doing right now - after reading >through much of on-line manuals). > > I would recommend that book also. From oneelkruns at hotmail.com Sat Jul 3 08:06:35 2004 From: oneelkruns at hotmail.com (Ron Kneusel) Date: 3 Jul 2004 05:06:35 -0700 Subject: Idle 2.3.4 on Red Hat 9 segmentation fault Message-ID: <2335b39d.0407030406.f8745cb@posting.google.com> I've installed Python 2.3.4 on Red Hat 9 and everything seems to be working fine. Tkinter is available and I can run GUI scripts. However, when I try to start Idle I get a segmentation fault. Using GDB and loading the idle script by hand: >gdb python2.3 (gdb) run ... >>> from idlelib.PyShell import main >>> main() error here: "Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 1074892416 (LWP 2870)] 0x407a3c6c in Tcl_FindExecutable () from /usr/lib/libtcl8.3.so" Is anyone else seeing this sort of thing? Ron From peter at engcorp.com Wed Jul 28 09:15:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jul 2004 09:15:59 -0400 Subject: Cookie Monster In-Reply-To: References: <41079cc6$0$3000$4d4ebb8e@news.nl.uu.net> Message-ID: Gene Heskett wrote: > Chuckle... This thing is approaching voting age by now. I remember > it was available for the amiga back in the late 80's-90's time frame. > That one was written in arexx IIRC. And ISTR that we had one written > in Basic09 for the tRS-80 Color Computer running os9 in the mid 80's. > I think its like the locusts, with a somewhat faster lifecycle. :-) The reference I just sent in another post mentions at the end that at least one publication has called this the earliest known computer virus, according to the author of the program (though he doesn't agree). From me at privacy.net Thu Jul 8 07:51:15 2004 From: me at privacy.net (Heather Coppersmith) Date: 08 Jul 2004 07:51:15 -0400 Subject: Parametrized module import References: <2l4iblF8ff9rU4@uni-berlin.de> Message-ID: On 08 Jul 2004 12:58:51 +0200, Jacek Generowicz wrote: > Oliver Fromme writes: >> You could create another module called "config" or "cfg" which >> contains some global variables. You import it into your >> configurable module as well as into your main program. Then >> you can configure the module's behaviour via those global >> variables before importing the module. > Yes, my initial crappy prototype idea was to add configuration > information to the sys module, but this variation is much neater > ... in fact, after the first 2 minutes of thinking about it, it > looks perfect :-) > However, one thing which keeps bothering me about the whole > business, is the possibilty of importing the module (with your > chosen configuration) after it has already been imported, > without you knowing it, with a different configuration. Ideally > there should be some warning about the fact that the > configuration you specified is being ignored as a result of the > module already being imported ... and I don't see how to achieve > this. Upon import, a module's "top level" code is executed, so try a variation on this theme at the top level of your module: i_am_configured = False if i_am_configured: print 'i am already configured' else: import my_configuration_module configure_myself( ) i_am_configured = True HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From ralf at mh-freiburg.de Mon Jul 12 08:43:10 2004 From: ralf at mh-freiburg.de (R. Mattes) Date: Mon, 12 Jul 2004 14:43:10 +0200 Subject: lisp is winner in DOM parsing contest! 8-] References: <2le3nlFb82reU1@uni-berlin.de> Message-ID: On Mon, 12 Jul 2004 02:19:03 +0200, Alex Mizrahi wrote: > Hello, All! > > i have 3mb long XML document with about 150000 lines (i think it has > about 200000 elements there) which i want to parse to DOM to work with. > first i thought there will be no problems, but there were.. first i > tried Python.. there's special interest group that wants to "make Python > become the premier language for XML processing" so i thought there will > be no problems with this document.. i used xml.dom.minidom to parse it.. > after it ate 400 meg of RAM i killed it - i don't want such processing.. > i think this is because of that fat class impementation - possibly > Python had some significant overhead for each object instance, or > something like this.. First of all: which parser did you actually use? There are quite a number of XML parsers for python. I personally use the libxml2 one and never had memory proplems like you describe. > then i asdf-installed s-xml package and tried it with it. it ate only 25 > megs for lxml representation. i think interning element names helped a > lot.. it was CLISP that has unicode inside, so i think it could be even > less without unicode.. Hmmm. Hmmm ... i guess you know that you compare apples with pears? S-XML is a nice, small parser but nowhere near a standard conformant XML parser. Have a closer look at the webpage: no handling of character encoding, no CDATA, can't handle what the author calls "special tags" (like processing instruction), no schema/DTD support, and, most important, no namespace support! > then i tried C++ - TinyXML. it was fast, but ate 65 megs.. ye, looks > like interning helps a lot 8-] Interning is _much_ easier without namespaces. > then i tried Perl XML::DOM.. it was better than python - about 180megs, > but it was slowest.. at least it consumed mem slower than python 8-] > > and java.. with default parser it took 45mbs.. maybe it interned > strings, but there was overhead from classes - storing trees is > definitely what's lisp optimized for 8-] But you never got to a _full_ DOM with you lxml parsing. What you got was a list-of-lists. There's no 'parent' implementation for your lxml elements (which means that you might need to path the whole thing arround all the time). If you want a serious comparison you either need to compare s-xml with similar "lightweight" parsers in Perl/Python/Ruby etc. or write your own fully DOM compliant parser in LISP (or is there one allready? I'm still looking for a good one). Just my 0.02 $ Ralf Mattes > so lisp is winner.. but it has not standard way (even no non-standard > but simple) way to write binary IEEE floating point representation, so > common lisp suck and i will use c++ for my task.. 8-]]] > > With best regards, Alex 'killer_storm' Mizrahi. From mwh at python.net Fri Jul 9 09:45:27 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 9 Jul 2004 13:45:27 GMT Subject: Debug build without PYMALLOC References: Message-ID: "Amaury" writes: > Hello, > > When debugging C extensions, I find the most difficult is to detect > that an object is Py_DECREF'ed when it should not. > And when you find yourself with an invalid object, it's a nightmare to > find where the error occured! > Normally tools like Purify are good to find this kind of memory > errors, but they are of no use with python's own memory allocator. > > That's why I recompiled python (on Windows) in debug mode after > removing the WITH_PYMALLOC option. > This worked very well: Purify warned about a "Free memory read", and > it turned out that a custom sys.stdout was incorrectly DECREF'ed just > before, which caused the crash. > > The problem is that this python build (debug/without-pymalloc) is not > compatible with extension modules built WITH_pymalloc. The DLL loader > fails with a "missing _PyObject_DebugMalloc" error. > Note that with release builds, extensions built with pymalloc are > compatible with python.dll built without pymalloc. Hmm, that makes sense but I hadn't thought of it before. You could also have recompiled the extensions, though. > My workaround was to add the three functions (_PyObject_DebugMalloc, > *Realloc and *Free) in obmalloc.c. > Isn't there another way? > Otherwise, should this be integrated in Python? Possibly. Post a bug report or maybe a patch to SF if you feel strongly about it... Cheers, mwh -- If you don't use emacs, you're a pathetic, mewling, masochistic weakling and I can't be bothered to convert you. -- Ron Echeverri From paul at prescod.net Fri Jul 9 01:47:54 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 08 Jul 2004 22:47:54 -0700 Subject: Why would I learn Python over other languages? In-Reply-To: References: Message-ID: <40EE318A.703@prescod.net> Arthur wrote: > ... > > I don't think that is true of Python. I think there is a layer of > Python that one cannot reasonably penetrate without stepping outside > of Python. > > One can get started with Python, with Python. > > But in the end I don't think Python serves as a fully adequate > introduction to itself. In one sense I think that any language is a sufficient introduction to itself. Given enough time and effort you learn every trick, see every corner exposed by someone (perhaps someone with a different background than you) and learn everything there is to possibly know. Sometimes it is MORE EFFICIENT to step outside the language to learn it but one can do the whole thing from the inside. It would be a lot easier to learn physics if we could step outside the universe and experiment with the rules but we scrape away at it from the inside and figure it out the hard way. Python is surely simpler to understand than the universe. In another sense, every language builds on other languages and you will always feel you are missing something if you know the language but not the ones it is built upon. A C++ programmer who doesn't understand assembly language does not know what an function call "really" is (in terms of its implementation). Sometimes Python's implementation language leaks through. "Why is it that way? Because it is in C?" But that is also true for C++. What does the register keyword mean? Or ask a Lisper what "cdr" means... I am skeptical that Python is either more or less self-revealing in these senses than any other language. Paul Prescod From squirrel at WPI.EDU Thu Jul 22 09:38:23 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 22 Jul 2004 09:38:23 -0400 Subject: python and ssh In-Reply-To: References: Message-ID: On Wed, 21 Jul 2004 jepler at unpythonic.net wrote: > You would have to ask the authors of ssh that question. > > I *suspect* that sshd creates special file descriptors that communicate > with the process started on the remote machine as the user. Then it > enters a select loop. Once all the programs with access to that file > descriptor close it (for instance, by exiting), sshd detects this because > the file descriptors are "readable" according to select, but a read gets > 0 bytes. When that happens, sshd closes down communication with ssh, > which exits. Building off of that, in order to get ssh to end the connection, the spawned process will need to close the descriptors it inherited from ssh: import sys sys.stdin.close() sys.stdout.close() sys.stderr.close() Basically, ssh is staying open because it knows that it's possible for the spawned process to write to these streams, which would normally be redirected over the ssh connection. By closing them, you're telling ssh "I don't need to do any more input or output to/from the console", and ssh (should) respond to this by closing the connection. (I say should because I haven't tested this!) From jarausch at igpm.rwth-aachen.de Fri Jul 23 03:29:54 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 23 Jul 2004 09:29:54 +0200 Subject: math module broken? In-Reply-To: <246a4e07.0407222219.23bb209b@posting.google.com> References: <246a4e07.0407222219.23bb209b@posting.google.com> Message-ID: <4100BE72.1040405@igpm.rwth-aachen.de> Frank Millman wrote: > Hi all > > I was helping my niece with her trigonometry homework last night. Her > calculator's batteries were flat, so I thought I would use Python's > math module to calculate sin, cos, and tan. > > I tried the example in the text book first, to ensure that I was > getting the correct result, but it did not agree. Then my wife had the > idea of using the Microsoft calculator in scientific mode, and that > one did give the correct result. > > Here are some examples - > > sin(32) - > Python 0.55142668 > Microsoft 0.52991926 > > > Version is Python 2.3.3. I get the same results on Linux and on > Windows 2000. I also get the same results using the cmath module. > > Can someone please explain these discrepancies? > Both are "correct" if you know what you have been asking for. In standard mathematics the argument to a trigonometric function like sin, cos, tan, ... is in radians (!) This is even the case with most pocket calculators but there you can switch modes. In the example above, Microsoft - something special as ever - seems to expect the argument in degrees (which is quite unusual) Since an argument in radians normally is between 0 and 2*pi or between -pi and pi, an argument of 32 is unusual for a radians argument though perfectly legal. If your input is in degrees, define def mysin(x) return math.sin(x/pi*180) # 1 degree = 180/pi radians (don's use x/180*pi) now print mysin(32) gives 0.529919264233 -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From dave at boost-consulting.com Thu Jul 22 16:08:49 2004 From: dave at boost-consulting.com (David Abrahams) Date: 22 Jul 2004 13:08:49 -0700 Subject: Windows build/debugging change for 2.3? Message-ID: <8a638f47.0407221208.723e3c2f@posting.google.com> Around the time I upgraded to Python 2.3 (can't be absolutely certain, though) I started to notice that debugging extension modules with VS 2003 became more painful. In particular, now, even if I stop debugging, I can't rebuild the extension module unless I explicitly quit VS. The complaint is that "the file is in use by some other process". Is this a change in the Python build, or something I am doing wrong, or something else? TIA, Dave -- David Abrahams Boost Consulting http://www.boost-consulting.com From mhammond at keypoint.com.au Sun Jul 18 20:13:14 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Mon, 19 Jul 2004 10:13:14 +1000 Subject: Beta testers for Python ISAPI module required. Message-ID: Phillip Frantz has contributed a very cool ISAPI (IIS extension) framework that I have been extending, and hope to include in later pywin32 builds. It supports both ISAPI extensions and filters. Along with this ISAPI extension is a Python framework that implements mod_python like functionality in IIS. This means it is a "server independent" framework for embedding Python in either Apache or IIS (and also means the framework itself is not Windows specific, even though the ISAPI extension itself is) At the moment I'm interested in people who would like to play with early versions of it, and offer feedback about the configuration and extension mechanisms employed. Ideally, I would love people experienced with Apache and mod_python, and *also* IIS, so feedback on the framework can also be offered. My experience with Python inside web servers is fairly limited, so I need all the advice I can get. If you fit this category and have a little time to play, please drop me a line by email. Thanks, Mark. From jjl at pobox.com Tue Jul 20 17:05:18 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jul 2004 22:05:18 +0100 Subject: Parsing SGML given DTD using python References: Message-ID: <87ekn68k4x.fsf@pobox.com> Martin Krallinger writes: > I wonder whether there is some sample code or > module to parse SGML files in python given the > DTD. [...] SGML is a bit esoteric these days. You might have better luck searching if you look for libraries written in C, C++, Java, etc., and then use those libraries from Python (use Jython for Java code; write a wrapper or find a pre-existing wrapper for C/C++). HTH John From jacek.generowicz at cern.ch Mon Jul 12 10:57:40 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Jul 2004 16:57:40 +0200 Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: Message-ID: Chris Share writes: > On Wed, 07 Jul 2004 18:36:05 -0400, Peter Hansen wrote: > > I'm actually pretty inept with vi (or vim), to the point that I don't > > actually know how to configure it for use with Python. > > FYI, it's pretty simple... > > I use vim for writing python in, with the following options: > :set et > :set tabstop=4 And how do I get it to send the function definition surrounding the cursor to the Python interpreter with which it is currently interacting ? (Only half joking ... if there is a way to make vi(m) provide the same interactive capabilities that Emacs does, then I would be able to recommend it to those who insist on using vi in my courses and end up trailing the rest of the class and slowing us all down.) From wweston at att.net Sun Jul 25 09:20:00 2004 From: wweston at att.net (wes weston) Date: Sun, 25 Jul 2004 13:20:00 GMT Subject: simple parsing help In-Reply-To: References: Message-ID: <4sOMc.134107$OB3.90998@bgtnsc05-news.ops.worldnet.att.net> Steve wrote: > Hi, > > I have a string that looks kinda like "Winner (121,10) blah blah blah > Winner (10,400) blah blah Winner (103,4) blah blah..." > > I just want to extract the coordinate parts of the string (xxx,xxx) > which could be 1-3 characters and put them into an array ideally. > What is the easiest way to do this in Python? Can anyone provide a > simple line or two of code to help me get started? > > Thanks very much, > > Steve Steve, Here's a long hand version (that makes assumptions). wes -------------------------------------------------------------- str = "Winner (121,10) blah blah blah Winner (10,400) blah blah Winner (103,4) blah blah" list = str.split() pts = [] for s in list: if (s[0] == '(' ) and (s[-1]== ')' ): try: temp = s[1:-1].split(',') pts.append( (int(temp[0]), int(temp[1])) ) except: pass for p in pts: print p[0],p[1] --------------------------------------------------- produces: >>> 121 10 10 400 103 4 >>> From DesertLinux at netscape.net Wed Jul 21 19:24:07 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 21 Jul 2004 23:24:07 GMT Subject: Python .ico In-Reply-To: References: Message-ID: Have an icon that you would like to share? I agree, Python is an excellent language. I just wish that more companies would give it a more serious look. Probably, the main source of resistance is the fact that the makers of Python do not provide a free, RAD (Rapid Application Development) tool that allows users to quickly and easily build GUIs visually, such as Java's Netbeans (www.netbeans.org) or Microsoft's Visual Basic. Most programmers like an easy-to-use RAD that allows users to quickly and easily develop GUI applications. Unfortunately, until Python is able to strongly complete in this area, most companies will continue to believe that Python is mostly a cute, somewhat enabled scripting tool. Byron --- Michael Scarlett wrote: > I was just thinking that we should get a new icon for Python. Its such > an amzing effective language, and I know it sounds silly, but I can't > help but think that one of the reasons it hasn't surpassed JAVA or at > least taken more seriouly than it is now - is because of the dorky > looking .py icon. > We need a icon that reflects python. Robust, flexible and Effective. > Something that says "we get the job done right and the code is tight". > Eat that!! > > > Anybody else think GVR and the PSF should put that in the next > release? I know it sounds silly. but I'm kinda tired of Python being > taken too lightly. Python rules. applications like ZOPE, Mailman and > BitTorrent are proving that. Let's step it up a notch any how we can. > > ---BitShadow From adam at npjh.com Wed Jul 7 22:23:18 2004 From: adam at npjh.com (Adam Flott) Date: Thu, 08 Jul 2004 02:23:18 GMT Subject: Help with regex on telnet output References: <20040705211348.51d6bfb0.adam@npjh.com> Message-ID: <20040707212324.7a71ee4e.adam@npjh.com> On Tue, 6 Jul 2004 11:12:17 +0000 (UTC) eddie at holyrood.ed.ac.uk (Eddie Corns) wrote: > Adam Flott writes: > > >I'm having some difficulty getting the expect function of telnetlib > >to capture some data that gets returned from a telnet connection. > > >Python's telnet debug reports this: > > >recv 'whoami\n\r\xff\xfc\x01\r\nHi, my name is : Home\r\nHere' > >IAC WONT 1 > >recv ' is what I know about myself:\r\nModel: ' > >recv ' VSX 7000\r\nSerial Number: 822232085C63K\r\nS' > >recv 'oftware Version: Release 1.0 - August 2001\r' > >recv '\nBuild Information: build at www.' > >recv 'a.com\r\nFPGA Revision: 4.3.0\r\nMain Proc' > >recv 'essor: BSP15 v0.0 ~ Core/Mem Clks 415/111 ' > >recv '[3:4 0:3]\r\nTime In Last Call: 0:00:00\r\nTotal Tim' > >recv 'e In Calls: 0:22:17\r\nTotal Calls: 18\r\nSNTP' > >recv ' Time Service: auto insync 21.1.1.1\r\nLocal Tim' > >recv 'e is: Mon, 5 Jul 2004 20:59:35 -0500\r\nNetw' > >recv 'ork Interface: ISDN_QUAD_BRI\r\nIP Video Number: ' > >recv ' 192.168.0.99\r\nISDN Video Number: 1.555.115047' > >recv '4\r\nH323 Enabled: True\r\nFTP Enabled: ' > >recv ' True\r\nHTTP Enabled: True\r\nSNMP Enabled: ' > >recv ' True\r\nNIC Slot 1 SW Ver: 6.03\r\nNIC Slot 1 B' > >recv 'oot Ver: 0.02\r\n\xff\xfb\x03' > >IAC WILL 3 > >recv '\xff\xfc\x01' > >IAC WONT 1 > >recv '\xff\xfb\x03' > >IAC WILL 3 > > >The call I made to expect including a timeout of 1 seconds, which is > >plenty of time to wait for a response, but keeps repeating WILL > >3/WONT 1 indefinitely. > > >I only want to match from the begginning (\r\nHi. to the end > >0.02\r\n). This data is not specific and I just want data that looks > >like this format to be returned from the call to expect. The only > >thing I've found that is constant is a colon separates one side to > >the other. > > >Here is the start to the regular expression I've been trying to get > >to work: > > >"^([\w\s]+?)(:)\s{1,}(.*):?\r\n$" > > The first thing to note is that expect does not MATCH in quite the > same sense as when matching a string. What it does is match all the > input from where it last left off until the point in the stream when > the regex matches. eg: > > if the stream looks like: > > "$ whereami\nYou are here.\n$ " > > and you match on "a.e", it will return "$ whereami\nYou are". The > next read() or expect() call will start from "here.\n$ " > > You would need to either pull out the portion you want from within > that or more usually make sure you've matched up to the start. > Secondly the ^ and $ don't really make sense on a stream ($ will > certainly cause it to hang; not sure why timeout doesn't fix that). > > I generally try to use read_until() instead of expect(), this only > works if you have well defined strings you can match on eg. "Hi, my > name is" to get the start or better still match on the echo of the > command you sent, and the user level prompt to finish (there doesn't > seem to be a prompt in your trace though). At worst you can use > timeouts to know when it's done. > > Fixed strings leads to more robust applications and easier to read > code IMHO. > > Eddie After I read your message I finnally figured out a solution. Just match the Hi part with the 6 or so variants that I know I will recieve. There isn't a prompt as this is an embedded device and doesn't work like a normal telnet login. The timeout issue is still a problem and I will have to investigate that further. But for another day. Thanks for the help, it is greatly appreciated. Adam From grey at despair.dmiyu.org Wed Jul 14 19:22:09 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 14 Jul 2004 23:22:09 GMT Subject: Too many return-statements = bad style? References: <10fb6848julv6c@corp.supernews.com> <10fb934hkq76c97@corp.supernews.com> <10fbev0b1lqh90e@corp.supernews.com> Message-ID: On 2004-07-14, Michael Geary wrote: > The Ruby code always closes the file when the code block (the loop body) > exits, even if the code block raises an exception. So, the Ruby code: Kinda breaks that whole explicit is better than implicit rule, don't it. What happens if I don't want the file closed at the end of the loop? I'm guessing I have to start fighting with the language. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From s.j.johnston at soton.ac.uk Wed Jul 7 11:19:49 2004 From: s.j.johnston at soton.ac.uk (Steven Johnston) Date: Wed, 7 Jul 2004 16:19:49 +0100 Subject: Dynamic classes Message-ID: <200407071519.i67FJsXK002962@mta2.sucs.soton.ac.uk> Hi, Sorry to mail this list (not sure how big it is) but I have a problem with python and was wondering if you may be able to help. I have a package that people can add classes to (just copy a class to that folder) But now I would like to create an instance of the classes based on a set of rules (depending on the __init__ signature) So my question is: Is there a way of finding out what the signature of a class is dynamically without trying to create an instance , and without writing a text parser to read the file? Many thanks in advance Steven From marco at reimeika.ca Thu Jul 29 01:47:41 2004 From: marco at reimeika.ca (marco) Date: 29 Jul 2004 01:47:41 -0400 Subject: tempfile.mkstemp problem? References: Message-ID: The last one! For real! marco writes: > I first create the dir as follows: > > work_dir = opts.get('-w', img_dir) > work_dir = os.path.abspath(work_dir) > if not os.path.isdir(work_dir): > if not quiet: print 'Creating ' + work_dir > try: > os.makedirs(work_dir) > except: > print 'Could not create the work directory ' + \ > work_dir > raise SystemExit > > This works fine. To make sure, I even added a check right > before making the tempfile: > > print os.path.isdir('/tmp/991319584/metd/') > mpegv = tempfile.mkstemp('.mpv', '', work_dir)[1] > > The "os.path.isdir" says "True". Here's the kicker: > after the tempfile.mkstemp error, the "metd" directory > disappears! It's deleted! If I create the "metd" dir by hand before calling the plugin from the GUI everything works! This is really puzzling: If the "metd" doesn't exist the Python script _appears_ to create it, but somehow tempfile.mkstemp can't put the tempfile inside. If, on the other hand, I create that directory beforehand there's no problem. What's going on? Is os.path.isdir('/tmp/991319584/metd/') lying to me when it says "True"? Is the "metd" actually there but in some weird state which messes up tempfile.mkstemp? I guess I could try making the temp dir from within the plugin instead (and then calling the script afterwards). This is all very strange, though... Anyway, sorry again for all the posts, it's really late! :/ Cheers, -- marco at reimeika.ca Gunnm: Broken Angel http://amv.reimeika.ca http://reimeika.ca/ http://photo.reimeika.ca From alan.gauld at btinternet.com Sun Jul 4 18:59:14 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 04 Jul 2004 22:59:14 GMT Subject: Black window References: Message-ID: <0t2he0p7dddvgnk6anad87l06v9celjn4c@4ax.com> On Sun, 04 Jul 2004 18:02:00 GMT, "Gropius" wrote: > Hi > i've a problem, i'd like that my application (for winxp) works in background > in the taskmanager (or in the systray) instead of in a window. How can i do? Use pythonw.exe to run it instead pf python.exe. But of course any output will be lost! So you might want to run it with redirection to a file. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From robin at reportlab.com Thu Jul 15 03:42:32 2004 From: robin at reportlab.com (Robin Becker) Date: Thu, 15 Jul 2004 08:42:32 +0100 Subject: List comprehensions and glob In-Reply-To: References: Message-ID: <40F63568.5090303@jessikat.fsnet.co.uk> I want to use a list of glob patterns to create a single flat list of files eg P = ['*.txt','*.py'] I expected I would somehow be able to use list comprehensions to do this, but in the end I could only do this hackish thing import operator, glob F = reduce(operator.add,[glob.glob(p) for p in P],[]) is there a more pythonic approach? -- Robin Becker From DesertLinux at netscape.net Wed Jul 21 11:49:28 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 21 Jul 2004 15:49:28 GMT Subject: [newbie] Writing to file : "name 'concat' is not defined"? In-Reply-To: References: Message-ID: Hi Fred, It looks like they have answered your questions. To reiterate in a simple form, to open a file for reading, it is best to use something like the following: f = open("c:/test.txt", "r") textlines = f.readlines() # Reads all lines into a list (array). for line in textlines: # Prints each line that is read from the text file. print line --- If you want to append (add additional information) to a text file, use the following: f = open("c:/test.txt", "a") f.write("This is an appended line.\n") f.close() Hope this helps, Byron ------------------------ Fred wrote: > Hi, > > I've searched the web and the archives of this ng for half an > hour already, and I'm still stuck. > > 1. On a W2K Pro host, installed the latest ActivePython MSI. Rebooted. > 2. Create test.py with the following: > > file=concat('test.txt','w') > file.close() > > 3. Open a DOS box, and type either "test.py" or "python test.py": > > "NameError: name 'concat' is not defined" > > I tried the following: > > - from operator import * -> "AttributeError: 'str' object has no > attribute 'close'" > - import operator -> "NameError: name 'concat' is not defined" > - file=concat('./test.txt','w') > - file=concat('.\test.txt','w') > > ... all to no avail. Obviously, I'm either missing a package or I need > to tweak something. Any idea? > > Thank you > Fred. From tim.peters at gmail.com Thu Jul 8 17:00:12 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 8 Jul 2004 17:00:12 -0400 Subject: Puzzled about random initialisation In-Reply-To: <40ED4DC0.8010602@chamonix.reportlab.co.uk> References: <40ED4DC0.8010602@chamonix.reportlab.co.uk> Message-ID: <1f7befae0407081400551cf667@mail.gmail.com> [Robin Becker] > We've been queried about the randomness of some filenames we're producing. > I worked through and seemed to satisfy myself that random is being initialised > from the system time in C > time(&now) > init_genrand(self, (unsigned long)now); > > where now is a time expressed in integral seconds since the eopoch. If you were calling the C code directly, that would be relevant. But you're not, Instead you're using the default instance of the Random class Python creates for you, with the initialization *it* uses. That code is in random.py: def seed(self, a=None): ... if a is None: import time a = long(time.time() * 256) # use fractional seconds super(Random, self).seed(a) time.time() typically changes value only 18.2 times per second on Windows, so the multiplication by 256 isn't as effective as it looks on Windows. But you'll still get a different seed on Windows if start times are more than about 0.055 seconds apart. All the start times in the example you gave later were at least 0.06 seconds apart, so the different outcomes are expected. Your machine is fast enough that you might start to see duplicates on Windows if you ran your Python instances with the -S switch (which skips a bunch of expensive initialization). Or, more directly, import time, random rd = {} td = {} ntries = 0 finish = time.time() + 10 while 1: t = time.time() if t > finish: break td[t] = 1 rd[random.Random().random()] = 1 ntries += 1 print len(rd), "unique random() values in", ntries, "attempts" print len(td), "unique time.time() values" On my WinXP box, that printed 641 unique random() values in 165923 attempts 641 unique time.time() values Since it ran for 10 seconds, I'm seeing time.time() change about 64 times per second. I believe that's because this is a hyper-threaded box, Whatever, if I had been able to start ~166000 instance of Python in that time, I would have seen only ~640 different seedings across them. From ville at spammers.com Fri Jul 2 07:06:20 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Jul 2004 14:06:20 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: <40E4F640.2060805@yahoo.com.au> Message-ID: >>>>> "Steve" == Steve writes: Steve> Ville Vainio wrote: >> Why do we write simple scripts to do simple things? Steve> Because building complicated programs to do simple things Steve> is a bad idea? Of course, the idea is to write even simpler *functions* to do the things. Even a simple script is much more complex than a simple function that can access the data directly. >> Why do we serialize data to flat text files >> in order to process them? Steve> Because it is a tried and tested method that works? I guess so was using flintstone to set up a fire :). Steve> Because flat text files are human readable, which is a huge Steve> advantage in the real world? (Just contrast the voodoo of But so is a pretty-printed python data structure. Flat text file breaks up as a solution when the data is not flat anymore. Steve> More powerful, maybe. Simpler, no. A Python script might be Steve> simpler than the equivalent assembly code that does the Steve> same thing, but when you include the complexity of the Steve> Python framework vs the assembler, it is far more complex. Isn't the general idea to shift complexity away from users to the things written by "someone else"? Steve> Which *might* very well mean more OS bugs, hacks and Steve> cracks. Exploits in your script will only affect you; Steve> exploits in the OS will affect everyone. The comparison Steve> between Windows and Linux is so obvious that you should Steve> already be thinking it :-) Needless replication of the code in the name of diversifying the system (and therefore improving the security through security-through-not-being-worthy-of-cracking) is really not the optimal path IMHO. Common frameworks and shared code are still fundamentally good things. Paranoid users just need to validate the data they are about to process, as always. I'll readily admit that highly integrated system would make it easy to implement some very sneaky trojans that log the data flow of other users (if they share the code). However, once you allow malicious code to be installed on your hard disk, you are screwed anyway. And as far the OS-ness goes - kernel and all the command line programs could (and should) stay. It's the user-interaction stuff like shell and GUIs that would benefit from the integration. Think of the functionality like am extra gear that you can switch to when you would otherwise implement non-trivial shell pipelines or a proper python script. -- Ville Vainio http://tinyurl.com/2prnb From brian at sweetapp.com Fri Jul 2 12:20:24 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 02 Jul 2004 18:20:24 +0200 Subject: Python code from XMLSchema? In-Reply-To: <2klec4F3urarU1@uni-berlin.de> References: <2klec4F3urarU1@uni-berlin.de> Message-ID: <40E58B48.9080307@sweetapp.com> Dave Kuhlman wrote: > http://www.rexx.com/~dkuhlman/gnosis_generateds.html Why do you think that XSLT is not a "full programming language"? Cheers, Brian From peufeu at free.fr Thu Jul 1 10:07:01 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 01 Jul 2004 16:07:01 +0200 Subject: Looking for minimal SQL References: <2kidfvF2iddkU1@uni-berlin.de> Message-ID: > Then you will have a _very_ limited subset of SQL, especially > when you take mysql into account, which is not very standard- Um, also consider the fact you can't do much with Mysql... From gabriel.cooper at mediapulse.com Thu Jul 22 09:04:33 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu, 22 Jul 2004 09:04:33 -0400 Subject: Python .ico In-Reply-To: References: Message-ID: <40FFBB61.20906@mediapulse.com> Michael Scarlett wrote: >I was just thinking that we should get a new icon for Python. Its such >an amzing effective language, and I know it sounds silly, but I can't >help but think that one of the reasons it hasn't surpassed JAVA or at >least taken more seriouly than it is now - is because of the dorky >looking .py icon. > I agree, on the Windows side anyway. I always thought the Windows py icon was a piece of crap, but the one for linux is pretty sweet. From jdc at uwo.ca Sun Jul 11 14:30:29 2004 From: jdc at uwo.ca (Dan Christensen) Date: Sun, 11 Jul 2004 14:30:29 -0400 Subject: timeit.timeit and timeit.repeat give different answers Message-ID: <87pt72bdmi.fsf@uwo.ca> The test below is done with Python 2.4a1 compiled from source, but the same thing happens with Debian's python2.3_2.3.4-2. Python 2.4a1 (#1, Jul 11 2004, 12:20:32) [GCC 3.3.4 (Debian)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> import time >>> t=timeit.Timer("pass","pass",time.time) >>> print t.timeit() 0.0560228824615 >>> print t.repeat(1) [0.042751073837280273] The results are consistent if repeated, i.e. timeit always produces about 0.056 and repeat always produces about 0.043. It doesn't help to do: for i in range(10): print t.timeit() vs. print t.repeat(10) The problem happens on both machines I've tested it on. One is a desktop. No other jobs running. With Python 2.3, the results are affected by the setting of the PYTHONPATH environment variable. With it unset or set to an empty directory /tmp/foo I get results like above. With it set to an empty directory /tmp/python, I get results that agree with each other. But with Python 2.4, all three settings give results that disagree. If I use the ipython shell, things are even worse: the results disagree by a factor of almost 2! I've read timeit.py and can't see how this might happen. Any thoughts? Dan From ramen at lackingtalent.com Thu Jul 29 20:30:39 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 30 Jul 2004 00:30:39 -0000 Subject: what does 'for _ in range()' mean? References: <2moucmFo8dpdU1@uni-berlin.de> <41076E3E.233CE3F1@alcyone.com> Message-ID: In article <41076E3E.233CE3F1 at alcyone.com>, Erik Max Francis wrote: > Note also there's a noticeable difference between the anonymous variable > in Prolog and the use of _ in Python; in Prolog, the anonymous variable > can be used multiple times in the same expression and there is no need > for the variable to represent the same thing. In > > middle(X) :- inOrder(_, X, _). In Python, it's possible to use _ multiple times in the same expression, too. I guess there's no obvious reason why this shouldn't work, but I discovered the following tuple-unpacking idiom recently: >>> for _, val, _ in ((1, 2, 3), (4, 5, 6), (7, 8, 9)): ... print val ... 2 5 8 -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "When the country is confused and in chaos, information scientists appear." Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html From xlii at xlii.supprimer.org Wed Jul 14 15:44:01 2004 From: xlii at xlii.supprimer.org (Ellen Herzfeld) Date: Wed, 14 Jul 2004 21:44:01 +0200 Subject: Bogus locales on Mac Message-ID: <140720042144012044%xlii@xlii.supprimer.org> I have been tearing my hair out trying to get Python to sort strings containing accented characters according to the French locale settings on Mac OS X (10.3). I think I've done it correctly because on a Linux box it works... What I find in the Mac's entrails is this: /usr/share/locale/fr_FR.UTF-8 contains LC_COLLATE -> ../la_LN.UTF-8/LC_COLLATE LC_CTYPE -> ../la_LN.UTF-8/LC_CTYPE LC_TIME ... I checked some other locale directories and found the same link to la_LN.UTF-8/LC_COLLATE, so whatever language you think you are choosing, you are actually getting the same thing... I don't know what la_LN is, maybe LATIN... The LC_COLLATE file in /la_LN.UTF-8 is 4642 bytes, the equivalent Linux file is 882134 bytes... The date strings for the months are really in French in LC_TIME, and using it does work correctly. I tried using the Linux LC_COLLATE file on the Mac but it didn't work. Has anyone using a Mac managed to sort accented strings correctly? The Mac has mostly tried to be quite international so I'm surprised at this. Have I missed something? Thanks. Ellen -- ------------------------------------------------------------------- xlii at xlii.supprimer.org | Ellen C. Herzfeld http://www.quarante-deux.org/ | Dominique O. Martel Quelques pages sur la Science-Fiction | Quarante-Deux ------------------------------------------------------------------- From olli at haluter.fromme.com Mon Jul 5 14:35:00 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 5 Jul 2004 18:35:00 GMT Subject: useless destructors References: Message-ID: <2ktlakF6atfrU2@uni-berlin.de> Aahz wrote: > David Turner wrote: > > http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html > > Finally had a chance to try this, and you're using a webserver that > barfs with Lynx. FWIW, it doesn't work with _any_ browser that I've tried (links, elinks, w3m, dillo, opera, and a self-written one). HEAD requests do work (and indicate it's an Apache server, unless the server signature is faked), but GET requests do not. There's probably something seriously broken with that web server. Best regards Oliver PS: I didn't bother to try lynx, because it is the least useful browser anyway. :-) Actually I'm surprised that there are still people who insist on using it, since there are better alternatives such as links or w3m. -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From heikowu at ceosg.de Tue Jul 13 22:12:46 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 14 Jul 2004 04:12:46 +0200 Subject: Somewhat OT... Computer playing Minesweeper In-Reply-To: <200407140402.26558.heikowu@ceosg.de> References: <200407132252.49595.heikowu@ceosg.de> <200407140402.26558.heikowu@ceosg.de> Message-ID: <200407140412.46243.heikowu@ceosg.de> Am Mittwoch, 14. Juli 2004 04:02 schrieb Heiko Wundram: > Anyway, as I said, I don't know if __iterConsistentFields() does what it > should, that's basically why I asked... And I don't know whether this > approach is the best approach to solving a minefield... PS-ing myself: I can't see a better (in terms of finding the solution) approach, but of course this algorithm lacks speed, as the amount of consistent states can become quite large for a single field which has very much scattered information, like: . . . . . . . . . x . x x . x . . . . . . . . . . . . x . . . . . . . . . . . x x . . . . . . x . x . . x . x . . . x . . . x x . . x . . x . . . . . . x . . . . x . . . . . . 2 . . . . . . . . . x . . x . . . . x . . . . . . . x . . . . x . . . . . . . . x . . . . . . . . . . . x x . . . . . . . . . x . . x x x x . . . . . . . x . . . . x . . . . . x x . . x 2 . x x . . . . . . . . . . 2 . . . . . . x . . . . x . . . 2 1 3 . . x . . x x . x . . x . . . . x x . . . . . x . . x 2 . . x . x . . x . . . . . x x . . . . . x . . x . . . . . . x . . . . . . x . . . x x . . x x . . . . . . 2 . . . . . . . . . . . . . . . x . x . x . x . x x . . . . . x . . . . x x . . . . . . . . x . . x . . . x . . . . . . . . x . x . . . . x . . . . . . x . . . x . . . . . x x . . . . . . . . x . . x . . . . . . . . . . x x . . . . . . . . . . . . . x . . . x . . . x x x . . x . . x x . . . . x . x . . . . . . . . . . . . . x x . . . . . . x . . . . . . . . . . x . . With the numbers being the only fields which were discovered so far. The number of states which are possible only taking this information into account already goes into the millions. As an example, my algorithm required about half an hour to solve this 30x16 field with 99 mines, on an Athlon XP 2400+... Heiko. From erno-news at erno.iki.fi Fri Jul 30 10:59:38 2004 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 30 Jul 2004 17:59:38 +0300 Subject: Why does start_new_thread() create an extra process under Linux? References: <2mrv6tFqlel5U1@uni-berlin.de> <410902F0.2080608@divmod.com> <2mtqiuFrdv0mU1@uni-berlin.de> Message-ID: Jon Perez writes: > Does this the fact that NPTL threads are 'just one process' mean they > are not created using clone()? Are NPTL threads not scheduled by > the kernel? they are just hidden from the /proc directory listing. (erno at fabulous) /home.b/erno % ls -l /proc/`pidof firefox-bin`/task total 0 dr-xr-xr-x 3 erno erno 0 Jul 30 17:56 28319 dr-xr-xr-x 3 erno erno 0 Jul 30 17:56 31596 dr-xr-xr-x 3 erno erno 0 Jul 30 17:56 31597 dr-xr-xr-x 3 erno erno 0 Jul 30 17:56 31599 (erno at fabulous) /home.b/erno % ls -l /proc/28319 | wc -l 16 (erno at fabulous) /home.b/erno % ls -l /proc|grep -c 28319 0 -- erno From a at a.com Sat Jul 10 20:46:31 2004 From: a at a.com (abcabc) Date: Sun, 11 Jul 2004 08:46:31 +0800 Subject: Is it Python supporting Palm development? Message-ID: <40f08d7b$1_2@rain.i-cable.com> From http Thu Jul 1 14:44:16 2004 From: http (Paul Rubin) Date: 01 Jul 2004 11:44:16 -0700 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <23891c90.0406290244.74c4ce2b@posting.google.com> <87isd8hh22.fsf@pobox.com> <7xfz8cttu3.fsf@ruckus.brouhaha.com> Message-ID: <7xr7rvsh33.fsf@ruckus.brouhaha.com> Paramjit Oberoi writes: > I can't claim to speak for others, but the few contributions that I have > made to open source software projects have been because the software > didn't do what I wanted it to do, and I was simply implementing that > functionality for myself. The exact license probably doesn't affect > people with this motivation... we do what we have to do, despite the > license. If I can fix my problem with a simple patch, sure, I'll do it and send it in whatever the license. If a real fix needs a substantial amount of development effort, but my immediate requirement can be solved with some kludgy workaround, I'm more likely to invest the development effort in the case of a GPL program, but go with the workaround for a BSD program. Also, if I make a substantial improvement to a BSD program, I (or my managers) now face the temptation of selling the improved version as a proprietary product rather than contributing the improvement back to the public distribution. There are several known cases of someone inside some company extending a GPL'd program (e.g. retargeting GCC to a new processor) and being allowed (by company management) to release the improved version as free software ONLY because the GPL had removed the option of releasing it as proprietary software. From irmen at -nospam-remove-this-xs4all.nl Wed Jul 7 19:57:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 08 Jul 2004 01:57:13 +0200 Subject: lesson to learn In-Reply-To: References: Message-ID: <40ec8dd9$0$35145$e4fe514c@news.xs4all.nl> David R. Stockwell (wg-xiao) wrote: > def fcn(day): you could add the following line here: assert type(day) is int, "day must be int" or: if type(day) is not int: raise TypeError("day must be int") > print "day is ", day > if (day < 10): > print "day is less than 10" > else: > if day < 20 : > print "day is less than 20 but greater than 10" --Irmen From http Thu Jul 8 03:04:51 2004 From: http (Paul Rubin) Date: 08 Jul 2004 00:04:51 -0700 Subject: Why would I learn Python over other languages? References: Message-ID: <7x7jtfugh8.fsf@ruckus.brouhaha.com> "Charif Lakchiri" writes: > Now here are my questions: > It is easy to learn? For the most part I'd say yes. > Does it support GUI programming? Hmm, yes, although the official GUI toolkit (tkinter) is cumbersome, doesn't look so great on the screen, and is poorly documented. > Does it support server-side programming, say for web apps? There's a cgi module. There's various third party packages for fancier types of web apps. > Does it have extensions and libraries, say for DB connectivity, > serial com or network programming...? There are reasonably good libraries included for various network protocols. There are third party extensions for DB connectivity and serial com. > Can it be used for administrative tasks, say as perl...? Sure, so can any language. I'd say it's generally simpler to toss off a 5-line perl script for some admin task than a comparable Python script. Python is better for somewhat more complex tasks, where Perl programs start getting hopelessly disorganized. > Also, can it be compiled to native code? There's a JIT compiler called psyco which isn't yet officially part of Python but which is coming along nicely. There's no ahead-of-time native code compiler and the language doesn't lend itself very well to that. > Also much appreciated would be simple comparisons with say JAVA (my other > candidate), and pointers to sites and docs where to start. www.python.org From tim.golden at viacom-outdoor.co.uk Thu Jul 8 06:23:41 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 8 Jul 2004 11:23:41 +0100 Subject: Package Problem, win32com Message-ID: | Following the example from the Python Win32 book, I type | >>> from win32com import storagecon | Traceback (most recent call last): | File "", line 1, in ? | ImportError: cannot import name storagecom | >>> Works ok for me. Same setup as yours. Is that a dump from your console? I suspect not, since the error is talking about "storagecom" while the import refers to storagecon. If you still can't get it to work, post back with an exact screen dump (not a bitmap, just the text cut-and-pasted). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From grey at despair.dmiyu.org Thu Jul 8 01:18:49 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 08 Jul 2004 05:18:49 GMT Subject: Why would I learn Python over other languages? References: Message-ID: On 2004-07-08, Charif Lakchiri wrote: > It is easy to learn? Yes. Of all the languages I've looked at Python's been one of the easiest. > Does it support GUI programming? Yes; in several different flavors. TK, QT, GTK just to name 3. > Does it support server-side programming, say for web apps? Yes. mod-python and zope come to mind. > Does it have extensions and libraries, say for DB connectivity, serial com > or network programming...? Yes. Standard, in fact. > Can it be used for administrative tasks, say as perl...? Yes. I Python has replaced Perl for my admin tasks since I find Python far more maintainable than Perl in the long run. > Also, can it be compiled to native code? No. However on i386 there is Psyco which provides some impressive speed boosts. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From me at privacy.net Tue Jul 27 04:20:15 2004 From: me at privacy.net (Duncan Booth) Date: 27 Jul 2004 08:20:15 GMT Subject: replace dict contents References: <41060AB3.9080600@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote in news:41060AB3.9080600 at jessikat.fsnet.co.uk: > Is there a simple way to replace the contents of a dictionary entirely > with those of another. > > for lists we can do > > L1[:] = L2 > > but there doesn't seem to be an equivalent for dicts. The simplest would seem to be d1.clear() d1.update(d2) although, this doesn't have the flexibility of a single assignment so you can't use it where 'd2' is actually an expression involding d1. From abra9823 at mail.usyd.edu.au Sun Jul 11 06:12:44 2004 From: abra9823 at mail.usyd.edu.au (Ajay Brar) Date: Sun, 11 Jul 2004 20:12:44 +1000 Subject: xml.marshal Message-ID: <023001c46732$0c02eac0$5700a8c0@nazgul> hi! where can i find help (tutorials/documentation) on xml.marshal I have a Python object which i would like to write out as XML. the howto at PyXML page contains an example using the generic module. I have defined my own DTD and would like to write out the Python object into XML using it. how would i go about doing it? where can i find any examples on it? thanks cheers ajay -------------- next part -------------- An HTML attachment was scrubbed... URL: From grey at despair.dmiyu.org Thu Jul 8 12:39:23 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 08 Jul 2004 16:39:23 GMT Subject: Tab wars revisited (was Re: Python indentation) References: <3N-dnXXXI9kf-nHdRVn-hg@giganews.com> Message-ID: On 2004-07-08, Thomas Bellman wrote: > Up to the next tab stop, and tab stops are placed at every 8th > column. No more, no less. Bzt. Next. > Because that's the way it has been since time eternal. Every > terminal I have seen have had tab stops at every 8th column. But we're not talking terminals. Nice try, you lose. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From jacek.generowicz at cern.ch Wed Jul 7 06:13:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jul 2004 12:13:43 +0200 Subject: Scheme style and Python style [was: Re: Typed Python?] References: <2kn746F4ci1vU1@uni-berlin.de> <2kofmgF4li52U2@uni-berlin.de> Message-ID: Fran?ois Pinard writes: > [Jacek Generowicz] > > Fran?ois Pinard writes: > > > > Also, there once was a notable distance between Scheme and Python > > > about lazy evaluation [...] but more recent versions of Python offer > > > fairly tractable, almost easy approaches for such things. > > > [...] what sort of lazy evaluation ? > [...] > In Scheme, lazy evaluation is part the language with the `(delay ...)' > and `(force ...)' constructs. In Python, one could already "simulate" > lazy evaluation by various means, but it turned out to be fairly easy > after iterator generators were introduced, and these are now used all > over the place in Python, often yielding interesting speedup. I find non-data descriptors quite useful for lazy evaluation, at times. I guess it comes down to a difference in what we consider a "notable distance" to be. Scheme and Python provide different means of built-in lazy evaluation ... this strikes me as considerably less notable than the difference between Haskell and Python/Scheme (wtr lazy evaluation). From claird at lairds.us Tue Jul 27 16:04:41 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 27 Jul 2004 20:04:41 GMT Subject: Recommendations for books on Python and XML References: <864c2cd6.0407261121.5a019d57@posting.google.com> Message-ID: <1foit1-fjj.ln1@lairds.us> In article , Ron Stephens wrote: >I liked Python & XML, by Christopher A. Jones and Fred L. Drake, Jr., >an O'Reilly book. I have posted a book review here >www.awaretek.com/book.html > >I have not read the McGrath book, XML Processing with Python, but >scanning it in the bookstore it also looked pretty good. > >Ron Stephens Sean's book *is* good, if dated, at least for some uses. Some people with an interest in XML and Python will find that *Text Processing in Python* is ideal: thorough, rich, interesting, and accurate. From ville at spammers.com Mon Jul 12 12:57:56 2004 From: ville at spammers.com (Ville Vainio) Date: 12 Jul 2004 19:57:56 +0300 Subject: Proposal: runtime validation statement References: <7xy8lq9rjx.fsf_-_@ruckus.brouhaha.com> Message-ID: >>>>> "Dave" == Dave Brueck writes: Dave> Also, a developer-defined function doesn't stand out as well Dave> as a statement would - a statement sets it apart from normal Dave> function calls which are doing the actual work to solve the Dave> problem at hand - and it'd be easy for syntax-highlighting Dave> editors to color it differently too. It's as easy to color a function. We have too much statements that don't need to be statements already. "validate" is obvious library stuff... -- Ville Vainio http://tinyurl.com/2prnb From newsgroups at jhrothjr.com Tue Jul 20 17:14:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jul 2004 17:14:34 -0400 Subject: unittest: Proposal to add failUnlessNear References: <10fobkud5fvgr9b@news.supernews.com> Message-ID: <10fr2qrka5o575a@news.supernews.com> "Antoon Pardon" wrote in message news:slrncfpk65.m9.apardon at trout.vub.ac.be... > Op 2004-07-19, John Roth schreef : > > "Antoon Pardon" wrote in message > > news:slrncfnaq7.kj.apardon at trout.vub.ac.be... > >> I have been working with unittests lately and found that the > >> self.failUnlessAlmostEqual, isn't as usefull as it could be. > >> > >> My main problem is, that it is only usefull with objects > >> that can be converted to floats, while there are a whole > >> bunch of objects that can be almost equal but not so > >> convertable. The first example coming to mind being > >> complex numbers. > >> > >> A secondary objection is that you are limited to > >> a very specific set of tolerances. If for instance > >> you want to verify that two numbers differ at most > >> by 0.0003 you can't specify that. > > > > Float and complex have two very different issues. > > Only if you want them to be. Floats are a subset > of complex and as such can be treated exactly > the same. Floats are not a subset of complex. I concur with Roy Smith's comments on that issue. There's no reason why complex numbers cannot be represented by a pair of integers, or rationals, or the new floating decimal type, or whatever. In addition, you're going to have to do significant type checking if you want to combine floats and complex in the same method call. That's just poor design. > > Since I'm maintaining the Python port of FIT, I > > had to deal with them. What I did for float was > > use the character form of the float to determine > > the precision. The default routine appends a > > character 5 and then uses this to calculate the > > bounds within which the other value must be found. > > > > An example may help. Let's say I want to > > test against '6.23e14'. This method would > > establish bounds of 6.235e14 and 6.225e14 > > and then test whether the other number was > > within those bounds. (Note that the '5' is > > appended before the numbers are converted > > to float, however the second bound is calculated > > after the conversion.) > > Why don't you just test whether the second > number lies within a fault tolerance of > 5e11 of 6.23e14 I take it you've never worked with FIT. It's intended to be used by non-technical people on a project, such as the on-site customer, business analysts and so forth. If I did something as silly as requiring them to insert a tolerance that is blatently obvious to anyone looking at the number involved, I'd get a change request so fast that the edges would char from the friction. It would also violate the interface agreement that all ports of FIT are supposed to conform to. John Roth > > -- > Antoon Pardon From oliver.magno at digitaleyecandy.biz Tue Jul 13 21:11:54 2004 From: oliver.magno at digitaleyecandy.biz (oliverm) Date: Wed, 14 Jul 2004 09:11:54 +0800 Subject: password script problem In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1304678127@its-xchg4.massey.ac.nz> References: <1ED4ECF91CDED24C8D012BCF2B034F1304678127@its-xchg4.massey.ac.nz> Message-ID: <40F4885A.9010704@digitaleyecandy.biz> An HTML attachment was scrubbed... URL: From peter at engcorp.com Sun Jul 11 22:01:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 11 Jul 2004 22:01:37 -0400 Subject: List Comprehension Syntax In-Reply-To: References: <8OXHc.13877$4y7.5713@newssvr27.news.prodigy.com> <2lc645Fb0cjgU2@uni-berlin.de> Message-ID: Ville Vainio wrote: > Nope, the only correct way is > > result = [x for x in range(10) > if x % 2 == 0 > if x % 3 == 0 > ] > > result = [x * y > for x in range(10) if x % 2 == 0 > for y in range(10) if y % 3 == 0 > ] > > Because that's the way python-mode.el does it in emacs :-). Unfortunately, python-mode.el is wrong, since it results in code that is harder to maintain (at least with another editor). Indentation that has to line up with random items on the previous line, as opposed to the standard four spaces, is clearly wrong. But if you let emacs define the limits of your world, then it's probably okay to do it that way. ;-) From Spam at ivonet.nl Fri Jul 23 12:29:17 2004 From: Spam at ivonet.nl (Ivo) Date: Fri, 23 Jul 2004 18:29:17 +0200 Subject: Longint?! References: <41011836$0$769$3a628fcd@reader20.nntp.hccnet.nl> <6P-dnZt_i7hbsJzcRVn-gQ@comcast.com> Message-ID: <41013cdd$0$762$3a628fcd@reader20.nntp.hccnet.nl> I will try the struct... Thanx -- Cheerz, Ivo. http://IvoNet.nl ============================ "Larry Bates" wrote in message news:6P-dnZt_i7hbsJzcRVn-gQ at comcast.com... > You must read it as binary and use struct.unpack() to convert > to long integer. > > HTH, > Larry Bates > Syscon, Inc. > > "Ivo" wrote in message > news:41011836$0$769$3a628fcd at reader20.nntp.hccnet.nl... > > Pythoneers, > > I am trying to reed a long integer (4 byte value like in pascal) in python > > but i don't seem to succeed. > > > > It's from a binary file where from a certain offset in the file 4 bytes > > (longint) tell how long a header is. > > > > because I don't have to assign a type to a variable I don't know how to > > ensure i get the longint type read from the file. > > > > Help very much appreciatend. > > > > -- > > Cheerz, > > Ivo. > > http://IvoNet.nl > > > > > > ============================ > > > > > > From jepler at unpythonic.net Fri Jul 9 08:22:51 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 9 Jul 2004 07:22:51 -0500 Subject: Too many return-statements = bad style? In-Reply-To: References: Message-ID: <20040709122251.GB25880@unpythonic.net> Some style guides discouraged multiple "return" statements out of some theoretical superiority of the single-return form. single-point- of-return was supposed to lead to easier analysis. Now, either this ease was for automatic analysis, in which case the transformation from multiple return-sites to a single return site might as well be done by the analysis software, rather than forcing a human to do it. ... or it's for human analysis, in which case I'd say that my gut reaction is the same as yours: having fewer indentation levels is more important than having fewer return sites, within reason. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From michael at foord.net Wed Jul 7 08:26:16 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jul 2004 05:26:16 -0700 Subject: Finding Script Directory Message-ID: <8089854e.0407070426.2fb90f95@posting.google.com> What's the best, cross platform, way of finding out the directory a script is run from ? I've googled a bit, but can't get a clear answer. On sys.argv[0] the docs say : argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). So this doesn't seem to be the answer. The script directory is always *somewhere* in sys.path - but not always in position 0. If you use py2exe then sys.path[0] is the zipfile it does the imports from !! Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From squirrel at WPI.EDU Wed Jul 21 09:39:15 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 21 Jul 2004 09:39:15 -0400 Subject: distutils alternatives? In-Reply-To: References: Message-ID: On Tue, 20 Jul 2004, Ellinghaus, Lance wrote: > Has anyone modified distutils to build Solaris PKG files?? Try Alien: http://www.kitenet.net/programs/alien/ It can convert packages between RPM, DPKG (.deb), Stamepede (.slp), Slackware (.tgz), and Solaris (.pkg): just build an RPM with distutils, and re-package it using Alien. From roy at panix.com Sat Jul 31 20:43:52 2004 From: roy at panix.com (Roy Smith) Date: Sat, 31 Jul 2004 20:43:52 -0400 Subject: transforming a list into a string References: Message-ID: Tim Peters wrote: > Note that Peter Otten previously posted a lovely O(N) > solution in this thread, although it may be too clever for some > tastes: > > >>> from itertools import izip > >>> items = ['1','2','7','8','12','13'] > >>> it = iter(items) > >>> ",".join(["{%s,%s}" % i for i in izip(it, it)]) > '{1,2},{7,8},{12,13}' Personally, I'm not a big fan of clever one-liners. They never seem like such a good idea 6 months from now when you're trying to figure out what you meant when you wrote it 6 months ago. From FBatista at uniFON.com.ar Fri Jul 16 08:44:07 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 16 Jul 2004 09:44:07 -0300 Subject: namespace for released packages? Message-ID: [Alex Hunsley] #- What is the python convention for namespaces of released #- packages? In #- Java you'd write your domain name (if you have one) backwards, this: #- #- uk.org.ohmslaw.myPackage #- #- ... thus ensuring uniqueness. Is it the same for Python? I don't really understand your question. What you mean with "released packages"? those which are in the standard library? In that case, whose domain you're talking about? . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informacion contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informacion confidencial o propietaria, cuya divulgacion es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no esta autorizado a divulgar, copiar, distribuir o retener informacion (o parte de ella) contenida en este mensaje. Por favor notifiquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnetico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefonica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electronicos pueden ser alterados, motivo por el cual Telefonica Comunicaciones Personales S.A. no aceptara ninguna obligacion cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jul 9 15:33:04 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Jul 2004 21:33:04 +0200 Subject: warnings filter? References: Message-ID: rob at encodia.biz wrote: > In Python 2.3, this code still prints a warning (when run as a script, > not from the interpreter). How do I get rid of the warning? I'd like > to do it without passing command line args to python. > > import warnings > warnings.filterwarnings('ignore') > a = 0xffffffff The warning is issued during the compilation, not the execution of your script. Therefore the attempt to turn off the warning, although before the offensive statement, comes too late. a = 0xffffffff One workaround is to precompile offensive.py (By the way is there a flag to do this that I've overlooked?): $ python -c"import offensive" offensive.py:1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up a = 0xffffffff and then invoke offensive.pyc: $ python offensive.pyc All quiet :-) The other option would be to reorganize your script to the same effect. $ rm offensive.pyc $ python driver.py $ Where driver looks like so: import warnings warnings.filterwarnings('ignore') # should probably be more specific import offensive Of course you could omit the first two lines when you can live with a warning the first time you run driver.py after every change of offensive.py. Peter From paul.bissex at gmail.com Fri Jul 9 16:04:00 2004 From: paul.bissex at gmail.com (Paul Bissex) Date: Fri, 9 Jul 2004 16:04:00 -0400 Subject: [python-list] What am I doing wrong here? In-Reply-To: <1001523104070912155f72848e@mail.gmail.com> References: <16622.59541.684345.30522@montanaro.dyndns.org> <1001523104070912155f72848e@mail.gmail.com> Message-ID: <1001523104070913042549520c@mail.gmail.com> Works for me with this change: s = """From skip Thu Jul 8 14:50:00 -0500 2004 is mailbox.PortableUnixMailbox supposed to be able to handle ">From" ? pb On Fri, 9 Jul 2004 15:15:38 -0400, Paul Bissex wrote: > Hey Skip, > > Either something stripped out the the script or you forgot to insert > it! Thought you'd want to know. > > pb > > > > > On Fri, 9 Jul 2004 13:48:53 -0500, Skip Montanaro wrote: > > > > Appended to this message is a simple script that uses the > > mailbox.PortableUnixMailbox class and email.message_from_file function to > > (attempt to) extract a message from a Unix mbox file. Unfortunately, it > > doesn't seem to work correctly. This code is more-or-less lifted from what > > spambayes.mboxutils.getmbox() does. Any clues about what I'm doing wrong? > > > > Thanks, > > > > Skip > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > paul bissex, e-scribe.com -- database-driven web development > 413.585.8095 > 69.55.225.29 > 01061-0847 > 72?39'71"W 42?19'42"N > -- paul bissex, e-scribe.com -- database-driven web development 413.585.8095 69.55.225.29 01061-0847 72?39'71"W 42?19'42"N From dd55 at cornell.edu Tue Jul 27 18:02:03 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 27 Jul 2004 18:02:03 -0400 Subject: Displaying print messages- Emacs In-Reply-To: References: Message-ID: > > Or just start Python with -u (unbuffered) or -i (interactive) from > within the shell. Avoids the need to change the script. > I forgot to ask, how would I do this from Emacs? From squirrel at WPI.EDU Tue Jul 27 10:48:04 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 27 Jul 2004 10:48:04 -0400 Subject: Dynamically create a class (or class instance) and its attributes? In-Reply-To: References: Message-ID: On Tue, 27 Jul 2004, Robert Oschler wrote: > For example, given a MySQL row object from a fetchone() call: > > employee_name = sqlrow[field_dict['empname']] > > To make the syntax easier and clearer, I would like to create a Python class > instance that would allow me to access the fields in the MySQL row as > attributes of a class created dynamically from the row structure. For > example: > > employee_name = ez_sqlrow.empname > > What would be the best way to create such a class or class instance? Any > code examples you have would be welcome. The other respondents have recommended using setattr(), but here's a way that will work completely dynamically: class ez_sql(object): def __init__(self,sqlrow): self._sqlrow = sqlrow def __getattr__(self,a): try: return self._sqlrow[fielddict[a]] except (IndexError,KeyError),e: raise AttributeError,e def __setattr__(self,a,v): try: self._sqlrow[fielddict[a]] = v except KeyError: self.__dict__[a] = v This is a bit slower than using setattr(), but might save a good deal of memory (especially if you keep the SQL rows around in another form). From eadorio at yahoo.com Sat Jul 31 06:36:15 2004 From: eadorio at yahoo.com (Ernie) Date: 31 Jul 2004 03:36:15 -0700 Subject: Quixote demo References: <5b42ae4.0407301634.2e72a8f8@posting.google.com> Message-ID: <5b42ae4.0407310236.5451acea@posting.google.com> Thanks a lot Harald. That slash really amounts to so much difference (and surprises!) On second reading of the demo.txt documentation, there is indeed a trailing backslash. Should not the ordinary web user of a quixote web page be insulated from this technical detail. :) Ernie. Harald Massa wrote in message news:... > Ernie, > > try: > > http://localhost/cgi-bin/demo.cgi/ > > instead of > > http://localhost/cgi-bin/demo.cgi > > There is some problem with cgi and demo and slashes > > Harald From tim.golden at viacom-outdoor.co.uk Thu Jul 8 09:53:24 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 8 Jul 2004 14:53:24 +0100 Subject: WaitForMultipleObjects in Python. Message-ID: | Tim Golden wrote in message | news:... | > | Is there any way to wait in multiple events, semaphores etc. For | > | examole on Queue and Event? Like you can do in WIN32. | > | > If you haven't already, install the pywin32 extensions from | > http://starship.python.net/crew/mhammond/win32/Downloads.html | > | > and look at the win32event module | | I mean portable with no win32. | | Speaking of win32event. Can I use WaitForMultipleObjects with | Python Event object? Ah. I'm perfectly certain that you can do or simulate all those sort of things. And it's possible that someone's already done it, but if they haven't it won't be trivial. (And if they have, it probably wasn't trivial). Over to the cross-platform gurus for more info. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From cjw at sympatico.ca Thu Jul 8 08:07:30 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 08 Jul 2004 08:07:30 -0400 Subject: open is not obsolete (was Re: understanding self In-Reply-To: References: Message-ID: <5OaHc.45662$JG5.971334@news20.bellglobal.com> Delaney, Timothy C (Timothy) wrote: > Jeff Shannon wrote: > > >>Okay, perhaps "legacy" is a better term than "obsolete". In either >>case, it's recommended that it not be used in new code, even if there >>is no current plan to remove it. Not that the specifics of this case >>are particularly germane to the point I was making... > > > As mentioned by Tony, this is not the case. From python-dev: > > >>>Then should the following line in the reference be changed? >>> >>>"The file() constructor is new in Python 2.2. The previous spelling, >>>open(), is retained for compatibility, and is an alias for file()." >>> >>>That *strongly* suggests that the preferred spelling is file(), and >>>that open() shouldn't be used for new code. >> >>Oops, yes. I didn't write that, and it doesn't convey my feelings >>about file() vs. open(). Here's a suggestion for better words: >> >>"The file class is new in Python 2.2. It represents the type (class) >>of objects returned by the built-in open() function. Its constructor >>is an alias for open(), but for future and backwards compatibility, >>open() remains preferred." >> >>--Guido van Rossum (home page: http://www.python.org/~guido/) > > > Tim Delaney "file" is analogous to a class constructor, while "open" becomes a factory function for that class, with the same signature. This raises the question as to which is the better way of creating an instance of a class. It seems to me that the constructor is, for simple cass, the better way to go. It provides one way and avoids the question of "Should I use A or B when there are more than one ways of doing some task. What is the general view? Colin W. From jlenton at gmail.com Wed Jul 21 13:09:25 2004 From: jlenton at gmail.com (John Lenton) Date: Wed, 21 Jul 2004 14:09:25 -0300 Subject: Linux, fcntl, F_SETLEASE and signals In-Reply-To: <2d9e37f90407211003789037b7@mail.gmail.com> References: <871xj5jpf6.fsf@ion.xlipstream.com> <2d9e37f90407211003789037b7@mail.gmail.com> Message-ID: <2d9e37f904072110096b5e0d06@mail.gmail.com> On Wed, 21 Jul 2004 14:03:56 -0300, John Lenton wrote: > On Wed, 21 Jul 2004 12:27:57 -0400, Chris Green wrote: > > Hey folks, > > > > Is there anyway for a signal handler in python to get the information > > from a 3 argument signal handler rather than just the signal number > > and stack frame? > > > > I've got an application where I have to check for F_SETLEASE on a file > > in python on Linux 2.4. What this does is tells the kernel to notify > > the current process with SIGIO that a particular file descriptor is being > > modified by another process. > > > > >>> import fcntl > > >>> f = open(".zshrc", "r+") > > >>> fcntl.fcntl(f, fcntl.F_SETLEASE, fcntl.F_WRLCK) > > 0 > > would this be close enough? > > Python 2.3.4 (#2, Jul 5 2004, 09:15:05) > [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import fcntl > >>> import ctypes > >>> libc = ctypes.cdll.LoadLibrary('/lib/libc.so.6') > >>> f = open("/home/john/.bashrc") > >>> libc.fcntl(f.fileno(), fcntl.F_SETLEASE, fcntl.F_WRLCK) > 0 > >>> > >>> # now someone cats .bashrc > ... I/O possible sorry, I got the wrong end of the stick. But ctypes lets you do what you want, anyways. Portable as Linux :) -- John Lenton (jlenton at gmail.com) -- Random fortune: bash: fortune: command not found From pinard at iro.umontreal.ca Fri Jul 2 22:56:12 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 2 Jul 2004 22:56:12 -0400 Subject: Eliminating duplicates entries from a list efficiently In-Reply-To: References: Message-ID: <20040703025612.GA13224@titan.progiciels-bpi.ca> [Roy Smith] > [Paul] > > Can anyone suggest an efficient way to eliminate duplicate entries > > in a list? The naive approach below works fine, but is very slow > > with lists containing tens of thousands of entries: > Something like: > d = {} > for item in list: > d[item] = True > list = d.keys() > This should do it and will run in, if I'm not mistaken, O(n). The > only problem is that it scrambles the order of the items in the list, > which may or may not be a problem, depending on your application. If order is not important, here is a short idiom: from sets import Set as set d = list(set(d)) This may be slower than the dictionary solution in current Python. Sets were experimental, but as they are stabilising, I think there are plans now to make them faster in subsequent Python releases. So, it might be a good bet, learning to depend on them in the long run. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From grante at visi.com Wed Jul 28 17:59:17 2004 From: grante at visi.com (Grant Edwards) Date: 28 Jul 2004 21:59:17 GMT Subject: Newbie question about formatting long conditionals References: Message-ID: <410821b5$0$8085$a1866201@newsreader.visi.com> > ... if the "if" condition gets too long and unweildy for a single > line, is there any way to format it along these lines?: > > ############# > a = 1 > b = 2 > c = 3 > d = 4 > > if a == 1 > and b < 4 > and (c == 2 or d == 4): > print "Conditions met!" > ############# if a == 1 \ and b < 4 \ and (c == 2 or d == 4): print "Conditions met!" if (a == 1 and b < 4 and (c == 2 or d == 4)): print "Conditions met!" -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From squirrel at WPI.EDU Fri Jul 16 12:04:15 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 16 Jul 2004 12:04:15 -0400 Subject: need simple parsing ability In-Reply-To: <20040716111324.09267883.gry@ll.mit.edu> References: <20040716111324.09267883.gry@ll.mit.edu> Message-ID: On Fri, 16 Jul 2004, george young wrote: > I need to read user input of a subset of these. The user will type a > set of names separated by commas (with optional white space), but there > may also be sequences indicated by a dash between two integers, e.g.: > > "9-11" meaning 9,10,11 > "foo_11-13" meaning foo_11, foo_12, and foo_13. > "foo_9-11" meaning foo_9,foo_10,foo_11, or > "bar09-11" meaning bar09,bar10,bar11 > > (Yes, I have to deal with integers with and without leading zeros) > [I'll proclaim inverse sequences like "foo_11-9" invalid] > So a sample input might be: > > 9,foo7-9,2-4,xxx meaning 9,foo7,foo8,foo9,2,3,4,xxx > > The order of the resultant list of names is not important; I have > to sort them later anyway. The following should do the trick, using nothing more than the built-in re package: --- import re def expand(pattern): r = re.search('\d+-\d+$',pattern) if r is None: yield pattern return s,e = r.group().split('-') for n in xrange(int(s),int(e)+1): yield pattern[:r.start()]+str(n) def expand_list(pattern_list): return [ w for pattern in pattern_list.split(',') for w in expand(pattern) ] print expand_list('9,foo7-9,2-4,xxx') --- If you want to let the syntax be a little more lenient, replace "pattern_list.split(',')" in expand_list() with "re.split('\s*,\s*',pattern_list)". This will allow spaces to surround commas. Note that because this uses generators, it won't work on Pythons prior to 2.3. Hope this helps! From martin at v.loewis.de Mon Jul 12 17:25:30 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 12 Jul 2004 23:25:30 +0200 Subject: How big is python24.dll? In-Reply-To: References: Message-ID: <40f301cb$0$159$9b622d9e@news.freenet.de> A. B., Khalid wrote: > [-] python24.dll, July, 10th, 2004, ? 1700k Regards, Martin From knightsofspamalot-factotum at gvdnet.dk Fri Jul 16 17:25:52 2004 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 16 Jul 2004 23:25:52 +0200 Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: Message-ID: <87fz7rlk4f.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Steve" == Steve Lamb writes: >> Emacs allows me to interact with a continuously live instance of >> the Python interpreter. Steve> You know, oddly enough this isn't something I demand of my Steve> editors. With things like screen, konsole, multiple rxvts or Steve> even plain old ALT-F1, ALT-F2 I get the exact same Steve> functionality. It's called learning how to use the tools given Steve> instead of insisting on having everything bolted onto one large Steve> bloatware application. You know, it strikes me as odd that you are so quick to dismiss the usefulness of something you have not tried in practice. I have tried it, and I very much miss it when it's not there. As for the whole 'bolted on' thing... being able to interact with another process is useful for a wide range of things, as I'm sure any purist vi user will agree. Also vi can run such processes, sending input to them and doing something with the output. This particular feature of Emacs' is simply having input to and output from the process in the same buffer, and it's reused widely. I've already sung the praise of its usefulness for interactive programming in Python and similar languages, but I've also found it invaluable e.g. for interacting with SQL databases (anyone who've used Oracle's sqlplus can surely quickly be persuaded of this), where the output is something that you'll often want to fiddle around with in your editor anyway. Well, at least I do. Now, if it's possible to run a Python process separately from vi which you can send code snippets to anytime, then you can conveniently have your small, separated tools and the functionality that Jacek and I are so fond of at the same time. As for the whole bloatware argument, I think it's getting a bit ridiculous. Fine, I build Python into Vim, and I'm all for that. I'm sure that means that I can hook into a _lot_ of Python code that way, thus making Vim every bit as much bloatware as Emacs is. Seriously, if you want a slim Emacs, don't load all the things you won't need. Sure, you'll never cut Emacs down to the minimum size of any vi implementation, I'm sure, but it was never designed for extreme compactness. At the computer science department I very recently graduated from (yay me!), Emacs was used significantly more than vi on our application servers, and none of our application servers have ever had scarceness of resources because of it. Sure, on a mobile phone or PDA with very limited resources, I might start to worry about size, but with even relatively low-end machines having at least 256 MB main memory these days, fussing over a couple of megs for something as important as the text editor one uses, which is probably in the top three of the most important programs people like us use, is nothing but pedantry. If that's what's going to tip over your box, it's time to put the old 386 out of its misery. Hell gVim compiled with Python support alone takes up 7.5 MB at startup on my box compared to Emacs' 8.2 MB with my own 'basic' stuff loaded (which is quite a lot for some). Is it really a big deal? It certainly isn't to me. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAkD4R+AACgkQYu1fMmOQldWB8ACg5GMNmMhC2IALb62dhMlu8dRh hJwAnjengArZINHPWOIYcXRuIqcFT+pu =32eg -----END PGP SIGNATURE----- From beliavsky at aol.com Sun Jul 4 15:04:58 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 4 Jul 2004 12:04:58 -0700 Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> Message-ID: <3064b51d.0407041104.7f7abffc@posting.google.com> Thomas Reichelt wrote in message news:<2kn746F4ci1vU1 at uni-berlin.de>... > Moin, > > short question: is there any language combining the syntax, flexibility and > great programming experience of Python with static typing? Is there a > project to add static typing to Python? > > Thank you, If you are using Python mainly for numerical work and use Numeric or Numarray for array operations, Fortran 90 or 95 may be the closest replacement with static typing. The syntax is fairly similar (assuming that the free source form of F90/F95 is used, as it should for new code). Fortran 2003 supports object-oriented programming with inheritance (as does Python), but full F2003 compilers are not available yet. From ghum at gmx.net Wed Jul 21 07:00:09 2004 From: ghum at gmx.net (Harald Armin Massa) Date: 21 Jul 2004 04:00:09 -0700 Subject: cPickle and pgsql...damn!! References: Message-ID: <5db4fffa.0407210300.1b8be573@posting.google.com> > >serializedDict = cPickle.dumps(damnDict) ... > The field where i put the serialized data is a text field. why don't you use bytea??? it's the field type CREATED for your purpose. Harald From martin at v.loewis.de Mon Jul 12 23:53:19 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 13 Jul 2004 05:53:19 +0200 Subject: How big is python24.dll? In-Reply-To: References: Message-ID: <40F35CAF.5090709@v.loewis.de> Chris wrote: > The size of the v2.4 dll isn't really known right now. It's only the > first alpha which means that: > > a: more stuff is going to be added > b: debugging code and other misc cruft is still in there. > > We won't have a decent idea of the dll size until the first release > candidate later this year or early next year. b) is actually not true: the DLL does not contain debug code. The alpha is very similar to the release wrt. the build process. Regards, Martin From fumanchu at amor.org Tue Jul 6 17:39:01 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 6 Jul 2004 14:39:01 -0700 Subject: __init__.py Message-ID: Joseph V Laughlin wrote: > I'm browsing through a python program that's broken up into many > subdirectories and files. In one of the higher-level directories is a > file called __init__.py. Does this file have any special purpose? > > Contents of __init__.py is: > __all__ = ["list", "of", "subdirectories"] http://docs.python.org/tut/node8.html#SECTION008400000000000000000 FuManChu From squirrel at WPI.EDU Thu Jul 1 12:37:47 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 1 Jul 2004 12:37:47 -0400 Subject: how to find "".encodings In-Reply-To: References: Message-ID: On Thu, 1 Jul 2004 P at draigBrady.com wrote: > How would one get a list of encodings > that can be passed to "".encode() > > I know base64,utf8,latin,ascii work > and these are listed in the encodings > and codecs modules, but where can one > get a definitive list? http://docs.python.org/lib/node127.html is the only list I know of; I don't think that there's a actually a function that can list all the currently registered codecs. From heikowu at ceosg.de Tue Jul 13 16:52:49 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 13 Jul 2004 22:52:49 +0200 Subject: Somewhat OT... Computer playing Minesweeper Message-ID: <200407132252.49595.heikowu@ceosg.de> Hi list! I've written a little program which plays Minesweeper, using quite a simple algorithm, which I've written in Python (pseudocode): total_fields = 0 for field in : total_fields += 1 for pos in : if pos is marked: hist[pos] += 1 for pos in hist: hist[pos] /= float(total_fields) Now, the only non-trivial algorithm in this program is compute all possible consistent fields, which does not compute all fields that are consistent, but only computes those fields which have mines next to already discovered numbers, to speed things up, and all positions which do not lie to a discovered field get the standard probability minesleft/fieldsleft, which should be the same as looping over all possible combinations (if I'm not mistaken). What the computer then does is evaluate the histogram: If a position has probability zero of having a mine: discover it, if it has possibility one: mark it, and only if there are no positions which have possibility zero or one: discover a random field from the list of fields which have the lowest probability of having a mine. This is done iteratively until no empty fields are left, or a discovery blows up. I've let this little program run to check the average number of "solvable" games on an 8x8 field, with 10 mines (this is the easy setting of any Minesweeper clone), and I get a number in the range 55-65%. Now, if I let KMines get the solvability rate for a field of this size, it spits out a number of 80%... So, I guess, either my algorithm is wrong (or suboptimal), or KMines algorithm for solving a field is wrong (taking information into account which it may not). If anybody here knows more about game-theory than I do, I'd be happy if he/she could enlighten me... For anybody willing to try the program, you can download it here: http://www.heim-d.de/~heikowu/PyMines.py In case you don't have psyco installed, comment out all lines which concern psyco. And be prepared that the runtime is somewhat slow, because the algorithm used to find the consistent fields is recursive. Thanks for any help! Heiko. From jepler at unpythonic.net Fri Jul 16 11:45:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 16 Jul 2004 10:45:52 -0500 Subject: need simple parsing ability In-Reply-To: <20040716111324.09267883.gry@ll.mit.edu> References: <20040716111324.09267883.gry@ll.mit.edu> Message-ID: <20040716154551.GB7839@unpythonic.net> COMMA = "," OPT_WS = "[ \t]*" STEM = "([a-zA-Z_]*)" NUMBER = "([0-9]+)" OPT_NUMBER = NUMBER + "?" OPT_SECOND_NUMBER = "(?:-" + NUMBER + ")?" import re splitter = re.compile(COMMA + OPT_WS).split print `STEM + OPT_NUMBER + OPT_SECOND_NUMBER` parser = re.compile(STEM + OPT_NUMBER + OPT_SECOND_NUMBER).match def expand(stem, n0, n1): if not n1: if n0: yield "%s%s" % (stem, n0) else: yield stem return l = len(n0) n0 = int(n0, 10) n1 = int(n1, 10) for i in range(n0, n1+1): yield "%s%0*d" % (stem, l, i) def parse_string(line): items = splitter(line) parsed_items = [parser(i) for i in items] for i, pi in zip(items, parsed_items): if i is None: raise ValueError, "Invalid item: %r" % i stem = pi.group(1) n0 = pi.group(2) n1 = pi.group(3) if n1 and not n0: raise ValueError, "Invalid item: %r" % i for j in expand(stem, n0, n1): yield j def test(): s = "9,foo7-9,bar_09-12,2-4,spam" print s, list(parse_string(s)) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From newsgroups at jhrothjr.com Wed Jul 21 20:55:15 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 21 Jul 2004 20:55:15 -0400 Subject: unittest: Proposal to add failUnlessNear References: <10fobkud5fvgr9b@news.supernews.com><10fr2qrka5o575a@news.supernews.com><10ftpi85r38cqcd@news.supernews.com> Message-ID: <10fu44tgo7cald0@news.supernews.com> "Tim Peters" wrote in message news:mailman.682.1090448229.5135.python-list at python.org... > Nope. abs(a - b) works for both cases, although for complex numbers > Python uses a numerical method less prone to spurious > overflow/underflow than the "square root of the sum of the squares" > formula. I didn't know that. It does make sense to do something like that, but it seems a bit like deep magic to make abs recognize that the operand is a subtraction. John Roth > From jolsen at mail2world.com Sun Jul 4 07:52:50 2004 From: jolsen at mail2world.com (Jesper Olsen) Date: 4 Jul 2004 04:52:50 -0700 Subject: distutil and debugging References: <6b17fa95.0407030838.2a8184cb@posting.google.com> <6b17fa95.0407032021.30aab655@posting.google.com> Message-ID: <6b17fa95.0407040352.25b1b69f@posting.google.com> Gerhard H?ring wrote in message news:... > Jesper Olsen wrote: > > [...] No - that does not change the options. I think it only links against a version > > of the python lib, which has been compiled for debugging. > > > > However, I want to debug my own extention - not the python interpretor. > > > > I'm not the first to have this problem: > > > > http://tinyurl.com/35ddd > > > > but that solution only works for the windows environment. > > I'm on OpenBSD, and would prefer to stay there also while debugging... > > I don't think that's relevant here. To be honest, I didn't need to add > any flags on Linux to debug my extensions. -g always gets added there > automatically. > > Perhaps this comment from distutils/unixcompiler.py will help you fixing > your build environment: > > # * optimization/debug/warning flags; we just use whatever's in Python's > # Makefile and live with it. Is this adequate? If not, we might > # have to have a bunch of subclasses GNUCCompiler, SGICCompiler, > # SunCCompiler, and I suspect down that road lies madness. > > Maybe your OpenBSD Python was compiled without -g and thus your > extensions are compiled without -g as well. > > -- Gerhard Thanks Gerhard. I think you are right - it simply grabs the options that were used for compiling the interpreter. So recompiling the interpreter would probably solve the problem. I thought I remembered that it was possible to specify your own options in the setup.py script - but I can't find it in the online manual, so maybe it is just Alzheimer. The easiest in this situation is probably to not use distutils, and simply write a normal makefile for creating that .so library. It is not hard to do, but I wish distutils could autogenerate it, and let me edit it. Most of the time distutils does a good job, and this would only be a small addition given what it does now. /Jesper From cpl.19.ghum at spamgourmet.com Sun Jul 4 04:54:44 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 4 Jul 2004 08:54:44 +0000 (UTC) Subject: Reporting References: Message-ID: Robert wrote in news:XFGFc.3928$R36.3268 @newsread2.news.pas.earthlink.net: > Planning to use python,PyQt and Postgresql for a up coming > cross-platform app. What do you guys use for reports? > > thanks; > Robert - slackware > Reportlab. www.reportlab.org Harald From tdelaney at avaya.com Thu Jul 22 20:45:24 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 23 Jul 2004 10:45:24 +1000 Subject: Generator not generating Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01BC78F5@au3010avexu1.global.avaya.com> Jeff Lowery wrote: > def plot_dist(self): > file = None; > > file = nextFile().next() # call to generator here ^^^^^^^^^^ > I trace through this in the debugger and the call to nextFile().next() > always starts at the beginning of the function (it always returns the > first file in C:/somedir). > > So what stoopid mistake am I overlooking here? I am running v2.3, BTW. You're restarting the generator every time ... Tim Delaney From tim.peters at gmail.com Fri Jul 9 16:56:06 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 9 Jul 2004 16:56:06 -0400 Subject: RELEASED Python 2.4, alpha 1 In-Reply-To: <4edc17eb.0407091037.30035e61@posting.google.com> References: <4edc17eb.0407091037.30035e61@posting.google.com> Message-ID: <1f7befae0407091356370d2c3d@mail.gmail.com> [Michele Simionato] > Uhm ... I see generator expressions have late bindings, just as list > comprehensions: > > >>> f1,f2,f3=tuple(lambda : i for i in [1,2,3]) > >>> f1() > 3 > >>> f2() > 3 > >>> f3() > 3 > > I was more in the camp of early bindings; I would like to know if late > bindings are final or subject to changes and it there a pronouncement > from Guido. Guido Pronounced: the expression in the leftmost "for" clause is evaluated immediately, but all the rest is delayed. So in your example, only "[1, 2, 3]" is evaluated at the time the genexp is created. If you had tried to iterate instead over, say, range(1/0), the ZeroDivisionError would have been raised immediately, which is the real point of evaluating that one piece "early". Don't ask me to justify the rest . Guido doesn't really care about examples like yours. He thinks genexps will overwhelmingly be consumed "on the same line" they're created, and that people doing fancy-pants stuff like you're doing there probably shouldn't (but could find more-or-less obvious workarounds if they had to, given that they're obsessed enough to try such fancy-pants stuff to begin with). The world won't end either way (IMO), and (also IMO) Python has pushed delayed code blocks in a scoped language without explicit scope declarations about as far as it can without becoming plainly incomprehensible. From fumanchu at amor.org Sat Jul 31 15:02:56 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 31 Jul 2004 12:02:56 -0700 Subject: what's the news on the pie-thon? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022DCB@exchange.hqamor.amorhq.net> Christos "TZOTZIOY" Georgiou wrote: > The only info so far: > > http://mail.python.org/pipermail/python-dev/2004-July/046568.html Glyph Lefkowitz wrote a bit more on his blog today: http://www.livejournal.com/users/glyf/ """Since everyone has been asking: Yes, Guido, being a good sport, did offer to spare Dan from the pie-thon. Dan, also a class act, baked the pies himself, and so Guido decided to share the pie with the community, and it was eaten. I am proud to have carried one of these Pies of Peace to the room where they were, after all, not thrown. However, after the Pythons were placated, the Perl community was still out for blood - delicious, banana-creme flavored blood. They (the Perl foundation) auctioned off a second pie-ing, in addition to the original Guido pie-ing, at a $500 opening bid. It sold for, if I was told correctly, $514. As the blood-thirst's description implied, they did not use a nice, baked Key Lime pie as would have been preferable. Morever, despite her circus experience, nobody asked Gina how to properly stage the pie-ing. I hope that future circus antics will be more expertly choreographed. Yes, I do have pictures.""" From mfranklin1 at gatwick.westerngeco.slb.com Mon Jul 12 16:47:48 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 12 Jul 2004 21:47:48 +0100 Subject: Database adapters References: <14BDB0C6-D43F-11D8-A64C-003065B11E84@leafe.com> Message-ID: On Mon, 12 Jul 2004 16:07:20 -0400, Ed Leafe wrote: > I'm using Python for my database work, and need to be able to connect > to various servers, such as MySQL, PostgreSQL, Firebird, and others. > There are a number of adapters available for each of these, but I run > into the same problem with all: I need to have that database server > installed on the machine for which I need to build the adapter. Since my > development work is done on a workstation and not a server, this causes > a problem. > > How do I accomplish this? How can I build, say, psycopg so that I can > connect from my dev machine to a server that's on another host somewhere > on the internet? > I can't answer for any of the databases you mention but with oracle you can install the client libraries required to get the adapter built. I guess there could be a way to do this with these other databases. Failing that build the adapters on the server machine(s) find out what libraries they require (ldd) and copy them to your desktop (this assumes that the servers and your desktop are the same platform, version etc...) Cheers Martin --- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From aahz at pythoncraft.com Wed Jul 7 09:38:51 2004 From: aahz at pythoncraft.com (Aahz) Date: Wed, 7 Jul 2004 09:38:51 -0400 Subject: REMINDER: BayPIGgies: July 8, 7:30pm Message-ID: <20040707133851.GA15231@panix.com> The next meeting of BayPIGgies will be Thurs July 8 at 7:30pm. It will feature Roger Binns talking about BitPim, a program that manipulates data on cell phones. http://bitpim.sf.net/ BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, some people meet at 6pm for dinner at Jing Jing in downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org Discussion of dinner plans is handled on the BayPIGgies mailing list. NOTE: Please RSVP by 3pm 7/8 if you want to attend the dinner. Jing Jing 443 Emerson St. (half block north of University) Palo Alto 650-328-6885 Advance notice: The August 12 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From db3l at fitlinxx.com Tue Jul 27 20:56:20 2004 From: db3l at fitlinxx.com (David Bolen) Date: 27 Jul 2004 20:56:20 -0400 Subject: Displaying print messages- Emacs References: Message-ID: Darren Dale writes: > > > > Or just start Python with -u (unbuffered) or -i (interactive) from > > within the shell. Avoids the need to change the script. > > > > I forgot to ask, how would I do this from Emacs? Well, let's assume that you're at the shell prompt from inside Emacs (how you got there could depend on your Emacs setup, whether M-x shell or some keystrokes). Then, instead of doing something like: (shell prompt) python yourscript.py do (shell prompt) python -u yourscript.py It'll run your script just as before but forceably disabling any output buffering, which it would otherwise enable automatically when detecting that its output did not appear to be a interactive (a TTY). You should see anything produced by your script in the Emacs buffer as soon as the script generates it. To answer your other question, short answer is that saying "is a tty" is more or less a shorthand for saying whether the output is being displayed to a user on an interactive device. Longer answer is that historically TTY was a teletypewriter (and still can mean that in the context of hearing impaired phone devices today), the idea being that a keyboard and display was used for communication. Over time, and particular with it's use in Unix systems, it's come to encompass the general idea of a terminal I/O device. More specifically it is common (in the Unix world) to use the term TTY to refer to an actual physical output device as opposed to other devices like pipes, files, network sockets, etc... So saying that output "appears to be a TTY" is a shorthand way of saying that the output device appears to be a true interactive display device rather than output being redirected to a file or other connection. There's even a (fairly portable) C library routine called "isatty" (is a tty) that Python uses to determine this. It's not uncommon for an application (generally through default behavior of the platform C library) to adjust buffering based on that status, so as to be more efficient in the non-TTY case where interactive latency of display is not as important as utilizing the bandwidth to the output device most effectively. Generally speaking, when one process opens a pipe or otherwise controls another process, it won't appear to be a TTY to the other process, since that process' output is going through some system object (for example, a pipe). There are packages that in fact exist soley to simulate TTYs (or provide PTTYs, Pseudo-TTYs) to better simulate a user running an application, such as Expect. Anyway, when Emacs is running the child shell, it executes that shell as a child process for which it controls the I/O, but the connection between Emacs and that child process is not perceived as a TTY by the system, and thus nor by Python, so it permits more efficient buffering to take place. Unfortunately, that more efficient buffering is not what you want when you are working with something interatively. Using the -u command line option tells Python to disable all output buffering regardless of the TTY status of it's output. This is actually even less efficient than the default TTY state (which is typically line buffered) but it ensures you'll see everything on the output as soon as it is generated. You can also get the same effect by having the PYTHONUNBUFFERED environment variable set when you start python. -- David From squirrel at WPI.EDU Mon Jul 12 12:11:30 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 12 Jul 2004 12:11:30 -0400 Subject: datetime.iterdate In-Reply-To: <7pb5f0pbst3mistd1ju3q8qk4mcqbct1o6@4ax.com> References: <7pb5f0pbst3mistd1ju3q8qk4mcqbct1o6@4ax.com> Message-ID: On Mon, 12 Jul 2004, Christos TZOTZIOY Georgiou wrote: > On Mon, 12 Jul 2004 09:20:38 -0400, rumours say that Christopher T King > might have written: > > [snip of a<=x<=b proposition to replace xrange] > > >To work perfectly, my > >proposal needs only a slight change in the parser (to compile a >(a >affect existing code though. > > A lot of code is based on "x and y" evaluating y only if x is true... Oh no, I don't mean to replace "x and y" with "x&y", I mean to replace the expansion of "x Explicit type checking is not typically seen in Python code, and usually that's not a big problem; most typing errors are likely to raise a TypeError or AttributeError sooner than later. There are cases, though, where typing errors are not caught (at least not early) because different classes happen to have methods with the same name; that's really subtle with the special methods like __eq__, __hash__, etc. that are common to all (or at least many) classes. It happened to me when I was passing arguments of some type B to a function instead of the correct type A; these arguments were entered as keys in a dictionary, and since both A and B were hashable the interpreter didn't complain. Of course, when later I was trying to retrieve the A()s I thought I had entered, I couldn't find them (debugging was even harder in this case because B was essentially a wrapper for A and the __str__ of both classes was deliberately the same, so the A()s appeared to be in the dict; that's not the issue here though). I wonder if people have come up with such pitfalls in practice or I was just careless. In any case, I was tempted enough to write a simple extensible runtime type checking module, which can be handy, at least during development. It's extensible in the sense that a "type" can be any constraint, not just a python type or class. Here's an example of usage: def foo(name, age, children, phonebook): assert TypeChecker.verify( (age, int), (name, TupleOf((str,str))), (children, ListOf(Child)), (phonebook, DictOf(str, ContainerOf(Phone)))) foo(name = ("Paul", "Smith"), age = 23, children = [Child(), Child()], phonebook = { "Mike": (Phone(), Phone()), "office": [Phone()] }) ContainerOf, TupleOf, ListOf and DictOf are all extensions of the abstract TypeChecker class, providing some limited but common templated-type checking. Of course in practice most complex structures (e.g. phonebook) would be encapsulated in a class, so it's questionable whether such functionality adds up anything to a list of "assert isinstance(object,type)" statements. Any ideas or suggestions are welcome. George From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Fri Jul 16 11:08:23 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Fri, 16 Jul 2004 15:08:23 +0000 (UTC) Subject: Any suggestions for a Unified Information Manager ? Message-ID: Does anyone know of a tool (python, obviously ;-) for managing ALL your information needs in one place? I'm talking about contacts,email, ICQ/MSN, Website favourites, RSS, To-do lists, infobases, faqs, newsgroups etc.etc. etc. I thought I'd find a Zope app to do something like this, but couldn't find anything. What I want to do is route all my information needs through a web-visible service on a PC at my house for central storage, search facilities etc. I'd even route SMS messages with the system through an SMS2EMAIL gateway so they'd be stored against the relevant contact. I'd then be able to access ALL my information from anywhere (security would be a vital feature here) via a single portal (so throw away separate outlook, newsreader,msn client, rss client etc). I think there's a microsoft passport application doing something similar (can't remember the name, was it my.net?) allbeit on a smaller scale, but I simply wouldn't trust them with all my data. Any ideas anyone? From jeff at ccvcorp.com Mon Jul 26 19:45:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 26 Jul 2004 16:45:46 -0700 Subject: File upload using httplib In-Reply-To: <23ae7099.0407260514.63f41232@posting.google.com> References: <23ae7099.0407260514.63f41232@posting.google.com> Message-ID: <10gb5su9a4h2v43@corp.supernews.com> alastair wrote: >Hi, > >I'm attempting to test out some functionality of the Apache http >server. What I'd like to do is send a file to the server - eg. a text >file or binary file (I will be testing gzipped transfers eventually >...). > Keep in mind that, in order to send a file, you must use a content type of multipart/form-data, rather than your current application/x-www-form-urlencoded. Neither urllib nor httplib directly support multipart/form-data, but (as someone else pointed out when I asked about this very recently) there's a recipe for it in ActiveState's Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 Note that the recipe uses an older httplib.HTTP() interface rather than the newer (and preferred) httplib.HTTPConnection() interface. However, the only change necessary to use the new interface (beyond changing the inital call) is to change the h.getreply() to h.getresponse(), and handle the HTTPResponse object properly. Jeff Shannon Technician/Programmer Credit International From squirrel at WPI.EDU Sun Jul 25 16:26:10 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Sun, 25 Jul 2004 16:26:10 -0400 Subject: JPEG2000 support? In-Reply-To: <54ubt1-nrn.ln1@lairds.us> References: <54ubt1-nrn.ln1@lairds.us> Message-ID: On Sun, 25 Jul 2004, Kyler Laird wrote: > I'm getting ready to build an application around a big JPEG2000 > image but I haven't found any Python support for JPEG2000. > > I plan to just use an external call to JasPer to handle the > conversion for now but I'd prefer to have a better integrated > solution. Are any Python libraries likely to have support for > it soon? My searches are yielding surprisingly little. PyMagick is a Python interface to the powerful, cross-platform ImageMagick graphics package, which supports JPEG2000 through an external library. So unlike something like PIL, you'd also need to install ImageMagick (compiled with JPEG2000 support) and a JPEG2000 library, but it seems to be very well integrated with Python, PIL, and numeric. Hope this helps. From peter at engcorp.com Wed Jul 14 14:30:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Jul 2004 14:30:52 -0400 Subject: returning a value from a thread In-Reply-To: References: Message-ID: Ken Godee wrote: [detailed version of the question in the subject line] This question is asked often enough that it maybe should become a FAQ, but in any case it was asked a few weeks ago and I posted sample code with the idiomatic approach, as I recall. A Google Groups search with your keywords and my name should find it pretty quick. -Peter From tim.peters at gmail.com Sat Jul 3 00:02:54 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 3 Jul 2004 00:02:54 -0400 Subject: rounding errors? In-Reply-To: References: Message-ID: <1f7befae04070221024c07b3d0@mail.gmail.com> [todd] ... > >>> .21 > 0.20999999999999999 > >>> > > Now, I realize that this is really small errors.. Does anybody have an > explanation why Python picks up or loses these? Many people do, and a few of them are even correct . If you start here, you can stop here too: http://docs.python.org/tut/node15.html From follower at gmail.com Fri Jul 2 13:15:03 2004 From: follower at gmail.com (Follower) Date: 2 Jul 2004 10:15:03 -0700 Subject: [ANN] libgmail 0.0.1 -- Gmail access via Python References: <3c18c08f.0407011159.9243ee1@posting.google.com> Message-ID: <3c18c08f.0407020915.1c408cb7@posting.google.com> > Announcing initial version of a library to provide access to Gmail via > Python. This library now has a home on SourceForge: --Phil. From f.geiger at vol.at Mon Jul 12 05:56:53 2004 From: f.geiger at vol.at (F. GEIGER) Date: Mon, 12 Jul 2004 11:56:53 +0200 Subject: Proposal: runtime validation statement In-Reply-To: <7xy8lq9rjx.fsf_-_@ruckus.brouhaha.com> References: <7xy8lq9rjx.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I frequently find myself writing stuff like > > # compute frob function, x has to be nonnegative > x = read_input_data() > assert x >= 0, x # mis-use of "assert" statement > frob = sqrt(x) + x/2. + 3. > > This is not really correct because the assert statement is supposed to > validate the logical consistency of the program itself, not the input > data. So, for example, when you compile with optimization on, assert > statements become no-ops. And yet, it's generally desirable to > validate input whenever you can, and raising an exception is > frequently the right thing to do with bad data. A function like > > class ValidationError(Exception): pass > def _validate(cond, message): > if not cond: raise ValidationError, message > > takes care of it, of course, so it's slightly redundant to add a > special statement like > > validate x >= 0, (x, "must not be negative") > > which works exactly like assert but raises a different exception and > is never optimized away. But the same can be said of the print > statement (use sys.stdout.write or a print function instead) and for > that matter the addition operator (use "x - (-y)" instead of x+y), the > bool type (use 1 and 0 instead of True and False), etc. > > We have to conclude that choosing what statements the language > supports is not just a matter of making things possible, but also of > steering what the common idioms should be. Using a user-defined > function to check input means a couple more program-specific things to > remember (the function itself and the exception class it raises), > clutters up the code, etc. And so I've come to feel that a "validate" > statement (maybe with some different keyword) like the above is in the > Pythonic spirit and should be considered for some forthcoming release. > > Thoughts? I use assert to protect my software from me, i.e. to catch programming errors, e.g. to catch cases where I called a method the wrong way. If this can happen under production consitions too, then it's a user error, not a programming error. So, I use raise to protect my software from user errors. Your sample seems to be a case of the latter, i.e. you have to write some sort of exception handling anyway. Issuing an error message anywhere in your code might not be what you really want. Kind regards Franz GEIGER From martin at v.loewis.de Sun Jul 18 16:42:46 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 18 Jul 2004 22:42:46 +0200 Subject: namespace for released packages? In-Reply-To: <40F716E4.10708@tardis.ed.ac.molar.uk> References: <40F716E4.10708@tardis.ed.ac.molar.uk> Message-ID: <40FAE0C6.8020900@v.loewis.de> Alex Hunsley wrote: > What is the python convention for namespaces of released packages? In > Java you'd write your domain name (if you have one) backwards, this: > > uk.org.ohmslaw.myPackage > > ... thus ensuring uniqueness. Is it the same for Python? No. If a Python library is released as a package, the author choses a package name that is unlikely to collide. Typically, such a name is readily available, as the project team developing the package has found a "product name" already. That product name stays with the package even if the affiliation of the authors changes. I find the Java convention evil - it brings into source code affiliation information which really doesn't belong there. Instead, package authors should come up with names that uniquely identify their software in the first place. Regards, Martin From tim.golden at tesco.net Mon Jul 19 15:49:52 2004 From: tim.golden at tesco.net (Tim Golden) Date: Mon, 19 Jul 2004 19:49:52 +0000 (UTC) Subject: How to activate a new window in Python In-Reply-To: <3c9e9b1b.0407190928.61b1b292@posting.google.com> References: <3c9e9b1b.0407190928.61b1b292@posting.google.com> Message-ID: Milon wrote: > Hi all, > > I am new to Python, and I just wrote a simple script to launch an > application from the windows's start menu's run command. (see code as > follow) There is an "OK" button on the new application I launched, > but I can't get Python to click on it because the new window is not in > focus and I read somewhere off the web that I need to activate the new > window first before I can do anything on the new window. I couldn't > find any useful information off the web, so, can someone please show > me how to do it? [... snip example code ...] Have a look at: http://www.brunningonline.net/simon/blog/archives/000652.html TJG From alexendl at hotmail.com Fri Jul 16 18:58:26 2004 From: alexendl at hotmail.com (Alex Endl) Date: Fri, 16 Jul 2004 17:58:26 -0500 Subject: help fast question Message-ID: <10fgnc8jsdd2779@corp.supernews.com> Ok i took an intro to programming class in school, and decided to work on python in the summer. a few thing 1)how do I make a variable a random # a = randint(1,5) seems logical, but i cant find a directory of commands to figure it out. 2)i cant find much info on sockets, and thats a big reason i want to program. what im trying to figure out is something that goes to a website, picks up some specified text, and shows it on the screen. is this possible? From aisaac at american.edu Fri Jul 30 14:33:07 2004 From: aisaac at american.edu (Alan G Isaac) Date: Fri, 30 Jul 2004 14:33:07 -0400 Subject: set to array Message-ID: <10gl500c9p92oe6@corp.supernews.com> Numeric.array(myset) returns an array with one element, which is the set. i. Even allowing that sets are not sequence types, is this not surprising? ii. What is the best way to produce an array of the set elements? Thanks, Alan Isaac From eric_brunel at despammed.com Thu Jul 8 04:41:02 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 08 Jul 2004 10:41:02 +0200 Subject: Why would I learn Python over other languages? References: <7x7jtfugh8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Charif Lakchiri" writes:[snip] [snip] >>Does it support GUI programming? Sorry: I couldn't resist: > Hmm, yes, although the official GUI toolkit (tkinter) is cumbersome, Obviously depends on who's talking: I personnaly always found *other* GUI toolkits cumbersome (I've tested wxPython and PyQT) > doesn't look so great on the screen, It seems to be the general opinion, but there is some work to make it better on the tcl/tk side; see http://tcl.projectforum.com/tk/Home > and is poorly documented. No it isn't; there are a lot of Tkinter resources around, not to mention plain tk ones. I do agree that they may be hard to find, but they exist. The docs for the other toolkits I've tried were usually worse than the ones for Tkinter (things may have improved for wxPython, since I tested it quite a while ago) -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From ext-sateesh.kavuri at nokia.com Wed Jul 7 07:44:41 2004 From: ext-sateesh.kavuri at nokia.com (Sateesh) Date: Wed, 07 Jul 2004 11:44:41 GMT Subject: Python indentation References: Message-ID: I surely understand the importance of indentation, but as you see there are beautification tools that can be used to beautiy the C code. Also indentation is based upon ones style of coding, and I feel somewhat restricted when the language itself restricts someone to code in a particular way. Sateesh "Brian Quinlan" wrote in message news:mailman.61.1089200252.5135.python-list at python.org... > Sateesh wrote: > > Why can't the indentation not so strict so as to give better freedom to the > > user? > > Can you specify what desirable construction Python is denying you? Or > are you talking about freedom in the abstract? > > Cheers, > Brian From olli at haluter.fromme.com Wed Jul 7 08:13:20 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 7 Jul 2004 12:13:20 GMT Subject: useless destructors References: <2ktlakF6atfrU2@uni-berlin.de> Message-ID: <2l27n0F7vks1U1@uni-berlin.de> Aahz wrote: > Oliver Fromme wrote: > > PS: I didn't bother to try lynx, because it is the least useful > > browser anyway. :-) Actually I'm surprised that there are still people > > who insist on using it, since there are better alternatives such as > > links or w3m. > > They work better as browsers, technically, but their keyboard operations > are much poorer. Can you be a little more specific, please? The keyboard navigation of links particularly mimics that of lynx pretty closely, as far as I can tell. However, I agree that the navigation in w3m is somewhat different (but it has its advantages, too, once you get used to it). Well, it's all a matter of taste, I guess. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From aborder at users.sourceforge.net Sun Jul 11 11:28:11 2004 From: aborder at users.sourceforge.net (Anakim Border) Date: Sun, 11 Jul 2004 17:28:11 +0200 Subject: Web Scraping/Site Scraping In-Reply-To: References: Message-ID: <200407111728.12075.aborder@users.sourceforge.net> > Hi, I'm interested in learning about web scraping/site scraping using > Python. I found this document interesting: http://www.rexx.com/~dkuhlman/quixote_htmlscraping.html HTH -- Anakim Border aborder at users.sourceforge.net From stephen.no at spam.theboulets.net.please Tue Jul 27 09:40:01 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Tue, 27 Jul 2004 08:40:01 -0500 Subject: Help with optionparse recipe References: <4edc17eb.0407270414.35bef24b@posting.google.com> Message-ID: Michele Simionato wrote: > It is the docstring. Try with this: > > """An example script invoking optionparse, my wrapper around optparse. > > usage:?%prog?[options]?args > -f,?--file=FILE:?file?to?attach > -s,?--subject=SUBJECT:?email?subject > -a,?--address=ADDRESS:?email?address > """ Thanks! -- Stephen If your desktop gets out of control easily, you probably have too much stuff on it that doesn't need to be there. Donna Smallin, "Unclutter Your Home" From lbates at swamisoft.com Mon Jul 19 10:38:50 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 19 Jul 2004 09:38:50 -0500 Subject: Run as service References: Message-ID: You should probably get your hands on Mark Hammond's, excellent book, Python Programming on Win32. It has a very good section on writing services. I'm not sure you want this to run as a service. Also take a look at Sam Rushing's site. There is an example of a POP3 mailbox system-tray app. Should be a good example to work from. It may already to what you want. HTH, Larry Bates Syscon, Inc. "Andr? Nobre" wrote in message news:mailman.509.1090009498.5135.python-list at python.org... > Hello, > i?m starting with python and i made this little piece of code, to know > if i have new mails to receive. > > import poplib, getpass > arquivo = 'mails.txt' > info = file(arquivo).read().split('\n') > d = {} > for e in info: > a = e.split('\t') > print "Verificando e-mail de %s" % (a[1],) > p = poplib.POP3(a[0]) > p.user(a[1]) > p.pass_(getpass.getpass()) > print "\n%s mensagens em seu mailbox.\n" % p.stat()[0] > p = None > print "Final" > > > it gets some information from mails.txt* file and watch new mails. I > want to know how to leave this code running as service under windows and > send a warning message (like that windows popup messages) when a there > is a new e-mail. > > * my file is like this (simple text) > mailserver \t maillogin \n > > Tkz and sorry about my english.... > > -- > Andr? From peter at engcorp.com Wed Jul 28 12:07:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jul 2004 12:07:08 -0400 Subject: eval() of empty string hangs In-Reply-To: <4107c099$1@buckaroo.cs.rit.edu> References: <5uidnRYv-6DqK5rcRVn-vQ@powergate.ca> <4107c099$1@buckaroo.cs.rit.edu> Message-ID: Chris Connett wrote: > Is it > possible that the exception is propagating up the wrong stack? This is > a separate thread, could it be on the main thread somehow? The creating > thread has ended by the time this exception is due to be raised. This doesn't make sense to me. What do you mean by 'creating thread'? If it's what I think you mean, then either it's not really the creating thread, or it hasn't really ended yet... after all, how could a thread that has ended cause an exception to occur? From sridharinfinity at gmail.com Sat Jul 24 03:32:23 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 24 Jul 2004 00:32:23 -0700 Subject: Safe process execution support in Python Message-ID: I like to execute programs from python. .. not by using os.system .. bcoz .. 1. the process could easily eat up the CPU 2. the process could use signal system call to even kill all other process of it's UID. 3. take more disk space, by writing big files 4. and lot more one could think of .. I know about resource module in python. Hope u understand my problem, is there any effective way to achieve this? From gmuller at worldonline.nl Sat Jul 17 13:24:15 2004 From: gmuller at worldonline.nl (GerritM) Date: Sat, 17 Jul 2004 19:24:15 +0200 Subject: is there an encyclopedia of software concepts? References: Message-ID: <40f960ce$0$62375$5fc3050@dreader2.news.tiscali.nl> "Stephen Ferg" schreef in bericht news:b16e4ef7.0407170806.2c84dec9 at posting.google.com... > > Lately I've been interested in what the word "framework" means, in the > context of software development. As in "XXX is a GUI development > framework". And I'm wondering things like "Where does the term > 'event-driven' (as in 'event-driven programming') come from? When was > it first used, and by whom?" And other similar questions. Try http://www.cetus-links.org/software.html regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From benevilent at optusnet.com.au Thu Jul 22 07:23:35 2004 From: benevilent at optusnet.com.au (benevilent at optusnet.com.au) Date: Thu, 22 Jul 2004 21:23:35 +1000 Subject: assertion error Message-ID: <40FFA3B7.6040109@optusnet.com.au> Hey, I'm getting an assertion error as a result of embedding python. "Modules/gcmodule.c:231: visit_decref: Assertion `gc->gc.gc_refs != 0' failed." I only get this assertion error with Python compiled with debugging flags, rathen than the standard library which comes with Debian. Using gdb I know on what type the object is, which is involved in the assertion. It is a subclass of a built-in type which I have defined. This subclass has variables which can cause instances of the subclass to participate in circular references (the built-in type I have defined itself has no member variables). Removing the circular references seems to avoid the error. I was under the impression that python can detect circular references, and that this should not be a problem. Any suggestions as to what else the problem might be? Thanks, Laurie From squirrel at wpi.edu Sat Jul 10 12:09:28 2004 From: squirrel at wpi.edu (Chris King) Date: Sat, 10 Jul 2004 12:09:28 -0400 Subject: .py from .pyc - how? Have deleted my .py file! In-Reply-To: References: Message-ID: <10f055jioiih609@corp.supernews.com> Matthias Huening wrote: > "F. GEIGER" wrote in news:ccp1gi$mpf$1 at newshispeed.ch: > >>However, the .pyc file is still there. Can I restore the .py file from >>the .pyc file somehow? > > > http://www.crazy-compilers.com/decompyle/ > > There is one drawback: > "# Costs only 10 EUR per 10 KB (or part thereof, counted per file)" There seems to be a free version still floating around, but it doesn't work for bytecode generated by Python 2.3 or newer: http://www.pypackage.org/packages/python-decompyle From cmg at dok.org Wed Jul 21 14:19:12 2004 From: cmg at dok.org (Chris Green) Date: Wed, 21 Jul 2004 14:19:12 -0400 Subject: Linux, fcntl, F_SETLEASE and signals References: <871xj5jpf6.fsf@ion.xlipstream.com> <2d9e37f90407211003789037b7@mail.gmail.com> Message-ID: <87y8ldgr4v.fsf@ion.xlipstream.com> John Lenton writes: > sorry, I got the wrong end of the stick. But ctypes lets you do what > you want, anyways. Portable as Linux :) Thanks for pointing me to that. Seems like a very interesting module. It may help me out :) -- Chris Green Let not the sands of time get in your lunch. From dd55 at cornell.edu Tue Jul 13 15:48:05 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 13 Jul 2004 15:48:05 -0400 Subject: Visual Studio not installed Message-ID: Hello, I have not been able to run "python setup.py install" on several packages, receiving the following error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isnt installed. Could someone explain what this means? I am working on windows XP at the moment, but when I move to Linux, does this mean I will not be able to install from source? From m.bless at gmx.de Tue Jul 6 08:36:25 2004 From: m.bless at gmx.de (Martin Bless) Date: Tue, 06 Jul 2004 12:36:25 GMT Subject: class MyList(list): Is this ok? Message-ID: <40ea99e8.20568968@news.versatel.de> Please have a look at my little program below. It works as expected but I still feel very unsure when inheriting from builtin types. Do I need line #1? Is line #2 ok? Why? I came to this one more by trial and error than by conclusion. My fingers wanted to write "self.append(v)" which creates a nice infinite loop ... I have read the article about "Unifying types and classes" by GvR http://www.python.org/2.2/descrintro.html several times but probably would need more practical examples or another tutorial. Martin import csv,sys class ColumnCollector(list): def __init__(self): self.sums = [] list.__init__(self) #1 def append(self, v, calc=None): list.append(self,v) #2 i = len(self)-1 try: self.sums[i] except IndexError: self.sums.append(0) if calc: if "sum" in calc: self.sums[i] += v if 1 and __name__=="__main__": print csvw = csv.writer(sys.stdout) cc = ColumnCollector() for rownum in range(4): cc.append(1,"sum") cc.append(2,"sum") cc.append(3,"sum") csvw.writerow(cc) del cc[:] print "totals:" csvw.writerow(cc.sums) """ Should print: 1,2,3 1,2,3 1,2,3 1,2,3 totals: 4,8,12 """ From daveweb at portico-services.net Thu Jul 22 12:39:19 2004 From: daveweb at portico-services.net (Dave Walker) Date: Thu, 22 Jul 2004 12:39:19 -0400 Subject: Problems with pygtk/gtk.glade Message-ID: <40ffed62$1_1@news.iglou.com> I've just setup a new box with Slackware 10, and am running into problems with simple programs that worked just fine on my old slak box (and still do). The only difference I can see between the two boxes is that the new one is running python 2.3.4, and the old is 2.3.3. The code is a barely modified version of one of the tutorials, and the errors I get are: Traceback (most recent call last): File "./oldmp3.py", line 78, in ? app=appgui() File "./oldmp3.py", line 15, in __init__ self.wTree=gtk.glade.XML (gladefile,windowname) TypeError: typedict must be a mapping And, as a matter of fact, when I try and run MathFlash from the tutorial in the latest Linux Journal, I get similar errors: Traceback (most recent call last): File "./MathFlash-final.py", line 165, in ? main(sys.argv) File "./MathFlash-final.py", line 158, in main w = MathFlash() File "./MathFlash-final.py", line 34, in __init__ self.init() File "./MathFlash-final.py", line 75, in init GladeWindow.__init__(self, filename, top_window, widget_list, handlers) File "/root/bin/GladeWindow.py", line 77, in __init__ self.xml = gtk.glade.XML(fname) TypeError: typedict must be a mapping Has something changed in the latest version of python, or is there something else in my setup that I've missed that is causing these errors? I've searched google/google groups in vain... Any assistance would be greatly appreciated. Thanks, From eldiener at earthlink.net Sat Jul 31 10:33:05 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sat, 31 Jul 2004 14:33:05 GMT Subject: Comments within a line References: <2n139cFrn37mU1@uni-berlin.de> Message-ID: Heike C. Zimmerer wrote: > "Edward Diener" writes: > >> Has there ever been any discussion of adding comments notation to >> Python, such as C++'s /* */, which could occur in the middle of a >> line or span multiple lines ? I would like to see it as a more >> elegant solution for quickly commenting out code. > > In C/C++, you wouldn't use /* */ for commenting out code, since it > would collide with any comment already there (comments can't be > nested). That's true but many times it will not, especially if one comments out code within a line, or if one is using // liberally also. > Instead, the usual way is using #if 0 ... #endif. Yes, this is the usual method in C++ which I often use, but Python has no preprocessor. > > You can use "if 0:" with python as well, but of course, you'd have to > indent the entire commented-out block. With most editors, this isn't > much of a problem. I usually use some smaller, "odd" indent than > usual to have an indicication later where the block ends. Decent idea. Still some sort of multi-line comment notation in Python would be preferable. From crap at crap.crap Sat Jul 10 15:42:36 2004 From: crap at crap.crap (Moosebumps) Date: Sat, 10 Jul 2004 19:42:36 GMT Subject: List Comprehension Syntax References: Message-ID: > What I like about LCs is that they made sense to me before reading the > documentation - they just came across as very expressive of what was > happening. I use the simplest forms, i.e. > > [op(x) for x in y] > [x for x in y if z] > (as well as some slight variations) That's true, I tend to use the simplest forms too -- but then that is not as maintainable. We all know that things don't always stay so simple. There is always something you need to add. IMO with that in mind, it is easier to keep everything consistent, then to try to "sneak in" the LC for the simpler cases. You would end up flipping back and forth too much when you need to add a condition, or add an expression. > > quite a bit, but rarely do I use the more complex forms (e.g. multiple > for's) because (1) the meaning doesn't jump right out as quickly (to me) > and (2) the more complex they are, the more they seem like a fancy trick > rather than the right thing to do. > > But most any time you're using map or filter or basically doing: > > L = [] > for item in L2: > L.append(op(item)) > > the LC form is often more desirable because it screams "I'm taking a > sequence and using it to create a list" - the intent of the code is very > clear. And by extension, if you're using an LC to do something obtuse, > you deserve a slap on the wrist (e.g. you write [f() for f in x] and > throw away the resulting list). > > >> Now that genexps are coming around, you'll be facing even bigger > >> payoffs. So just keep using them, even if they might not feel as > >> maintanable at the moment. LC's (and genexps even to a bigger extent) > >> are pretty much what defines the "pythonic" way of doing things for me > >> these days. > > > > this is not meant to be picking on you in any way shape or form but my > > experience has been that any time you find yourself having to "thinking > > in the language", you are not really solving the right problem and are > > more likely using a collection of magic tricks to confound and amaze > > others and possibly insure job security. > > That's not what I understood by Ville's comment. I think he just meant > that LC's (and genexps) are powerful tools in the Python toolbox, and > useful enough that the OP should continue working to become familiar > with them. They're not obscure magic tricks but "first class" features > of the language. > > I've seen many comments on c.l.py to the effect of "LCs seem bad because > they can abused", citing bizarre made-up examples with 4 loops and as > many if statements. Those *are* magic tricks and should be avoided, but > then again any feature can be abused. > > > if you have models that can be implemented independent of the language > > and you can express a problem in terms that are natural to the problem, > > you invariably have a better solution for the people following you as > > well as the machine. > > > > generalize, don't pythonize. > > I'm not so sure. Why program to the lowest common language denominator? > I don't suggest going to the extreme to use obscure language quirks just > because you can, but it doesn't make sense to avoid using a feature at > your disposal because it's unique to a language (or, in this case, a > small set of languages). > > Half the reason you use one language over another is because of the > toolset it gives you. In the case of list comprehensions, they are > usually chosen for the very reason that they *do* allow you to express a > problem in natural terms. > > -Dave From donn at drizzle.com Fri Jul 23 00:58:46 2004 From: donn at drizzle.com (Donn Cave) Date: Fri, 23 Jul 2004 04:58:46 -0000 Subject: befuddled by os.exec functions References: Message-ID: <1090558725.78082@yasure> Quoth Avi Kak : | 1) How does one get one of the os.exec functions | in Python to execute a shell script that | includes some sort of a control structure in | the shell script itself? | | For example, I can do the following in Perl | | $ENV{ACK_MSG} = "You said: "; | exec('while a=a; do read MYINPUT; echo $ACK_MSG $MYINPUT; done'); | | How can one use one of the os.exec functions | in Python to do the same? All of the os.exec | functions require a pathname for the first | argument, followed by well-defined arguments. | But the above example does not break down | into pathname and argument components. As you probably know, the os (posix) module also provides a system() function that does what you describe. While that's actually implemented by calling a C library function, this would be about the same: def system(cmd): pid = os.fork() if pid: ... else: ... os.execve('/bin/sh', ['sh', '-c', cmd], os.environ) That pathname and arguments are implicit in your example. (Well, I don't know what your example actually does, since I haven't used Perl for many years.) | 2) In the following example, I am mystified as | to why the first element of the list in the | second argument has to be ignored. If it is | going to be ignored anyway, why does it need | to be supplied at all? The following call | does the same regardless of what one has in the | first element of the second-arg list. | | os.execvp( 'ls', ['ls', '-al'] ) It's up to the application - some applications look at this value, sys.argv[0] in Python, others don't. "ls" may actually use it for a "usage" message - try os.execvp('ls', ['xx', '--yikes']) and then there are various situations where argv[0] is used in some more significant way. So it's useful to be able to provide a value for argv[0] separately from the execution path. Donn Cave, donn at drizzle.com From peter at engcorp.com Tue Jul 6 18:38:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jul 2004 18:38:25 -0400 Subject: Typed Python? In-Reply-To: References: Message-ID: Michael Sparks wrote: > And whilst this might seem a trivial point, it's worth remembering that > new users generally don't interpret things you expect. For example: > > if x is not None: > print "hello" > else: > print "Goodbye" > > Looks pretty unamiguous to a programmer's eyes. The most interesting > description I've heard from a non-programmer looking at that is: > "If x is something, print 'hello' and if that fails print 'goodbye'" Was your sample non-programmer a native English speaker? I don't know anyone who interprets "if/then/else" as implying some kind of exception mechanism, programmer or not. > ie something semantically more like: > > if x is not None: > try: > print "hello" > except: > print "Goodbye" That's ludicrous. Is it possible _you_ were misinterpreting what your non-programmer meant by "if that fails"? -Peter From anthonybaxter at gmail.com Mon Jul 12 06:55:40 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Mon, 12 Jul 2004 20:55:40 +1000 Subject: RELEASED Python 2.4, alpha 1 In-Reply-To: <4edc17eb.0407091037.30035e61@posting.google.com> References: <4edc17eb.0407091037.30035e61@posting.google.com> Message-ID: > Uhm ... I see generator expressions have late bindings, just as list comprehensions: I think you'll find if you check the PEP that this is the decision of the BDFL. The feeling was that early binding was too different and would lead to more confusion than late binding. While late binding can give suprising results if you're not aware of it, it is at least consistent with other language features (such as lambdas and list comps) Anthony From jacek.generowicz at cern.ch Sun Jul 11 04:30:37 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: Sun, 11 Jul 2004 10:30:37 +0200 Subject: Modifying func_closure In-Reply-To: References: Message-ID: <95DCD086-D314-11D8-83ED-000A95909800@cern.ch> On 11 Jul 2004, at 06:17, Robert Brewer wrote: > I asked: >> Which immediately brings up the question: why not use a >> class instead? > > to which Jacek replied: >> a) The closure is faster, and my inner loops consist almost >> entirely of them. >> >> b) The closure is much clearer, shorter and more convenient. >> I have so many of these things that using the class version >> would make the code a real mess. >> >> c) The closure can be stuck on to a class, and works as a >> method (bound & unbound and all that). >> >> d) The outer function which creates the closure can be a method >> of a class. >> >> Probably quite a few more ... > > I have to wonder about 'b'; does anyone have an example where a > closure is clearer? Well, I guess that you can't argue with it being shorter and more convenient: with the closure you do away with the constructor (in which you explicitly enclose the variables you need), and you don't need to use "self" to refer to the enclosed variables in the closure itself. If you have only one closure, referring to the state, then the class-based version can use __call__ to simulate function-call syntax, but if the state is shared between more than one closure, you need to prepend calls with some instance name. All this is just simple fact: the closure version is more concise. Whether it's clearer, is, of course, a matter of opinion. If Python formed your programming mind, and you believe in the third line of the Zen of Python to the extreme, then you will probably find the class-based version clearer; if you are comfortable with lexical scoping, then you will probably find the closure clearer. Personally, I (would) find it annoying to have to install the plumbing myself every time. In the application I'm writing at the moment, I have many functions which generate other functions. When I need the generated function to have some state, it requires exactly zero extra effort on my part: I merely refer to the variable just like any other, and it works. If I had to use the class, I would need to rewrite the code, add the plumbing, the generated function would require extra work before it could be used as a method (and it's impossible before Python 2.3[*]), and I wouldn't be able to generate it in methods of a class. Sorry, I'm not going to come up with code samples showing that the closure is clearer, because the class-based version is (to me) so inconvenient that I just can't be bothered to even try to make it work in the interesting situations. > Yes, this means you have to invent syntax to mutate the cell variable > if you want to discuss it. ;) Having perused previous discussions, I > think I'm favoring the 'lexical'/'outer' keyword idea; seems we're > just waiting for someone to write a PEP... A "lexical" keyword would (sorry, I haven't googled for the discussions, so I'm guessing what was proposed: essentially the same as the "global" keyword) certainly be least surprising to Pythoneers, but it would require the introduction of a new keyword, which means any such proposal is likely to be rejected. An alternative solution, coming from the "Classes are Python's mechanism for sharing state" school of thought, could be to endow classes and instances with the function descriptors which are responsible for binding methods - not sure what would happen when you want an instance method to be bindable again ... or some approach based on subclassing FunctionType. But the bottom line is, when I want functions which happen to have some state, I really don't want to have to go to the hassle of simulating them with classes. Closures are an extremely, simple, easy, clear and efficient way of adding state to a functon. It's just a pity that that state is not mutable. [*] I may be wrong about this, as I don't actually use the class version myself, so I don't really care ... but I think there was an issue with MethodType not being instantiable before Python2.3 (or something along those lines, at least). IIRC, Michael Hudson pointed out to me that something which I assumed did not work (because it didn't in 2.2), actually did work (in 2.3) ... all on c.l.py. From jlenton at gmail.com Wed Jul 7 17:37:54 2004 From: jlenton at gmail.com (John Lenton) Date: Wed, 7 Jul 2004 18:37:54 -0300 Subject: reading file contents to an array (newbie) In-Reply-To: References: Message-ID: <2d9e37f904070714371bb552bb@mail.gmail.com> On Wed, 07 Jul 2004 17:03:42 -0400, Darren Dale wrote: > One more thing, I am reading into arrays that can be 5000 cells wide, > and arbitrarily long (time-resolved scientific data.) The datafiles are > reorganized such that only 16 columns are listed on a line, and a '\' > character indicates that the row continues on the next line of the file. > Do you have ideas of how to quickly reconstruct these rows? I think mmap > gets me half the way there, but should I try to avoid testing each > readline for the presence of a '\' character? you can either build the string and then split it again, line = m.readline() while line.endswith("\\\n"): line = line[:-2] + m.readline() Or, you could build the array bit by bit, which gets a bit messy but might be faster (you'd have to test it) more = True while more: row = array() while True: line = m.readline() if not line: more = False # goto end row.extend(map(float, line.split()[:16])) if not line.endswith("\\\n"): break data.append(row) as usual in this kind of example, the code is very fragile and you'll want to generalize it a bit before using it "production". -- John Lenton (jlenton at gmail.com) -- Random fortune: bash: fortune: command not found From kamikaze at kuoi.asui.uidaho.edu Mon Jul 12 17:50:34 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 12 Jul 2004 21:50:34 GMT Subject: Interactive Python programming in ... vi [was: Tab wars revisited] References: Message-ID: Jacek Generowicz wrote on 12 Jul 2004 16:57:40 +0200: > Chris Share writes: >> On Wed, 07 Jul 2004 18:36:05 -0400, Peter Hansen wrote: >> > I'm actually pretty inept with vi (or vim), to the point that I don't >> > actually know how to configure it for use with Python. >> FYI, it's pretty simple... >> I use vim for writing python in, with the following options: >> :set et >> :set tabstop=4 > And how do I get it to send the function definition surrounding the > cursor to the Python interpreter with which it is currently > interacting ? > (Only half joking ... if there is a way to make vi(m) provide the same > interactive capabilities that Emacs does, then I would be able to > recommend it to those who insist on using vi in my courses and end up > trailing the rest of the class and slowing us all down.) Simple way: Select the block of code you want to execute with V and motion keys, then !python^M Complex way: :help python, and read. Vim's considerably faster to work with than emacs (and easier on the carpal tunnel than escape-meta-alt-control-shift), and Python's completely hooked in, at least if Vim was compiled that way. You're just not familiar with it yet. -- Mark Hughes "The void breathed hard on my heart, turning its illusions to ice, shattering them. Was reborn, then, free to scrawl own design on this morally blank world. Was Rorschach." --Alan Moore, _Watchmen #6_, "The Abyss Gazes Also" From martin at v.loewis.de Wed Jul 14 01:14:16 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Jul 2004 07:14:16 +0200 Subject: test_format fails In-Reply-To: <40f4835a$0$65124$e4fe514c@news.xs4all.nl> References: <40eef27c$0$43451$e4fe514c@news.xs4all.nl> <40F35E2D.3030002@v.loewis.de> <40f4835a$0$65124$e4fe514c@news.xs4all.nl> Message-ID: <40f4c128$0$26997$9b622d9e@news.freenet.de> Irmen de Jong wrote: > I'll try when I have some time for that... > As Michael Hudson pointed out it's probably a test that > messes with the locale settings and forgets to set them back, > or some such. Rather "some such". If this was a systematic error, it would fail for many more people. Regards, Martin From mwh at python.net Tue Jul 13 07:49:26 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jul 2004 11:49:26 GMT Subject: How big is python24.dll? References: <40f3690b$0$26125$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > Delaney, Timothy C (Timothy) wrote: > > Ouch. Did changing to .Net 2003 add that much overhead? Do we know what it would be with VC6? > > No, and no. python24.dll incorporates many extension modules which were > separate .pyd files before. In particular, it contains all .pyd files > which don't require additional libraries (DLLs or external libraries). > A number of new extension modules were added for 2.4 also, which got > incorporated into python24.dll. CJKCodecs must add a fair bit, I'd have thought. Cheers, mwh -- It's a measure of how much I love Python that I moved to VA, where if things don't work out Guido will buy a plantation and put us to work harvesting peanuts instead. -- Tim Peters, comp.lang.python From nick at nick8325.freeserve.co.uk Thu Jul 8 15:06:48 2004 From: nick at nick8325.freeserve.co.uk (Nick Smallbone) Date: Thu, 8 Jul 2004 20:06:48 +0100 Subject: csv reading fields References: <40ed95dd$1_6@corp.newsgroups.com> Message-ID: <40ed9b43$0$7804$db0fefd9@news.zen.co.uk> "Mark F" wrote in message news:40ed95dd$1_6 at corp.newsgroups.com... > To say I'm a python newbie would be an understatement but I think it is a > language worth learning and would make a great replacement for perl in our > shop. > > I'm trying to read a CSV file using the python csv module but I can't seem > to determine how to use the API, it seems to me that I can do nothing more > than opening the file and printing the lines of the file. I can do that > without the CSV module. I need to know how to address individual fields. > > Something like this: (not actual python code) > > > import csv > reader = csv.reader(file("some.csv")) > for row in reader: > print row.field(3) or import csv > reader = csv.reader(file("some.csv")) > if reader.field(2,1) == "test.zip": print "test.zip exists" > Thanks,-Mark > How about: import csv reader = csv.reader(file("some.csv")) for row in reader: print row[3] Nick From jody.burgess at sewardconsulting.com Fri Jul 16 12:13:31 2004 From: jody.burgess at sewardconsulting.com (Jody Burgess) Date: Fri, 16 Jul 2004 10:13:31 -0600 Subject: Printing Images through python post Message-ID: The example in this post appears to be incomplete, -----Original Message----- > From: Tim Golden > Sent: 03 October 2003 09:49 > To: 'Kevin' > Cc: python-list at python.org > Subject: RE: Printing images through Python Is The ratios calculation correct? It does not appear to be complete. # # Resize the image to fit the page but not to overflow # ratios = [1.0 * printer_resolution[0] / bmp.size[0], 1.0 * printer_resolution[1] / bmp.size[1]] print "ratios =", ratios scale = min (ratios) print "scale =", scale Jody Burgess ISP Systems Analyst Seward Consulting Ltd. 780.702.5103 jody.burgess at sewardconsulting.com From lbates at swamisoft.com Tue Jul 20 12:14:28 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 20 Jul 2004 11:14:28 -0500 Subject: Image Module Bug References: Message-ID: You should be able to use the struct module to pack your data into a binary structure, then pass that to the C++ module. I do this in quite a few programs I have that need to pass this type of data to C, C++ routines. HTH, Larry Bates Syscon, Inc. "Jim Bob" wrote in message news:gpaLc.241120$rCA1.188380 at news01.bloor.is.net.cable.rogers.com... > Hi, > > I've got a problem with loading images using the Image Module. When I load > images and then try to pass them to my C++ module using tostring() I get the > following error: > > TypeError: argument 1 must be string without null bytes, not str > > After tearing my hair out I figured out that it was because there was full > black (0) in my image which was screwing up the NULL string terminator. > > Here's my question. How can I get around this? Can I pass the raw image > data in another format? Can I use the encoder options on the tostring() > method? Anyone have any ideas? > > This is also a problem when I am trying to do RGBA format because the alpha > channel is 0 in transparent places. > > Thanks, > Peter > > From missive at frontiernet.net Mon Jul 26 23:42:02 2004 From: missive at frontiernet.net (Lee Harr) Date: Tue, 27 Jul 2004 03:42:02 GMT Subject: PostgreSQL connector and Zope connector References: Message-ID: On 2004-07-26, Dave Brueck wrote: > Ian S. Nelson wrote: >> What's the current state of Python and PostgreSQL? There is PoPy, >> PygreSQL and PsycoPG, maybe others? PygreSQL was part of the PostgreSQL >> tree, now it's not. What's up with it? >> >> Then a Zope wrapper for it. ZPygresql seems to be dead. Anyone in the >> know have any ideas on what's the best right now and has the most >> promise of being supported? > psycopg works well. The only problem I have with it is that it does not use the standard python datetime type dates, but when I searched their mailing list the other day this was already being addressed. From asouzaleite at gmx.de Thu Jul 8 09:42:05 2004 From: asouzaleite at gmx.de (Aroldo Souza-Leite) Date: Thu, 8 Jul 2004 15:42:05 +0200 (MEST) Subject: PYPI:(error 451) References: <20040708131620.7AC4C1E4006@bag.python.org> Message-ID: <8908.1089294125@www48.gmx.net> Hi, trying to register in PyPI, I get this SMTPRecipientsRefused: {'asouzaleite at gmx.de': (451, 'envelope address appears to be forged')} Can anybody help me there? Yours, Aroldo. From lbates at swamisoft.com Tue Jul 27 09:08:21 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 27 Jul 2004 08:08:21 -0500 Subject: Installer References: <81a41dd.0407270021.331f8248@posting.google.com> Message-ID: py2exe is located here: http://starship.python.net/crew/theller/py2exe/ Inno Setup installer is located here: http://www.jrsoftware.org/isinfo.php HTH, Larry Bates Syscon, Inc. "Lad" wrote in message news:81a41dd.0407270021.331f8248 at posting.google.com... > Does anyone know where I can download the latest version of Installer > to make exe file from my Python script? > Thanks for help > Lad From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jul 18 17:20:47 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 18 Jul 2004 23:20:47 +0200 Subject: namespace for released packages? In-Reply-To: References: <40F716E4.10708@tardis.ed.ac.molar.uk> Message-ID: <40fae9b2$0$34762$e4fe514c@news.xs4all.nl> Terry Reedy wrote: > Third party packages are generally put in the site-packages directory. So > far, there has not be much problem with name clashes. I experienced only one problem so far: you probably know Pyro (Python Remote Objects), which I wrote. Much later there was somebody else who did some stuff with Python and Robotics, and also called his project "pyro"... http://pyro.sourceforge.net http://pyrorobotics.org Now, if you only use one or the other, you're safe, but there was this person that needed to use *both* at the same time. What would be the best solution in this case? I was (and still am) not prepared to change my project's name or package name because it has been around much longer and is by now commonly recognised... --Irmen de Jong. From vincent at visualtrans.de Wed Jul 7 05:38:27 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 07 Jul 2004 11:38:27 +0200 Subject: Short if In-Reply-To: References: Message-ID: Thomas Lindgaard wrote: > Hello > > Does Python have a short if like C or PHP: > > bool = false > string = 'This is ' + (( bool ) ? 'true' : 'false') > > ? Nope. PEP308 to introduce a ternary operator like idiom has been rejected (see: http://www.sourcekeg.co.uk/www.python.org/peps/pep-0308.html), but you can emulate it: >> bool = False >> s = "This is " + ('false', 'true')[bool] >> print s This is false In this case bool evaluates to 0 and 'false' is at index 0 of the tuple ('false', 'true'). -- Vincent Wehren From peter at engcorp.com Mon Jul 12 18:58:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jul 2004 18:58:35 -0400 Subject: "helper function" style question In-Reply-To: <73b00f0c.0407121008.3175107f@posting.google.com> References: <73b00f0c.0407121008.3175107f@posting.google.com> Message-ID: Robert Ferrell wrote: > I have a style question. I have a class with a method, m1, which > needs a helper function, hf. I can put hf inside m1, or I can make it > another method of the class. The only place hf should ever be invoked > is from inside m1. > > Is either style preferred? If either is, it's the first one, not the following one. > class K(object): > def m1(self): > def hf(): > print 'Yo' > hf() > return Here you are wasting time executing the "def" statement every single time you invoke m1. I'm not sure if that also means it is compiling it each time (I think not), but at least it is rebinding the local hf to the function each time through. But I would just make hf() a function outside the class. Since it does not reference anything inside K, it has nothing inherently to do with K and should be outside, possibly (eventually) to be moved to another module where such helper functions reside to make them more maintainable. -Peter From stephendotboulet at motorola_._com Fri Jul 16 11:10:58 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Fri, 16 Jul 2004 10:10:58 -0500 Subject: IDE In-Reply-To: References: <390d8a01.0407150105.363017ac@posting.google.com> Message-ID: Paul Morrow wrote: > Unlike the earlier (and currently stable) version of Wing, Wing 2.0 beta > sports a lot of "polish". The IDE has been substantially rewritten, > using (I believe) the QT gui library (you can see the new look from the > screen shots on the wingware web site). I see some files with 'gtk' in their names in the install directory, so maybe that's what they are using. If so I've never seen gtk look so good. For you people with eclipse experience, does their gui toolkit wrap just motif on linux (why oh why)? I wonder what the potential for developing gui apps under eclipse with python is. Stephem From blk at srasys.co.in Mon Jul 19 05:56:23 2004 From: blk at srasys.co.in (Bala) Date: Mon, 19 Jul 2004 15:26:23 +0530 Subject: How to put a lock Message-ID: <00b101c46d76$a68418e0$f80210ac@Bala> Hi, From My Application, iam creating Multiple thread.. Each thread will acesss this function RedirectStdOut. sys.stdout is a global pointer.. So i got an exception called "I/O Operation on Closed File".. How to solve this problem..Kindly give some solution.. is it possible to put a lock for each thread..so that one thread accessing the RedirectStdOut, other thread can wait untill the lock get released. if so, i kindly request you to give some sample program... def RedirectStdOut(): print "This is stdout" oldStd = sys.stdout sys.stdout = open("c:\\std.out", "w") print "This is Redirecting stdout to a file" sys.stdout.flush() sys.stdout.close() sys.stdout = oldStd Thanks in advance Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From milon513 at yahoo.com Mon Jul 19 13:28:20 2004 From: milon513 at yahoo.com (Milon) Date: 19 Jul 2004 10:28:20 -0700 Subject: How to activate a new window in Python Message-ID: <3c9e9b1b.0407190928.61b1b292@posting.google.com> Hi all, I am new to Python, and I just wrote a simple script to launch an application from the windows's start menu's run command. (see code as follow) There is an "OK" button on the new application I launched, but I can't get Python to click on it because the new window is not in focus and I read somewhere off the web that I need to activate the new window first before I can do anything on the new window. I couldn't find any useful information off the web, so, can someone please show me how to do it? Really appreciate it, Milon __________________________________________________________________ import SendKeys # starts the TempApp using the windows start menu # run option def StartTempApp(): SendKeys.SendKeys( "{LWIN}{SLEEP .25}r") SendKeys.SendKeys( "C:\\TempApp\\bin\\main") SendKeys.SendKeys( "{ENTER}") # tab to OK button on the application and hit enter def StartTempApp(): SendKeys.SendKeys( "{TAB}{TAB}{ENTER}") From peter at engcorp.com Wed Jul 14 14:34:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Jul 2004 14:34:35 -0400 Subject: returning a value from a thread In-Reply-To: References: Message-ID: Peter Hansen wrote: > Ken Godee wrote: > > [detailed version of the question in the subject line] > > This question is asked often enough that it maybe should > become a FAQ, but in any case it was asked a few weeks > ago and I posted sample code with the idiomatic approach, > as I recall. A Google Groups search with your keywords > and my name should find it pretty quick. Oops, doesn't look like I'm remembering the right thread, since I didn't post in it. Anand Pillai, however, did post sample code: http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&th=8b49efa529006da0&rnum=1 -Peter From davidf at sjsoft.com Fri Jul 9 05:49:37 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 09 Jul 2004 11:49:37 +0200 Subject: understanding self In-Reply-To: <10er2up3q9vtqa5@corp.supernews.com> References: <10ep4094gjuik8e@corp.supernews.com> <10er2up3q9vtqa5@corp.supernews.com> Message-ID: Jeff Shannon wrote: > David Fraser wrote: > >> For example, there could be a keyword 'method' which defines a method >> object that takes self as its first parameter even though it's not >> declared. So the two __cmp__ definitions below would be equivalent: >> >> class Complex: >> # ... >> def cmpabs(self, other): >> return self.abs().__cmp__(other.abs()) >> method cmpabs2(other): >> return self.abs().__cmp__(other.abs()) > > > > Another Python design principle is to minimize the number of keywords. > You *could* do that... but it doesn't really gain you anything except an > extra keyword. And I personally find it clearer to see "self" in the > parameter list than to have to think "Oh yeah, this is a method, so > there's an implied self..." > But most importantly, an implicit 'self' would violate the second "Zen > of Python" guideline -- "Explicit is better than implicit." Unless you > can point to a significant *gain* by having 'self' implicit, then it's > better (or at least, more Pythonic) to have it explicit. So far, I've > heard plenty of alternatives to having explicit 'self', but very little > indication of why it would be an improvement other than that it would > allow less typing -- and Python has always placed ease-of-reading over > ease-of-typing. ("Readability counts.") > > (Heck, back when I was learning C++, I tended to explicitly use 'this' > when referring to class members/methods even though it was unnecessary, > simply because it made it easier to *see* what was a class member and > what wasn't; the "m_***" naming convention that's often used instead > strikes me as just being a weak way of doing the same thing...) > > Jeff Shannon > Technician/Programmer > Credit International > Actually the reason I think its worthwhile having another keyword here is that Python actually has separate types for functions and methods. Explicit is better than implicit - at the moment the method binding to self all happens behind the scenes, and you have bound and unbound method types that are all produced using the 'def' keyword like functions, but can actually operate differently. I think it is more readable, I'm not so concerned about the typing. There is magic happening here but no evidence for it ... a method keyword would justify the magic... That's why I still think you should refer to members of the class using self. rather than having magical name binding David From mwh at python.net Wed Jul 21 12:32:31 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 21 Jul 2004 16:32:31 GMT Subject: Linux, fcntl, F_SETLEASE and signals References: <871xj5jpf6.fsf@ion.xlipstream.com> Message-ID: Chris Green writes: > Hey folks, > > Is there anyway for a signal handler in python to get the information > from a 3 argument signal handler rather than just the signal number > and stack frame? No. > I've got an application where I have to check for F_SETLEASE on a file > in python on Linux 2.4. What this does is tells the kernel to notify > the current process with SIGIO that a particular file descriptor is being > modified by another process. > > >>> import fcntl > >>> f = open(".zshrc", "r+") > >>> fcntl.fcntl(f, fcntl.F_SETLEASE, fcntl.F_WRLCK) > 0 > > Now, when another process opens ".zshrc", I get a SIGIO saying > something happened. The kernel provides the information on what > descriptor changed in a siginfo_t's si_fd field. > > Is there anyway to get this from python? What a wonderful interface. I think you'll have to write some C for this... Cheers, mwh -- I recompiled XFree 4.2 with gcc 3.2-beta-from-cvs with -O42 and -march-pentium4-800Mhz and I am sure that the MOUSE CURSOR is moving 5 % FASTER! -- from Twisted.Quotes From http Thu Jul 8 02:59:47 2004 From: http (Paul Rubin) Date: 07 Jul 2004 23:59:47 -0700 Subject: Prothon 0.1.2 is getting close to Alpha [Prothon] References: Message-ID: <7xbrirugpo.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > I meant it is designed to be industrial strength when it is > > finished. The architecture/foundation is built from the ground up > > with that in mind. I'm also making a bit of a comment that it > > will be more industrial strength than Python. > > That claim interests me a lot. I've found recent versions of > Python to be *very* robust. I'd trust them with almost anything > at this point, more than I could say of most code in other > languages I've used. Why do you think you can improve on that, > (or even be on par with it if you're writing the interpreter > from scratch)? Python has all kinds of annoying little limitations and misfeatures that make me think an "industrial strength" version could do some things differently. Yes, you can write reasonably reliable programs in Python if you're careful about the different traps, but maybe Python tries to accomplish too many things at once. So it will be interesting to see how Prothon comes along. From davidf at sjsoft.com Tue Jul 13 14:44:35 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 13 Jul 2004 20:44:35 +0200 Subject: How do I speedup this loop? In-Reply-To: References: <40f385dc$1@clarion.carno.net.au> Message-ID: Istvan Albert wrote: > David Fraser wrote: > >> Except if you're aiming for database independence, as different >> database drivers support different means of escaping parameters... > > > IMHO database independence is both overrated not to mention impossible. > You can always try the 'greatest common factor' approach but that > causes more trouble (and work) than it saves. Not overrated or impossible. It's part of our business model. It works. > I agree with the previous poster stating that escaping should be done > in the DB API, but it is better to use the 'typed' escaping: > > sql = 'SELECT FROM users WHERE user_id=%d AND user_passwd=%s' > par = [1, 'something'] > cursor.execute(sql, par) > Better if the database driver you are using supports it... otherwise userless I think there is a need to drive towards some sort of standard approach to this in DB-API (maybe version 3?) as it otherwise nullifies parameters for anyone using multiple database drivers. David From dippyd at yahoo.com.au Fri Jul 2 01:44:32 2004 From: dippyd at yahoo.com.au (Steve) Date: Fri, 02 Jul 2004 15:44:32 +1000 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: <40E4F640.2060805@yahoo.com.au> Ville Vainio wrote: > Why do we write simple scripts to do simple things? Because building complicated programs to do simple things is a bad idea? > Why do we serialize data to flat text files > in order to process them? Because it is a tried and tested method that works? Because flat text files are human readable, which is a huge advantage in the real world? (Just contrast the voodoo of the Registry in the Windows world with simple text-based config files under Linux.) > Everything > could be so much simpler and immensely more powerful More powerful, maybe. Simpler, no. A Python script might be simpler than the equivalent assembly code that does the same thing, but when you include the complexity of the Python framework vs the assembler, it is far more complex. Likewise, under your system, you are merely shifting the complexity from the script to the operating system. Overall, you should expect a great *increase* in complexity, not a decrease. Which *might* very well mean more OS bugs, hacks and cracks. Exploits in your script will only affect you; exploits in the OS will affect everyone. The comparison between Windows and Linux is so obvious that you should already be thinking it :-) -- Steven From tdelaney at avaya.com Mon Jul 19 18:02:51 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 20 Jul 2004 08:02:51 +1000 Subject: Sorted list as an alternative to dictionary for when you only needkeys? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01B48588@au3010avexu1.global.avaya.com> http://www.python.org/peps/pep-0218.html Available as sets.Set in 2.3, and the builtin set (and frozenset) in 2.4. Tim Delaney -----Original Message----- From: python-list-bounces+tdelaney=avaya.com at python.org [mailto:python-list-bounces+tdelaney=avaya.com at python.org] On Behalf Of Daniel Eloff Sent: Tuesday, 20 July 2004 6:19 AM To: python-list at python.org Subject: Sorted list as an alternative to dictionary for when you only needkeys? I've used a dictionary with None values before when I've needed a container with fast lookup by value. Just insert all the values as keys. But this is not optimal at all. Better would be a python list that is sorted and uses a binary search algo to find values. Now it's not that much work to write a wrapper class for list that does this, but is there maybe not such a thing already in Python (surely it's very common, it's like a C++ STL set or a .NET sorted list, or a...). Or at least a wrapper already written in Python. I think this really should be a data structure added to the language, if it isn't already. -Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Tue Jul 20 22:55:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jul 2004 22:55:04 -0400 Subject: Question For Language Lawyers - WAS: Re: Combining colon statements In-Reply-To: References: <20040716050940.73131.qmail@web51810.mail.yahoo.com> <8i5us1-d7a1.ln1@eskimo.tundraware.com> Message-ID: Christopher T King wrote: > I remember reading something about this in a previous thread, and I think > it was decided that int(True) will always evaluate to 1, and int(False) > will similarly always evaluate to 0. So it may not be good style, but it > should be guaranteed behaviour for some time. (Note: AFAICT, this isn't > in the official language spec, though.) It's in the PEP though (from memory), along with examples of cases which are to be considered completely legal in Guido's own words... if the accepted PEPs are not to be considered part of the official spec (at least until replaced by other documentation), I don't know what is... > Not necessarily -- you aren't really assuming they're 1 and 0 in Python > ((1 is True) == False), but rather that they evaluate to 1 and 0 in an > integer context, which is something that can be (and it seems is) as well > defined as the fact that float(1) evaluates to 1.0. Uh, that "1 is 1" returns true is probably an implementation detail right now... it's not likely guaranteed. "a = 100" followed by "a is 100" returns False, after all. (Strange quirk, probably due to some obscure corner of the compiler, but "a = 100; a is 100" returns True, as does "100 is 100".) As usual, identity should be used to compare things unless you really want identity. In the case of booleans, 1 == True and always will. Read the PEP again for more detail. -Peter From pecora at anvil.nrl.navy.mil Thu Jul 15 08:21:37 2004 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Thu, 15 Jul 2004 08:21:37 -0400 Subject: ANN matplotlib-0.60.2: python graphs and charts References: Message-ID: In article , John Hunter wrote: > matplotlib is a 2D plotting library for python. You can use > matplotlib interactively from a python shell or IDE, or embed it in > GUI applications (WX, GTK, and Tkinter). matplotlib supports many > plot types: line plots, bar charts, log plots, images, pseudocolor > plots, legends, date plots, finance charts and more. > > What's new since matplotlib 0.50 [cut] Sounds tremendous. Anyone have any experience running this on Mac OS X? What does it take to get it up and running. I'm enticed. Will check it out on my own, too, but any info welcome. Thanks. -- Lou Pecora (my views are my own) They laughed at Galileo. They laughed at Newton. But they also laughed at Bozo the Clown. -- Carl Sagan From indigo at bitglue.com Wed Jul 28 15:13:14 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 28 Jul 2004 15:13:14 -0400 Subject: what does 'for _ in range()' mean? In-Reply-To: References: <10gevuasrt08rae@news.supernews.com> Message-ID: <20040728191314.GA6021@unununium.org> At Some Point, Someone Asked Something to The Effect of: > where does this _ thing come from? In ML, _ is used as magic "don't care" variable. It's often used when unpacking tuples and some elements are irrelevant. Example: Ocaml: let (fu, bar, _, _) = returns_a_4_tuple () Python: (fu, bar, _, __) = returns_a_4_tuple() One difference is that _ is allowed multiple times in Ocaml, while in Python it is not. Also to Python, it's a variable like any other, while in Ocaml it's magic. From klapotec at chello.at Fri Jul 9 01:20:10 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 09 Jul 2004 05:20:10 GMT Subject: Random thoughts from an aspiring Pythonista References: Message-ID: On Thu, 8 Jul 2004 16:33:41 -0400, Chris wrote: >-It's a language you can swear by, not at. Or in. :-) -- Christopher From R.Brodie at rl.ac.uk Fri Jul 9 05:45:38 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 9 Jul 2004 10:45:38 +0100 Subject: convert html References: Message-ID: wrote in message news:mailman.156.1089355200.5135.python-list at python.org... > I want to convert html to xml. > > I am doing this: ... > Can you suggest another way of doing this in Python? I haven't benchmarked but I would imagine using HTML Tidy (or ?Tidylib) is as good as any, particularly if your HTML source is a bit rough. From listserver at tdw.net Fri Jul 23 07:59:42 2004 From: listserver at tdw.net (Tim Williams) Date: Fri, 23 Jul 2004 12:59:42 +0100 Subject: Socket Timeout and SMTP References: <00c401c470a9$18523080$506b81c2@twilliams> <5a309bd30407230440f8051f7@mail.gmail.com> Message-ID: <00f101c470ac$8a0f4980$506b81c2@twilliams> ----- Original Message ----- From: "Steve" > Hi Tim, > On Fri, 23 Jul 2004 12:35:03 +0100, Tim Williams wrote: > > (python newbie) > > > > Is it possible to individually set the socket timeout of a connection > > created by smtplib, rather than use the socket.setdefaulttimeout() value > > used by the rest of the prog/script? > > def smtp_client(mx, from, to_list, msg): > > server = smtplib.SMTP(mx) > server.sock.settimeout(XX) Perfect, thanks Steve, I was trying server = smtplib.SMTP(mx) server.settimeout(XX) the correct version is now in my code, tested and working. > HTH most certainly did :-) Tim From apardon at forel.vub.ac.be Fri Jul 16 09:53:31 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Jul 2004 13:53:31 GMT Subject: Which style is preferable? Message-ID: For the sake of this question I'm writing a vector class. So I have code something like the following from types import * import operator class Vector: def __init__(self, iter): self.val = [ el for el in iter ] for el in self.val: if not isinstance(el, FloatType): raise TypeError def __add__(self, term): if ! isinstance(term, Vector): raise TypeError if len(self.val) != term.val: raise ValueError resval = map(operator.add, self.val, term.val) return Vector(resval) The problem I have with the above code is, that I know that resval will contain only floats so that calling Vector with resval will needlessly do the type checking. So one way to solve this would be to have a helper function like this: def _Vec(lst) res = Vector() res.value = lst return res The last line of the __add__ method would then look like this. return _Vec(resval) But I'm not really satified with this solution either because it needs a double call to generate an unchecked Vector. So I would prefer to write it like this: def Vector(iter): lst = [ el for el in iter ] for el in lst: if not isinstance(el, FloatType): raise TypeError return _Vec(lst) class _Vec(lst): def __init__(self, lst): self.val = lst def __add__(self, term): if ! isinstance(term, _Vec): raise TypeError if len(self.val) != term.val: raise ValueError resval = map(operator.add, self.val, term.val) return _Vec(resval) The only problem with this is that it is awkward to use with isinstance and such, so I would finaly add the folowing: VectorType = _Vec My question now is, would this be considered an acceptable style/interface whatever to do in python? -- Antoon Pardon From bart_nessux at hotmail.com Thu Jul 29 13:17:34 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 29 Jul 2004 13:17:34 -0400 Subject: A goto-like usage of a function In-Reply-To: References: <41091DD7.6070500@hotmail.com> Message-ID: Peter Hansen wrote: > Bart Nessux wrote: > >> I understand recursion to be a loop or a loop to be recursion... >> however you prefer to look at it. > > > Absolutely not. Recursion is more like a spiral, rapidly closing > in on itself until you're trapped in the middle, or maybe a > swirling whirlpool that will sink your program over time... > > Just because you can use recursion to implement something that > appears to loop doesn't mean it's a good idea. Much better > to get out of that frame of mind... Recursion does _not_ get > you back to where you were, as a real loop would. > > The key is to understand that each time you call a function, > more data is put on the "stack", which has a finite size. > Basically the context of the calling function is preserved > when you call a subroutine, including all the local variables, > plus the "return address" so the interpreter knows where to > go back to. > > Whether you do it through recursion or some other means, > if you get too deeply nested you will crash, and even if you > don't you still have the overhead of "unwinding" all those > stack frames when you finally return. It may look like > it falls off the end of the function, but in fact it is > actually returning to the previous stack frame, in the place > just after where the function call was, then it returns from > there to the previous stack frame, then returns to the previous > one, each time popping a frame off the stack, all the way up > to the top of the stack. > > While it might be okay for a trivial script that is just asking > for user input, it is terribly bad style and you would do well > to learn to do it differently. > > All IMHO, and theoretical discussions of tail recursion > notwithstanding. > > -Peter Thanks to all for detailing how loops and recursion differ. I'm going with Tim's loop suggestion now that I realize why I shouldn't use recursion for this type of thing. From harry.g.george at boeing.com Fri Jul 2 16:59:39 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 2 Jul 2004 20:59:39 GMT Subject: doing successive prints without space in between References: <2klsonF3m87gU1@uni-berlin.de> Message-ID: Jon Perez writes: > I'd like to print a series of successive periods as a > progress status in a command line script using python. > Unforutnately, if I do a series of successive > > print ".", > > I get a space in between. Is there any way to avoid > this? This show up regularly and might be a FAQ. The print is trying to help you out. If you want total control, go to the lower levels: wr=sys.stdout #redirect as desired def myprint(txt): wr.write(txt) #raw print wr.flush() #flush the dots as they occur for i in range(100): do_something() myprint('.') myprint('\n') -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From ville at spammers.com Thu Jul 1 20:08:13 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Jul 2004 03:08:13 +0300 Subject: Status of PEPs? References: <2kfjf7F1nk33U1@uni-berlin.de> <10e58dpcbogogce@news.supernews.com> <2kj9dmF32eojU1@uni-berlin.de> Message-ID: >>>>> "Thomas" == Thomas Reichelt writes: Thomas> Thank you for your explanation. What I don't understand, Thomas> though, is that the PEPs for which an implementation Thomas> exists aren't discussed further, but are just lying around Thomas> in a corner, though there is a significant advantage in Thomas> the PEP's proposal. I understand that the introduction of Thomas> a new keyword is Even if something has a significant advantage, it's might not be significant enough to warrant bloating the language. The cost of implementing a feature is trivial compared to the cost of increased language complexity. In that way python is different from perl or ruby, where everything that someone bothers to provide a patch for gets included. Thomas> It is clear that most of the proposed syntactic Thomas> enhancements can be rebuilt with the existing language, Thomas> but sometimes only with code duplication or clumsy Thomas> constructs. Many features are only attractive because some other language has it, and people mistakenly believe that python should have it too. do-while is an example of a worthless feature that people think they want, but that really adds nothing to while 1: do stuff if condition: break -- Ville Vainio http://tinyurl.com/2prnb From missive at frontiernet.net Thu Jul 22 17:42:04 2004 From: missive at frontiernet.net (Lee Harr) Date: Thu, 22 Jul 2004 21:42:04 GMT Subject: Zope Products newbie question. References: <425cc8d1.0407212145.2cf59ff@posting.google.com> Message-ID: On 2004-07-22, mir nazim wrote: > Hi, > I am a PHP developer. i am currently studying Zope and want to migrate > to it. I have developed a school management system in PHP. but now I > want to implement it in Zope. I have worked through The Zope Book 2.6 > and Zope Developers Guide quickly(not thoroughly). My problem is that > I am confused where to start. > > System is supposed to admit students and assign unique ids to > them. student object will be stored in ZODB. searching on id, first, > mid and last names and possibly on other attributes like sex, date of > birth etc has to be provided. system is to be used by end users and > not zope administrators. > > Now the problem is that I am confused how to implement these > classes. Should I implement them as ZClass or in External methods or > as a Zope Product. Please Clarify. Also tell me how, actually, am I > supposed to start. small code sample can be a of great help. Links to > similar free projects undertaken on zope can be useful. > > PS: Actually it is a small part of overall system which provides > transport management, class/course management, exam/result management, > employees payrolls and basic accounting for high schools. but to start > with it should be enough to help me get a better feel of zope. > I have worked with Zope and Python quite a bit with databases. My approach lately has been to use a relational database (postgres) for the data and just provide interfaces with Zope (and most recently with Twisted/ nevow). For instance, if your data were in a database working with PHP you could just write interface code and access the same database with Zope. If you are just getting started with Zope, you may want to look at Zope 3, as I understand it is quite different from the current Zope system. I moved to nevow for my current project because I want to run the entire system on Pentium I systems (database, web front-end, and a curses front-end also) and Zope was too heavy. So far nevow is working out very well. Years ago (before finding python) I used PHP quite a bit also. I remember trying to use an object oriented style and running in to a lot of strange problems. When I saw Python, I said "Oooh. Now I understand object oriented!" I read that the PHP object system was majorly overhauled for PHP5, but I also read that it is still not quite right. I should take a look though and see for myself... From arigo at tunes.org Fri Jul 30 12:48:11 2004 From: arigo at tunes.org (Armin Rigo) Date: Fri, 30 Jul 2004 17:48:11 +0100 Subject: psyco for python 2.4? In-Reply-To: References: Message-ID: <410a7ce1@news.ecs.soton.ac.uk> Hello, >>I've tried the cvs version of psyco and it causes python 2.4a1 to dump >>core when I "import psyco". Does anyone know the timeline for getting >>psyco working with 2.4? I fixed this particular problem. Now Psyco (CVS tree version) appears to work on 2.4a1, but extensive testing is still needed. Armin From jeff at ccvcorp.com Thu Jul 22 17:24:28 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 22 Jul 2004 14:24:28 -0700 Subject: bend or redirect a class method and then call it again In-Reply-To: References: <9cpsf0phun8hquadm7i266jk19a560h22j@4ax.com> <40fec581$1@nntp0.pdx.net> <97ouf0djcp4ovavsfgfi17qo3o428qluep@4ax.com> Message-ID: <10g0bu2arvlre0c@corp.supernews.com> Francesco wrote: >>What's the point of this extra 'NewStatusText' method? You're already >>overriding SetStatusText. Without the NewStatusText and the setattr() >>call, when someone calls SomePluginObject.SetStatusText(), it will call >>your new version rather than the wx.Frame (or DrFrame) version >> >> > >but not from drFrame itself; that is the point. > > Unless I'm misunderstanding your intent, then yes, from drFrame itself. Every Plugin object is also a drFrame object (and a wx.Frame object). *Every* SetStatusText() call on any such object will use the most-derived version of SetStatusText(), i.e. the Plugin version. Even the calls that are part of the drFrame class definition. The *only* exception to this is if, instead of using self.SetStatusText(), you're using drFrame.SetStatusText(self, ...) -- in that case, you've explicitly asked for the drFrame version. But if you have, for example, something like this: class drFrame(wx.Frame): def do_something(self, *args): # [....] self.SetStatusText("New Status") then despite the fact that this is a drFrame method, and doesn't know anything about the Plugin derived class, it will indeed result in the Plugin version of SetStatusText() being called. That's the whole *point* of inheritance. I can see two cases where what you're doing would have some effect that doesn't replicate normal method resolution order, and to be honest I think that using either case is a sign of some very questionable design decisions and definitely violates the guiding principles of OO and inheritance. One case would be that there are indeed places where the drFrame.SetStatusText(self, ...) is explicitly called, and you're trying to override those explicit requests. This is bad form -- an explicit request should be honored, because there's probably a real reason for it. The other case is where you are trying to modify the behavior of all drFrame instances, including those which are *not* also Plugin instances. In both cases, you're doing something magic behind your back. It's much better to do that kind of stuff up front, where it can be seen. (For instance, in the second case, simply derive an intermediate class from drFrame, and then derive Plugin from that. Use the intermediate class anywhere where you'd currently use drFrame, and you're set.) I would bet that there's a more straightforward way of accomplishing what you actually want to do, without resorting to this kind of sleight-of-hand. (I trust sleight-of-hand in programs about as much as I trust sleight-of-hand in people who're holding my wallet -- there may be cases where it's justified and where it can be trusted, but I'm not going to hand my wallet to just anyone...) Jeff Shannon Technician/Programmer Credit International From __peter__ at web.de Mon Jul 19 12:42:03 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jul 2004 18:42:03 +0200 Subject: Python 2.2 code continues running before list comprehension is completed? References: <3f233389.0407190625.4a32e753@posting.google.com> Message-ID: Chris P. wrote: > Hi. I've made a program that logs onto a telnet server, enters a > command, and then creates a list of useful information out of the > information that is dumped to the screen as a result of the command. > Here's a generic version of the code in question: > > ##### > > # Prior code opens telnet connection "tn" and logs in. > tn.read_until('> ') > tn.write('THE COMMAND IS HERE\n') > dump = tn.read_very_eager() You could try tn.read_all() instead (just a guess). assert "string1\r" in dump # would do no harm assert ""string2\r" in dump > dump_lines = dump.split('\n') > dump_info = [x for x in dump_lines if (VARIOUS CONDITIONS ON x)] > > # string1 and string2 are strings that are known to > # always appear in the dump. Bold claim :-) > A = dump_info.index('string1\r') > B = dump_info.index('string2\r') > C = A - B - 1 > > ##### > > The thing is, I can step through this code in the debugger and it > works fine. When run from the command line, however, I get the > following error in response to my dump_info.index lines: > > ValueError: list.index(x): x not in list > > So I tried putting (for x in dump_info: print x) right after I make > the list comprehension and, when I run that, it shows that the list is > incomplete... so it SEEMS like Python begins to create the list > comprehension and then continues to execute commands before the list > comprehension is finished! I'm pretty sure that the list comprehension is finished. Look out for something else. Peter From pm_mon at yahoo.com Mon Jul 12 08:04:43 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Mon, 12 Jul 2004 08:04:43 -0400 Subject: Inheritance and Inner/Nested Classes Message-ID: I'm hoping that someone can explain why I get the following exception. When I execute the code... ###################################### class Parent(object): class Foo(object): baz = 'hello from Parent.Foo' class Child(Parent): #Foo.baz = 'hello from Child.Foo' pass print Child.Foo.baz print dir(Child) ###################################### ...it displays what I expect... hello from Parent.Foo ['Foo', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] ...but when I uncomment the first line of the Child class, Python complains that Foo is undefined... Traceback (most recent call last): File "test1.py", line 5, in ? class Child(Parent): File "test1.py", line 6, in Child Foo.baz = 'hello from Child.Foo' NameError: name 'Foo' is not defined Thanks in advance. Paul From me at privacy.net Fri Jul 30 09:48:02 2004 From: me at privacy.net (Duncan Booth) Date: 30 Jul 2004 13:48:02 GMT Subject: Importance of C# References: <278de0e.0407281353.27b6a457@posting.google.com> <5dydnZSDZaARoZXcRVn-ug@powergate.ca> <1n5z28erh2m3u.dlg@baczek.net.invalid> <9418be08.0407300306.673d9951@posting.google.com> <410A4334.9080002@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in news:410A4334.9080002 at v.loewis.de: >> What is wrong with this argument. Java evolved for more then 10 years >> (and still is). This group is dedicated to an evolving language - >> Python. Why not to allow C# to evolve too. > > Sure. And ten years from now, the issue of C# not providing generic > programming might not be an issue anymore. However, this is not > relevant for people who use C# today - they just can't use generics; > that future versions may provide it still means they can't use it > today. So if this is a flaw, it is a flaw today. Saying that people > want to remove the flaw still makes it a flaw. Whilst what you say is true in general, C# containing generics is available today (although still in beta). See http://lab.msdn.microsoft.com/vs2005/ BTW, elsewhere in this thread someone said that C++ doesn't fit well into .Net framework so it is worth mentioning that vs2005 also includes completely revamped support for C++. Naturally this is incompatible with their earlier attempt, but it really is much improved. From jeff at ccvcorp.com Thu Jul 8 14:03:56 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 08 Jul 2004 11:03:56 -0700 Subject: understanding self In-Reply-To: References: <10ep4094gjuik8e@corp.supernews.com> Message-ID: <10er2up3q9vtqa5@corp.supernews.com> David Fraser wrote: > For example, there could be a keyword 'method' which defines a method > object that takes self as its first parameter even though it's not > declared. So the two __cmp__ definitions below would be equivalent: > > class Complex: > # ... > def cmpabs(self, other): > return self.abs().__cmp__(other.abs()) > method cmpabs2(other): > return self.abs().__cmp__(other.abs()) Another Python design principle is to minimize the number of keywords. You *could* do that... but it doesn't really gain you anything except an extra keyword. And I personally find it clearer to see "self" in the parameter list than to have to think "Oh yeah, this is a method, so there's an implied self..." But most importantly, an implicit 'self' would violate the second "Zen of Python" guideline -- "Explicit is better than implicit." Unless you can point to a significant *gain* by having 'self' implicit, then it's better (or at least, more Pythonic) to have it explicit. So far, I've heard plenty of alternatives to having explicit 'self', but very little indication of why it would be an improvement other than that it would allow less typing -- and Python has always placed ease-of-reading over ease-of-typing. ("Readability counts.") (Heck, back when I was learning C++, I tended to explicitly use 'this' when referring to class members/methods even though it was unnecessary, simply because it made it easier to *see* what was a class member and what wasn't; the "m_***" naming convention that's often used instead strikes me as just being a weak way of doing the same thing...) Jeff Shannon Technician/Programmer Credit International From aahz at pythoncraft.com Thu Jul 22 10:09:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Jul 2004 10:09:39 -0400 Subject: List Comprehension Syntax References: <2lc645Fb0cjgU2@uni-berlin.de> Message-ID: In article , Moosebumps wrote: > >>>> result = [x for x in range(10) if x % 2 == 0 if x % 3 == 0] >>>> result >[0, 6] >>>> result = [ x*y for x in range(10) if x%2 == 0 for y in range(10) if y % >3 == 0] >>>> result >[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72] > >Just curious -- anyone care to tell me how they would format the above? (or >maybe you wouldn't write it all) Wouldn't use either. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Barbara Boxer speaks for me: http://buffaloreport.com/2004/040713.boxer.marriage.html From DesertLinux at netscape.net Wed Jul 21 14:53:09 2004 From: DesertLinux at netscape.net (Byron) Date: Wed, 21 Jul 2004 18:53:09 GMT Subject: How to lunch webpage without using SMTP server? In-Reply-To: References: Message-ID: Hi Doug, I agreed with your response. In my reply, I mentioned that she would have two options, which are to either *get* SMTP access -- or -- to find some program, plugin, etc that would act as a SMTP server for her. If she is able to obtain smtp access, then the code I provided below could be used / modified for it. Byron --- Doug Holton wrote: > Byron wrote: > >> Hi Nancy, >> >> In order to be able to send an e-mail, you need to use either an SMTP >> server or have the know-how skill to be able to route the message >> yourself. I would HIGHLY recommend that you use an SMTP server. >> >> Here's a code snipplet that you might find helpful: >> >> def sendmessage(toaddr, fromaddr, message): >> server = smtplib.SMTP('mail.some-server.com') >> server.login("webmaster at some-server.com", "mySecretPassword") >> server.sendmail(fromaddr, toaddr, message) >> server.quit() >> > > Again, we've been through all this before. She doesn't have access to > an SMTP server, apparently. She only uses hotmail. > That is why I answered her with instructions on how to run her own SMTP > server just for testing purposes. From jzgoda at gazeta.usun.pl Mon Jul 12 15:06:33 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 12 Jul 2004 19:06:33 +0000 (UTC) Subject: Snack UI examples/docs References: <106ad2cd.0407091220.6a930c9d@posting.google.com> <106ad2cd.0407120326.38607550@posting.google.com> Message-ID: Doug Farrell pisze: >> There's no such thing. You can only look at 2 scripts in source package, >> plus sources of old Anaconda installer and maybe 1 or 2 other programs. > > I'm assuming the source package you are referring to is the source for > snack.py itself? NEWT/Snack (aka python-newt in Debian) is a C extension interfacing with libnewt.so. In source package (e.g. from Debian or better src.rpm for newt from PLD) you will find only these 2 short "demos". To see python-newt in something bigger, look for src.rpm for RedHat's Anaconda installer (I am sure RH 7.3 has it, don't know if newer versions of RH also use text-mode installation routine). And that's all I know of python-newt examples. -- Jarek Zgoda http://jpa.berlios.de/ From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jul 17 15:59:31 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 17 Jul 2004 20:59:31 +0100 Subject: Collaborative Text Editor In-Reply-To: <871xjbx77g.fsf@pobox.com> References: <-OidnYKNZa0mC2jdRVn-hQ@centurytel.net> <87smbuw7pp.fsf@pobox.com> <9uGdne3kE92fdmjdRVn-vA@powergate.ca> <871xjbx77g.fsf@pobox.com> Message-ID: <40F98523.9040100@jessikat.fsnet.co.uk> John J. Lee wrote: > Peter Hansen writes: > > >>John J. Lee wrote: >> >>>The way I've always imagined it working is as follows. I'm sure >>>experimentation is the way to find out what works, though, so Twisted >>>certainly sounds like a great idea. >>>- At any time, exactly one person has control. >>>- The only person able to move the cursor and edit text is the one >>> with control. >> >>[snip other ideas] >> >>There are already editors that support such things, so imagining >>how it works, while interesting, might not be the best approach >>to get started... vim, for example, already can do this sort >>of thing. I'm certain there are others out there. > > > Could you provide a link to any info on how to do this in vim? > > > John There's some info at http://docsynch.sourceforge.net/index.php and http://www.vi-improved.org/wiki/index.php/TunnelDataInCommands -- Robin Becker From db3l at fitlinxx.com Wed Jul 7 11:05:09 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jul 2004 11:05:09 -0400 Subject: Short if References: <40EC03F5.6040308@holdenweb.com> Message-ID: Steve Holden writes: > Vincent Wehren wrote: (...) > > class Klass: > > def __init__(self, a, b, foo=None, bar=None): > > self.a = a > > self.b = b > > self.foo = (foo, someDefaultMutable)[foo is None] > > self.bar = (bar, someOtherDefaultMutable)[bar is None] (...) > I should have thought that this is about the same as > > self.foo = foo or someDefaultMutable > self.bar = bar or someOTherDefaultMutable > > but as you say, tastes vary. I find the latter much more readable, as > I don't have to mentally convert the Boolean to a zero or one > subscript value to realise what happens when foo *is* None. Except that your code will result in using the default mutable if a user passes in their own mutable that happens to be empty. That may still work in some cases, but it's certainly not equivalent code. In Vincent's example, None is a true Sentinel value (thus the "is" check) and isn't just being used as equivalent to any false value. Of course, this use case is really only needed due to Python's handling of default variables (constructed once at compile time), making it unsuitable in many cases when the default variable should be mutable. So if there were a way to address that in a backwards compatible manner, it would also simplify this scenario. -- David From grante at visi.com Thu Jul 22 12:00:38 2004 From: grante at visi.com (Grant Edwards) Date: 22 Jul 2004 16:00:38 GMT Subject: Wondering about learning Python References: Message-ID: <40ffe4a6$0$230$a1866201@newsreader.visi.com> On 2004-07-22, Chris wrote: > I've written a small QBASIC program which draws a spiral. Here is the > code: > > SCREEN 12 > CLS > FOR t = 1 TO 400 STEP .01 > x = .5 * t * COS(t) > y = .5 * t * SIN(t) > PSET (x + 320, y + 240) > NEXT t > > I noticed that it generated some interesting patterns, probably as a > result of rounding errors. I suspect the patterns to which you refer are the moire patterns generated when you superimpose the pattern you are drawing and the two "grids" imposed by the rasterizaion done by your frame buffer and the grid formed by the phosphor dots and shadow mask of your CRT. http://www.mathematik.com/Moire/ http://www.exploratorium.edu/snacks/moire_patterns.html http://eluzions.com/Illusions/Moire/ -- Grant Edwards grante Yow! Vote for ME at -- I'm well-tapered, visi.com half-cocked, ill-conceived and TAX-DEFERRED! From grante at visi.com Wed Jul 7 09:08:25 2004 From: grante at visi.com (Grant Edwards) Date: 07 Jul 2004 13:08:25 GMT Subject: Python indentation References: Message-ID: On 2004-07-07, Sateesh wrote: > I surely understand the importance of indentation, but as you see there are > beautification tools that can be used to beautiy the C code. Also > indentation is based upon ones style of coding, and I feel somewhat > restricted when the language itself restricts someone to code in a > particular way. All languages are restrictive. C requires blocks are delimited by {} and statements by ;. Python isn't more restrictive, it just has _different_ restrictions. -- Grant Edwards grante Yow! What I want to find at out is -- do parrots know visi.com much about Astro-Turf? From lard at tardis.ed.ac.molar.uk Sun Jul 4 18:42:34 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Sun, 04 Jul 2004 22:42:34 GMT Subject: iterator over a numarray? Message-ID: I'm looking for a way to iterate over all the items in a numarray. Writing a few nested loops isn't going to cut it, because the numarray in question could be of any dimension... I am aware of the revel function, but that appears to just flatten the numarray. What I need is an iterator that can give each value and the coordinates in the array of that item.... thanks alex From tor.iver.wilhelmsen at broadpark.no Wed Jul 7 11:32:47 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 07 Jul 2004 17:32:47 +0200 Subject: Short if References: Message-ID: Thomas Lindgaard writes: > writing ('true', 'false')[bool] does not strike me as being very > readable, ... which makes it a perfect candidate for the ?: ternary operator. :) (Also, if the variable "bool" can hold some non-boolean value you want to check, use the builtin bool() function, as someone was nice to point out to me the last time a similar question came up.) From python at elehack.net Tue Jul 27 08:23:21 2004 From: python at elehack.net (Michael Ekstrand) Date: Tue, 27 Jul 2004 07:23:21 -0500 Subject: syntax-check with regular expressions? In-Reply-To: References: Message-ID: <200407270723.22676.python@elehack.net> On Tuesday 27 July 2004 07:00, Detlef Jockheck wrote: > What is the best way to do this. regexp? At the moment it would be > sufficient to check for > [digit][digit].[digit][digit].[digit][digit][digit][digit] but a full > date verification (Month in range 1-12 ...) would be very nice too. There is a way to do it with a regexp, I believe, but it is far from simple. Jeffery Friedl's book Mastering Regular Expressions (at least the first edition) develops such an expression as one of its examples. The easy way, though, is the calendar module. You can do import calendar day, month, year = date.split('.') if month < 1 or month > 12: raise ValueError("Invalid month") if day < 1 or day > calendar.monthrange(year, month)[1]: raise ValueError("Invalid day") HTH, Michael From squirrel at WPI.EDU Thu Jul 29 09:17:00 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 29 Jul 2004 09:17:00 -0400 Subject: if or exception In-Reply-To: References: Message-ID: On Thu, 29 Jul 2004, Thomas Lindgaard wrote: > Just wondering what is "the right thing to do": > > number = 0 > if len(list) > 0: number = anotherNumber / len(list) > > or > > try: > number = anotherNumber / len(list) > except: > number = 0 The first will be faster if you expect len(list) to be zero very often, whereas the latter will be faster if you expect it to be zero very rarely. This is because in the normal case, the latter needs no extra code (except a quick 'setup try block'), whereas the former requires a function call and a comparison for all cases. In the exceptional case, the latter must raise an catch an exception, which (I believe) is more expensive than the check in the former. How much more expensive, I'm not qualified to say ;) From chrisccc_3k at yahoo.com Wed Jul 28 11:04:53 2004 From: chrisccc_3k at yahoo.com (Chris Connett) Date: Wed, 28 Jul 2004 11:04:53 -0400 Subject: eval() of empty string hangs In-Reply-To: <5uidnRYv-6DqK5rcRVn-vQ@powergate.ca> References: <5uidnRYv-6DqK5rcRVn-vQ@powergate.ca> Message-ID: <4107c099$1@buckaroo.cs.rit.edu> Peter Hansen wrote: > > As an alternative, and not requiring that you special case > anything, does it work if you simply append '\n' to the > string to be eval'ed in all cases? I did try a number of ways of massaging the input string, though far from exhaustive; I tried adding the single newline - it didn't help. I did however localize the problem more tightly. It does not seem to be eval that's hanging, but raise-ing is not working. When I tried my original plan of special casing '', I added a check for equality, then manually raised a SyntaxError. This exhibited the same behavior. I then tried unconditionally raising SyntaxError, same result. Is it possible that the exception is propagating up the wrong stack? This is a separate thread, could it be on the main thread somehow? The creating thread has ended by the time this exception is due to be raised. There are numerous try-excepts to catch this, all should log at least some message, but the log shows nothing. From dave at pythonapocrypha.com Thu Jul 22 15:39:23 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 22 Jul 2004 13:39:23 -0600 Subject: timeout and sockets example request?? In-Reply-To: <938a4680.0407221133.1e49ce05@posting.google.com> References: <938a4680.0407221133.1e49ce05@posting.google.com> Message-ID: <410017EB.6050700@pythonapocrypha.com> Ishwar Rattan wrote: > In section 7.2 of Python library reference manual: > > exception timeout > This exception is raised when a timeout occurs on a socket which has had > timeouts enabled via a prior call to settimeout(). The accompanying value > is a string whose value is currently always ``timed out''. New in version 2.3. > > I assumed that settimeout() is an attribute of newly created socket object, > but is not so! What version of Python are you using? Could you post some code showing what didn't work? Here's why I ask: Python 2.3.4 (#53, May 25 2004, 21:17:02)... Type "help", "copyright", "credits" or "l... >>> from socket import * >>> s = socket(AF_INET, SOCK_STREAM) >>> s.settimeout(5) >>> (no errors) setdefaulttimeout is handy when you don't have access to the actual socket object, e.g.: >>> import socket >>> socket.getdefaulttimeout() 10.0 >>> socket.setdefaulttimeout(3) >>> import urllib >>> urllib.urlopen('http://www.google.com').read() ' Message-ID: Dan wrote: > This is relatively simple, borrowing from my C++/PHP background: > > str = "abcdefg" > str2 = "abcde" > > i = 0 > for c in str: > print c, " ", str2[i] > i += 2 > > But that is a C++/PHP way of doing things. > >>From what I've seen of python, I almost expected python to allow: > > for c, c2 in str, str2: > > But it didn't. I would be very surprised if there isn't another clever > way of doing the same though. >>> for c, d in zip("abc", "xyzwillbeignored"): ... print c, d ... a x b y c z or, if i += 2 isn't there by mistake: >>> for c, d in zip("abc", "xyzwillbeignored"[::2]): ... print c, d ... a x b z c i >>> Using itertools.izip() instead of zip() doesn't create an intermediate list of tuples which is an advantage when the zip/izip arguments are large sequences. > My question to you is, how would you do this? And do you think I should > propose a PEP for supporting the above for loop syntax? It seems like a > relatively harmless feature in that it won't break existing code, but > then I am very new to python. What you propose already has a meaning and therefore _will_ break existing code. >>> for c, d in "ab", "cd": ... print c, d ... a b c d Peter From squirrel at WPI.EDU Thu Jul 29 20:01:18 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 29 Jul 2004 20:01:18 -0400 Subject: IronPython-0.6 is now available! In-Reply-To: References: <278de0e.0407281353.27b6a457@posting.google.com> Message-ID: > Here, I had see a COMPLETE implementation of BrainF*** pour .NET & Mono: > > http://bluesorcerer.net/esoteric/bf.html Well, if this is where the thread is going, here you can find a complete BF implementation for PostScript: http://users.wpi.edu/~squirrel/postscript/bf.ps ;) From donn at drizzle.com Mon Jul 12 01:33:00 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 12 Jul 2004 05:33:00 -0000 Subject: if/elif chain with assignment expressions References: <7xvfguflq1.fsf_-_@ruckus.brouhaha.com> <7x4qoe6vae.fsf@ruckus.brouhaha.com> Message-ID: <1089610378.712205@yasure> Quoth Fernando Perez : ... | Well, the problem here (and apparently others share this opinion) is that this | particular restriction genuinely forces kludgy code in certain circumstances. | As John Roth pointed out, the looping case is easily solved with iterators, but | Paul's original one is not. | | I know that the if(x=0) bug in C/C++ is a potentially nasty one, having been | bitten by it myself in the past. It is also true that having this particular | option available allows certain kinds of code to be written in a clear and | concise manner. So yes, it is a slightly dangerous feature, but one which | offers true expressive power. Hence my characterization of it as 'training | wheels': I don't mean to say that only beginners can fall into the trap (even | Lance Armstrong can fall off a bike), but rather that experienced users will | know what to watch for, and will be willing to pay the price of potentially | falling for the liberty of going faster :) I know people who would like this feature a lot, if it existed in Python and if they wrote in Python. I know this from their C code, which I have had miserable occasion to deal with. If what we get is kludgy code, I accept that gladly in return for the guarantee that I shall never have to deal with this kind of mess in Python. Donn Cave, donn at drizzle.com From peter at engcorp.com Wed Jul 28 10:21:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jul 2004 10:21:44 -0400 Subject: eval() of empty string hangs In-Reply-To: References: Message-ID: <5uidnRYv-6DqK5rcRVn-vQ@powergate.ca> Chris Connett wrote: [...] > When I eval the empty string in this context, instead of a > SyntaxError, like I expect and am prepared to handle, the program > hangs. If I run the example in a standard interactive shell, it > raises a SyntaxError, like I expect. Only here does it hang. [...] > I should be able to work around this, just check a special case for > the empty string, since that seems to be the only actual case that > arises, but this problem is a real puzzle to me, and I wanted to throw > it out there to see what others think. As an alternative, and not requiring that you special case anything, does it work if you simply append '\n' to the string to be eval'ed in all cases? -Peter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 5 06:08:44 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 05 Jul 2004 12:08:44 +0200 Subject: ANN: PySQLite 0.5.1 In-Reply-To: References: Message-ID: <40e928b4$0$14941$e4fe514c@news.xs4all.nl> Gerhard H?ring wrote: > PySQLite makes the embedded database engine SQLite available to Python > programmers via the DB-API interface. > > I've just released PySQLite 0.5.1, a looooooooong overdue bugfix release > for 0.5.0 released in last December. Gerhard, do you recommend compiling Sqlite with or without the THREADSAFE=1 option? --Irmen From walter at livinglogic.de Thu Jul 22 06:26:37 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 22 Jul 2004 12:26:37 +0200 Subject: [Python-Dev] Logging with no handlers configured In-Reply-To: <000701c46f6b$68e8fd60$652b6992@alpha> References: <000701c46f6b$68e8fd60$652b6992@alpha> Message-ID: <40FF965D.3040001@livinglogic.de> Vinay Sajip wrote: > Currently, if the logging module is used with no handlers configured for a > logger or its parents and you try to log events with that logger, a single > message is printed to sys.stderr: > > No handlers could be found for logger > > It has been suggested that this puts out a spurious message when, for > whatever reason, a developer intentionally does not configure any > handlers. > [...] > > All feedback gratefully received, How about a LoggingConfigurationWarning and using warnings.warn()? Then what should happen with the warning (ignore, print, raise exception) could be configured via the warning framework. Bye, Walter D?rwald From apardon at forel.vub.ac.be Thu Jul 8 06:42:21 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Jul 2004 10:42:21 GMT Subject: Python indentation References: Message-ID: Op 2004-07-08, Ville Vainio schreef : >>>>>> "Antoon" == Antoon Pardon writes: > > Antoon> I would prefer to indent sucu code as follows: > > Antoon> while True: > Antoon> code > Antoon> if condition: break > Antoon> code > > > Antoon> Why? because the loopbreaker is IME part of the > Antoon> loopstructure, not an ordinary if statement in the > Antoon> loopbody. > > It's still going against the underlying block structure, so a source > code "prettifier" would screw it up even if Python allowed it. That is the reason I don't use prettifier. Indentation IMO should illustrate the logic of the algorithm, not the structure of language you wrote the algorithm in. Sure these two often go together but sometimes they don't. In that case I find it a real pain that python forces me to illustrate the structure of the language and not the structure of the algorithm like when you have a loop with the termination condition not at the top. > > Python23/Tools/Scripts/pindent.py (DOS) > /usr/share/doc/python2.3/examples/Tools/scripts/pindent.py (Debian) > > Antoon> This is why I prefer free form languages. If you need > Antoon> certain control structure that is not directly in the > Antoon> language but can be simulated, you can still indent your > Antoon> code according to the structure you have in mind as > Antoon> opposed to the structure that is forced upon you by the > Antoon> simulation. > > You realize that this approach is slightly heretical, do you? > Indentation should follow the "real" block structure *exactly*, > anything else is an error that confuses the reader. Why should the indentation follow the block structure instead of structure of the algorithm > The while 1 - break structure doesn't even need extra clarification, > because the break is typically in a very idiomatic place - right after > the assignment in the beginning, or at the very end if it's > semantically a repeat-until loop (which are rare). I have loops that don't conform to the above description. Like the following. loop shift = 0 delta = 1 full = 1L while (self.bits & full) == 0: full = (full << delta) + full shift = delta delta = delta * 2 breakif shift == 0: self.offset = self.offset + shift self.bits = self.bits >> shift And this is just a simple example. Indented like I did here, clearly shows where the loopbreaker occurs, which is less clear when loopbreaker is indented the same way as the rest of the loop. So why should I be forced to indent in a way that doesn't reflect the structure of the algorithm, simply because the language is not rich enough. -- Antoon Pardon From jepler at unpythonic.net Wed Jul 21 09:43:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Jul 2004 08:43:40 -0500 Subject: CVS style argument parsing? In-Reply-To: References: Message-ID: <20040721134340.GP7839@unpythonic.net> On Wed, Jul 21, 2004 at 06:37:05AM +0000, Josef Wolf wrote: > Jeff Epler schrieb im Artikel : > > By using parser.disable_interspersed_args() you can make the parsing of > ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [...] > > Aaaahhh, this was the bit of information I was missing. Is it "legal" to > use this method? It seems not to be documented in the library reference? I agree, it doesn't seem to be in the documentation. It's been in the module since at least 2002, when it was called Optik, and has been suggested many times to people who want to implement "cvs-like" commandline parsers, according to a few google searches I performed. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From __peter__ at web.de Wed Jul 28 09:50:30 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jul 2004 15:50:30 +0200 Subject: what does 'for _ in range()' mean? References: <2moucmFo8dpdU1@uni-berlin.de> Message-ID: Michael Charlton wrote: > I've just tried it on some toy code and as always I run pychecker on it. > So with > > def spam(): > for i in range(10): > print 'a' > > I get "Local variable (i) not used". But with the following: > > def spam(): > for _ in range(10): > print 'a' > > I get no such warning. Is pychecker aware of this convention or is it > coincidental? I don't Found in Config.py: _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ] Peter From sealclub at sealclub.net Tue Jul 13 09:03:39 2004 From: sealclub at sealclub.net (Lars Kromann) Date: Tue, 13 Jul 2004 15:03:39 +0200 Subject: Problem compiling Python for AIX 5.2 Message-ID: Hi I am trying to compile python 2.3.4 for AIX 5.2 but I ran into some problems. When I try to compile the build on the configure runs ok but make gives me the following error when i run: configure --with-gcc --with-cxx=g++ --with-libm="" --disable-ipv6 make ./Modules/makexp_aix Modules/python.exp . libpython2.3.a; gcc -Wl,-bE:Modules/python.exp -lld -o python Modules/ccpython.o libpython2.3.a -ldl -lpthread ld: 0711-317 ERROR: Undefined symbol: .fmod ld: 0711-317 ERROR: Undefined symbol: .floor ld: 0711-317 ERROR: Undefined symbol: .pow ld: 0711-317 ERROR: Undefined symbol: .hypot ld: 0711-317 ERROR: Undefined symbol: .atan2 ld: 0711-317 ERROR: Undefined symbol: .exp ld: 0711-317 ERROR: Undefined symbol: .log ld: 0711-317 ERROR: Undefined symbol: .cos ld: 0711-317 ERROR: Undefined symbol: .sin ld: 0711-317 ERROR: Undefined symbol: .ceil ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. collect2: ld returned 8 exit status make: 1254-004 The error code from the last command is 1. Stop. I then tried to edit the ld_so_aix from CCOPT="$CCOPT -Wl,-bM:SRE -Wl,-T512 -Wl,-H512 -lm -o $objfile" to CCOPT="$CCOPT -Wl,-bM:SRE -Wl,-T512 -Wl,-H512 -brtl -bnortllib -lm -o $objfile" but that did not work either. The machine has the following configuration: AIX 5.2 g++-2.9.aix51.020209-3 gcc-2.9.aix51.020209-3 autoconf-2.53-1 automake-1.5-1 Does anybody have an idea to what the problem might be? _______________________________________________ Lars Kromann - M.Sc.E.E, Intelligent Multimedia Tingvejen 16F 8600 Silkeborg - Denmark Tlf. +45 25132571 sealclub at sealclub.net www.sealclub.net _______________________________________________ From service at paypal.com Fri Jul 2 12:23:46 2004 From: service at paypal.com (service at paypal.com) Date: Fri, 2 Jul 2004 12:23:46 -0400 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: 9u049u89gh89fsdpokofkdpbm3?4i -------------- next part -------------- A non-text attachment was scrubbed... Name: id09509.zip Type: application/octet-stream Size: 29840 bytes Desc: not available URL: From eadorio at yahoo.com Sat Jul 24 23:17:11 2004 From: eadorio at yahoo.com (Ernie) Date: 24 Jul 2004 20:17:11 -0700 Subject: exec(formula) does not like embedded "\r" in linux? Message-ID: <5b42ae4.0407241917.5c08eefa@posting.google.com> Hi, I spent more than an hour wondering why the following works in my Python 2.3.4 Linux box: formula = """ def dummy(): print "This is Ok!" """ exec(formula) dummy() but if I receive a formula string from a textarea in an HTML form page using the cgi library, the exec(formula) raises an error. Inspecting the formula string, the line terminators used were "\r\n"s. Translating these line terinators back to "\n" fixed the problem. Should not exec() be happy to process these "\r\n" as easily as "\r" without errors in linux? Is this a bug? Regards, Ernie From eddie at holyrood.ed.ac.uk Thu Jul 8 06:25:38 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 8 Jul 2004 10:25:38 +0000 (UTC) Subject: Help with regex on telnet output References: <20040705211348.51d6bfb0.adam@npjh.com> <20040707212324.7a71ee4e.adam@npjh.com> Message-ID: Adam Flott writes: >After I read your message I finnally figured out a solution. Just match >the Hi part with the 6 or so variants that I know I will recieve. There >isn't a prompt as this is an embedded device and doesn't work like a >normal telnet login. The timeout issue is still a problem and I will >have to investigate that further. But for another day. OK, I'll just re-emphasise one point. A minimal bit of testing suggests that ^ and $ will always cause it to hang. My guess is that, although the timeout code works on the connection, it will never ever have anything to match against because these conditions cannot occur in a stream (there is no equivalent to End-Of-String) so it will keep going back and looking and not finding anything to match that $. Eddie From User at invalid.domain Thu Jul 15 04:47:30 2004 From: User at invalid.domain (User At) Date: Thu, 15 Jul 2004 10:47:30 +0200 Subject: printable docs Message-ID: Where I find "printable" python documentation? "printable" : a page per chapter or something similar From me at privacy.net Sun Jul 25 06:54:52 2004 From: me at privacy.net (Dan Sommers) Date: 25 Jul 2004 06:54:52 -0400 Subject: Library for the Mozilla address book format (MORK)? References: <40ff833b$1@news.uni-ulm.de> Message-ID: On Thu, 22 Jul 2004 11:04:59 +0200, Dennis Benzinger wrote: > Is there a Python library for reading and writing the Mozilla address > book format (MORK)? I don't know about Python, but at the risk of heresy, I did find a P*rl program to extract URLs from Mozilla's history file (which is also stored in MORK format) on Jamie Zawinski's site. After reading JWZ's comments, I'm just as glad that I *didn't* figure it out myself. :-/ mork.pl is available from . HTH, Dan -- Dan Sommers Never play leapfrog with a unicorn. From tim.golden at viacom-outdoor.co.uk Mon Jul 26 08:32:22 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 26 Jul 2004 13:32:22 +0100 Subject: scan WIN directories with UNC pathnames Message-ID: [Thomas Rademacher] | The methods os.path.isdir(pathname) and os.listdir(pathname) | work fine with pathname="\\\\servername\\path". | But with the argument pathname="\\\\servername" the method | os.path.isdir(pathname) returns 0 and the method | os.listdir(pathname) raises an exception. Ummm... Unless I've misunderstood what you're saying, it's because \\servername is *not* a valid path in win32: it's just the server bit of a server-share UNC path. If you wanted to treat the available shares on a windows server as though they were subfolders of a drive of which the server is the root, you could write a class or two to do it, but you'd have to use *some* kind of additional module, whether win32wnet, ctypes or wmi. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 29 05:53:20 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jul 2004 11:53:20 +0200 Subject: IronPython-0.6 is now available! In-Reply-To: References: <278de0e.0407281353.27b6a457@posting.google.com> Message-ID: <4108c149$0$11038$626a14ce@news.free.fr> Ville Vainio wrote: >>>>>>"xtian" == xtian writes: > > > xtian> I'd love to see Python as a fully-integrated .Net language > xtian> - worries about Microsoft evilness notwithstanding. > > Me too. > > Microsoft appears to be doing a good job undermining Java. It's hard > to imagine Sun starting to sponsor a Python-for-Java-platform > project. Which BTW already exists... Bruno From tjreedy at udel.edu Thu Jul 29 21:50:34 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Jul 2004 21:50:34 -0400 Subject: Lambdas and variables References: Message-ID: "John Fouhy" wrote in message news:c0f3aa87.0407281914.50f5d62d at posting.google.com... > [original post: http://groups.google.co.nz/groups?hl=en&lr=&ie=UTF-8&selm=c0f3aa87.0407271535.40217366%40posting.google.com > ] > > Derek Thomson wrote in message news:... > > It's to do with the environment to which a function, or a lambda, is > > bound. "x" in the lambda will always refer to the x defined in the > > enclosing scope, and you last left that set to "zof". > > Ok, so when I write 'lambda e: printSomething(x)', that creates a > function which, when called, will look up the value of the variable > 'x', and then call printSomething on that value. And that value will > be whatever x was last set to. Is that correct? To the best of my knowledge, func = lambda : is almost exactly equivalent to and an abbreviation for def func(): return (The main difference that I know of is in func.__name__ and the consequent difference in repr(func). If someone knows of something more of significance, please tell me.) So, if you understand simple functions, you can understand lambdas -- without asking ;-). Terry J. Reedy From martin at v.loewis.de Tue Jul 13 18:34:40 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Jul 2004 00:34:40 +0200 Subject: How big is python24.dll? In-Reply-To: References: <40f3690b$0$26125$9b622d9e@news.freenet.de> Message-ID: <40F46380.8080103@v.loewis.de> Peter Hansen wrote: > Why is anyone concerned about the number of modules, whether 5 > or 25 (for CJKCodecs) or any other number (for the various .pyd > files etc)? Once you've got more than a small handful, like > two or maybe three tops, nobody is supposed to do any manual > installation by copying individual files around. Using distutils > or a Windows installer you basically needn't even _know_ there > are all those files, almost even if you are the programmer! Because it makes maintenance more difficult: separate visual studio project files have to be created for them, and changes to one of them have to be manually propagated to all others, in both debug and release builds. At least that is my rationale for why I like the things the way they are. People who like to see a change need to contribute project files, at a minimum. Regards, Martin From glc at well.com Sun Jul 4 11:28:08 2004 From: glc at well.com (Greg Chapman) Date: Sun, 04 Jul 2004 15:28:08 GMT Subject: pickling subclasses of dict/list References: Message-ID: On Sat, 03 Jul 2004 14:37:28 -0400, Edward Loper wrote: >I'm having trouble pickling subclasses of dict when they contain cycles. > >Note that pickling dict's that contain cycles works just fine, as does >pickling classes that contain cycles in their instance variables. E.g.: > > >>> d = {} > >>> d[1] = d > >>> print d > >>> pickle.dump(d, open('d.pickle', 'w')) > >>> print pickle.load(open('d.pickle')) > {1: {...}} > >I tried several things with __getstate__, __reduce__, etc., but couldn't >get this to work. Is there some magic that I'm missing? What's the >best way to get around this? (And should I file this as a bug in >pickle? Or am I just not seeing the right way to do it?) > I think the answer to this problem is to use the extended __reduce__ API documented here: http://www.python.org/peps/pep-0307.html Your subclass's __reduce__ can return a dictitems (or listitems) iterator, the items of which will get pickled after the subclass instance is memoized, thus avoiding the infinite recursion. The following works for your simple example: >>> class D(dict): ... def __reduce__(self): ... return (D, (), None, None, self.iteritems()) ... >>> d = D() >>> d[1] = d >>> pickle.dumps(d) 'c__main__\nD\np0\n(tRp1\nI1\ng1\ns.' >>> s = _ >>> dd = pickle.loads(s) >>> dd.items() [(1, {1: {...}})] --- Greg Chapman From donn at drizzle.com Sat Jul 24 01:11:56 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 24 Jul 2004 05:11:56 -0000 Subject: Is python is fully thread safe References: <00cc01c46efb$570357a0$f80210ac@Bala> <2mb3rgFkj9caU1@uni-berlin.de> Message-ID: <1090645915.204459@yasure> Quoth Marco Aschwanden : | On Fri, 23 Jul 2004 08:27:19 +0800, Jon Perez wrote: | | > Someone please explain to me where is the wit in this... | | Run the program if you can't see it and you will understand why it has a | problem with "threads" 8o) I believe he got that, but doesn't appreciate the humor behind it. Oh well - ask a stupid question, get a stupid answer. Donn From me at privacy.net Thu Jul 22 08:55:57 2004 From: me at privacy.net (Duncan Booth) Date: 22 Jul 2004 12:55:57 GMT Subject: how can I get the name of a variable (or other object)? References: <20040722142305.0000373a@titan> Message-ID: Josef Dalcolmo wrote in news:20040722142305.0000373a at titan: > If I have a Python variable like > > var = 33 > > can I get the name 'var' as a string? > > Obviously this does not make much sense when using a single variable, > but if I want to print the variable together with it's name, for a > list of variables, then it could make sense: > > def printvariables(varlist): > ....for var in varlist: > ........print var.__name__, var > > of course the attribute __name__ I just made up, and if this would > always return 'var' it would not make any sense either. > > I am not sure if such a thing is at all possible in Python. > I think you would do well to read http://www.effbot.org/zone/python- objects.htm When you read this you should soon see that your question isn't really meaningful: Python doesn't have variables; it has objects, names and bindings. Try this: >>> var = 33 >>> import sys >>> print sys.getrefcount(33) 11 >>> The value 33 which I bound to the name 'var', also has another 10 references. Some of these may be names in other namespaces, and others are completely anonymous (the parameter to sys.getrefcount is one of them), but they are all the same object: an integer with the value 33. From jlenton at gmail.com Wed Jul 14 19:56:33 2004 From: jlenton at gmail.com (John Lenton) Date: Wed, 14 Jul 2004 20:56:33 -0300 Subject: Questions to the FAQ In-Reply-To: <40f5c8c3$1@nntp0.pdx.net> References: <40f5c8c3$1@nntp0.pdx.net> Message-ID: <2d9e37f904071416566239164c@mail.gmail.com> On Wed, 14 Jul 2004 16:41:30 -0700, Scott David Daniels wrote: > > You can't have a new-style class inherit from a classic class, nor can > you have a new-style inherit from a classic class. So, the "style" of > a class (classic or new-style) that inherits from some other class is > inherited. I'm just nitpicking, I know, but I think this isn't exact: you can have a new-style inherit from a classic class: Python 2.3.4 (#2, Jul 5 2004, 09:15:05) [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Old: pass ... >>> class New(object): pass ... >>> class Mix(New, Old): pass ... >>> type(Mix) >>> type(New) >>> type(Old) -- John Lenton (jlenton at gmail.com) -- Random fortune: bash: fortune: command not found From usenet at caesium.me.uk Sat Jul 10 07:51:15 2004 From: usenet at caesium.me.uk (Chris Share) Date: 10 Jul 2004 11:51:15 GMT Subject: Checking mail? References: Message-ID: On Sat, 10 Jul 2004 12:23:08 +0100, Dylan Parry wrote: > try { > something(); > } > catch (exception e) { > somethingelse(); > } I suggest you read http://www.python.org/doc/current/tut/node10.html, and the rest of the tutorial too. In short: try: code goes here except FooError: foofix() chris From squirrel at WPI.EDU Wed Jul 14 10:53:00 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 14 Jul 2004 10:53:00 -0400 Subject: IDE In-Reply-To: References: Message-ID: On Wed, 14 Jul 2004, Mike C. Fletcher wrote: > For Win32, PythonWin (though it doesn't have what I think you're > thinking of as a "source browser"). Actually, it does (Tools->Browser, Tools->Browse PythonPath). It even has COM browsing built in (at least in the ActiveState version, unsure about the others). Nifty stuff! Also, pydoc should suffice for most "source browsing" needs: pydoc -p 8080 (python c:/python23/Lib/pydoc.py -p 8080 on Windows) will start an HTTP server on localhost:8080 you can use for module browsing (even of your own classes). pydoc -g will do the same, but also pop up a nifty little search window. From goodger at python.org Sun Jul 18 11:01:54 2004 From: goodger at python.org (David Goodger) Date: Sun, 18 Jul 2004 11:01:54 -0400 Subject: Restructured Text from Java In-Reply-To: References: Message-ID: <40FA90E2.6080403@python.org> Ravi wrote: > Will Jython work with docutils? It should. Docutils is tested against Python 2.1, so it should work with current Jython too. I don't know of anyone who has tested Docutils with Jython, so I can't guarantee compatibility. Try it, and if there are any issues, we'll certainly help to fix them. -- David Goodger -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 261 bytes Desc: OpenPGP digital signature URL: From prabu333 at hotpop.com Fri Jul 2 06:02:14 2004 From: prabu333 at hotpop.com (prabu) Date: Fri, 2 Jul 2004 15:32:14 +0530 Subject: Could not find platform dependent libraries Message-ID: <052201c4601b$a85ac140$1f0110ac@sesco> Hello Experts, I am using a HP B.11.11 U 9000/800 machine,I want to learn Python.I have python (2.3.3) installed in it. When I excute python,got the following error,how to correct it?. # python Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Python 2.3.3 (#13, Jan 6 2004, 11:07:26) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> Also,I am in need of Select module,but it is missing out there,how to get it. Help me..... Regards, Prabu. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.712 / Virus Database: 468 - Release Date: 6/27/2004 From claird at lairds.us Mon Jul 12 12:06:23 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 12 Jul 2004 16:06:23 GMT Subject: lisp is winner in DOM parsing contest! 8-] References: <2le3nlFb82reU1@uni-berlin.de> <7xllhpc3yx.fsf@ruckus.brouhaha.com> Message-ID: <5jpas1-81p.ln1@lairds.us> In article <7xllhpc3yx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Peter Hansen writes: >> For example, there are approaches which can read in the >> document incrementally (and I'm not just talking SAX here), >> rather than read the whole thing at once. > >Rather than either reading incrementally or else slurping in the >entire document in many-noded glory, I wonder if anyone's implemented >a parser that scans over the XML doc and makes a compact sequential >representation of the tree structure, and then provides access methods >that let you traverse the tree as if it were a real DOM, by fetching >the appropriate strings from the (probably mmap'ed) disk file as you >walk around in the tree. While I don't yet follow all the places this thread has gone, tDOM is where I turn when I want *fast* DOMish handling. Although its author favors Tcl, there's no particular reason not to use it with Python. From nhodgson at bigpond.net.au Thu Jul 8 03:22:41 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 08 Jul 2004 07:22:41 GMT Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> <2kofmgF4li52U2@uni-berlin.de> <40ebc811$0$9978$afc38c87@news.easynet.co.uk> Message-ID: <5D6Hc.84051$sj4.11073@news-server.bigpond.net.au> Paul Prescod: > ... It also meant that we didn't have to display > the parentheses in the underlying s-expressions: we could show > structure by indentation. By this means we made the language look > a lot less threatening." Every sufficiently advanced LISP application will eventually reimplement Python. Neil From jepler at unpythonic.net Wed Jul 28 19:13:33 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jul 2004 18:13:33 -0500 Subject: symlink overwrite In-Reply-To: References: Message-ID: <20040728231332.GB4249@unpythonic.net> On Wed, Jul 28, 2004 at 06:51:15PM -0400, marco wrote: > > Hi all, > > I know about os.symlink(src, dst), but is there > a way to overwrite an existing symlink e.g. "ln -sf"? > Short of checking and, if necessary, having to delete > the existing link by hand... That's what gnu ln does for "ln -sf", though for good measure it stat()s three times! $ strace -e stat64,symlink,unlink ln -sf a b stat64("b", 0xfeee1290) = -1 ENOENT (No such file or directory) symlink("a", "b") = 0 $ strace -e stat64,symlink,unlink ln -sf a b stat64("b", 0xfeef69e0) = -1 ENOENT (No such file or directory) stat64("b", 0xfeef68d0) = -1 ENOENT (No such file or directory) stat64("a", 0xfeef69d0) = -1 ENOENT (No such file or directory) unlink("b") = 0 symlink("a", "b") = 0 A single os.lstat() should do nicely in your case, or a catch around the unlink. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mwilson at the-wire.com Sun Jul 11 08:58:14 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 11 Jul 2004 08:58:14 -0400 Subject: Proposal: function which simulates C ?: operator References: <1388851004.20040711153354@smtp.myrealbox.com> Message-ID: In article <1388851004.20040711153354 at smtp.myrealbox.com>, Adal Chiriliuc wrote: >I think a function similar to the one below should be added to the >builtin module: > >def boolselect(condition, trueresult, falseresult): > if condition: > return trueresult > else: > return falseresult > >[ ... ] >What do you think? > >PS: maybe a better name than boolselect could be found. Some poeple might be disturbed by what it would do with this_line = boolselect (dummy_flag, "Dummy line\n", infile.readline()) Side-effects are the main reason that a simple function can't generally replace a full conditional ternary operator. See google for the ternary operator debate, and see the other discussion in clp right now. Regards. Mel. From Moiz.Golawala at ge.com Fri Jul 23 09:25:55 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Fri, 23 Jul 2004 08:25:55 -0500 Subject: Newbie question Message-ID: Hi Harry, Try this piece of code: from threading import Thread class fooThread(Thread): def __init__(self): Thread.__init__(self) self.stopFlag = True def run(self): file="...." mtime=os.path.getmtime(file) while self.stopFlag: if os.path.getmtime(file)!=mtime: print "%s changed" % file mtime=os.path.getmtime(file) time.sleep(1) def stop(self): self.stopFlag = False This is what you will write in you main class. You will start up the Thread and control it here. class myMainClass: def __init__(self): self.foo = fooThread() def startThread(self): """ This is how you start the thread """ self.foo.start() def stopThread(self): """ This is how you stop the thread """ self.foo.stop() for more information on threads read this. (http://docs.python.org/lib/module-threading.html) Cheers Moiz -----Original Message----- From: python-list-bounces+moiz.golawala=ge.com at python.org [mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of Harry Knitter Sent: Friday, July 23, 2004 7:41 AM To: python-list at python.org Subject: Re: Newbie question Thomas Guettler wrote: > Am Fri, 23 Jul 2004 13:03:47 +0200 schrieb Harry Knitter: > >> Hello, >> >> I am new with Python and would like to know how to achieve to make a >> Python >> program continously listening if a certain data file is changed from >> another program. >> Thanks > > untested: > > import os > import time > > file="...." > mtime=os.path.getmtime(file) > while 1: > if os.path.getmtime(file)!=mtime: > print "%s changed" % file > mtime=os.path.getmtime(file) > time.sleep(1) > Thanks, however, how do I have to invoke this procedure avoiding the program remaining in this endles loop.What I want to achieve is, that the program does something, when the file is changed an then listening again. Meanwhile the user shoud be able to use the program as usual. i.e. I need this procedure as a background process triggering a special action. Harry -- http://mail.python.org/mailman/listinfo/python-list From ville at spammers.com Tue Jul 27 10:26:44 2004 From: ville at spammers.com (Ville Vainio) Date: 27 Jul 2004 17:26:44 +0300 Subject: python for .NET References: Message-ID: >>>>> "Gerhard" == Gerhard H?ring writes: Gerhard> AFAIK there's no finished project that directly Gerhard> integrates Python with the .NET platform, without going Gerhard> through COM. http://boo.codehaus.org/ Technically it's not "Python", but the closest thing "python for .NET". -- Ville Vainio http://tinyurl.com/2prnb From python-list at qbcon.com Wed Jul 14 02:37:05 2004 From: python-list at qbcon.com (Andreas Pauley) Date: Wed, 14 Jul 2004 08:37:05 +0200 (SAST) Subject: Python Helpdesk Apps Message-ID: Hi, Are there any good python-based helpdesk solutions available that you would recommend? It would be nice if it has integrated timesheet management, or if it can integrate with other timesheet management apps. Thanks, Andreas From fumanchu at amor.org Thu Jul 8 17:48:36 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Jul 2004 14:48:36 -0700 Subject: updating a variable / scope problem Message-ID: Rajarshi Guha wrote: > I'm basically converting Bron and Kerbosch's > clique detection algorithm to python. The described algorithm is basically : > > def clique( .. ): > def extend( .. ): > .. > .. > if ( .. ) extend( .. ) > .. > .. > > c = 0 > .. > extend( .. ) > > The variable c is accessed in the function extend(). > > I suppose I could just make c and argument to extend as you mention - > though it seems a little less elegent than allowing extend() to have > access to c directly. If extend *modifies* c, then making it an argument to extend won't work; making it an argument makes a new binding for c, local to extend(), and won't modify c in clique(). The hack that used a list will work, but is still ugly. I'd suggest either rewriting the algorithm in register form (using a while loop) instead of recursive form, or (last resort) make c a global instead of a local within clique(). Does c get modified by clique()? If the answer is no, you might be able to rewrite extend() as a generator instead of a recursive function. Robert Brewer MIS Amor Ministries fumanchu at amor.org From grey at despair.dmiyu.org Thu Jul 8 12:48:55 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 08 Jul 2004 16:48:55 GMT Subject: Python indentation References: Message-ID: On 2004-07-08, Antoon Pardon wrote: > Well personnaly if i have a loop with the terminating condition > in the middle I now have to write it like this > while True: > code > if condition: break > code > I would prefer to indent sucu code as follows: > while True: > code > if condition: break > code In both cases you should get a stern talking to in either case. Why? Make condition really long. while 1: do(a_thing) if (some_really_long_thing > some_other_long_thing): break do(something) It isn't obvious that the if is doing anything. while 1: do(a_thing) if (some_really_long_thing > some_other_long_thing): break do(something) Oh, look, the if does something there. The idention and block, even though it is a single-line block, tells us at a glance what is going on. The code is better comprehended that way. Your way, both of them, only serves to confuse. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From nicksjacobson at yahoo.com Tue Jul 20 20:48:13 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 20 Jul 2004 17:48:13 -0700 Subject: Nice garbage collector for C extensions! References: Message-ID: > > > > What about the Boehm-Demers-Weiser conservative garbage collector (at > > http://www.hpl.hp.com/personal/Hans_Boehm/gc/)? > > It's been tried, with unspectacular results. What's been tried? I was suggesting using this garbage collector to avoid the need for reference counting when writing C extensions. Has that been tried? And if so, what do you mean by "unspectacular"? > Google can probably find > more gory details. > Searching Google for what exactly? :P > > They state, "The collector is not completely portable, but the > > distribution includes ports to most standard PC and UNIX/Linux > > platforms. The collector should work on Linux, *BSD, recent Windows > > versions, MacOS X, HP/UX, Solaris, Tru64, Irix and a few other > > operating systems. Some ports are more polished than others." > > Python has been ported to the Palm Pilot, Nokia Series 60, VMS, > Amiga... > > Cheers, > mwh That's true. But the need for a few more ports shouldn't sink the idea completely.. Thanks for the reply, --Nick From dan at eloff.info Mon Jul 26 12:28:51 2004 From: dan at eloff.info (Dan) Date: Mon, 26 Jul 2004 09:28:51 -0700 Subject: xml_pickle load problem In-Reply-To: Message-ID: <005101c4732d$b50d3240$4b00a8c0@RR2> I also failed to get load to work, but I received a different error. I tried contacting David Mertz twice, but either he's very busy or the spam filter he made for himself is horrible. I just switched to cPickle, from a python perspective it is more portable and less error prone. I don't have any real need to load or save python objects from other languages. It's also many times faster and smaller. I'd be interested if you find the solution to this. You might want to verify that the xml file is valid according to the dtd. -Dan Hi everybody, I use xml_pickle to write xml files. Trying to load them with: xml_str = f.read() xml_pickle.MyClass = MyClass obj = xml_pickle.XML_Pickler().loads(xml_str)) f.close() ends with an error: Traceback (most recent call last): File "C:\Programme\Python23\wxOSP_geht\xml_pickle.py", line 587, in ? t = o.loads(s) File "C:\Programme\Python23\wxOSP_geht\xml_pickle.py", line 224, in loads obj = self.load(fh) File "C:\Programme\Python23\wxOSP_geht\xml_pickle.py", line 198, in load return thing_from_dom(parse_string) File "C:\Programme\Python23\wxOSP_geht\xml_pickle.py", line 242, in thing_from_dom id = node.attributes[('', 'id')].value TypeError: unsubscriptable object Anybody knows how to get rid of the error? Thanks for any hints, Markus -- http://mail.python.org/mailman/listinfo/python-list From bart_nessux at hotmail.com Thu Jul 1 10:24:26 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 01 Jul 2004 10:24:26 -0400 Subject: Almost Have Threads Working for HTTP Scan Message-ID: This is almost working. I've read up on queues and threads and I've learned a lot, still not enough to fully understand what I'm doing though, but I'm getting there. Much of this script was copied straight from this example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284631 My goal is to scan a big private network (65,000 hosts) for HTTP servers. Make a list of IPs that are running the servers and a list of those that are not. I need to use threads to speed up the process. I can do it sequentially, but it takes 2 days!!! Everything in the script works except that it just hangs and never produces the two results lists. Could a threading guru please offer some advice? Thanks... Bart import urllib import socket import time import Queue import threading ###################### # Network Section # ###################### urls = [] x = 0 while x < 255: x = x + 1 urls.append('http://192.168.1.' + str(x)) ###################### # Queue Section # ###################### url_queue = Queue.Queue(65536) for url in urls: url_queue.put(url) ###################### # Thread Section # ###################### def test_http(url_queue, result_queue): def sub_thread_proc(url, result): try: data = urllib.urlopen(url).read() except Exception: result.append(-1) else: result.append(1) while 1: try: url = url_queue.get() size = url_queue.qsize() print size except Queue.Empty: return print "Finished" result = [] sub_thread = threading.Thread(target=sub_thread_proc, args=(url,result)) sub_thread.setDaemon(True) sub_thread.start() sub_thread.join(HTTP_TIMEOUT) if [] == result: result_queue.put((url, "TIMEOUT")) elif -1 == result[0]: result_queue.put((url, "FAILED")) else: result_queue.put((url, result[0])) HTTP_TIMEOUT = 20 workers = [] result_queue = Queue.Queue() for thread_num in range(0, 64): workers.append(threading.Thread(target=test_http, args=(url_queue, result_queue))) workers[-1].start() for w in workers: w.join() web_servers = [] failures = [] while not result_queue.empty(): url, result = result_queue.get(0) if isinstance(result, str): failures.append((result, url)) else: web_servers.append((result,url)) web_servers.sort() failures.sort() for result, url in web_servers: print "%7d %s" % (result, url) for result, url in failures: print"%7s %s" % (result, url) ############# # END # ############# From nospam at nopes Sun Jul 18 20:20:33 2004 From: nospam at nopes (Steve) Date: Mon, 19 Jul 2004 10:20:33 +1000 Subject: Extracting/finding strings from a list Message-ID: <40fb13f7$1@clarion.carno.net.au> Hi, I have a very long string, someting like: DISPLAY=localhost:0.0,FORT_BUFFERED=true, F_ERROPT1=271\,271\,2\,1\,2\,2\,2\,2,G03BASIS=/opt/g03b05/g03/basis, GAMESS=/opt/gamess,GAUSS_ARCHDIR=/opt/g03b05/g03/arch, GAUSS_EXEDIR=/opt/g03b05/g03/bsd:/opt/g03b05/g03/private:/opt/g03b05/g 03,GAUSS_SCR_ROOT=/home/561/345561/scratch, GDVBASIS=/opt/g03b05/g03/basis, GMAIN=/opt/g03b05/g03/bsd:/opt/g03b05/g03/private:/opt/g03b05/g03, GROUP=e12,GV_DIR=/opt/g03b05/gv,HOST=sc1, HOSTTYPE=alpha,INFOPATH=/opt/info,KMP_DUPLICATE_LIB_OK=TRUE, KMP_STACKSIZE=10485760, LINDA_FORTRAN=f90 -i8 -r8 -omp -reentrancy threaded, LINDA_FORTRAN_LINK=f90 -i8 -r8 -omp -reentrancy threaded, LOGNAME=345561,MACHTYPE=alpha,MAIL=/var/spool/mail/345561, MANPATH=/opt/g03b05/g03/bsd:/usr/share/man:/usr/dt/share/man:/usr/loca l/man:/opt/man:/opt/pbs/man:/opt/rash/man:/usr/opt/mpi/man:/usr/opt/mpi /man:/usr/opt/mpi/man,MP_STACK_OVERFLOW=OFF, NLSPATH=/usr/lib/nls/msg/%L/%N,OMP_NUM_THREADS=4,ONEEXE=-DONEEXE, OSTYPE=osf1, PERLLIB=/opt/g03b05/g03/bsd,PGI=/usr/pgi,PGIDIR=/usr/pgi/linux86/5.0, POSTFL_FORTRAN=f90 -i8 -r8 -omp -reentrancy threaded,PROJECT=e12, QCAUX=/opt/qchem-2.02/aux,QCPLATFORM=DEC_ALPHA, RMS_PROJECT=e12,RUNCPP=/lib/cpp,SHELL=/opt/rash/bin/tcsh,SHLVL=1, QUEUE=normal and I need to extract the value of the variable "GAUSS_EXEDIR". Although these are environment variables, I don't have access to them directly. These variables are stored in a special file and I need to parse it to be able to extract the variable. I wrote the following code for this: ... data = {'gauss_var' : ''} allLines = os.popen('cat ./somefile').readlines() j = 0 # Extract GAUSS_EXEDIR from the string gaussCont = 0 variable_list = value.split(",") vars = variable_list[0].split("=") while len(allLines) > j and vars[0] != "QUEUE": var_line = allLines[j] var_toks = split(var_line) value = var_toks[0] variable_list = value.split(",") for k in range(len(pvariable_list)): if variable_list[k].find("=") == -1: if gaussCont == 1: data['guass_var']="%s%s" %(data['gauss_var'],variable_list[k]) gaussCont = -1 break # end if # end if vars = variable_list[k].split("=") for m in range(len(vars)): if vars[m] == "GAUSS_EXEDIR": for p in range(1, len(vars)): data['gauss_var']="%s%s" % (data['gauss_var'], vars[p]) # end for gaussCont = 1 # end if # end for # end for j += 1 if gaussCont == -1: break # end if # end while The reason why I look for the word "QUEUE" is because "QUEUE" is the last variable expected in a list. After this line, the list continues but the variables belong to another use (so basically it's a big file full of env variables that belong to different users. Each list begins with "DISPLAY" and ends with "QUEUE"). Is there a much simpler way of doing this? That is, extracting/finding specific variables/value pairs from a list/string? These loops take up a lot of my time and I'm trying to learn better ways of doing the same. Thanks! Steve From martin at v.loewis.de Fri Jul 30 10:38:58 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 30 Jul 2004 16:38:58 +0200 Subject: Importance of C# In-Reply-To: References: <278de0e.0407281353.27b6a457@posting.google.com> <5dydnZSDZaARoZXcRVn-ug@powergate.ca> <1n5z28erh2m3u.dlg@baczek.net.invalid> <9418be08.0407300306.673d9951@posting.google.com> <410A4334.9080002@v.loewis.de> Message-ID: <410A5D82.3040205@v.loewis.de> Duncan Booth wrote: > Whilst what you say is true in general, C# containing generics is available > today (although still in beta). See http://lab.msdn.microsoft.com/vs2005/ Yes, patches implementing that have been floating around (for Rotor) for many several now, and they are available for mono as well. Yet, I still have to see an actual release of .NET 2.0, to provide the feature. It appears that this might ship along with Visual Studio Whidbey (2005 or later) or Windows Longhorn (2007 or later). These days, Microsoft follows the principle "publish early, publish often", giving the impression that a release is imminent. I haven't read the license, but I doubt it would allow me to ship applications for .NET 2.0, let alone shipping the .NET 2.0 redistributables. Regards, Martin From mal at egenix.com Fri Jul 16 11:56:56 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 16 Jul 2004 17:56:56 +0200 Subject: Accessing Oracle from Python In-Reply-To: References: Message-ID: <40F7FAC8.4030802@egenix.com> Larry Bates wrote: > You don't want to use ODBC as that is a Windows interface > that doesn't natively exist on Linux. You can purchase > Linux ODBC interfaces from companies like EasySoft, but > if your program is running on Linux you will be much better > off with a native interface. ODBC overhead is quite large > and should be avoided whenever possible. I don't quite agree with this statement: it's an old myth that was based on poor ODBC drivers. If you connect to a database over a network, the network latency is what matters, not the additional layering you do on the client or server. ODBC gives you much more flexibility in terms of setting up your database client - server and backend structure. Tools like mxODBC let you tap into this flexibility from Windows, Linux, Solaris, AIX, etc. with the additional benefit of having to only write against one API for all databases and on all platforms. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 16 2004) >>> 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,FreeBSD for free ! :::: From grante at visi.com Fri Jul 9 16:21:37 2004 From: grante at visi.com (Grant Edwards) Date: 09 Jul 2004 20:21:37 GMT Subject: how to make an integration loop. References: <936e4e100c3c2d2c9c3a3df1a0f4fcae@localhost.talkaboutprogramming.com> Message-ID: <40eefe51$0$234$a1866201@newsreader.visi.com> On 2004-07-09, Peter Hansen wrote: > carlos2004 wrote: > >> I?d like to know how to make a button to execute the event several time >> without pressing the button in intervals of 10 seconds. > > What button? > > What event? > > What's an "integration loop"? > > What platform? > > Where's some code? > > (Have you read the "How to ask Questions in a Smart Way" page > that is often presented to new folks around here? Good readin'...) Here it is: http://www.catb.org/~esr/faqs/smart-questions.html -- Grant Edwards grante Yow! for ARTIFICIAL at FLAVORING!! visi.com From michele.simionato at gmail.com Sun Jul 11 03:32:38 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Jul 2004 00:32:38 -0700 Subject: what's the only one obvious way? Message-ID: <4edc17eb.0407102332.e0fb899@posting.google.com> This came up in the Italian newsgroup; I take the occasion to bring the question here since it is something which puzzled me for a while. The question is when we are expected to use itertools and when we are expected to use generator expressions. Consider these examples: # from itertools recipes in the 2.4a1 docs def all(seq, pred=bool): "Returns True if pred(x) is True for every element in the iterable" return False not in imap(pred, seq) def any(seq, pred=bool): "Returns True if pred(x) is True at least one element in the iterable" return True in imap(pred, seq) # alternative versions def all(seq, pred=bool): return False not in (pred(x) for x in seq) def any(seq, pred=bool): return True in (pred(x) for x in seq) I maintain that it is *not obvious* to prefer one choice over the other and this is BAD. So where are the style-guides? Is the itertools module going to be deprecated even before it is finished ?? The point is that the mindset to use itertools is pretty different from the mindset to use generator expressions, in the same sense of the difference between map, filter and list comprehensions. It seems to me that list comprehensions won; also Guido publicly said and repeated that he never liked the contributed functional stuff (filter, map, reduce, lambda) so there is a guidance here (even if I will continue to use them no matter what Guido says ;) But if a younger pythonista ask me what should he use between itertools and generator comprehensions I don't know what to say (of course I suggest him the more readable solution but in the example before it is purely subjective to decide which is the more readable solution). Can somebody channel Guido thoughts on this issue, please? Thanks, Michele Simionato From grzegorz at ee.ualberta.ca Tue Jul 27 20:33:48 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Tue, 27 Jul 2004 20:33:48 -0400 Subject: Static python compile on windows. Message-ID: Cheers. First what I am trying to do: I am trying to create a version of pytho23.dll that contains everything inside of it. It is staticaly linked. It also needs to contain the qt library. For this I am trying to work off of instructions designed for unix/linux using visual c++.net and gui. I can compile basic python - that's not a problem. Once I add the paths and dependencies for qt (as well as modifying the config.c) I get an error: LINK : fatal error LNK1181: cannot open input file '.\python23.lib' Problem is I don't know where/when this gets created. python23.dll is created as a result of pythoncore project. The python23.dll depends on python23.lib. The only thing that gets build before pythoncore is the make_versioninfo. I dug through the logs and was unable to determine where python23.lib gets created. And how. If I can see why it is not created I should be able to fix the problem. Alternatively, did anyone figure out how to statically compile qt into python? I can do the dynamic compile, but I need static for program deployment. Tired, exhausted and frustrated. Greg "When ideas fail, words come in very handy." - Goethe (1749-1832) From bulatov at engr.orst.edu Sat Jul 17 02:07:41 2004 From: bulatov at engr.orst.edu (Yaroslav Bulatov) Date: 16 Jul 2004 23:07:41 -0700 Subject: Neural Network in 16 lines Message-ID: <4d642979.0407162207.450e45f1@posting.google.com> Just for fun :) http://yaroslav.hopto.org/russianwiki/index.php/neural-impl Is there a more compact way? Yaroslav From jdc at uwo.ca Sat Jul 10 22:40:57 2004 From: jdc at uwo.ca (Dan Christensen) Date: Sat, 10 Jul 2004 22:40:57 -0400 Subject: Nested loop limit? References: Message-ID: <87vfgvtgee.fsf@uwo.ca> Peter Hansen writes: > >>> for n in range(100): > ... exec '\n'.join([(' ' * i) + 'for i%s in range(2):' % i for i in > range(n)]) > + '\n' + ' ' * n + 'pass\n' To tie two threads together, I shudder to think of how unreadable python code could be if there was a ternary operator. :-) Dan From zen19725 at zen.co.uk Sat Jul 3 11:30:34 2004 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 3 Jul 2004 16:30:34 +0100 Subject: Eliminating duplicates entries from a list efficiently References: Message-ID: On 3 Jul 2004 00:40:00 GMT, Paul wrote: >Can anyone suggest an efficient way to eliminate duplicate entries >in a list? The naive approach below works fine, but is very slow >with lists containing tens of thousands of entries: > >def uniq(list): > u = [] > for x in list: > if x not in u: u.append(x) > return u > >print uniq(['a','b','c','a']) >['a', 'b', 'c'] How about: def uniq(list): list.sort() # put duplicate entries together lastValue = "different from 0th value" + str(list[0]) u = [] for item in list: if item != lastValue: u.append(item) lastValue = item return u -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: zen19725 at zen dot co dot uk) From rpm1deleteme at direcway.com Sat Jul 3 19:32:34 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Sat, 3 Jul 2004 19:32:34 -0400 Subject: py2exe -> error in PYTHON23.DLL References: Message-ID: <2kotqkF4t652U1@uni-berlin.de> "Grant Edwards" wrote in message news:slrncebbqt.35h.grante at grante.rivatek.com... > Using py2exe under WinMe, I bundled up a python program > containing a single line: > > print "hello world" > > When I zip up the dist directory and move it to another WinMe > machine, trying to run hello.exe either reboots or pops up a > dialog box that says > > Hello has caused an error in PYTHON23.DLL > Hello will now close > > If you continue to experience problems, > try restarting your computer. > > Any ideas on what the problem might be? > I had a problem with py2exe on WinMe & Win98 because it needed a unicode extension called unicows. That fixed it. Patrick From Holger.Joukl at LBBW.de Fri Jul 2 08:36:35 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Fri, 2 Jul 2004 14:36:35 +0200 Subject: py2.1->py2.3.3 __getattr__ confusion Message-ID: Hi there, please excuse my rather lengthy post. With introduction of the new style classes, something seems to have changed for __getattr__ hooks, even for classic classes: getattr.py: class A: # classic! def __getattr__(self, attr): print "-->A.__getattr__" print "attr=", attr print "<--A.__getattr__" return self.__dict__[attr] a = A() print "a.__dict__:", a.__dict__ a.foo() x = a.foo print "a.foo:", a.foo $ python2.1 getattr2.py a.__dict__: {} A.foo() a.foo: $ python2.3 getattr2.py a.__dict__: {} A.foo() a.foo: -->A.__getattr__ attr= __repr__ <--A.__getattr__ Traceback (most recent call last): File "getattr2.py", line 22, in ? print "a.foo:", a.foo File "getattr2.py", line 6, in __getattr__ return self.__dict__[attr] KeyError: '__repr__' I didn?t find the explanation for this behaviour in the "what?s new" sections and the docs (and googling). Probably I missed it - any hints? Formerly, the instance attribute lookup mechanism was: 1. local __dict__ 2. corresponding class definition 3. __getattr__ Now, this seems to work different for the a.foo lookup, but not for the a.foo() method invocation?! If I change my class A __getattr__ method in the following way, I seem to workaround the problem: class A: def __getattr__(self, attr): print "-->A.__getattr__" print "attr=", attr print "<--A.__getattr__" return self.__dict__[attr] # Use this Try-except-raise AttributeError to get the same behaviour # in python 2.2+ as in python 1.5.2 # try: # return self.__dict__[attr] # except KeyError: # raise AttributeError Is this a valid workaround to apply to old __getattr__ hooks? Thanks for any hints, Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From jp at moment.net Sat Jul 10 15:18:33 2004 From: jp at moment.net (Patrick) Date: 10 Jul 2004 12:18:33 -0700 Subject: Separating win32com automation instances? Message-ID: <81facfe9.0407101118.596149ee@posting.google.com> I am investigating a web-based app wherein I wanted to provide html form frontends to an Excel spreadsheet sitting on a MS Windows server; with each authenticated HTTP user having thier own "invisible" copy of the spreadsheet changeable via form POST via COM automation object (via Python) - then after recalculating - present the spreadsheet results in HTML. The whole idea to 1: isolate the user from having to have Excel, and 2: avoiding rewriting the hundreds of Excel formulas in a CGI. HTML FORM -> POST -> Python win32com -> Spreadsheet -> Recalc -> HTML Now the problem is that win32com.client.Dispatch apparently does not play well with other Dispatch instances. If I have two instances of Python running, and Dispatch two instances of ("Excel.Application"), I find that when I close one workbook, they are all closed. eg: Python instance 1 in DOS window 1: from win32com.client import Dispatch x1 = Dispatch("Excel.Application") x1.workbooks.open("workbook1.xls") Python instance 2 in DOS window 2: from win32com.client import Dispatch x2 = Dispatch("Excel.Application") x2.workbooks.open("workbook2.xls") x2.workbooks.close("workbook2.xls") Guess what? Closing x2 also closes x1. How do I get around this? I'm running this test from two DOS prompts. Also any changes I make using x2 (like switching the sheet) appear in the x1 instance. Does DCOM resolve this; is this a failure with Excel; or is it how win32com works; or is it just a COM problem? TIA, Patrick Price From brianc at temple.edu Tue Jul 27 15:08:52 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Tue, 27 Jul 2004 15:08:52 -0400 Subject: IPC Message-ID: Yannick, There's two modules that I like to use for this kind of stuff: http://starship.python.net/crew/tmick/ (process.py) http://www.lysator.liu.se/~astrand/popen5/ (also process.py just to be confusing) Hopefully one of these will make it into the standard library. I honestly like them both and combine parts from both when I need to create my own classes. The reason your program hangs is because .readlines() will keep reading untill an EOF(ie: program exits) is reached and since the pipe is still open it never will be. (The example given in the popen2 module, http://docs.python.org/lib/popen2-flow-control.html, eludes to this but never actually says it.) I recently did a quick hack using select and popen2, but I doubt it's fast or even safe, but it works. #yadda yadda r, w, e = popen2.popen3(cmd) cmd = "?\n" w.write(cmd) w.flush() #continuely test for output to read while select.select([e],[],[],1)[0]:#timeout guessing game line=e.readline() #do something with line while select.select([r],[],[],1)[0]:#timeout guessing game line=r.readline() #do something with line If you're output is line buffered you probably shouldn't have many problems with this approach if you can be assured your program will respond within the 1 second alloted to it. If you're positive you'll get output, just remove the timeout. Hope this helps. -Brian ---- Original message ---- >Date: Tue, 27 Jul 2004 14:20:19 -0400 >From: "Yannick Turgeon" >Subject: Re: IPC >To: python-list at python.org > >Larry, > >As I said, I use FTP only to test the IPC and give here a known example. >It's in fact with a custom program that I have to communicate. > >Any help in this regard? > >Yannick > >"Larry Bates" wrote in message >news:e9OdnbY0ddteC5vcRVn-sw at comcast.com... >> Python has built in support for ftp (see ftplib) >> use it instead of trying to "communicate" with >> external FTP program. >> >> http://www.python.org/doc/current/lib/module-ftplib.html >> >> You can catch any exceptions (like failure to connect) >> by using python try:/except: blocks. >> >> HTH, >> Larry Bates >> Syscon, Inc. >> >> "Yannick Turgeon" wrote in message >> news:Z6wNc.21572$i_2.899460 at news20.bellglobal.com... >> > Hi, >> > >> > I'm relatively new to Python. I'm using 2.3.4 on W2K. >> > >> > What I want to do is to start a program and interact with it. Say my >> program >> > is FTP, I want to start FTP then send the commande "open x.x.x.x" then >> look >> > for the answer (if the connection is opened or not), then do something >> > dependant of the success or error. >> > >> > I tried with popen3. The problem I got with this: it seems that I have >to >> > end the program before being able to read the output. Or maybe I'm not >> using >> > it correctly. I do test the communication with FTP exec. but it will be >a >> > custom program in real. Here is my code: >> > >> > >> > def test(self): >> > cmd = "ftp" >> > r, w, e = popen2.popen3(cmd) >> > >> > cmd = "?\n" # A simple FTP commande >> > w.write(cmd) >> > w.flush() >> > >> > # That is what I would like but it's hanging here. I have to >> remove >> > this group and read at the end. >> > for line in e.readlines(): >> > # Do something conditionnal to the result of "line" >> > pass >> > for line in r.readlines(): >> > # Do something conditionnal to the result of "line" >> > pass >> > >> > >> > cmd = "quit\n" >> > w.write(cmd) >> > w.flush() >> > >> > for line in e.readlines(): >> > print line >> > for line in r.readlines(): >> > print line >> > >> > w.close() >> > r.close() >> > e.close() >> > ---------------------- >> > >> > Anybody can help? Thanks for your time. >> > >> > Yannick >> > >> > >> >> > > >-- >http://mail.python.org/mailman/listinfo/python-list From paul at boddie.net Mon Jul 12 11:45:42 2004 From: paul at boddie.net (Paul Boddie) Date: 12 Jul 2004 08:45:42 -0700 Subject: Time Module References: Message-ID: <23891c90.0407120745.5308305@posting.google.com> at14 at st-andrews.ac.uk wrote in message news:... > To whom it may concern, > > My group has python version 2.2.1 installed on a linux system. I am in the > process of trying to run some software that requires a module called time. > For some reason, our python installation is missing this module. As far as I can tell, the time module is implemented as a C extension and should always be present, unless some "advanced" configuration has been undertaken somewhere. Is this a vendor/distribution-supplied version of Python? > Our > administrator has tried to install a new version, but has hit a brick wall > with requests for strange dependencies. Would it be possible to import the > necessary files into our current installation directories? Since the time module seems to be implemented by Modules/timemodule.c then the answer to that question would be "no". What kinds of strange dependencies are we talking about? Python compiles from source code without any real configuration on any sane Linux distribution, and should you *really* need to get Python running (before your administrator sorts the problem out) then you could just build from source and then install into some place in your home directory. I'm starting to suspect package management issues in your environment, however. Another possibility might be dynamic linking against a libpython.so belonging to another Python release, but I've never encountered that personally. Paul From dswj at plasa.com Mon Jul 19 22:51:32 2004 From: dswj at plasa.com (dw) Date: Tue, 20 Jul 2004 09:51:32 +0700 Subject: aspn python Message-ID: Thought that someone would need ASPN's python cookie book inside chm for easy offline-searching. http://miaw.compeng.org/~dody/aspncookbook.chm last grabbed around 15jan04. -- dody wijaya =========================================================================================== "Gabung INSTANIA, dapatkan XENIA. Daftar di www.telkomnetinstan.com, langsung dapat akses Internet Gratis.. Dan ..ikuti "Instan Smile" berhadiah Xenia,Tour S'pore, Komputer,dll, info hub : TELKOM Jatim 0-800-1-467826 " =========================================================================================== From nhodgson at bigpond.net.au Tue Jul 27 19:05:13 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 27 Jul 2004 23:05:13 GMT Subject: [wxPython] Smileys in my text ctrl References: <419d7cae.0407211039.460468c1@posting.google.com> <10g008j74u97a3@corp.supernews.com> Message-ID: Peter Maas: > Neil Hodgson schrieb: > > There is no reasonable way to get Scintilla to display smileys. It is a > > very serious widget :-( > > What does your 'frowney' mean? Do you dislike the idea of displaying > smileys or do you regret that Scintilla is a serious widget? It was more sympathy with the OP not being able to achieve their goal. > But anyway, there is a way: open a Scite window, switch to Unicode > and enter the Unicode character U+263A: This is a smiley: ? > > :-) OK, it is available! I expect the OP wanted colourful smileys as are displayed in some mail applications. Neil From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Wed Jul 7 05:40:04 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Wed, 7 Jul 2004 09:40:04 +0000 (UTC) Subject: Short if References: Message-ID: > Does Python have a short if like C or PHP: > > bool = false > string = 'This is ' + (( bool ) ? 'true' : 'false') > If you are really convinced that this is a good road to go down (think of code readability), you could do bool = False # check capitalisation! string = 'This is ' + ('false','true')[bool] I never liked the C ? operator, always finding code was clearer using the full if, and this hack is even worse! From lbates at swamisoft.com Mon Jul 12 14:34:47 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 12 Jul 2004 13:34:47 -0500 Subject: datetime.iterdate References: Message-ID: List comprehension to the rescue: day_range=[first+datetime.timedelta(x) for x in range((last-first).days+1))] for day in day_range: do_something_with(day) I'm not entirely sure the syntax is correct (I just copied yours for the example) , but you get the idea. I think it clearly defines the list of items you are iterating over and keeps the definition close to the loop where you do something (rather in a function that may be defined far away in the code). Larry Bates Syscon, Inc. "Robert Brewer" wrote in message news:mailman.236.1089594533.5135.python-list at python.org... Anyone else tired of typing date-addition logic when iterating? It would be nice if the datetime package had something like: def iterdates(first, last): for day in range((last - first).days + 1): yield first + datetime.timedelta(day) ...notice the inclusive boundaries (i.e. last gets returned). This simple construct would make ugly date loops a lot cleaner: for day in datetime.iterdates(first_date, last_date): do_something_with(day) Robert Brewer MIS Amor Ministries fumanchu at amor.org From mfaine-usenet at knology.net Thu Jul 8 15:21:52 2004 From: mfaine-usenet at knology.net (Mark F) Date: Thu, 8 Jul 2004 14:21:52 -0500 Subject: csv reading fields References: <40ed95dd$1_6@corp.newsgroups.com> <40ed9b43$0$7804$db0fefd9@news.zen.co.uk> Message-ID: <40ed9eaa_6@corp.newsgroups.com> Thanks, could have sworn I tried that. -Mark "Nick Smallbone" wrote in message news:40ed9b43$0$7804$db0fefd9 at news.zen.co.uk... > > "Mark F" wrote in message > news:40ed95dd$1_6 at corp.newsgroups.com... > > To say I'm a python newbie would be an understatement but I think it is a > > language worth learning and would make a great replacement for perl in our > > shop. > > > > I'm trying to read a CSV file using the python csv module but I can't seem > > to determine how to use the API, it seems to me that I can do nothing more > > than opening the file and printing the lines of the file. I can do that > > without the CSV module. I need to know how to address individual fields. > > > > Something like this: (not actual python code) > > > > > > import csv > > reader = csv.reader(file("some.csv")) > > for row in reader: > > print row.field(3) or import csv > > reader = csv.reader(file("some.csv")) > > if reader.field(2,1) == "test.zip": print "test.zip exists" > > Thanks,-Mark > > > > How about: > > import csv > reader = csv.reader(file("some.csv")) > for row in reader: > print row[3] > > Nick > > -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From ialbert at mailblocks.com Fri Jul 30 11:26:07 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 30 Jul 2004 11:26:07 -0400 Subject: slowdown with massive memory usage In-Reply-To: References: Message-ID: Hallvard B Furuseth wrote: > When I moved a function to create one such dict from near the beginning > of the program to a later time, that function slowed down by a factor > of 8-14: 38 sec at 15M memory usage, 570 sec at 144M, 330 sec at 200M. I suspect there is more to it than just "moving". There must be a reason for the reorganization and... check what other things are you doing and profile your program http://docs.python.org/lib/profile.html Istvan. From imbaczek-nospam at poczta.fm.cut-from-here.no-spam.info Thu Jul 29 09:10:49 2004 From: imbaczek-nospam at poczta.fm.cut-from-here.no-spam.info (Marek =?iso-8859-2?Q?Baczy=F1ski?=) Date: Thu, 29 Jul 2004 15:10:49 +0200 Subject: Importance of C# (was Re: IronPython-0.6 is now available!) References: <278de0e.0407281353.27b6a457@posting.google.com> <5dydnZSDZaARoZXcRVn-ug@powergate.ca> Message-ID: <1n5z28erh2m3u.dlg@baczek.net.invalid> Dnia Wed, 28 Jul 2004 19:53:48 -0400, Peter Hansen napisa?(a): > As near as I can figure, those who find Python has significant > advantages for many applications over Java and C++ will likely > feel the same way about C#, only more so. Isn't it basically > a highly MS-centric remake of Java, but missing the very > cross-platform nature which has served Java (and Python) best? Isn't it MS-centricity that serves C#? IMHO it's so popular (relatively) because MS backs it. -- Marek Baczy?ski :: UIN 57114871 :: GG 161671 :: JID imbaczek at jabber.gda.pl He who knows best best knows how little he knows. -- Thomas Jefferson From me at privacy.net Fri Jul 9 09:45:10 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jul 2004 13:45:10 GMT Subject: updating a variable / scope problem References: Message-ID: "Robert Brewer" wrote in news:mailman.142.1089323574.5135.python-list at python.org: > Rajarshi Guha wrote: >> I'm basically converting Bron and Kerbosch's >> clique detection algorithm to python. The described algorithm is > basically : >> >> def clique( .. ): >> def extend( .. ): >> .. >> .. >> if ( .. ) extend( .. ) >> .. >> .. >> >> c = 0 >> .. >> extend( .. ) >> >> The variable c is accessed in the function extend(). >> >> I suppose I could just make c and argument to extend as you mention - >> though it seems a little less elegent than allowing extend() to have >> access to c directly. > > If extend *modifies* c, then making it an argument to extend won't work; > making it an argument makes a new binding for c, local to extend(), and > won't modify c in clique(). The hack that used a list will work, but is > still ugly. I'd suggest either rewriting the algorithm in register form > (using a while loop) instead of recursive form, or (last resort) make c > a global instead of a local within clique(). Does c get modified by > clique()? If the answer is no, you might be able to rewrite extend() as > a generator instead of a recursive function. If extend *modifies* c, then it surely isn't too hard to do this: def clique( .. ): def extend(c, .. ): .. .. if ( .. ) c = extend(c, .. ) .. .. return c c = 0 .. c = extend(c, .. ) This way it is obvious that you are modifying c in the inner function. Alternatively how about using a class? From tim.peters at gmail.com Wed Jul 14 22:59:07 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 14 Jul 2004 22:59:07 -0400 Subject: bugs at iter file() ? In-Reply-To: References: Message-ID: <1f7befae04071419595bc41387@mail.gmail.com> [dswj at plasa.com] > Python 2.3.4, winxp: > > I have a large text file that unknowingly contains ascii > character 1A, or chr(26). Then, when you're running on Windows, and don't want chr(26) to be treated as an end-of-file marker, you must open the file in binary mode. > And doing this: > > for line in file(sys.argv[1]): > print line > > would stop iteration at the specific line containing ascii > char 1A, without raising exception or warning, although > there were still remaining lines which has not been > iterated. I was wondering whether this was a bug in > Python. Nope, that's how Windows treats all files opened in text mode, regardless of programming language. Do file(sys.argv[1], "rb") instead to open it in binary mode. Linux people should also open binary files in binary mode, for portability, but since the "text versus binary" distinction doesn't exist on Linux, many don't. From export at hope.cz Thu Jul 29 02:58:47 2004 From: export at hope.cz (Lad) Date: 28 Jul 2004 23:58:47 -0700 Subject: Online shop e-commerce solution Message-ID: <81a41dd.0407282258.6b20334b@posting.google.com> Is there an online shop e-commerce solution available in Python? I know about some ( e.g. http://www.oscommerce.org/) but they are in php only. Thanks for reply Lad From mutah at NOSPAM-libertysurf.fr Thu Jul 8 11:19:28 2004 From: mutah at NOSPAM-libertysurf.fr (Mutah) Date: Thu, 8 Jul 2004 15:19:28 +0000 Subject: detachable thread ? References: Message-ID: <20040708151928.23bdd9f5.mutah@NOSPAM-libertysurf.fr> may be this helps : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 and others in : http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Threads On Thu, 8 Jul 2004 15:02:42 +0200 Olivier Ravard wrote: > Hi everybody, > > Is there a recepie to make a "detachable" thread with python ? (a kernel > thread). > > Thanks. > > From google at spiceaid.com Wed Jul 28 17:00:40 2004 From: google at spiceaid.com (Jeff Smith) Date: 28 Jul 2004 14:00:40 -0700 Subject: Problems using freeze with platform dependant compiles Message-ID: <3d4251a8.0407281300.5e14958b@posting.google.com> When following the instruction to create platform dependant builds by running configure in a different directoty than the unpacked source, I find that freeze no longer works because it looks for things in the source tree that are now in the platform tree. Is this expected? Is there an easy workaround without creating a complete source tree for every platform? Thanks, Jeff From peter at engcorp.com Wed Jul 7 20:10:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 07 Jul 2004 20:10:56 -0400 Subject: Prothon 0.1.2 is getting close to Alpha [Prothon] In-Reply-To: References: Message-ID: Mark Hahn wrote: > Prothon is an industrial strength language that uses native OS > threads and 64-bit architecture. Mark, as someone with an "industry" perspective, I interpret the phrase "industrial strength" as meaning two things**, primarily: power and reliability. Does Prothon already have enough users and runtime to justify a claim that it is highly reliable? I believe Python can make this claim fairly easily at this point, though even a few years ago I'm not sure that was the case. What do _you_ mean by "industrial strength"? -Peter ** That is, when I don't think it's just a marketroid talking. I know Mark isn't a marketroid, in spite of the similarity in the names. ;-) From paolo_veronelli at yahoo.it Mon Jul 12 05:10:44 2004 From: paolo_veronelli at yahoo.it (paolo veronelli) Date: Mon, 12 Jul 2004 11:10:44 +0200 Subject: Closures python,scheme,ruby Message-ID: I've a vague idea of the differences,I don't know scheme anyway. I'd like to see an example to show what is missing in python about closures and possibly understand if ruby is better in this sense. Iuse ruby and python in parallel for my job just to learn them and their differences and python is shorter and cleaner ,but i feel it's missing something, in closures.Any hints? grazie Paolino -- ....lotta dura per la verdura From nick at no.spam.org Mon Jul 12 06:13:42 2004 From: nick at no.spam.org (Nick Efford) Date: Mon, 12 Jul 2004 11:13:42 +0100 Subject: QOTW! (was RE: Random thoughts from an aspiring Pythonista) References: <2l6om1F9e68kU1@uni-berlin.de> Message-ID: On Fri, 09 Jul 2004 01:27:22 -0400, Leif K-Brooks wrote: > I'm a greedy so-and-so, so here's proof that I should never be allowed > near graphic design: . You are far too modest! I really like the 'P turned into a snake' idea; it would make a great official logo, IMHO - certainly better than the random renderings of "Python" used on www.python.org. Or maybe I also should never be allowed near graphic design... Nick From me at privacy.net Fri Jul 2 06:33:51 2004 From: me at privacy.net (Duncan Booth) Date: 2 Jul 2004 10:33:51 GMT Subject: execution time with global variables References: Message-ID: sarmin kho wrote in news:mailman.346.1088760869.27577.python-list at python.org: > i have been using a lot of global variables in the python script i am > working on. the global variables are shared and used by all various > 'definitions' : > > def name (): > global all globs... > ..... > > my question is: 'is it safe using global variables in term of its > execution time? Is the program running fast enough? If so, the answer is 'yes'. If not then using local variables might provide some speedup, but usually changing your algorithm is a better way to optimise. > > i cant think of any other ways not to use the globs because some > variables simply have to be shared among those definitions.. > The usual solution is to define a class and then all your globals simply become attributes within the class. Try doing it that way and see if you like it. From tzot at sil-tec.gr Fri Jul 30 07:44:01 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 30 Jul 2004 14:44:01 +0300 Subject: sending a file as an attachment with smtplib References: Message-ID: <73dkg0pj5ak3qu5u2s50ju3isfnqgror15@4ax.com> On Wed, 28 Jul 2004 04:18:42 -0500, rumours say that Stephen Boulet might have written: >Is it possible to send a file as an attachment using smtplib? http://groups.google.com/groups?q=group%3Acomp.lang.python+email+smtplib+attachment&ie=UTF-8&hl=en Cheers :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From peter at engcorp.com Tue Jul 13 08:14:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jul 2004 08:14:41 -0400 Subject: Monte Carlo Method and pi In-Reply-To: References: <87llhqbbh5.fsf@uwo.ca> <40f32168_1@127.0.0.1> Message-ID: Tim Hochberg wrote: > beliavsky at aol.com wrote: >> Does it make two calls to sin()? There is a performance hit for 'y = >> sin(x)*sin(x)' >> when not using Psyco. > > It appears that it does not make this optimization. I suppose that's not > suprising since my understanding is that Psyco generates really simple > machine code. I suppose technically, since this is Python, two consecutive calls to sin(x) could easily return different values... It would be insane to write code that did this, but the dynamic nature of Python surely allows it and it's even possible such a dynamic substitution would be of value (or even improve performance) in some other situations. -Peter From kamikaze at kuoi.asui.uidaho.edu Thu Jul 8 19:00:06 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 8 Jul 2004 23:00:06 GMT Subject: Tab wars revisited (was Re: Python indentation) References: <3N-dnXXXI9kf-nHdRVn-hg@giganews.com> Message-ID: Istvan Albert wrote on Wed, 07 Jul 2004 17:13:38 -0400: > Peter Hansen wrote: >> Ambiguity sucks but a SPACE is a SPACE is a SPACE. > Is there a reason why a TAB is not a TAB is not a TAB? foo bar baz quux wibble pting One of those indentation levels is not like the others. Guess which one! >> *Any* decent editor can be configured to inject spaces up to the >> next defined tab-stop when TAB is hit. By definition, therefore, >> any editor that cannot is broken. > Is it really that trivial to set up an editor so that when one hits > delete/backspace to 'un-align' a line of code it deletes as > many space characters as the soft-tab has inserted? > I don't think so. You think wrong. Basically every programmer's editor does that, quite easily, and has for decades--it's been at least 20 years since I've seen an editor that didn't. In Vim: set sw=4 sta et ai bs=2 Put that in your .vimrc, and you're done. The key labelled Tab is now just a convenient way of specifying "indent the standard four spaces", and backspace on leading spaces removes the last four. Done. Nobody would accuse Vim of being the easiest editor in the world to learn or configure, but you learn that the way you learn anything about it: you ask a local guru who tells you, or you type :help just like it says when it starts up without a file. Other editors are easier--less powerful, but easier. Most come with that behavior turned on by default, or with a pretty checkbox option on their pretty GUI option page. You have confused tabulation, which is an ancient display hack for terminals, with indentation, which is a representation of nesting depth. They're separate concepts. You can use tabulation for indentation, but as my example above shows, that's very error-prone. -- Mark Hughes "The void breathed hard on my heart, turning its illusions to ice, shattering them. Was reborn, then, free to scrawl own design on this morally blank world. Was Rorschach." --Alan Moore, _Watchmen #6_, "The Abyss Gazes Also" From tismer at stackless.com Thu Jul 29 21:08:49 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 30 Jul 2004 03:08:49 +0200 Subject: Ann: Revival of the BytecodeHacks Message-ID: Dear community, I could not resist to do this announcement, although this project belongs to Michael Hudson. Mike, please forgive me. I owe you a beer. In a single day-and-night session, I hacked against bytecodehacks, to upgrade it from Python 1.5.2 to Python 2.3 . This was quite some work, although not so very much, due to the excellent basic layout which Michael created. What are the Bytecodehacks? --------------------------- The bytecodehacks allow you to do certain modifications to compiled Python code objects. There are lots of applications included, like macro expansions and function inlining, things which Python does not provide and also is not supposed to provide. This kind of madness exists for people who ask for it, without worring those who don't care. Again, this great package was written by Michael Hudson in early 2000, and to my knowledge, it was never ported to the more recent Python versions. Michael told me that this is a package he is no longer too fond of, since it was written in his early days. He also told me that he is not keen on supporting it so much, because he would be tempted to give it a whole rewrite. Now, I'm thinking differently. I got the package to work, after about 12 hours of hacking, and it simply works. Since I didn't write the initial version, I have a different relationship to it. In other words: It is easier to maintain a foreign package than your own, since you are not married with it. Why do I dig into foreign areas? -------------------------------- Well, I have enough work with my Stackless package. Stackless is almost ready. (Almost, like your toy railway gets really ready; it really never will.) I just built a minimum Psyco support into it, because I'm basically always after as much speed as I can get. But there are limits with the regular Python interpreter. So my idea is to use these crazy other projects to get more performance, and to support them directly. My first idea to accelerate Psyco using Stackless was to provide Stackless with extra hardware stacks, which can be switched at light-speed. I still have this idea in mind, but the implementation is not so trivial. Comparatively, replacing generators (yield calls) with a couple of save/restores of tuples *is* almost trivial, as I'm probably going to show tomorrow. In Python, these "fake-generators" would be reasonably slower. But, by the fact that these are then Psyco-enabled, makes them really, really fast, and also completely inlineable. I think to name the module "renegate". :-) Why do I want to revive this package ------------------------------------ Well, I am a pragmatic guy, and I have a really good reason why I need the bytecodehacks. I am writing a sophisticated package which involves parsing of PDF files, and I want to do it all in Python. In order to get this PDF processor to almost C speed, I used Armin Rigo's wonderful Psyco package. Unfortunately, Psyco has a few limitations, which act as a show-stopper: - generators are not supported. That means, whenever I use a generator, Psyco will not accelerate it, but will act as a small slow-down. - Psyco is great at optimizing simple structures like lists, tuples, numbers and strings. It is less able to enhance things like object properties. Using self frequently disables almost all of Psyco's capabilities. - Psyco has difficulties with inlining. Simple functions *are* inlined, but when they contain a conditional branch or they exceed some limit, inlining is disabled. This *could* be changed, but with a lot of effort by changing C code. This is not going to happen, because all of this stuff will be enhanced and re-implemented during the PyPy project. Now, by combining the re-animated bytecodehacks project with Psyco, I am almost sure that I can remove certain restrictions from Psyco, by turning problematic Python structures into simple ones, which the current Psyco can handle natively. Poor man's PyPy --------------- Although I am a member of the PyPy project, and I do belong to the people who initiated the PyPy project, I am impatient, and I want to get a few of the expected PyPy results right now. Psyco is phantastic but not perfect, and it needs some help to gather maximum performance. By adding Bytecodehacks in the right manner, I think I can fill this gap. With BCH, I can replace generators by ordinary methods of a class (plus a few bytecode instructions which have no real Python equivalent, like goto). By inspecting the data flow of a self.attribute, I can prove that it is invisible outside and replace it by a simple local variable in many cases. By using Bytecodehacks for proper inlining of functions, I can deliver Psyco from this difficult task. The expected result ------------------- By consequently applying the methods I sketched above, I expect that I can make almost every existing application reasonably faster. I will provide this as a service for customers and charge them for relevant acceleration. The software will stay open-sourced. This is just a few add-ons to Psyco and Bytecodehacks, and I'm not the author of these. I just found out how nicely they can fit together. My guess is an overall acceleration of at least a factor of five for almost any native Python application. There is no proof yet, this is all Vodoo from my stomach. But this stomach tends to be quite reliable Mike, please forgive me this announcement. You should have written it, but I was so very inspired. Getting the bytecodehacks for Python 2.3 ---------------------------------------- The current source code is available at cvs -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/bytecodehacks login cvs -z3 -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/bytecodehacks co bytecodehacks cheers -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From csae1211 at uibk.ac.at Sat Jul 31 10:42:52 2004 From: csae1211 at uibk.ac.at (Julien Poissonnier) Date: Sat, 31 Jul 2004 16:42:52 +0200 Subject: PyGTK overload In-Reply-To: References: Message-ID: <410bb02e@sia.uibk.ac.at> Egbert Bouwman wrote: > I have not yet found the tutorial or otherwise that explains concepts > like setting (relative) sizes, setting or manipulating focus, > setting colors, etc. Have a look at the PyGTK tutorial and reference: http://www.pygtk.org/pygtk2tutorial/index.html http://www.pygtk.org/pygtk2reference/index.html and here's a list of articles about PyGTK: http://www.pygtk.org/articles.html If you haven't allready done so, be sure the try out Glade, a GUI builder for (Py)GTK. -Julien From fperez528 at yahoo.com Sun Jul 25 23:16:41 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 25 Jul 2004 21:16:41 -0600 Subject: capturing the output of external commands References: <0pg7g0tjoe0c9075kqdg7pjvlnlkqodf7k@4ax.com> Message-ID: Avi Kak wrote: > Is there a Python function in any of the > standard-distribution modules that does > what the backticks do in Perl? Yes. > I want to run an external command and I'd > like its output to be captured directly > in my Python script in the form of a string > object. In [1]: import commands In [2]: commands.getoutput? Type: function Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.2/commands.py Definition: commands.getoutput(cmd) Docstring: Return output (stdout or stderr) of executing cmd in a shell. You can get fancy using popen, and capture separately stdout/err, but for a simple capture getoutput should do. Best, f From jacek.generowicz at cern.ch Tue Jul 13 07:09:45 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jul 2004 13:09:45 +0200 Subject: Pattern matching?: References: <2kn746F4ci1vU1@uni-berlin.de> <2kofmgF4li52U2@uni-berlin.de> <2kpsp2F4svknU1@uni-berlin.de> Message-ID: Peter Maas writes: > Oh. Thanks for correcting me and my apologies to Jacek. No probs. > I should have read the thread from the beginning but it was way too > long. :) ... I know the feeling :-) From guettli at thomas-guettler.de Mon Jul 12 09:43:53 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 12 Jul 2004 15:43:53 +0200 Subject: [Zope] ZClass/External File or What? References: <425cc8d1.0407120517.b089619@posting.google.com> Message-ID: Am Mon, 12 Jul 2004 06:17:03 -0700 schrieb mir nazim: > Hi, > I am a PHP deleloper. i am currently studying Zope and want to migrate > to it. I have developped a school management system in PHP. but now I > want to implement it in Zope. I have worked through The Zope Book 2.6 > quickly. My problem is that I am confused where to start. Hi, In the year 2001 I had the same questions. I found it difficult to code with Zope. So I switched to ZODB+Quixote: Here is a good introduction to ZODB programming: http://zope.org/Wikis/ZODB/FrontPage/guide/index.html Regards, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From danieleloff at hotmail.com Mon Jul 19 18:29:20 2004 From: danieleloff at hotmail.com (Daniel Eloff) Date: Mon, 19 Jul 2004 15:29:20 -0700 Subject: Sorted list as an alternative to dictionary for when you onlyneedkeys? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE01B48588@au3010avexu1.global.avaya.com> Message-ID: <002501c46ddf$d59828b0$4b00a8c0@RR2> >http://www.python.org/peps/pep-0218.html? >Available as sets.Set in 2.3, and the builtin set (and frozenset) in 2.4. Perfect. From NAIGIMSESRIMAIL at gims.com Sun Jul 4 05:00:52 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sun, 4 Jul 2004 11:00:52 +0200 Subject: ALERT - GroupShield ticket number OB2_1088931640_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: michele.simionato at gmail.com Sent: 1639285376,29647269 Subject: Re: Testing for empty iterators? Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1824 bytes Desc: not available URL: From gyromagnetic at excite.com Fri Jul 23 10:08:56 2004 From: gyromagnetic at excite.com (gyromagnetic) Date: 23 Jul 2004 07:08:56 -0700 Subject: string search function Message-ID: <4620daca.0407230608.55e54e95@posting.google.com> Hi, I have written a function that searches a text string for various words. The text is searched using a boolean 'and' or a boolean 'or' of the input list of search terms. Since I need to use this function for many long strings and many search words, I would like to use as efficient a method as possible. Are there improvements that can be made to the code below? Are there better alternatives? I am currently using Python 2.3. Thanks. -g ----- def bsearch(fterms, stext, btype='AND'): if btype == 'AND': # boolean 'and' search found = True for f in fterms: if f not in stext: found = False break else: # boolean 'or' search found = False for f in fterms: if f in stext: found = True break return found if __name__ == '__main__': stext = "hello to you all" terms = ['hello', 'goodbye'] btype = 'OR' if bsearch(terms, stext, btype): print 'found' else: print 'not found' From daniel.dittmar at sap.com Tue Jul 13 09:59:43 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 13 Jul 2004 15:59:43 +0200 Subject: Iterators References: Message-ID: Chris Lyon wrote: > coming from a Vb'ish sort of background, issues like iterators and > list comprehensions appear at first site to be a confusion. However > since I have a great deal of respect for the large brains in a jar > (LBIAJ) that post on this list and construct my favourite language I > realise I'm missing something. Perhaps it's best explained by the problem these constructs were intended to solve: = list comprehension = There seems to be a lot of code like the following: # transforming a list result = [] for element in sourcelist: result.append (transform (element)) # filtering a list result = [] for element in sourcelist: if passesFilter (element): result.append (element) # both filtering and transforming result = [] for element in sourcelist: if passesFilter (element): result.append (transform (element)) Some thought that this is a lot of typing and possibly obfuscates the intent of the code, so list comprehension syntax was borrowed from the Haskell programming language: result = [transform (element) for element in sourcelist] result = [element for element in sourcelist if passesFilter (element)] result = [transform (element) for element in sourcelist if passesFilter (element)] In the old days, this was done using map (for transformation) and filter (for filtering): result = map (transform, sourcelist) result = filter (passesFilter, sourcelist) result = map (transform, filter (passesFilter, sourcelist)) This looks actually shorter than list comprehension. But assume that transform and passesFilter are member functions. Then it becomes result = map (lambda e: e.transform (), sourcelist) result = filter (lambda e: e.passesFilter (), sourcelist) result = map (lambda e: e.transform (), filter (lambda e: e.passesFilter (), sourcelist)) versus result = [element.transform () for element in sourcelist] result = [element for element in sourcelist if element.passesFilter ()] result = [element.transform () for element in sourcelist if element.passesFilter ()] The main disadvantages of list comprehension: - you can't insert print statements - you can't transform first and filter last unless you nest list comprehension result = [outer for outer in [transform (inner) for inner in sourcelist] if passesFilter (outer)] 2.4 will also introduce 'generator comprehension': - no [] around the construct - more efficient because the list isn't built in memory = Iterators = The code to read all lines of a file used to be as follows: while 1: line = stream.readline () if not line: break # end of file pass # do something with line which is cumbersome to write. Or for line in stream.readlines (): pass # do something with line which will consume too much memory if the file is large. So what was needed was some kind of object: - that could be used in a for loop - doesn't put everything in memory Another example would be potentially large SQL queries, where you want to loop over all the rows. A simple implementation to iterate over the lines of a file class LineIterator: def __init__ (self, fname): self.stream = open (fname, 'r') def next (self): line = self.stream.readline () if not line: raise StopIteration return line def __iter__ (self): return self Disadvantage of using iterators: - you can read them only once - print doesn't write anything useful Daniel From R.Brodie at rl.ac.uk Wed Jul 28 09:00:33 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 28 Jul 2004 14:00:33 +0100 Subject: Codecs for ISO 8859-11 (Thai) and 8859-16 (Romanian) References: <4106C84C.2000505@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in message news:4106C84C.2000505 at v.loewis.de... > ISO-8859-11 is actually very difficult to implement, as it is unclear > whether the characters \x80..\x9F are assigned in this character set > or not. In fact, it is unclear whether the character set contains > even C0. That seems like a very fine distinction to me; the Unicode mapping tables are the same for those points as in ISO-8859-1, so what's the difference? From tor.iver.wilhelmsen at broadpark.no Fri Jul 30 05:26:17 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 30 Jul 2004 11:26:17 +0200 Subject: A goto-like usage of a function References: <41091DD7.6070500@hotmail.com> Message-ID: Bart Nessux writes: > I understand recursion to be a loop or a loop to be recursion... No, loop is _iteration_. From donn at u.washington.edu Wed Jul 7 14:11:15 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 07 Jul 2004 11:11:15 -0700 Subject: try: finally: question References: <40eadf77@usenet01.boi.hp.com> <40eb00db@usenet01.boi.hp.com> <35-dnVL-0qrXtnbdRVn-jg@powergate.ca> <2IadnfA7t7M3vXHdRVn-ug@powergate.ca> <40ec2dbc@usenet01.boi.hp.com> Message-ID: In article <40ec2dbc at usenet01.boi.hp.com>, djw wrote: > Peter Hansen wrote: > > [snip] > > > > Hmm... Also, I think it really *is* unusual (as in, "not usual" > > meaning not really common) to nest try blocks. At least, I > > recall lone try/finally or try/except blocks being much much > > more common in most code than a mix. Perhaps my memory is > > poor on this. Perhaps someone will actually go and research > > it and prove it one way or the other. If it really is > > very common, it might be worth revisiting the subject... > > If it's not very common, then this is once again just another > > discussion about syntactic sugar for an uncommon use case, > > and that kind of thing is so last year. And the year before. > > And.... > > > > -Peter > > I am suprised that what I am trying to accomplish is unusual. Basically, I > want to acquire some resource/object (that requires cleanup). Then make > some calls against that object/resource, catching any excpetions along the > way (assuming that try/except is the right way to do this). If anything bad > happens, I want stop opererating on the object and insure that the object > is cleaned up (presumably a finally is the best way to do this). > > This seems like a really normal bit of code to me. I am suprised there isn't > a more elegant way to handle this (I thought that try/except/finally would > come to the rescue, but...) Is there a better way to handle this situation? Not per se. My reflex would be to suggest more functions, like def f(p0, p1): t = acquire_resource(p0) try: v = ft(p1) finally: release_resource(t) return v def ft(p1): try: x = g(p1) except Eg, ev: print >> sys.stderr, ev return None try: return fx(x) except: gu(x) raise def fx(x): try: return fy(h(x)) except Eh, ev: print >> sys.stderr, ev raise etc. Note that the exception handling will be more or less elaborate depending on how much you can take for granted about what exceptions may be raised, what state you need to recover from them, etc.' Conceptually, what you're after is a nested try: block, like try: x = g(p1) try: y = h(x) try: ... except: ... except: handle h error except: handle g error That's how you handle an exception from g without proceeding to h, with try/except alone. I don't find that grossly wrong, it's just more palatable with a few functions when it gets very deep. Donn Cave, donn at u.washington.edu From godoy at ieee.org Mon Jul 5 10:37:33 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 05 Jul 2004 11:37:33 -0300 Subject: TypeError: this constructor takes no arguments References: <325d00dd.0407020033.1fe893b2@posting.google.com> <325d00dd.0407041758.635a6d8c@posting.google.com> Message-ID: On Dom 04 Jul 2004 22:58, Manoj wrote: > Here is the full program. > -------------------------- > class myclass: > def printout(self, string): > print string > class person: > def __init__(self, lname, fname): > self.__lname = lname > self.__fname = fname > def getFirstname(self): > return(self.__fname) > def getLastname(self): > return(self.__lname) > def putFirstname(self, s): > self.__fname = s > def putLastname(self, s): > self.__lname = s > __fname = "" > __lname = "" > > #Here we go > my = myclass("Paul", "John") This class accepts no parameter for its initialization. You probably meant the person class... Try: class myclass(person): ... It makes myclass inherits from the person class. >>> class person: ... def __init__(self, lname, fname): ... self.__lname = lname ... self.__fname = fname ... >>> class myclass(person): ... def printout(self, string): ... print string ... >>> m = myclass("Paul", "John") >>> m.printout("Just testing") Just testing >>> Be seeing you, -- Godoy. From jcarlson at uci.edu Sat Jul 3 03:50:40 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Jul 2004 00:50:40 -0700 Subject: Time delay loop - better way? In-Reply-To: References: Message-ID: <20040703002129.6EAB.JCARLSON@uci.edu> On Sat, 3 Jul 2004 13:16:59 +1000 Anthony Baxter wrote: > On Thu, 01 Jul 2004 23:28:17 -0700, Josiah Carlson wrote: > > > Q: Is there some way to gracefully suspend a python app for a second or > > > so then resume? I could write the classic basic dumb > > > loop-tenzillion-times delay, but that seems inelegant, and well, just > > > wrong. By the way, I'm also using wxPython, if that helps any. > > > > wxTimer > > > > The wxPython demo and documentation are your friends. > > Note, though, that wxTimer guarantees only 1Hz-1000Hz. On windows, you > get only about 40-50Hz. This makes it completely unsuitable for some tasks. I have used wxTimers for doing asyncore.poll() scheduling every 1/100th a second, and it seemed to work pretty reliably on my celeron 400. - Josiah From rich_NOSPAM_ at _NOSPAM_holmteam.net Sat Jul 3 23:54:30 2004 From: rich_NOSPAM_ at _NOSPAM_holmteam.net (RichH) Date: Sat, 3 Jul 2004 22:54:30 -0500 Subject: wxPython: wxGrid vs. wxListCtrl References: <39cbe663.0406291116.166f436a@posting.google.com> <1v4erg10g7cds.y7kspsysjyuy.dlg@40tude.net> Message-ID: In article <1v4erg10g7cds.y7kspsysjyuy.dlg at 40tude.net>, project5 @redrival.net says... > Piet wrote on 29 Jun 2004 12:16:11 -0700: > > > The Grid table is basically sitting in between the grid that the user sees > and whatever storage backend you have. The grid asks the table for data to > be inserted in cell at some coordinates, the table does whatever it deems > necessary and answers. Even better, the grid asks the table about what > attributes each displayed cell should have (color, read-only, custom > editor, the whole lot). > > I've built a grid in this way and it was slow as I was changing the data in the table continuously. Is there any way to tell the grid that just a few cells have changed? My program was redrawing the whole grid (the visible portion of the grid) each time I changed any cell. Cheers, Rich From wxling3 at hotmail.com Thu Jul 29 12:55:29 2004 From: wxling3 at hotmail.com (Nancy) Date: 29 Jul 2004 09:55:29 -0700 Subject: How to use python or mod_python file to handle HTML form? References: Message-ID: > 1) Do you have access to a web server? [yes / no] > 2) Do you have access to a SMTP server? [yes / no] For question 1, is YES, for question 2 is NO. I know I cann't following this example. My question is if I don't use SMTP server, is there any other way to handle HTML form? for example php, ASP, java Applet can do it very well (by using some functions or variables). Thanks. Nancy From m.boeren at guidance.nl Wed Jul 14 04:42:17 2004 From: m.boeren at guidance.nl (Marc Boeren) Date: Wed, 14 Jul 2004 10:42:17 +0200 Subject: Can a List Comprehension do ____ ? Message-ID: <0C77C7530EA52A4EBD1C47C80D1D291E07F988@sbs.GuidanceBV.local> > >>> breaks = [(133, 137), (181, 185), (227, 231), (232, 236), > (278, 282), > (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)] > >>> it = iter(breaks) > >>> [(start, end) for ((_, start), (end, _)) in zip(it, it)] > [(137, 181), (231, 232), (282, 283), (356, 412), (489, 490)] > >>> That's not quite the result the OP wanted (it misses e.g. (185, 227)), but this solution combined with an earlier one (which used a copy of the list starting at position one) yields the desired result (with the efficiency of the iterator): >>> breaks = [(133, 137), (181, 185), (227, 231), (232, 236), (278, 282), (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)] >>> it = iter(breaks) >>> it2 = iter(breaks) >>> it2.next() # from the other solution, which used breaks[1:] (133, 137) >>> [(start, end) for ((_, start), (end, _)) in zip(it, it2)] [(137, 181), (185, 227), (231, 232), (236, 278), (282, 283), (287, 352), (356, 412), (416, 485), (489, 490)] >>> Cheerio, Marc. From donn at u.washington.edu Tue Jul 13 14:23:02 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 13 Jul 2004 11:23:02 -0700 Subject: named pipe question References: Message-ID: In article , Rajarshi Guha wrote: > I'm having a little trouble when I read from a named pipe. I create a > pipe by > > os.mkfifo('/tmp/mypipe') > > and then open it for reading with > > fin = open('/tmp/mypipe','r+') > > (I don't use 'r' as that cause the open command to block). However when I > do from another terminal: > > ls -l /tmp/mypipe > > and then from my Python session do: > > fin.readlines() > > it just hangs and I have to Ctrl-C to get out. But when I do from a > terminal: > > ls -l /tmp/mypipe ; cat < /tm/mypipe > > I get the output of the ls command. Why does'nt Python read from the pipe > when some other program writes to it? Well, there may be a couple of issues here. The first is that in order for anything to be read from a named pipe, something has to be written to it. That's elementary, but neither of your examples suggest that this is happening. Once you're writing to it, you will find that readlines() will work only when the writer closes its pipe file descriptor (possibly by exiting), because readlines() can't return until the entire "file" has been read. Don't use a named pipe if an ordinary disk file would do. Donn Cave, donn at u.washington.edu From db3l at fitlinxx.com Tue Jul 27 21:04:55 2004 From: db3l at fitlinxx.com (David Bolen) Date: 27 Jul 2004 21:04:55 -0400 Subject: python for .NET References: Message-ID: Gerhard H?ring writes: > AFAIK there's no finished project that directly integrates Python with > the .NET platform, without going through COM. There's also http://zope.org/Members/Brian/PythonNet, which while still in beta is pretty interesting. It doesn't use COM, nor generate IL code from Python source, but provides a layer of managed code to interface the Python interpreter to the CLR. In many respects, it's sort of like a generalized win32all (oops pywin32) for .NET. -- David From brett at python.org Mon Jul 5 21:47:48 2004 From: brett at python.org (Brett C.) Date: 5 Jul 2004 18:47:48 -0700 Subject: Typed Python? References: <2kn746F4ci1vU1@uni-berlin.de> Message-ID: <8ab0589d.0407051747.43838332@posting.google.com> > To put it another way: Jarek complains that static typing would destroy > the "fun". I think he means Python's flexibility. A type inferencer > removes the need to declare types but a statically type-inferenced > language is still statically typed. It will still be strict about type > usage. This is not necessarily true. While this is how Standard ML and friends use it, this is not how Python would use it. Type inferencing can be used to infer types purely for performance reasons. In this situation you just want to know either what possible types a variable can be holding at any time in a block or what it's exact type is at any point in time (time-insensitive compared to time-sensitive). In either situation you just use the type inferencing information to see if you can make a more direct call for the object. Take the LIST_APPEND opcode in 2.4, for instance. With type inferencing, if you knew you had exactly a list when you called 'append', you could skip CALL_FUNCTION and all of its code (of which there is a lot) and just call LIST_APPEND which is just PyList_Append(). Remember that IronPython made such noise initially because its function calls were extremely fast ... thanks to cutting out dynamicism when possible and type inferring. And as just a general comment, type inferencing in Python without changing semantics is **very** limited. My masters thesis is on adding as much type inferencing as possible without changing any semantics short of better argument checking at compile-time (read: you can only type inference atomic types, which are those types with syntactic support such as lists and dicts, in local variables since you can inject into the global and built-in namespace and thus make it all unknown at compile-time). Otherwise restrictions will need to be put into place. Not being able to inject into the namespace of a module would help a good amount. That would make keeping track of return types worth it. Also adding support for C code that have specific return types would help. Lastly, type-checking of arguments would help, but *only* if it is strict; it is no help to know something subclasses list unless you have other restrictions to help guarantee you know that whatever method you care about is not overridden. And all of this is why Starkiller and IronPython compile down to something. They restrict stuff by locking down what code you are running against. If you don't practically everything is unknown until run-time. So decisions would have to be made if extensive type inferencing is added in terms of what kind of restrictions code will have on it in order to get type inferred. The other option after this is type feedback, which tries to approximate what type a variable might hold. With that you make a guess and check it before you execute. If your guess is right, you take the fast code path, otherwise you fall back on the normal way. Trouble is that requires type information from running the program at least once to gather run-time type information. From kumanna at myrealbox.com Tue Jul 13 06:52:28 2004 From: kumanna at myrealbox.com (Adayapalam Appaiah Kumaraswamy) Date: Tue, 13 Jul 2004 16:22:28 +0530 Subject: [ann] CGI Link Checker 0.1 Message-ID: <40F3BEEC.9080904@myrealbox.com> Dear Python users, I am new to Python. As I learnt a bit more on coding in Python, I decided to try out a simple project: to write a CGI script in Python to check links on a single HTML page on the web. Although I am just a hobby programmer, I thought I could show it to others and ask for their comments and suggestions. It is my first CGI script as well as my first Python application, so you might find the coding immature. Please do correct me wherever necessary. I looked about around the net, but found only a few link-checking details related to Python. So, I thought I could write a no-frills one myself. BTW the W3C Link Checker is written in Perl. I don't know Perl, so I couldn't look at it for ideas. I had to face the following problems: 1.Delayed responses for large pages: I worked around this by flushing sys.stdout after every three links checked; that might lead to inefficiency, but it does throw the results three at a time to the impatient user. Otherwise, the Python interpreter would wait until the output buffer is filled till dumping it to the web server's output. 2.Slow: I don't know how to make the script perform better. I've tried to look into the code to make it run faster, but I couldn't do so. Also, I think the hosting server's bandwidth may contribute to this. Still, it takes only about 5 to 10 seconds more than the W3C validator for very large pages, and 2 to 3 seconds more for smaller ones. Your results may vary, I'd love to know. 3.HTML parsing: I have made no attempt to (and I do not propose to) check pages with incorrect HTML/XHTML. This means that if the Python HTMLParser fails, my script exits gracefully. An example of invalid HTML is http://www.yahoo.com/. Finally, since this is my first Python program, I might not have properly adapted to the style of programming experienced Python users may be accustomed to. So, I request you to please correct me in this regard as well. In all, it was an good experience, and gave me more than a glimpse of the power offered by Python. Please read the instructions on the page before entering your URL to test the script. Remember to enter the link as http:// and don't forget to add the slash (/) for those links which and in a directory, like http://myserver/my/dir/ You can spawn the script from: http://kumar.travisbsd.org/pyprogs/example.html Personally, I have tried the following sites with this script: http://www.w3.org/ - Works 100% perfect. http://www.yahoo.com/ - Invalid HTML. Exits gracefully. Source code only (meaning without the fancy images and CSS I have used): http://kumar.travisbsd.org/pyprogs/cgilink.txt If you want to try hosting the script on your own server, get this and see the README (This includes all the images and fancy CSS): http://kumar.travisbsd.org/pyprogs/cgilink-0.1.tar.gz Thank you. Kumar -- Adayapalam Appaiah Kumaraswamy (Kumar Appaiah) Web: http://www.ee.iitm.ac.in/~ee03b091/ From jcarlson at uci.edu Fri Jul 2 02:28:17 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Jul 2004 23:28:17 -0700 Subject: Time delay loop - better way? In-Reply-To: References: Message-ID: > Q: Is there some way to gracefully suspend a python app for a second or > so then resume? I could write the classic basic dumb > loop-tenzillion-times delay, but that seems inelegant, and well, just > wrong. By the way, I'm also using wxPython, if that helps any. wxTimer The wxPython demo and documentation are your friends. - Josiah From michael at foord.net Fri Jul 23 11:26:37 2004 From: michael at foord.net (Fuzzyman) Date: 23 Jul 2004 08:26:37 -0700 Subject: Error Codes From a URLError Message-ID: <8089854e.0407230726.6e63331e@posting.google.com> I've written a CGI proxy that remotely fetches web pages. I use the urlopen function in CLientCookie which replaces (and ultimately uses) the urlopen function in urllib2. What I'd like to do is give a more useful message to the user when the page fetch fails. My understanding was that a URLError exception had a 'code' attribute which was the error code. I trap the error with a simple : (excuse the horrible indentation, this is from the middle of a program) try: req = urllib2.Request(theurl, txdata, txheaders) if data['name'] and data['pass']: import base64 base64string = base64.encodestring('%s:%s' % (data['name'], data['pass']))[:-1] req.add_header("Authorization", "Basic %s" % base64string) u = openfun(req) ..... except IOError, e: # an error in fetching the page will raise a URLError which is a subclass of IOError if not cdone: print "Content-type: text/html" # this is the header to the server print # so is this blank line if not hasattr(e, 'code'): # If it's not an http error - raise it as an error raise elif e.code == 401: # authorisation print authmess % (theurl, data['mod']) print authend elif e.code in errorlist: # standard http errors the_err = errorlist[e.code] print err_mes % (the_err[0], the_err[0], the_err[1]) else: # any others raise openfun is urlopen function from ClientCookie (if available) or from urllib2. What ought to happen in my limied understanding, is that the exception (e) should have the attribute 'code' if it a URLError - and that value ought to tell me what type of error it is... (the error message is then ina dictionary called errorlist which I nicked from BaseHTTPServer). *However*, when I use it to try to fetch a non-existent page (expecting a 404 error) - it falls at the first raise statement. Evidently the exception *is* an IOError, but doesn't have the code attribute. *However* - you see the explicit test for a 401 (authentication) error. I have code that can handle authentication... if I go to a page that requires authentication it picks it up fine...... (so the URLError in that case does have the code attribute). The exact error traceback is below - and you can see where urllib2 raises the URLError - because of what it sees as a socket problem... but it obviously isn't returning the error code properly. Any suggestions ? URLError Python 2.2.2: /usr/bin/python Fri Jul 23 11:06:39 2004 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/buildin/public_html/cgi-bin/approx.py 280 print "Content-type: text/html" # this is the header to the server 281 print # so is this blank line 282 if not hasattr(e, 'code'): # If it's not an http error - raise it as an error 283 raise 284 hasattr undefined, e = /home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in urlopen(url=, data=None) 969 finally: 970 urlopen_lock.release() 971 return _opener.open(url, data) 972 973 def urlretrieve(url, filename=None, reporthook=None, data=None): global _opener = , _opener.open = >, url = , data = None /home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in open(self=, fullurl=, data=None) 567 req = meth(req) 568 569 response = urllib2.OpenerDirector.open(self, req, data) 570 571 # post-process response response undefined, global urllib2 = , urllib2.OpenerDirector = , urllib2.OpenerDirector.open = , self = , req = , data = None /usr/lib/python2.2/urllib2.py in open(self=, fullurl=, data=None) 320 type_ = req.get_type() 321 result = self._call_chain(self.handle_open, type_, type_ + \ 322 '_open', req) 323 if result: 324 return result req = /usr/lib/python2.2/urllib2.py in _call_chain(self=, chain={'file': [], 'ftp': [], 'http': [], 'https': [], 'unknown': []}, kind='http', meth_name='http_open', *args=(,)) 299 func = getattr(handler, meth_name) 300 301 result = func(*args) 302 if result is not None: 303 return result result undefined, func = >, args = (,) /home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in http_open(self=, req=) 883 class HTTPHandler(AbstractHTTPHandler): 884 def http_open(self, req): 885 return self.do_open(httplib.HTTP, req) 886 887 http_request = AbstractHTTPHandler.do_request_ self = , self.do_open = >, global httplib = , httplib.HTTP = , req = /home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in do_open(self=, http_class=, req=) 728 h.endheaders() 729 except socket.error, err: 730 raise URLError(err) 731 if req.has_data(): 732 h.send(req.get_data()) global URLError = , err = URLError: __doc__ = None __getitem__ = > __init__ = > __module__ = 'urllib2' __str__ = > reason = Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From __peter__ at web.de Wed Jul 28 05:49:09 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jul 2004 11:49:09 +0200 Subject: changing __getattr__ dynamically References: Message-ID: Dan Bentley wrote: > Is there a way to change the actual __getattr__ used at runtime? Special methods are always looked up in the class, any changes must therefore be made in the class and will affect all instances. >>> class foo(object): ... def __getattr__(self, name): ... return 42 ... >>> def e(self, name): ... return 2.7 ... >>> bar = foo() >>> print bar.baz 42 >>> bar.__class__.__getattr__ = e >>> print bar.baz 2.7 Peter From p_s_oberoi at hotmail.com Thu Jul 29 18:26:40 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Thu, 29 Jul 2004 17:26:40 -0500 Subject: a document I would like to see... References: Message-ID: Use CHM docs (available with the windows installer). You still wouldn't be able to grep, but you would have a sorted index of headings, as well as full-text search capability. I use xchm (xchm.sourceforge.net) as my CHM reader on Linux. There is also GnoCHM (gnochm.sourceforge.net) which is written in Python itself, but I've had stability problems with that one. -param On Thu, 29 Jul 2004 18:02:00 +0000, Mark Harrison wrote: > A text file containing one-line summaries of everything in > the standard library, including module name. > > Then I could do things like this: > > grep dircmp # what module is dircmp in? > grep sort # what are my options for sorting? > grep print | grep -v xmllib # what can print, ignoring xmllib? > > Any such thing exist? > > Many TIA! > Mark From __peter__ at web.de Sat Jul 17 01:41:04 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 17 Jul 2004 07:41:04 +0200 Subject: Lists, tuples and memory. References: <9418be08.0407151109.15894fe7@posting.google.com><9418be08.0407160626.4e5b58db@posting.google.com> Message-ID: Terry Reedy wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:cd936h$akf$06$1 at news.t-online.com... >> Christopher T King wrote: >> >> > Try using a set instead of a dictionary. You should get the good access >> > time of dictionaries with nearly the low memory usage of a list: >> >> sets.Set() holds its data in a dict. I fear the same goes for 2.4's > builtin >> set type which is coded in C but also built on top of dict. > > My impression was that it was based on the dict code, but without reading > the source, I don't really know. The "fear" was rhetoric, I actually looked it up. In setobject.c, as of 2.4a1: make_new_set(PyTypeObject *type, PyObject *iterable) { PyObject *data = NULL; PyObject *tmp; PySetObject *so = NULL; data = PyDict_New(); if (data == NULL) return NULL; .... Peter From wchew at qualcomm.com Tue Jul 20 15:04:20 2004 From: wchew at qualcomm.com (Wilson Chew) Date: Tue, 20 Jul 2004 12:04:20 -0700 Subject: keep Java object alive between two script Message-ID: Hi, This is more of a Jython question, I guess. Say I have a Java program MyJavaClass which will be called from two Jython scripts: script_1.py and script_2.py: ---------------------------------------------- #script_1.py from MyJavaClass import * myObj = MyJavaClass() myObj.startJavaFunc() #startJavaFunc() is a method in MyJavaClass() ============================== Then I have a Manager class that will invoke these scripts, as shown below: ------------------------------------------------ package TestSuiteManager; import org.python.util.PythonInterpreter; import org.python.core.*; public class TestSuiteManager { public static void main(String[] args) { PythonInterpreter interp = new PythonInterpreter(); interp.execfile("script_1.py"); // will I be able to keep "myObj" alive after the execution of script_1.py ? // will I be able to somehow get the object "myObj" that was created in script_1.py and use it? interp.execfile("script_2.py"); } } ================================ My questions are written in the program above as comments. Thanks everyone in advance. Wilson Chew Summer Intern, Qualcomm. Inc. From kamikaze at kuoi.asui.uidaho.edu Tue Jul 20 11:24:03 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 20 Jul 2004 15:24:03 GMT Subject: Alternative suggestion for conditional expressions (see PEP 308) References: <390d8a01.0407150701.7e3f9776@posting.google.com> Message-ID: Pierre-Fr?d?ric Caillaud wrote on Mon, 19 Jul 2004 19:31:07 +0200: > Flame suit on. > - add a switch-case statement : > I do miss a switch-case in Python. > The interpreter can't really optimize if/elif as a dictionary lookup, > because what if there is a AND or OR clause, or if the object has defined > a __cmp__ method with side effects ? This would be pervert... > switch color: > case 1: > name = 'red' > case 2: > name = 'blue' > case 3: > case 4: > name = 'colorblind' > Could use a 'break' (like in C) or not (cleaner). > - add a switch-case statement which can return a value. > Problem : you need a new keyword for that, which is a bad thing... and it > starts to look like lisp... Simpler version that already works: colornames = { 1: "red", 2: "blue", } print colornames.get(color, "colorblind") > I think the ternary operator is a half-baked solution to a more general > problem ; it is useful as a little shortcut like " x ? 'Yes' : 'No' but > doing more with it leads to obfuscation. It's more for selecting between function calls than for constants. A common idiom with a ternary in Java is: value = test == null ? null : test.something(); That doesn't happen as often in Python, but choosing between different methods depending on a flag happens more often. > Still, something lacks in Python... just like the break-n-levels. At least there's a consistent and easy way to do that. Use exceptions, or extract your inner loops into a method, and return when you want to "break out". -- Mark Hughes "Spontaneous deliquescence is now a protected condition under the Americans with Disabilities Act." -John J. Reilly, "Cthuluism and the Cold War" From python-help-bounces at python.org Tue Jul 6 04:23:22 2004 From: python-help-bounces at python.org (python-help-bounces at python.org) Date: Tue, 06 Jul 2004 10:23:22 +0200 Subject: Auto-response for your message to the "Python-Help" mailing list Message-ID: Your message for python-help at python.org, the Python programming language assistance line, has been received and is being delivered. This automated response is sent to those of you new to python-help, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the helpers. The most comprehensive overview of python.org help resources is at http://www.python.org/Help.html The Python FAQ is available at http://www.python.org/doc/FAQ.html and it has answers to many questions that people ask, possibly including your question. Another wealth of information and experience can be found via the python.org searches, at http://www.python.org/search/ There you'll find comprehensive, easy-to-use searches over the python.org web site and the Python newsgroup -- comp.lang.python, also available as a mailing list, python-list at python.org. You can subscribe to the mailing list by visiting http://www.python.org/mailman/listinfo/python-list Finally, when you do consult with the python-helpers, be as clear as you can about the problem, including, when relevant, details like: - Precise error messages, including complete tracebacks - The hardware platform (available in the Python sys module as sys.platform) - Whether you're using `regular' Python or JPython - The python version (sys.version) - The python search path (sys.path) In general, be specific about what was going on connected with the problem. The better the info you provide, the more likely the helpers will be able to glean the answer... Note that the helpers are volunteers, and often have other work that demands their attention. Python-help requests are usually answered fairly promptly, but occasionally a request slips by, so if you do not get a response with one or two working days (it's usually quicker than that), please feel free to send a followup, asking whether anyone is working on your question. Note also that python-help occasionally receives verbatim copies of school homework assignment questions. While it's nice to know that Python is being studied, if you want help with your homework, please explore the materials on the web site, first - a great starting place is the collection of introductory materials, found via the Help.html page mentioned above. That way, you won't be asking others to expend effort that you, yourself, are not willing to exert... Anyway, your message is being delivered to the helpers as this one is being sent. Thanks! Webmaster at python.org For those of you asking questions about python snakes, we cannot help you - python.org is about the Python programming language, not the snake. Nor do we know about python tape drives - see below for leads on them. Many of us *like* the Monty Python comedy troup, but we can't tell you much about them, either :) For those of you asking for help concerning Python tape drives - www.python.org is about the Python programming language, and is not connected with the tape drives. Check around http://www.seagate.com for help - Seagate acquired Conner Peripherals, who had acquired Archive Corp., who originally made the Python drives. We have nothing to do with the drives or the companies... If you are looking for information on how to be a hacker, you should start with Eric Raymond's seminal article "How To Become a Hacker" at http://www.tuxedo.org/~esr/faqs/hacker-howto.html From exploredher at xxx-adult-toons.com Tue Jul 6 08:45:00 2004 From: exploredher at xxx-adult-toons.com (He) Date: Tue, 06 Jul 2004 12:45:00 GMT Subject: Want to touch Lisa Simpson's pussy?!!?!!! Message-ID: Also, i have sooooo many pics of Maggie Simpson masturbating Browse to Http://ToonToon.com///ximpsons? Visit next to HTTP://www.ComicsOrgy.com///simpsons? for wilder pictures of Maggie & Bart touching their privates. Or try Http://WWW.XXX-Adult-Toons.com/simpsons for the verymost intimate pics of Bart and Lisa moaning in most incredible orgazms. Crawled wrote in message news:18CBqir9CXwNkhnkwRjGW0ixe68iXc4u5n at xxx-adult-toons.com... > > the bed now and was lying next to her as she explored > > > pe419aa From charif at kuc.biglobe.ne.jp Thu Jul 8 01:06:08 2004 From: charif at kuc.biglobe.ne.jp (Charif Lakchiri) Date: Thu, 8 Jul 2004 14:06:08 +0900 Subject: Why would I learn Python over other languages? Message-ID: Okay, here's what I know so far about Python: It's an object-oriented scripting language, supported on many platforms. Now here are my questions: It is easy to learn? Does it support GUI programming? Does it support server-side programming, say for web apps? Does it have extensions and libraries, say for DB connectivity, serial com or network programming...? Can it be used for administrative tasks, say as perl...? Also, can it be compiled to native code? Also much appreciated would be simple comparisons with say JAVA (my other candidate), and pointers to sites and docs where to start. Thank you in advance. -- charif From Holger.Joukl at LBBW.de Fri Jul 2 09:57:31 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Fri, 2 Jul 2004 15:57:31 +0200 Subject: Urgent:help needed Message-ID: Prabu wrote: Hi Holger Joukl, Thanks for the replyye,yes,I am using HPUX OS 11.23.But i am having that file /usr/local/lib/python2.3/lib-dynload/select.sl,but not with extension of .py or .pc,with .sl,it is present.Also all files in lib-dynload/are with the extension of .sl.I found at a FAQ,may be read premision may not be available,so problem arrives for selcet module..But i checked it,read permission is there for that file. ====== Hi Prabu, you do not have a module /usr/local/lib/python2.3/select.py , do you? I do not know HPUX, but I guess select.sl (in the lib/lib-dynload directory) corresponds to the select.so on solaris. Did you install python2.3 over an older installation? Does ldd /usr/local/lib/python2.3/lib-dynload/select.sl give any hints? Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From oudkerk at ma.man.ac.uk Wed Jul 21 10:13:47 2004 From: oudkerk at ma.man.ac.uk (Richard Oudkerk) Date: Wed, 21 Jul 2004 15:13:47 +0100 Subject: Image Module Bug In-Reply-To: References: Message-ID: I had this problem too a week ago. You should use "s#" with PyArg_ParseTuple instead of "s". See http://www.python.org/doc/1.5.2p2/ext/parseTuple.html So instead of doing something like: static PyObject * spam_something(PyObject *self, PyObject *args) { char *string; if (!PyArg_ParseTuple(args, "s", &string)) return NULL; you do this: static PyObject * spam_something(PyObject *self, PyObject *args) char *string; int length; if (!PyArg_ParseTuple(args, "s#", &string, &length)) return NULL; 'length' will be length of the string passed from python. Richard From webstuff at fluidic.com Sat Jul 10 20:17:38 2004 From: webstuff at fluidic.com (J) Date: Sun, 11 Jul 2004 00:17:38 GMT Subject: Porting Java web application to Python to make it faster? References: <1inbbvrpmu1n6$.a0ikxbujiqk3$.dlg@40tude.net> <1uhvs3btilleq$.gkcozee1w36$.dlg@40tude.net> Message-ID: <2004071020173716807%webstuff@fluidiccom> On 2004-07-08 08:19:30 -0400, Wolfgang Keller said: >> There was thread on a another list that I read like this recently. The >> difference in performance between Java and python on the web server >> probably doesn't really matter that much. If anything I might guess that >> Java would be faster. Tons of huge applications are run by Java servers >> everyday. A gig of RAM on the server is nothing. > > Errr, >>1 GByte just to provide an interactive GUI to something like 5 > users and doing some inter-application communication - I wouldn't really > consider that as nothing. Especially not if it scales hyper-exponentially > with the number of users and/or the data volume. After this first > application, we expect to be able to use the same application for sites > with something like 100 concurrent users as well. > i have a gig of memory in my laptop. Memory is cheap. If you are going to have a DB, WebServer, Application Server on a server 1 gig of memory is a mininum. I create database data loads, and my boss almost lost his lunch when I told him I want a server 10gigs of main memory. -- J "If there is anything I can do for you or more to the point to you, let me know." From squirrel at WPI.EDU Fri Jul 30 10:44:48 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 30 Jul 2004 10:44:48 -0400 Subject: PDF parser In-Reply-To: References: <2mu98mFqhmqsU1@uni-berlin.de> Message-ID: On Fri, 30 Jul 2004, Michael Hudson wrote: > OK, but I think Armin, psyco's author, is interested too and hasn't > done it yet... this might tell you something :-) IIRC, the Psyco web site says something to the effect of "I'll look into implementing generators if there's sufficient demand"; I just figured there wasn't sufficient demand yet. From jfouhy at paradise.net.nz Tue Jul 27 19:35:39 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 27 Jul 2004 16:35:39 -0700 Subject: Lambdas and variables Message-ID: So I'm trying to generate Tkinter callback functions on the fly, but it's not working, and I don't understand what's going on. Here is an example program: -------------------------- from Tkinter import * def printSomething(x): print x tk = Tk() stuff = ['foo', 'bar', 'baz', 'zif', 'zaf', 'zof'] for x in stuff: l = Label(tk, text=x) l.pack() l.bind('', lambda e: printSomething(x)) tk.mainloop() -------------------------- The desired behaviour is that the program should print to stdout the text on the label whenever the mouse enters that widget. However, what actually happens is that it prints out 'zof' whenever the mouse enters any of the widgets. To further confuse me, if I add a bit of indirection: -------------------------- from Tkinter import * def makeFunction(x): return lambda e: printSomething(x) def printSomething(x): print x tk = Tk() stuff = ['foo', 'bar', 'baz', 'zif', 'zaf', 'zof'] for x in stuff: l = Lable(tk, text=x) l.pack() l.bind('', makeFunction(x)) tk.mainloop() -------------------------- ...then everything works as it should. I am running Python 2.3.4. Can anyone explain this to me? -- John. From http Mon Jul 12 20:45:50 2004 From: http (Paul Rubin) Date: 12 Jul 2004 17:45:50 -0700 Subject: Proposal: runtime validation statement References: <7xy8lq9rjx.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xpt70hgzl.fsf@ruckus.brouhaha.com> "F. GEIGER" writes: > I use assert to protect my software from me, i.e. to catch programming > errors, e.g. to catch cases where I called a method the wrong way. If > this can happen under production consitions too, then it's a user > error, not a programming error. > > So, I use raise to protect my software from user errors. But I write a lot of code for my own use, which means the user and the programmer are the same person, and any user error is also a programming error. Lots of times also, the data came from some other part of the program, so if the data is invalid, that's still a programming error. > Your sample seems to be a case of the latter, i.e. you have to write > some sort of exception handling anyway. Issuing an error message > anywhere in your code might not be what you really want. If you want to keep running after an AssertionError, you have to handle that too, but that doesn't make the assert statement useless. From olli at haluter.fromme.com Thu Jul 8 12:32:34 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 8 Jul 2004 16:32:34 GMT Subject: Parametrized module import References: <2l4iblF8ff9rU4@uni-berlin.de> <2l4sspF8p3vvU1@uni-berlin.de> Message-ID: <2l5b92F8ku1eU1@uni-berlin.de> Jacek Generowicz wrote: > But this doesn't quite solve the problem I'm trying to solve, which is > to warn, at the time the import statement is executed, that the > configuration which is in place is not being respected. I see. > There's nothing wrong with the user changing the mode twenty times > before the first import. I guess the imported module could block > further configuration changes, and the warning can come when you try > to change the configuration _after_ the first import. In that case, why don't you let the imported module change the definition of the function in the "config" module? That's exactly the place after which modifications should be disallowed, if I understand you correctly. Third try. #--- File config.py: --- foo_interface_mode = 0 # default def set_foo_interface_mode (mode): foo_interface_mode = mode #--- File your_module.py: --- import config def config_warn(): print "foo_interface_mode may only be set once!" config.set_foo_interface_mode = config_warn if config.foo_interface_mode == 0: ... this interface else: ... that interface #--- File main_program.py: --- import config config.set_foo_interface_mode (1) import your_module Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From jarausch at igpm.rwth-aachen.de Wed Jul 28 05:28:11 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 28 Jul 2004 11:28:11 +0200 Subject: SimpleIPPServer anywhere Message-ID: <2mp9tbFppdk2U1@uni-berlin.de> Hi, does anybody know of simple IPP (internet printing protocol) server without the need to install CUPS. Many thanks for a pointer, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From ilya at glas.net Tue Jul 13 04:25:19 2004 From: ilya at glas.net (Ilya Etingof) Date: Tue, 13 Jul 2004 08:25:19 +0000 (UTC) Subject: Speed of pysnmp References: Message-ID: Roy Smith wrote: [ skipped ] > It's entirely expected that the pysnmp version had much higher CPU times > (from about 0.25 to 1.5 total user+sys). What I don't understand is why > the real time went up so much, from about 4 seconds to about 9 seconds. > Most of the time doing a mib walk is waiting for UDP packets on the wire. My guess is that Python code takes up so much CPU time on a single SNMP message processing, that OS's likely to schedule out (involuntarily context switch) python process for greater number of times than it is with C version. In other words, if you burn 0.01 CPU sec, you're likely to get it done within a process's time slice. Although, when you burn 10 CPU secs in bulk, you're likely to 1) run out of process's time slice (context switch) 2) compete for CPU time with other processes on the system. In the end, both factors might contribute to real time increase... -ilya From jeff at ccvcorp.com Wed Jul 28 14:16:29 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 28 Jul 2004 11:16:29 -0700 Subject: atomic operations in presence of multithreading In-Reply-To: References: <4f24b4e5.0407271001.7d3bf9c4@posting.google.com> Message-ID: <10gfrbj5cbgcv58@corp.supernews.com> Duncan Booth wrote: >Paul Moore wrote in news:y8l55cwa.fsf at yahoo.co.uk: > > > >>Given that the original question was about dictionaries, which are >>coded in C (and so not subject to this issue) there is still the >>following case: when the old value stored in the dictionary is >>replaced, that could be the last reference to it. When the old value >>is freed, its __del__ method gets called - arbitrary Python code >>again. >> >> > >Right, but the new value has already been stored in the dictionary at the >point where the __del__ method is called, so as far as the OP is concerned >this is still safe. > > For some definition of "safe", perhaps. It won't corrupt any Python internals, but if the __del__() method has side effects that the threaded code is relying on, it may give unexpected results. (One might want to rely on the fact that, once an object holding a socket is removed from a dictionary, that socket will be closed; if that close happens in the object's __del__(), then there's no guarantee that it *will* actually be closed before a thread switch occurs. (Relying on __del__() is hazardous in any case, actually, thanks to differing GC between different implementations of Python, but it's even worse in a threaded environment.)) Jeff Shannon Technician/Programmer Credit International From lbates at swamisoft.com Fri Jul 23 15:30:15 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 23 Jul 2004 14:30:15 -0500 Subject: How to get some information about a user or computer in ActiveDirectory? References: Message-ID: Can you be more specific about what "information" you want to gain access to? I may be able to help but I don't REALLY understand what it is that you desire. Larry Bates Syscon, Inc. "Dirk Hagemann" wrote in message news:a37aa972.0407220417.70e50e07 at posting.google.com... > Hi! > I'm working in an ActiveDirectory Network and want to get some > information about a user-account or computer (OS for example) account. > I think this works with the win32com.client module and the LDAP-Path, > but I couldn't find yet a simple and working sample-script just to > test some things or have a first small success. > Does anybody know a simple example for this task? > The ActivePython Documentation was no real help yet and scripts I > found in the internet didn't work (probably because of mistakes I > implemented...). > > Thanks for your help! > > Bestr regards > Dirk Hagemann From ialbert at mailblocks.com Tue Jul 20 09:35:17 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 20 Jul 2004 09:35:17 -0400 Subject: Call for Grant Proposals In-Reply-To: <40fcaa90$0$27091$9b622d9e@news.freenet.de> References: <40fcaa90$0$27091$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > The Python Software Foundation is seeking grant proposals for projects > related to the further development of Python, Python-related technology, > and educational resources. The PSF plans to issue calls for proposals > regularly. This is such an awesome idea and even more amazing is that you guys have the funds to do it. A biased opinion here, coming from java I think funding Jython (hopefully they apply) would promote python better than just about any other project. I wish companies like IBM would (or maybe already do) invest some resources into Jython after all they seem to have bet a lot on Java. Python + Jython could blow out of water just about any other development environment. cheers, Istvan. From michael at foord.net Fri Jul 9 07:46:29 2004 From: michael at foord.net (Fuzzyman) Date: 9 Jul 2004 04:46:29 -0700 Subject: Text Parsing - character at a time... Message-ID: <8089854e.0407090346.5b73274f@posting.google.com> I want to parse some text and generate an output that is similar but not identical to the input. The string I produce will be of similar length to the input string - but a bit longer. I'm parsing character by character and adding the characters of the input string to the output until I come to ones I want to modify. This means creating a new string for every character (since strings are immutable) which seems very inneficient - particularly when I know roughly what the output length will be. In a language like c I think I could reserve a chunk of memory and keep a track of how much I'd filled... just putting characters into it.(If I filled it I could reserve a smaller chunk more - not difficult to keep a track of). What's an efficient equivalent in python ? I could use a list, appending characters onto the end of it.. converting to a string at the end using ''.join(thelist). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From tdelaney at avaya.com Fri Jul 9 02:34:03 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 9 Jul 2004 16:34:03 +1000 Subject: str(bigint) is slow Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01ACB50F@au3010avexu1.global.avaya.com> Bryan wrote: > does anyone know how to make this faster? it seems that str(x) is > the slow part. > > > >>> def foo(): > ... t1 = time.time() > ... x = 19 ** 314159 > ... t2 = time.time() > ... y = str(x) > ... t3 = time.time() > ... print y > ... t4 = time.time() > ... print t2-t1, t3-t2, t4-t3 > ... > >>> foo() > > 3.78499984741 230.490999937 0.0700001716614 Bryan wrote: > does anyone know how to make this faster? it seems that str(x) is > the slow part. > > >>> def foo(): > ... t1 = time.time() > ... x = 19 ** 314159 > ... t2 = time.time() > ... y = str(x) > ... t3 = time.time() > ... print y > ... t4 = time.time() > ... print t2-t1, t3-t2, t4-t3 > ... > >>> foo() > > 3.78499984741 230.490999937 0.0700001716614 401732 digits actually ... that's not even half a million ... There was a recent thread titled "How to get decimal form of largest known prime?" ... http://tinyurl.com/3b2no http://groups.google.com.au/groups?hl=en&lr=&ie=UTF-8&threadm=2is27mFqee n8U1%40uni-berlin.de&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8% 26selm%3D2is27mFqeen8U1%2540uni-berlin.de Tim Delaney Tim Delaney From nun at example.com Sun Jul 11 09:52:48 2004 From: nun at example.com (Mitja) Date: Sun, 11 Jul 2004 15:52:48 +0200 Subject: Proposal: function which simulates C ?: operator References: <1388851004.20040711153354@smtp.myrealbox.com> Message-ID: Adal Chiriliuc (news:1388851004.20040711153354 at smtp.myrealbox.com) wrote: > I think a function similar to the one below should be > added to the > builtin module: > > def boolselect(condition, trueresult, falseresult): > if condition: > return trueresult > else: > return falseresult > > --- WITH > > scalewidth = boolselect(self.__vertical, _scalew, _scaleh) > > --- WITHOUT > > if self.__vertical: > scalewidth = _scalew > else: > scalewidth = _scaleh > What do you think? Here's a nifty workaround I figured out myself but am sure others use it as well: scalewidth=(_scaleh,_scalew)[__self.vertical] HTH It's not as readable as the "if cond ? true_expr : false_expr", but I think introducing syntax like this is far from needed and pretty complicated. From jepler at unpythonic.net Tue Jul 6 19:54:39 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 6 Jul 2004 18:54:39 -0500 Subject: reading file contents to an array (newbie) In-Reply-To: References: Message-ID: <20040706235439.GA7455@unpythonic.net> Here's my solution, using 2.3's "csv" module. Unfortunately, it holds the whole array in Python lists to pass to the array() constructor. $ cat dale.ssv 1 2 3 4.0 5.9 6.0e23 $ python dale.py [[ 1.00000000e+00 2.00000000e+00 3.00000000e+00] [ 4.00000000e+00 5.90000000e+00 6.00000000e+23]] $ cat dale.py import csv from numarray import array, Float64 def sniff(f, delimeters=None): sample = "".join(f.readlines(3)) f.seek(0, 0) return csv.Sniffer().sniff(sample, delimeters) def file_to_array(f, dialect=None, kind=Float64, conv=float): if dialect is None: dialect = sniff(f) l = csv.reader(f, dialect) return array([map(conv, row) for row in l], kind) print file_to_array(open("dale.ssv")) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From danb_83 at yahoo.com Sun Jul 11 22:35:49 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Jul 2004 19:35:49 -0700 Subject: Proposal: function which simulates C ?: operator References: <1388851004.20040711153354@smtp.myrealbox.com> Message-ID: "Mitja" wrote in message news:... > Adal Chiriliuc > (news:1388851004.20040711153354 at smtp.myrealbox.com) wrote: > > I think a function similar to the one below should be > > added to the > > builtin module: > > > > def boolselect(condition, trueresult, falseresult): > > if condition: > > return trueresult > > else: > > return falseresult > > > > --- WITH > > > > scalewidth = boolselect(self.__vertical, _scalew, _scaleh) > > > > --- WITHOUT > > > > if self.__vertical: > > scalewidth = _scalew > > else: > > scalewidth = _scaleh > > > What do you think? > > Here's a nifty workaround I figured out myself but am sure others use it as > well: > scalewidth=(_scaleh,_scalew)[__self.vertical] If you're going to use the "(F, T)[C]" syntax, it would be better to write it as "(F, T)[bool(C)]" to ensure that the array index is 0 or 1. However, a better alternative is "(C and [T] or [F])[0]", which short-circuits and also has the advantage of having the same order as "if". If you're absolutely certain that T will never be false, you can simplify this to "C and T or F". From Widgeteye at widgets.com Fri Jul 23 11:55:03 2004 From: Widgeteye at widgets.com (Widgeteye) Date: Fri, 23 Jul 2004 15:55:03 GMT Subject: How did I screw this up? Message-ID: I was experimenting with defining functions, as I am new to python. And now one of the functions in the /usr/local/lib/python2.3/random.py modules is screwed up. I didn't do anything to it. I wasn't even in that directory. I was in the /shared/src directory where I do all my experimenting. But I made a little program called random.py in the /shared/src directory and put a def go(): in that file. Now when I run any program with random.randrange() in it I get the following error: Traceback (most recent call last): File "blackjack.py", line 3, in ? import math, string, random, sys File "/usr/local/lib/python2.3/random.py", line 7, in ? sequences File "/usr/local/lib/python2.3/random.py", line 4, in go -------- AttributeError: 'module' object has no attribute 'randrange' Up until I made the file random.py with the function go() in it everythiing was working fine. I deleted the file and rebooted (silly I know) but nothing seems to help. What do I do now and what happened????? Thanks Widgeteye From della at toglimi.linux.it Thu Jul 29 13:54:21 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 29 Jul 2004 17:54:21 GMT Subject: what does 'for _ in range()' mean? In-Reply-To: <-IednYvL85_frJTc4p2dnA@powergate.ca> References: <10gevuasrt08rae@news.supernews.com> <4I1Oc.18712$1V3.430865@twister2.libero.it> <-IednYvL85_frJTc4p2dnA@powergate.ca> Message-ID: Peter Hansen wrote: > Phil said Ocaml allowed multiple _ in tuple assignments but > that Python did not, while I attempted to correct that assertion by > showing that it in fact did. > > David and you were discussing a case involving function languages, > which Python is not, where the use of multiple _ (which now has > syntactical meaning, as opposed to being just an "ignore this" by > convention) is allowed. > > Sounds to me like the two discussions are unrelated. More or less so. It was only a discussion on the etimology of the underscore convention. :-) -- Ciao, Matteo From walter at livinglogic.de Thu Jul 15 12:16:32 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 15 Jul 2004 18:16:32 +0200 Subject: Accessing Oracle from Python In-Reply-To: References: Message-ID: <40F6ADE0.4050300@livinglogic.de> Dan Ellis wrote: > Hi, > > [...] > > I need to access an Oracle database running on a Windows server from > Python running on Linux. I've tried building DCOracle2, but it seems > that the 'oracle-installclient-basic' thing I downloaded from the > Oracle site doesn't contain enough. I've tried various other > approaches, such as mxODBC/iODBC, but without much luck. I'm hoping to > not have to resort to a Windows solution. > > Can someone help me figure out what combination of Python module, > Oracle download and/or ODBC driver will work? Try cx_Oracle: http://www.computronix.com/utilities.shtml#Oracle (and of course you need an Oracle client installation on your Linux machine) HTH, Walter D?rwald From ville at spammers.com Thu Jul 8 06:02:31 2004 From: ville at spammers.com (Ville Vainio) Date: 08 Jul 2004 13:02:31 +0300 Subject: Typed Python? References: <2kofmgF4li52U2@uni-berlin.de> <20040707223402.258$ii@news.newsreader.com> <20040708045519.202$tz@news.newsreader.com> Message-ID: >>>>> "Hamilcar" == Hamilcar Barca writes: >> Python supports recursion, second order functions, numerical >> programming and hundreds of other important concepts. Hamilcar> How about currying and deferred list evaluation? Deferred list evaluation: generators Lazy evaluation in general: lambda : f(1,2) Currying: lambda x,y : f(x,y,1,2) Hamilcar> Is this a good place to insert my "Smalltalk is the only Hamilcar> language good enough for teaching people to program" Hamilcar> rant? What's better about Smalltalk compared to Python, educationally? Just a brief list will do. -- Ville Vainio http://tinyurl.com/2prnb From BruceEckel at MailBlocks.com Fri Jul 30 14:32:14 2004 From: BruceEckel at MailBlocks.com (Bruce Eckel) Date: Fri, 30 Jul 2004 12:32:14 -0600 Subject: Percentage matching of text In-Reply-To: <1f7befae04073010016c093cca@mail.gmail.com> References: <1678860800.20040730075239@MailBlocks.com> <1f7befae04073010016c093cca@mail.gmail.com> <664460359.20040730123214@MailBlocks.com> Message-ID: Ah, but here's an interesting one: >>> sm(None, 'abcd', 'abdc').ratio() 0.75 >>> sm(None, 'abcd', 'abxx').ratio() 0.5 So if it matches half the string it's 50% but if the last two characters are out of order that's an additional 25%. Other examples: >>> sm(None, 'abcd10', 'abdc20').quick_ratio() 0.83333333333333337 >>> sm(None, 'abcd10', 'abdc20').ratio() 0.66666666666666663 >>> sm(None, 'abcd10', 'abdc20').real_quick_ratio() 1.0 You get a different interpretation for each "speed" of ratio. I started thinking that all I wanted was a pass-fail kind of thing so I wondered if real_quick_ratio() might do the trick. But with the following experiments: >>> sm(None, 'abcd10', 'abdc20').real_quick_ratio() 1.0 >>> sm(None, 'abcd10', 'abxx20').real_quick_ratio() 1.0 >>> sm(None, 'abcd10', 'abxx24').real_quick_ratio() 1.0 >>> sm(None, 'abcd10', 'anxx24').real_quick_ratio() 1.0 >>> sm(None, 'abcd10', 'qnxx24').real_quick_ratio() 1.0 It seems like there's no way to get real_quick_ratio() to say anything except "it's a perfect match!" I'm wondering if someone didn't leave a code stub unwritten: def real_quick_ratio(self): return 1.0 Friday, July 30, 2004, 11:01:28 AM, you wrote: > [Bruce Eckel] > ... >> What I'd like to do is find an algorithm that produces the results of >> a text comparison as a percentage-match. Thus I would be able to >> assert that my test samples must match the control sample by at least >> (for example) 83% for the test to pass. >>>> from difflib import SequenceMatcher as sm >>>> sm(None, 'abc', 'xyz').ratio() >>>> sm(None, 'abcd', 'abcd').ratio() > 1.0 >>>> sm(None, 'abcd', 'uvwx').ratio() > 0.0 >>>> sm(None, 'abcd', 'axyd').ratio() > 0.5 >>>> > SequenceMatcher works on sequences of hashable elements. Above, it's > working on sequence of characters (aka "strings" ). Other > possibilites include sequences of lines ("files") and lists of > integers. Bruce Eckel http://www.BruceEckel.com mailto:BruceEckel at MailBlocks.com Contains electronic books: "Thinking in Java 3e" & "Thinking in C++ 2e" Web log: http://www.mindview.net/WebLog Subscribe to my newsletter: http://www.mindview.net/Newsletter My schedule can be found at: http://www.mindview.net/Calendar "The whole problem with the world is that fools and fanatics are always so certain of themselves, and wiser people so full of doubts." --Bertrand Russell From eppstein at ics.uci.edu Wed Jul 28 17:48:14 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 28 Jul 2004 14:48:14 -0700 Subject: what does 'for _ in range()' mean? References: <10gevuasrt08rae@news.supernews.com> Message-ID: In article , Peter Hansen wrote: > Phil Frost wrote: > > One difference is that _ is allowed multiple times in Ocaml, while in > > Python it is not. > Why do you say that? > > c:\>python > Python 2.3.4 (#53, May 25 2004, 21:17:02) .... > >>> a = 1, 2, 3, 4 > >>> b, c, d, e = a > >>> b, c, d, d = a > >>> b, c, _, _ = a > >>> _, _, _, _ = a > >>> _ > 4 In that context, it's allowed multiple times, but in some other contexts it's not: >>> def foo(_,_): pass ... File "", line 1 SyntaxError: duplicate argument '_' in function definition >>> -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From ptmcg at austin.rr._bogus_.com Fri Jul 16 14:53:53 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 16 Jul 2004 18:53:53 GMT Subject: need simple parsing ability References: <20040716111324.09267883.gry@ll.mit.edu> Message-ID: <5vVJc.3210$WP1.2399@fe1.texas.rr.com> "george young" wrote in message news:20040716111324.09267883.gry at ll.mit.edu... > [python 2.3.3, x86 linux] > For each run of my app, I have a known set of (<100) wafer names. > Names are sometimes simply integers, sometimes a short string, and > sometimes a short string followed by an integer, e.g.: > > 5, 6, 7, 8, 9, bar, foo_6, foo_7, foo_8, foo_9, foo_10, foo_11 > > I need to read user input of a subset of these. The user will type a > set of names separated by commas (with optional white space), but there > may also be sequences indicated by a dash between two integers, e.g.: > > "9-11" meaning 9,10,11 > "foo_11-13" meaning foo_11, foo_12, and foo_13. > "foo_9-11" meaning foo_9,foo_10,foo_11, or > "bar09-11" meaning bar09,bar10,bar11 > > (Yes, I have to deal with integers with and without leading zeros) > [I'll proclaim inverse sequences like "foo_11-9" invalid] > So a sample input might be: > > 9,foo7-9,2-4,xxx meaning 9,foo7,foo8,foo9,2,3,4,xxx > > The order of the resultant list of names is not important; I have > to sort them later anyway. > > Fancy error recovery is not needed; an invalid input string will be > peremptorily wiped from the screen with an annoyed beep. > > Can anyone suggest a clean way of doing this? I don't mind > installing and importing some parsing package, as long as my code > using it is clear and simple. Performance is not an issue. > > > -- George Young > -- > "Are the gods not just?" "Oh no, child. > What would become of us if they were?" (CSL) Here's a pyparsing solution. The best way to read this is to first look over the grammar definitions, then to the parse actions attached to the different bits of the grammar. The most complicated part is the parse action for integer ranges, in which we try to keep leading zeroes if they were given in the original string. You said exception handling is not a big deal, but it is built into pyparsing. So use as much or as little as you like. -- Paul # download pyparsing at http://pyparsing.sourceforge.net from pyparsing import Word,delimitedList,alphas,alphanums,nums,Literal,StringEnd,ParseException # define basic grammar integer = Word(nums) integerRange = integer.setResultsName("start") + "-" + \ integer.setResultsName("end") word = Word(alphas+"_") wordRange = word.setResultsName("base") + ( integerRange | integer ) waferList = delimitedList( integerRange | integer | wordRange | word ) + \ StringEnd() # define parse actions (to expand range references) def expandIntRange(st,loc,toks): expandedNums = range( int(toks.start), int(toks.end)+1 ) # make sure leading zeroes are retained if toks.start.startswith('0'): return [ "%0*d"%(len(toks.start),n) for n in expandedNums ] else: return [ str(n) for n in expandedNums ] def expandWordRange(st,loc,toks): baseNumPairs = zip( [toks.base]*(len(toks)-1), toks[1:] ) return [ "".join(pair) for pair in baseNumPairs ] # attach parse actions to grammar elements integerRange.setParseAction( expandIntRange ) wordRange.setParseAction( expandWordRange ) # run tests (last one an error) testData = """ 9,foo7-9,2-4,xxx 9,foo_7- 9, 2-4, xxx 9 , foo07-09,2 - 4, bar6, xxx 9,foo7-9,2-4,xxx,5, 6, 7, 8, 9, bar, foo_6, foo_10-11 9,foo7-9,2-4,xxx,5- 9, bar, foo_06, foo_010-11 9,foo7-9,2-4,xxx,foo_099-101 9,f07-09-12,xxx """ for t in testData.split("\n")[1:-1]: try: print t print waferList.parseString(t) except ParseException, pe: print t print (" "*pe.loc) + "^" print pe.msg print ===================== output: 9,foo7-9,2-4,xxx ['9', 'foo7', 'foo8', 'foo9', '2', '3', '4', 'xxx'] 9,foo_7- 9, 2-4, xxx ['9', 'foo_7', 'foo_8', 'foo_9', '2', '3', '4', 'xxx'] 9 , foo07-09,2 - 4, bar6, xxx ['9', 'foo07', 'foo08', 'foo09', '2', '3', '4', 'bar6', 'xxx'] 9,foo7-9,2-4,xxx,5, 6, 7, 8, 9, bar, foo_6, foo_10-11 ['9', 'foo7', 'foo8', 'foo9', '2', '3', '4', 'xxx', '5', '6', '7', '8', '9', 'bar', 'foo_6', 'foo_10', 'foo_11'] 9,foo7-9,2-4,xxx,5- 9, bar, foo_06, foo_010-11 ['9', 'foo7', 'foo8', 'foo9', '2', '3', '4', 'xxx', '5', '6', '7', '8', '9', 'bar', 'foo_06', 'foo_010', 'foo_011'] 9,foo7-9,2-4,xxx,foo_099-101 ['9', 'foo7', 'foo8', 'foo9', '2', '3', '4', 'xxx', 'foo_099', 'foo_100', 'foo_101'] 9,f07-09-12,xxx 9,f07-09-12,xxx ^ Expected end of text From chris at acheris.net Mon Jul 19 10:37:24 2004 From: chris at acheris.net (The Dark Seraph) Date: Mon, 19 Jul 2004 14:37:24 +0000 (UTC) Subject: static class variables and module scope Message-ID: I have a singleton object that works perfectly from inside my main .py file. However, when I want to access the object that backs the singleton from another file ( either from an execfile() or thru my telnet listener ), it appears the underlying object is reset to null, resulting in a duplicate object being created. I figure I am doing something painfully stupid, but for the life of me, I can't see it. Here is my singleton wrapper: class SingletonWrapper: __instance = None def __init__ ( self, user = None, password = None ): if SingletonWrapper.__instance is None: SingletonWrapper.__instance = ImplSingletonWrapper ( user, password ) def instance ( self ): return SingletonWrapper.__instance In my ImplSingletonWrapper class, I print out that I am creating a new object when its constructor is called. Inside the owner file, it is only called once , but if I do SingletonWrapper().instance() from anohter module, it makes a new object, and id() reports different ids. I banged my head against this yesterday, and today doesn't seem to be going any better, any ideas out there? -- chris at acheris.net | Fight Censorship, Boycott Wal-Mart Now is the winter of your discontent! - Stewie From gnupeaker at yahoo.com Sat Jul 24 18:51:40 2004 From: gnupeaker at yahoo.com (Eyal Lotem) Date: Sat, 24 Jul 2004 15:51:40 -0700 (PDT) Subject: object pickling In-Reply-To: <5nxMc.38911$OR2.2067630@news3.tin.it> Message-ID: <20040724225140.95162.qmail@web50407.mail.yahoo.com> --- "max(01)*" wrote: > also i would like to know: why in the world would > anyone want to pickle > a builtin function, as the documentation says it's > possible? In PyInvoke (http://pybuild.sf.net/pyinvoke.html), I use pickling of all types of objects as the basis for the pyinvoke protocol, allowing all sorts of funky stuff :-) Actually, in order to invoke arbitrary methods at the server-side with minimum fuss, I simply send a pickled tuple containing the function to run, the arguments and the keywords, which is a very convinient way to denote a function reference at the server-side. Ofcourse I use this only on functions that really exist at the server-side as someone else said: it is pickled by reference. I still think PyInvoke is a really nice demonstration of what can be done with Python's dynamic power and the powerful pickle module. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From peterm at resmed.com.au Wed Jul 14 18:22:54 2004 From: peterm at resmed.com.au (Peter Milliken) Date: Thu, 15 Jul 2004 08:22:54 +1000 Subject: IDE References: Message-ID: Let's not do the war thing :-) But perhaps an exchange of information? Me, I use Emacs - have done so for 20 years now with never a regret. When I see a feature that I like (enough) in another editor I implement it in Emacs (if it doesn't already have it - something that is getting harder and harder to do these days :-)). I understand completely that many do not like Emacs because of the "magic incantations" required to run commands i.e. sets of key sequences - but I don't like using mice and menus - takes longer than keyboard access (right hand off the keyboard onto the mouse, then back again) and how else can you provide efficient access to such a wealth of commands? :-) But I shouldn't digress into look and feel - many an argument could be had with a Vi user over that! :-) So what are the interesting "features" (as opposed to "I just like the look and feel of editor X" - I don't desire a discussion on "warm, fuzzy feelings" about your favourite editor - we all know how "religious" these things can be :-)) in any of the editors that people have settled upon for their personal use? For example the following comment is made in another (later) thread: "augment Leo's mind blowing qualities" - which means what? :-) Other than the fact the writer likes Leo? :-) I'll (attempt) to kick the discussion off with the features of Emacs that I like and use in everyday programming of Python (not necessarily in order of importance :-)): 1. available for any OS/platform that I have worked on over the last 20 years and the forseeable future - the one time I couldn't get a native binary was for VMS and the company didn't want the expense of installing NFS so then I used the (transparent) ftp access built into Emacs to edit files on the VMS file system all from a PC running Windoze (ange-ftp allows editting of files that are accessed using standard ftp operations but are hooked into the standard Emacs read/write file commands - so the user is "unaware" of the file access mechanism). 2. the (obvious) generic IDE capability i.e. compile and debugging from within the editor 3. code completion - a la LSE from the VMS editor of that name (see the reference to ELSE on http://www.python.org/cgi-bin/moinmoin/EmacsEditor) - note this is not "syntax completion", although I have written some code that allows scanning of Python modules and then generation of code templates for ELSE that generate call templates with the named parameters filled in and code templates for where the coder must supply the arguments. But I guess I am not big on "syntax completion" - I haven't really used to the code since I wrote it, although I do use ELSE itself extensively in writing my Python code :-) 4. User extendable using either Lisp or Python ( :-) ) - (see the reference to Pymacs on http://www.python.org/cgi-bin/moinmoin/EmacsEditor). "Extendability" of the editor to create new commands/functionality as opposed to "macro" capability. 5. Integration with Ispell/Aspell i.e. Emacs is intelligent enough to spell check only the comments and strings - which can be extremely handy when writing code! Nothing more embarrassing than a poorly spelt message to a user! :-) 6. Unix "screen" like capability i.e. having multiple "virtual" instances of the editor (each with its own window/buffer view) available via simple key switching - but not "cluttering" the Windoze landscape with multiple instances (although you can configure Emacs to work that way too :-)). 7. Given sufficient physical screen real-estate, you can "split" the editor display into multiple "windows" - both horizontally and vertically - the number of "splits" limited only by the physical display. My "faviourite" configuration is two vertical, 80 column windows side-by-side - one or both then generally get split horizontally as I look at other files or positions within the same file. 8. "Free" - in this day of powerful editors that are available for zero cost, why purchase one? Either shareware or commercial? 9. syntax highlighting (almost not worth mentioning since it is so common?) These are just some of the reasons I use Emacs. What features of *your* editor attracted you? How does it help you with writing Python code (the intent after all of this news group :-)). Does your editor have a feature that I have not listed above and yet you consider it *essential* (or at least very handy :-)) in your generation of Python code? So whilst I know that Thomas does not "want Emacs or Vi", I believe my response is in the spirit of the original email :-) Regards Peter "Thomas Lindgaard" wrote in message news:pan.2004.07.14.12.38.48.968534 at it-snedkeren.BLACK_HOLE.dk... > Hello > > I am probably going to start a war now... but so be it :) > > I just want to hear what all you guys who eat pythons for breakfast use > for python coding. Currently I use Kate, but I would really like an IDE > with debugger and a source browser (ie. one the I can use to browse > through modules etc. when looking for just the right curses stuff and such > - I am a newcomer to Python). > > ... and no, Emacs or Vi are not what I want :) > > -- > Mvh. > /Thomas > From nhodgson at bigpond.net.au Sun Jul 11 20:10:30 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 12 Jul 2004 00:10:30 GMT Subject: if/elif chain with assignment expressions References: <7xvfguflq1.fsf_-_@ruckus.brouhaha.com> <7x4qoe6vae.fsf@ruckus.brouhaha.com> Message-ID: Fernando Perez: > In general I applaud python's efforts for being clear, readable, > and not error-prone. But this is one of those cases where leaving > the training wheels on causes genuine grief (I have in the past > many times run into the example you mentioned, and have cursed > it silently). I hope this does not change as it makes analysis of the code easier. Reading and understanding code is as important as writing it. Analysis of a problem depends as much on restricting the set of possible causes ('it is *not* the case that') as it does on generating a larger set of possible causes ('it is the case that'). Pruning the possible cause tree is extremely valuable and Python cooperates with a well thought out set of restrictions. Being able to depend on the absence of assignments in if and while statements is a benefit when fixing Python code over C/C++. Characterizing these as "training wheels" and thus only of use to beginners is unreasonable. Neil From db3l at fitlinxx.com Wed Jul 21 16:17:06 2004 From: db3l at fitlinxx.com (David Bolen) Date: 21 Jul 2004 16:17:06 -0400 Subject: How to lunch webpage without using SMTP server? References: <40febcca$0$8082$a1866201@newsreader.visi.com> Message-ID: Grant Edwards writes: > On 2004-07-21, Byron wrote: (...) > > I would HIGHLY recommend that you use an SMTP server. > > I simply don't see how you can send mail without using an SMTP > server. If that includes the final delivery agent that is listening on an SMTP port to provide delivery to a mailbox on the remote end, I agree. But to the extent that such a server is being run by a separate administrative entity, you might not include it in discussions talking about the client machine. That SMTP server is handling the delivery end of the mail, not the transmitting. Typically, when I see discussions of running your own SMTP server, it's to get the benefits that most servers implement of queueing, handling DNS information, error bounce messages, and in general robust management of delivery to the target. But that refers to a local SMTP server providing such functionality and not the delivery SMTP agent/server at the destination address. I'm guessing that's what Bryan may have been referring to. (Run a server locally, and just hand it messages to deliver). But you can certainly write SMTP client code that can deliver a message properly to anyone on the net without needing a local SMTP server. Heck, you can do it interactively with dig/nslookup and telnet. Just ask DNS for the MX information properly, resolve the host(s) down to their IP addresses, and then connect to the delivery agent there, and transmit the message. It's much easier to have a smart local SMTP server to take care of the grunge work for you, but it's certainly doable if you don't have one. -- David From me at privacy.net Wed Jul 7 10:20:56 2004 From: me at privacy.net (Heather Coppersmith) Date: 07 Jul 2004 10:20:56 -0400 Subject: Short if References: Message-ID: On Wed, 7 Jul 2004 15:08:38 +0200, "Vincent Wehren" wrote: > class Klass: > def __init__(self, a, b, foo=None, bar=None): > self.a = a > self.b = b > self.foo = (foo, someDefaultMutable)[foo is None] > self.bar = (bar, someOtherDefaultMutable)[bar is None] self.foo = foo or someDefaultMutable self.bar = bar or someOtherDefaultMutable Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From klachemin at home.com Tue Jul 13 23:06:46 2004 From: klachemin at home.com (Kamilche) Date: 13 Jul 2004 20:06:46 -0700 Subject: Numeric - Multiply a byte array by a float. Message-ID: <889cbba0.0407131906.2ae5bed@posting.google.com> I have a need to multiply all the bytes in a Numeric array, by a float, such as .9, .8, etc. I can't figure out a way to do that. Does anyone have a clue how this is accomplished? I need the resulting array to be truncated to an array of bytes. Thanks! --Kamilche From squirrel at WPI.EDU Thu Jul 29 16:35:01 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 29 Jul 2004 16:35:01 -0400 Subject: A goto-like usage of a function In-Reply-To: <64ednb5vPfE7yJTcRVn-pw@powergate.ca> References: <41091DD7.6070500@hotmail.com> <64ednb5vPfE7yJTcRVn-pw@powergate.ca> Message-ID: On Thu, 29 Jul 2004, Peter Hansen wrote: > I'm curious though. Is it considered perfectly acceptable style > to implement a "pure loop" in the form of recursion in a tail- > recursive language, or is that feature really intended just to > allow truly recursive algorithms to be implemented without > fear of stack overflow or performance problems? In Scheme, it's not only perfectly acceptable, it's the standard way to do things. > The acceptance test would probably be: if a mature programmer > in the language in question encountered a loop-done-as-recursion > in code from, say, a junior programmer, would she refactor it to > use a more conventional control structure (e.g. while, or for) > or would she not give it a second thought? Not being a mature Scheme programmer, I can't say for sure, but my gut feeling is that the exact opposite would happen; i.e. if the mature programmer found a loop utilizing do (Scheme's generalized looping construct), she would likely rewrite it using either recursion, or one of for-each or map. (I would provide an example, but my Scheme is wayyy to rusty for that ;).) From newsgroups at jhrothjr.com Thu Jul 22 08:30:53 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 22 Jul 2004 08:30:53 -0400 Subject: how can I get the name of a variable (or other object)? References: <20040722142305.0000373a@titan> Message-ID: <10fvcrk7hmjob60@news.supernews.com> "Josef Dalcolmo" wrote in message news:20040722142305.0000373a at titan... > If I have a Python variable like > > var = 33 > > can I get the name 'var' as a string? > > Obviously this does not make much sense when using a single variable, but if I want to print the variable together with it's name, for a list of variables, then it could make sense: > > def printvariables(varlist): > ....for var in varlist: > ........print var.__name__, var > > of course the attribute __name__ I just made up, and if this would always return 'var' it would not make any sense either. > > I am not sure if such a thing is at all possible in Python. As a general rule, the answer is no. The basic reason is that there is a many-to-one relationship between the names to which an object is bound, and the object itself. In your example, the integer '33' could be bound to a large number of different identifiers in different objects. Python doesn't maintain that kind of a crossreference, and even if it did, you'd still need to figure out the context you were asking about. If you know the context, you might consider building an inverse dictionary so you can use it to look up the object and find the name(s) that it's bound to in that context. Timing is important here! John Roth > > Best regards - Josef Dalcolmo From elbertlev at hotmail.com Thu Jul 15 15:09:47 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 15 Jul 2004 12:09:47 -0700 Subject: Lists, tuples and memory. Message-ID: <9418be08.0407151109.15894fe7@posting.google.com> Hi, all! Here is the problem: I have a file, which contains a common dictionary - one word per line (appr. 700KB and 70000 words). I have to read it in memory for future "spell checking" of the words comming from the customer. The file is presorted. So here it goes: lstdict = map(lambda x: x.lower().strip(), file("D:\\CommonDictionary.txt")) Works like a charm. It takes on my machine 0.7 seconds to do the trick and python.exe (from task manager data) was using before this line is executed 2636K, and after 5520K. The difference is 2884K. Not that bad, taking into account that in C I'd read the file in memory (700K) scan for CRs, count them, replace with '\0' and allocate the index vector of the word beginnigs of the size I found while counting CRs. In this particular case index vector would be almost 300K. So far so good! Then I realized, that lstdict as a list is an overkill. Tuple is enough in my case. So I modified the code: t = tuple(file("D:\\CommonDictionary.txt")) lstdict = map(lambda x: x.lower().strip(), t) This code works a little bit faster: 0.5 sec, but takes 5550K memory. And maybe this is understandable: after all the first line creates a list and a tuple and the second another tuple (all of the same size). But then I decieded to compare this pieces: t = tuple(file("D:\\CommonDictionary.txt")) # 1 lstdict = map(lambda x: x.lower().strip(), t) # 2 lstdict = map(lambda x: x.lower().strip(), file("D:\\CommonDictionary.txt")) # 3 As expected, after line 2 memory was 5550K, but after line 3 it jumped to 7996K!!! The question: If refference counting is used, why the second assignment to lstdict (line 3) did not free the memory alocated by the first one (line 2) and reuse it? So one more experiment: t = tuple(file("D:\\CommonDictionary.txt")) # 1 lstdict = map(lambda x: x.lower().strip(), t) # 2 del lstdict # 3 lstdict = map(lambda x: x.lower().strip(), file("D:\\CommonDictionary.txt")) # 4 In this case executing line 4 did not add memory! By the way, the search speed is very-very good when done by function: def inDict(lstdict, word): try: return lstdict[bisect(lstdict, word) - 1] == word except: return False 500 words are tested in less then 0.03 seconds. From peter at engcorp.com Wed Jul 7 09:58:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 07 Jul 2004 09:58:20 -0400 Subject: Finding Script Directory In-Reply-To: <8089854e.0407070426.2fb90f95@posting.google.com> References: <8089854e.0407070426.2fb90f95@posting.google.com> Message-ID: Fuzzyman wrote: > What's the best, cross platform, way of finding out the directory a > script is run from ? > > I've googled a bit, but can't get a clear answer. I've seen twenty threads on this and I still don't know/recall whether there's a clear answer. :-( > On sys.argv[0] the docs say : > argv[0] is the script name (it is operating system dependent whether > this is a full pathname or not). > > So this doesn't seem to be the answer. Actually, it's all you've got to work with. On Linux and Windows, at least, it's got either just the script name, if you're running from the current directory, or a path (relative or absolute) to the directory where the script is run from. It's like this whether py2exe'd or not, too. __file__ could be of assistance, but it doesn't exist when you've py2exe the thing... > The script directory is always *somewhere* in sys.path - but not > always in position 0. If you use py2exe then sys.path[0] is the > zipfile it does the imports from !! Yeah, sys.path isn't much good for this sort of thing. -Peter From mstenzler at ssaris.com Thu Jul 22 15:19:32 2004 From: mstenzler at ssaris.com (Mike Stenzler) Date: Thu, 22 Jul 2004 15:19:32 -0400 Subject: any cx_Oracle sample code? Message-ID: <9rULc.45998$DR3.15494@fe31.usenetserver.com> Does anyone have any sample code for the cx_Oracle library? www.computronix.com I have the doco and can connect and do simple ops against my database but I'm struggling with the correct syntax for implementing bind variables with a cursor. TIA Mike From me at privacy.net Tue Jul 27 08:22:24 2004 From: me at privacy.net (Duncan Booth) Date: 27 Jul 2004 12:22:24 GMT Subject: syntax-check with regular expressions? References: Message-ID: spamnews at gmx.de (Detlef Jockheck) wrote in news:b5a042c1.0407270400.13d9c94b at posting.google.com: > Hi, > > I would like to check if a string contains a valid date format > (Format: "dd.mm.yyyy") or not. > > What is the best way to do this. regexp? At the moment it would be > sufficient to check for > [digit][digit].[digit][digit].[digit][digit][digit][digit] but a full > date verification (Month in range 1-12 ...) would be very nice too. > > Sample code would help me very much. > > regards > Detlef > > PS: I'm a python newbie, so excuse this silly question > Don't use a regexp for this sort of task, its much better to do the conversion and catch an error if the conversion fails. In this case you should use time.strptime with an appropriate format. Sample code as requested: >>> import time >>> time.strptime("27.7.2004","%d.%m.%Y") (2004, 7, 27, 0, 0, 0, 1, 209, -1) >>> time.strptime("27.13.2004","%d.%m.%Y") Traceback (most recent call last): File "", line 1, in -toplevel- time.strptime("27.13.2004","%d.%m.%Y") File "C:\Python23\lib\_strptime.py", line 424, in strptime raise ValueError("time data did not match format: data=%s fmt=%s" % ValueError: time data did not match format: data=27.13.2004 fmt=%d.%m.%Y >>> time.strptime("29.2.1800", "%d.%m.%Y") Traceback (most recent call last): File "", line 1, in -toplevel- time.strptime("29.2.1800", "%d.%m.%Y") File "C:\Python23\lib\_strptime.py", line 513, in strptime julian = datetime_date(year, month, day).toordinal() - \ ValueError: day is out of range for month >>> time.strptime("29.2.2000", "%d.%m.%Y") (2000, 2, 29, 0, 0, 0, 1, 60, -1) >>> From jepler at unpythonic.net Tue Jul 27 08:57:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 27 Jul 2004 07:57:54 -0500 Subject: ANN: NamerTamer Photo Processor In-Reply-To: References: Message-ID: <20040727125753.GF23727@unpythonic.net> I'm not interested. Here are some of the reasons that come to mind. 0. If I had seen "namertamer" in a list of software, even graphics-related software, I would have had no idea that it performed operations like resize, crop, and red-eye reduction. 1. I can't tell what requirements the program has, and whether it'll run on Unix in the first place. 2. The most common task I perform, and the one that should be the most automatable, is crop & resize for printing. I don't see that on the list of actions your software performs. (Crop region with appropriate aspect ratio, resize to at most WxH pixels, and save a copy) 3. This program will be very threatening for a beginning user. Remember, everyone but you will begin using this software as a beginner. Put all the commands in a nicely-organized menu bar or on a toolbar, which provides a way to teach users the keyboard shortcut at the same time (by giving the key-combination in the menu or in the toolbar item's tooltip) 4. I don't know how much this applies to other digital photographers, but once a photo makes it off my camera and onto my hard drive, I want to keep a copy of that original jpeg file forever, even if I make some adjustments. You suggest manually making a copy and running namertamer, but I would rather see this integrated. 5. If your application is a Windows-specific application, use some Win32 API to move files to the Recycling Bin or whatever it's called, instead of deleting them forever. Then, users can recover from an accidental deletion just as though they had deleted the file using Windows Explorer. 5a. Add a Netscape-style "never ask this question again" to a prompt on delete, because all users expect delete to at least ask for confirmation. This will allow those users to get what they expect, but allow people who trust their fingers to avoid hitting another key at every deletion. 6. Provide a before & after shot of your red-eye reduction. 7. For rotation, read the related EXIF tag and automatically rotate the image to match it when the image is loaded. On save, set the EXIF tag to indicate that the image is properly oriented. 8. Preserve EXIF information on save. 9. Why are "rect" and "oval" radiobuttons instead of keyboard shortcuts? Why don't you use standard icons for rectangular and oval selection, like all the other programs in the world? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From indigo at bitglue.com Fri Jul 16 07:37:04 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 16 Jul 2004 07:37:04 -0400 Subject: Combining colon statements on one line? In-Reply-To: <20040716050940.73131.qmail@web51810.mail.yahoo.com> References: <20040716050940.73131.qmail@web51810.mail.yahoo.com> Message-ID: <20040716113704.GA26034@unununium.org> newdate = date + (1000,2000)[ date < 500 ] On Thu, Jul 15, 2004 at 10:09:40PM -0700, Dave Blackington wrote: > > Hi, I'm trying to figure out how to combine an 'if' > and 'else' statement on one line. Tonight I was > programming and came up with a very short if/else > scenario that demanded 4 lines due to the fact that > python can't read an 'if' & 'else' on the same line. > In order to do the same thing in 1 line, I needed to > make a dictionary. If you want to know the whole > scenario. Here it is: > > '972' '006' > > I have two dates without the millenium included. > Using basic 'if' 'else' communication, this, it seems > to me would require 4 lines of python to add the > correct millenium. These lines will also be so short > and waste a lot of blank space on the screen which > could be devoted to other commands in your function. > For digestion and organization purposes, it seems like > it helps to limit your functions (whenever possible) > to one screen. Taking up those 4 lines for such a > simple short 'if' 'else' seems a bit much, no? > > I don't know if this is would be a desirable upgrade > for other python users or not, but I figured I would > mention it... assuming it's not already implemented. > > Thanks, -Dave From peter at engcorp.com Tue Jul 13 08:37:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jul 2004 08:37:50 -0400 Subject: Iterators In-Reply-To: References: Message-ID: Chris Lyon wrote: > So can anyone point me at some applications, tutorials, websites and > advantages that these mechanisms provide? that don't rely on having > done LBIAJ courses such that I dare use them in my own code that > thrives on the massive over application of lists and dictionaries that > I believe I finally got my head round. There is *nothing* wrong with continuing to use (or over-use :-) lists and dictionaries. I fully intend to do so myself! > Apologies to all for continually stirring up the mud at the bottom of > the crystal clear river that is python but I fear being left behind > when whatever is built on top of these constructs raises it's head in > the forseable future. > > As ever I am attempting to use humour (badly) to voice issues that are > assumed by many but complicated to a few. I understand where you're coming from, and I'm sure you'll get some responses from others that will actually point you somewhere that can help improve your understanding in this area. I just wanted to reassure you that you don't need to be too concerned about the whole thing. I didn't figure out how to write a list comprehension for at least a year after they were first added to the language... I had too much productive work to do with lists. I have _not_ gone back to change any of the list-based code(*), and still only rarely reach for list comprehensions as my first option. There's nothing wrong with not being a leader in adopting new language features. If you try too hard to keep up, you'll probably "churn" too much and waste time rewriting code or something, when you could just be writing working code using the features you know and understand well. -Peter * The fact that I no longer work at that the company would, of course, mean that going back to change the code would result in criminal trespassing and probably industrial sabotage charges, but that's beside the point. ;-) From godoy at ieee.org Sun Jul 4 12:51:19 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 04 Jul 2004 13:51:19 -0300 Subject: Python with PalmOS: anything newer than the 1.5.2 PipPy? References: Message-ID: <60plr1-1iu.ln1@wintermute.g2ctech> On Dom 04 Jul 2004 12:15, Lucas Raab wrote: > You could do something about that and develop a new version. If it wouldn't be extremely out of the tasks we're developing now and if this was really an strategic point for us --- there is more interest by myself on the Linux powered PDAs --- I would go after something like that. For now, I'm just studying the alternatives and seeing if it's viable. -- Godoy. From bgudorf at neurokode.com Sat Jul 24 22:28:54 2004 From: bgudorf at neurokode.com (Bryan J Gudorf) Date: Sat, 24 Jul 2004 22:28:54 -0400 Subject: Python 1.3.0 Released Message-ID: <41031AE6.6050700@neurokode.com> PDO 1.3.0 is now available for download. This addresses an issue in the fields object which accounts for memory issues when using the module. Also in this release are bugfixes for array_from_column() and dictionary_from_columns in the ResultSource Object. As released previously: Python Database Objects (PDO) provides an easy to use Object Oriented API for database developers. PDO utilizes DB-API modules for database access, but allows for a Common Object Oriented API across RDBMS. Thus, PDO can be thought of as a 'wrapper' around the DB-API and database specific modules. PDO offers a unique interface which includes such features as column access by name, forward and backward movement through a result set and much, much more. Downloads for Python Database Objects are available on SourceForge.Net or for more information please visit pdo.neurokode.com. Bryan J Gudorf ~NeuroKode Labs, LLC From mrseb at mrseb.com Mon Jul 12 02:11:48 2004 From: mrseb at mrseb.com (Mr Seb) Date: Mon, 12 Jul 2004 07:11:48 +0100 Subject: SocketServer - how to close the server gracefully? Message-ID: <20040712061159.A9FE84C00193@pengo.systems.pipex.net> Hi. I've been playing with ServerSocket.TCPServer, and I can manage new connections fine, and broadcast data to them all, by managing all the connections in a list. But I seem to have issues closing the individual connections, and then when I have no connections left, the server dies, and python then decides to take up 100% cpu (iterating the serve_forever() handle() basehandler. ) Does anyone have any experience with ServerSocket? I can't seem to find any *examples* of its use on the web. Help appreciated :-) -S -------------- next part -------------- An HTML attachment was scrubbed... URL: From della at toglimi.linux.it Wed Jul 7 12:22:48 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 07 Jul 2004 16:22:48 GMT Subject: sets.Set doesn't honour __eq__ In-Reply-To: References: Message-ID: David Vaughan wrote: > The _base is to allow for unicode. I had removed > some lines for clarity. I'm including > support for Windows filenames (hence the case- > insensitive strings). So I've recycled the start of > Jason Orendorff's excellent path module: > > > # Pre-2.3 support. Are unicode filenames supported? > _base = str > try: > if os.path.supports_unicode_filenames: > _base = unicode > except AttributeError: > pass Wow, Unicode filename support. Right this morning I had problems trying to convert latin-9 filenames to utf-8, and I couldn't do it with a quick python script because (now ) os.path.supports_unicode_filenames is False (in 2.3) even if right now I have unicode filenames and they seem to work OK. :-) Is this a bug, or is it me not understanding something? > Or is it conventional to assume v2.3 these days? I think that if you have no compelling reasons to support 2.2, maybe you can spare yourself the effort :-) -- Ciao, Matteo From peter at engcorp.com Fri Jul 9 08:52:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jul 2004 08:52:03 -0400 Subject: Too many return-statements = bad style? In-Reply-To: References: Message-ID: <5OudnS2ux_ZuCXPd4p2dnA@powergate.ca> Jeff Epler wrote: > Some style guides discouraged multiple "return" statements out of > some theoretical superiority of the single-return form. single-point- > of-return was supposed to lead to easier analysis. Or for easier maintenance... it's still a decent rule to _try_ to follow, but sometimes the contortions needed to avoid it make things even worse. That's why they're style "guides"... -Peter From steve_thompson at prodigy.net Wed Jul 14 10:13:50 2004 From: steve_thompson at prodigy.net (Steve Thompson) Date: 14 Jul 2004 07:13:50 -0700 Subject: Too many return-statements = bad style? References: Message-ID: Marco Aschwanden spammotel.com> writes: > I prefer multiple returns instead of increasingly complex nesting. Obviously > having too many returns (or too much nesting) is showing that you've got a > function which is in need of splitting - I think 5 and especially 7 is a lot, > but it depends on the function. I also like having the conditions such, that the > short code is at the top of the if-else clause, while some programming > guidelines claim you should write the most common cause first (even if that's > considerably longer than the uncommon one). > I guess that I'm going to be the only voice of dissenting opinion here :-). Having programmed in many languages, I've picked up what I would like to think are some of the best practices in software development, and single entry/single exit, which is enforced in the Eiffel language at least, is one such technique. The promise of this practice is that it forces you to factor your code, and in fact I've found it unusual when adhering to this to produce routines longer than about a dozen lines. I should mention that the Eiffel language also does not support gotos of any kind, and so in sharp contrast to a 'C' project I was forced to maintain several years ago, one does not encounter functions that are thousands of lines long. These days, all of my Python routines are single entry/single exit. It is a practice that to me is a mark of good software engineering, as is never using 'continue' (why does this useless artifact survive from language to language?) and leaving loops only when the loop condition is met. At the end of the day this means my code is easy to read, easy to follow, and fairly well factored. And for those folks that actually view many exits as a Good Thing, I would argue that increasing the cyclomatic complexity of any piece of code is by definition the very antithesis of good software engineering. Best regards to all, Steve From exarkun at divmod.com Sat Jul 31 12:29:38 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 31 Jul 2004 12:29:38 -0400 Subject: transforming a list into a string In-Reply-To: References: Message-ID: <410BC8F2.7020100@divmod.com> > In article , > [snip] > > This works, and is pretty straight-forward: > > source = ['1','2','7','8','12','13'] > temp = [] > > while source: > x = source.pop(0) > y = source.pop(0) > temp.append ('{%s,%s}' % (x, y)) > > result = ','.join (temp) > print result > > [snip] > > How long is "much longer", and how important is it that this runs fast? > The code above runs in O(n). You can probably play some tricks to tweak > the speed a little, but in the big picture, you're not going to do any > better than O(n). > Are you sure? Did you consider the complexity of list.pop(0)? Jp From jacek.generowicz at cern.ch Thu Jul 15 04:25:47 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Jul 2004 10:25:47 +0200 Subject: speed of python 2.4 References: <87658wdgvg.fsf@blakie.riol> Message-ID: Peter Hansen writes: > > What is the value of XX and YY ? > > No, "what" is a word that is used to introduce some types of > questions. ;-) You need to fix your parser. If he had written '"What" is the value of XX and YY'[*], then your parse would have been valid. :-) [*] Note: a) Quoted "What" b) No question mark From dd55 at cornell.edu Tue Jul 27 18:49:19 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 27 Jul 2004 18:49:19 -0400 Subject: saving and reloading variables for interactive work Message-ID: If I am working interactively with 10 variables and wanted to pickle them and reload them tomorrow using the same variable names, would there be a direct way of doing it? Thanks, Darren From xtian at toysinabag.com Thu Jul 29 01:43:14 2004 From: xtian at toysinabag.com (xtian) Date: 28 Jul 2004 22:43:14 -0700 Subject: IronPython-0.6 is now available! References: <278de0e.0407281353.27b6a457@posting.google.com> Message-ID: luismg at gmx.net (Neuruss) wrote in message news:<278de0e.0407281353.27b6a457 at posting.google.com>... > IronPython is currently at a pre-alpha stage suitable for > experimentation but not for serious development work. > > http://www.ironpython.com This snippet's pretty exciting! """ ...I've decided to join the CLR team at Microsoft beginning on August 2. At Microsoft I plan to continue the work that I've begun with IronPython to bring the power and simplicity of dynamic/scripting languages to the CLR. My work with Python should continue as a working example of a high-performance production quality implementation of a dynamic language for the CLR. """ I'd love to see Python as a fully-integrated .Net language - worries about Microsoft evilness notwithstanding. xtian From max at alcyone.com Wed Jul 21 16:21:11 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 21 Jul 2004 13:21:11 -0700 Subject: exec "statement" VS. exec "statement" in globals(), locals() References: Message-ID: <40FED037.C464277E@alcyone.com> James Henderson wrote: > Update and return a dictionary representing the current local symbol > table. Warning: The contents of this dictionary should not be > modified; > changes may not affect the values of local variables used by the > interpreter. It doesn't matter whether you use the value directly from locals() or assign it to a secondary variable, it's still read-only. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ History is a bucket of ashes. -- Carl Sandburg From PPNTWIMBXFFC at spammotel.com Thu Jul 1 08:52:19 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 01 Jul 2004 14:52:19 +0200 Subject: Looking for minimal SQL References: <2kidfvF2iddkU1@uni-berlin.de> Message-ID: Thanks for your hints. From mail at markus-franz.de Fri Jul 2 11:28:20 2004 From: mail at markus-franz.de (Markus Franz) Date: Fri, 2 Jul 2004 17:28:20 +0200 Subject: threads instead od processes Message-ID: Hi. I've got a little script: #!/usr/bin/python import sys, os for x in sys.argv[1:]: pid = os.fork() if pid == 0: # do something with x break This creates some new processes (depending on the number of passed command line arguments) and inside each process x is one command line argument. Now my question is: How can I do the same by using threads instead of processes? Thank you. Best regards Markus Franz From narshe at gmail.com Wed Jul 21 16:48:43 2004 From: narshe at gmail.com (Josh Close) Date: Wed, 21 Jul 2004 15:48:43 -0500 Subject: number format Message-ID: <4a0cafe20407211348ee4ea6d@mail.gmail.com> How do I do a number format in python? Like with php's number_format() function you can do number_format(1000) and it will return 1,000 It just adds the ',' and has another option for decimal places too. -- -Josh From aisaac at american.edu Thu Jul 29 10:46:18 2004 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 29 Jul 2004 10:46:18 -0400 Subject: Question on lists References: <41071cfe$0$60648$d5a6236f@newsreader.cybernetik.net> Message-ID: <10gi3baktalska7@corp.supernews.com> "Heiko Wundram" wrote in message news:mailman.866.1090988681.5135.python-list at python.org... > >>> import sets > >>> list(sets.Set(['a','a','b','b','d','b','c','a','ladida'])) > ['a', 'c', 'b', 'd', 'ladida'] Newbie question: OK, this is great. But I was not aware of this module, and I was working in my own sets.py. So how do I handle this namespace issue? I.e., how can I 'import sets' and get the Python module, when my own script is named sets.py? Thanks, Alan Isaac From ThomasBartkus at Comcast.net Thu Jul 29 12:48:51 2004 From: ThomasBartkus at Comcast.net (Thomas Bartkus) Date: Thu, 29 Jul 2004 11:48:51 -0500 Subject: Looking for comments on BlackAdder References: Message-ID: "dusty" wrote in message news:g89fg09hsauqgr5er4jnv2irf6r3ed9ten at 4ax.com... > Hi, > I recently switched from windoze to Linux (SuSE 9.1) and want to write > some applications (mostly for personal use). I have several years > experience writing with Borland Delphi and now I am looking at Python. > BlackAdder incorporates Python and QT into a application similar to > Delphi for writing GUI applications. (I looked at Kylix and didn't > like it) > > I wonder if BlackAdder is worth the price or would I be just as well > off using Idle and QT Designer? > > I would appreciate any comments on BlackAdder. > Can't comment on BlackAdder AND I'm still too green with Python to offer "intelligent" opinions :-) BUT if you are looking for cross-platform development of GUI apps under Python, do take a look at www.wxPython.org. At first glance, wxPython looks like a cleaner API as well as better integration with Python. Note that I said GUI apps - not GUI development! That still remains elusive although I don't know why. The underlying software infrastructure seems to make it eminently doable! If I weren't so green with Linux and Python, I could see writing a GUI programming front end myself! It's a shame about Kylix! I had high hopes for that myself. Thomas Bartkus From me at privacy.net Wed Jul 7 04:21:41 2004 From: me at privacy.net (Duncan Booth) Date: 7 Jul 2004 08:21:41 GMT Subject: X is confusing References: <40eb114e$0$58816$bed64819@news.gradwell.net> Message-ID: "Peter Mott" wrote in news:40eb114e$0$58816$bed64819 at news.gradwell.net: > I get this inb the Python interpreter v. 2.3 > >>>> >>>> X=99 >>>> X is 99 > True >>>> Y=100 >>>> Y is 100 > False >>>> > > Numbers less that 100 get True, more than 100 get False. It seems. > What does this mean? If nothing, then why does it happen? I mean how > do you explain 'is' or 'id(X)' to the first time programmer when it > does this to you. > Similar things happen with strings: >>> x = 'hello' >>> x is 'hello' True >>> y = 'hello world' >>> y is 'hello world' False >>> The compiler is free to optimise immutable values if it wishes. First time programmers probably don't need to know all of the details of 'is', for that matter even experienced programmers rarely need to use it. From gh at ghaering.de Sun Jul 4 02:01:32 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 04 Jul 2004 08:01:32 +0200 Subject: distutil and debugging In-Reply-To: <6b17fa95.0407032021.30aab655@posting.google.com> References: <6b17fa95.0407030838.2a8184cb@posting.google.com> <6b17fa95.0407032021.30aab655@posting.google.com> Message-ID: <40E79D3C.2030907@ghaering.de> Jesper Olsen wrote: > [...] No - that does not change the options. I think it only links against a version > of the python lib, which has been compiled for debugging. > > However, I want to debug my own extention - not the python interpretor. > > I'm not the first to have this problem: > > http://tinyurl.com/35ddd > > but that solution only works for the windows environment. > I'm on OpenBSD, and would prefer to stay there also while debugging... I don't think that's relevant here. To be honest, I didn't need to add any flags on Linux to debug my extensions. -g always gets added there automatically. Perhaps this comment from distutils/unixcompiler.py will help you fixing your build environment: # * optimization/debug/warning flags; we just use whatever's in Python's # Makefile and live with it. Is this adequate? If not, we might # have to have a bunch of subclasses GNUCCompiler, SGICCompiler, # SunCCompiler, and I suspect down that road lies madness. Maybe your OpenBSD Python was compiled without -g and thus your extensions are compiled without -g as well. -- Gerhard From markus_wankusGETRIDOFALLCAPS at hotmail.com Wed Jul 14 20:13:33 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Wed, 14 Jul 2004 20:13:33 -0400 Subject: IDE In-Reply-To: References: Message-ID: Thomas Lindgaard wrote: > Hello > > I am probably going to start a war now... but so be it :) > > I just want to hear what all you guys who eat pythons for breakfast use > for python coding. Currently I use Kate, but I would really like an IDE > with debugger and a source browser (ie. one the I can use to browse > through modules etc. when looking for just the right curses stuff and such > - I am a newcomer to Python). > > ... and no, Emacs or Vi are not what I want :) > If you don't mind "bleeding edge" software - pydev for Eclipse is coming along. You can try it for yourself: http://pydev.sourceforge.net/ Markus. From thomas at it-snedkeren.BLACK_HOLE.dk Thu Jul 29 04:13:16 2004 From: thomas at it-snedkeren.BLACK_HOLE.dk (Thomas Lindgaard) Date: Thu, 29 Jul 2004 10:13:16 +0200 Subject: if or exception Message-ID: Hi Just wondering what is "the right thing to do": number = 0 if len(list) > 0: number = anotherNumber / len(list) or try: number = anotherNumber / len(list) except: number = 0 -- Regards /Thomas From kevryan0701 at yahoo.com Wed Jul 21 09:16:17 2004 From: kevryan0701 at yahoo.com (Kevin T. Ryan) Date: 21 Jul 2004 06:16:17 -0700 Subject: Reading a file and then writing something back Message-ID: <7e1b5feb.0407210516.de7eb49@posting.google.com> Hi All - I'm not sure, but I'm wondering if this is a bug, or maybe (more likely) I'm misunderstanding something...see below: >>> f = open('testfile', 'w') >>> f.write('kevin\n') >>> f.write('dan\n') >>> f.write('pat\n') >>> f.close() >>> f = open('testfile', 'r+') >>> f.readline() 'kevin\n' >>> f.readline() 'dan\n' >>> f.write('chris\n') Traceback (most recent call last): File "", line 1, in ? IOError: (0, 'Error') I've figured out that I can do an open('testfile', 'r+') and then seek and write something (without an error), but it just seems odd that I would get an IOError for what I was trying to do. Oh, and I also tried to do "f.flush()" before the write operation with no luck. I've searched google, but can't seem to find much. Any thoughts??? TIA, Kevin From jepler at unpythonic.net Tue Jul 20 20:21:19 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Jul 2004 19:21:19 -0500 Subject: CVS style argument parsing? In-Reply-To: References: Message-ID: <20040721002119.GA6880@unpythonic.net> Don't use OptionGroups for each command. Instead, you'll have the OptionParser for the "main" arguments, and the option parser for each command. By using parser.disable_interspersed_args() you can make the parsing of "-a b -c".split() handle "-a" and return "b -c".split() as the positional args. Then, depending on what b is, send -c to a separate parser instance. I don't see where disable_interspersed_args() is documented, but it's right there in optparse.py Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From grante at visi.com Mon Jul 5 11:12:56 2004 From: grante at visi.com (Grant Edwards) Date: 05 Jul 2004 15:12:56 GMT Subject: py2exe -> error in PYTHON23.DLL References: <2kotqkF4t652U1@uni-berlin.de> Message-ID: On 2004-07-03, RPM1 wrote: > > "Grant Edwards" wrote in message > news:slrncebbqt.35h.grante at grante.rivatek.com... >> Using py2exe under WinMe, I bundled up a python program >> containing a single line: >> >> print "hello world" >> >> When I zip up the dist directory and move it to another WinMe >> machine, trying to run hello.exe either reboots or pops up a >> dialog box that says >> >> Hello has caused an error in PYTHON23.DLL >> Hello will now close >> >> If you continue to experience problems, >> try restarting your computer. >> >> Any ideas on what the problem might be? > > I had a problem with py2exe on WinMe & Win98 because > it needed a unicode extension called unicows. That fixed it. AFAICT, it's py2exe that needs unicows.dll, not the resulting application package. IOW, you need unicows.dll on the development machine but not on the target machines. -- Grant Edwards grante Yow! Darling, my ELBOW at is FLYING over FRANKFURT, visi.com Germany... From k.robert at gmx.de Thu Jul 22 11:20:51 2004 From: k.robert at gmx.de (Robert) Date: 22 Jul 2004 08:20:51 -0700 Subject: BS_DEFPUSHBUTTON doesn't work inside ProperyPage !? Message-ID: <19804fd8.0407220720.20de3b17@posting.google.com> I have a Combobox and a DefPushButton in a PropertyPage as form (a main window; not modal dialog) Pressing RETURN in the Combobox or any Editfield in the form doesn't issue a WM_COMMAND/OnOK (When running the dialogtemplate as normal dialog it works.) I also made a extra invitation by DM_SETDEFID : self.SendMessage(wc.DM_SETDEFID, 303, 0) - it still won't work. I'm also not able to catch the return key (WM_KEYDOWN, WM_CHAR) at all inside the combobox control or the page, but I can catch all other keys. Playing with DLGC_WANTALLKEYS also doesn't help to get the VK_RETURN in any case. Whats going with [RETURN] in a non-modal sub-prop-page form ? What can I do? Robert (I use Pythonwin on top of MFC; it should not matter.) From jjl at pobox.com Sun Jul 11 18:06:53 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jul 2004 23:06:53 +0100 Subject: Newbie problem with HTTP Redirection in Python 2.4 urllib2 References: <5ab3ec6c.0407100457.229b14a0@posting.google.com> Message-ID: <87smbyci6a.fsf@pobox.com> sriram_2001spam at yahoo.co.in (Sriram Krishnan) writes: > I've just downloaded the alpha of Python 2.4 and I'm not able to get > HTTP Redirection to work - even the examples are failing for me. They > all give the same error message (whenever a site issues a HTTP 302) [...] This is broken in 2.4a1, and was fixed in CVS on Saturday's bug day. If you want cookie handling now, I'm pretty sure you can just grab cookielib.py and urllib2.py from CVS and use them with 2.3. Alternatively, use ClientCookie (cookielib is a tidied-up version of ClientCookie): http://wwwsearch.sf.net/ClientCookie/ HTH John From jepler at unpythonic.net Thu Jul 29 07:20:42 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 29 Jul 2004 06:20:42 -0500 Subject: python startup very slow on win2000 In-Reply-To: <2ms1ctFqhogiU1@uni-berlin.de> References: <2mol2jFp403oU1@uni-berlin.de> <2mplmkFpkndcU1@uni-berlin.de> <2ms1ctFqhogiU1@uni-berlin.de> Message-ID: <20040729112042.GA24721@unpythonic.net> Then you've at least learned something: Files loaded due to site.py, or files on PYTHONPATH, add 3-4 seconds to start time. However, 6-7 seconds for "python -vc 'print 1'" is still excessive. That takes only 1/2 second here, and "python -c 'print 1'" takes 0.05 seconds (the difference being the time to print all the "-v" lines, basically). (This is on an 650MHz Unix machine--A modern 2.7GHz Unix machine I just tested took 0.005 seconds for "python -SEc 'print 1'") The number one reason I've seen for slow Python startups are sys.path directories on the network (from personal experience). Other problems might be importing modules from directories without .pyc files and without write permissions (Python must parse and byte-compile the source files each time), or a module being imported attempts to do some network-related activity, such as find the hostname, but your network is misconfigured. ... or it could be some obscure Microsoft Windows misconfiguration that we'll never guess in a million years. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From marco at reimeika.ca Thu Jul 29 01:31:17 2004 From: marco at reimeika.ca (marco) Date: 29 Jul 2004 01:31:17 -0400 Subject: tempfile.mkstemp problem? References: Message-ID: Sorry for yet another followup. > the plugin/script is being called from yet another > Perl script. I guess I should look more closely > at how this is taking place. In the meantime, any ideas > would be appreciated! The Perl script runs: system("$plugin encode $fields"); When I do: plugin encode fields on the command line things work fine. Any ideas? Cheers! -- marco at reimeika.ca Gunnm: Broken Angel http://amv.reimeika.ca http://reimeika.ca/ http://photo.reimeika.ca From riccardo_cut-me at cut.me.sideralis.net Sat Jul 10 13:53:47 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Sat, 10 Jul 2004 19:53:47 +0200 Subject: simple question References: Message-ID: On Sat, 10 Jul 2004 17:42:22 +0000, madgww wrote: > I am new with python how do you put a time delay between each programming > line import time time.sleep(1) <- sleep wants seconds Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From apardon at forel.vub.ac.be Thu Jul 8 03:57:37 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Jul 2004 07:57:37 GMT Subject: try: finally: question References: <40eadf77@usenet01.boi.hp.com> <40eb00db@usenet01.boi.hp.com> <35-dnVL-0qrXtnbdRVn-jg@powergate.ca> <2IadnfA7t7M3vXHdRVn-ug@powergate.ca> Message-ID: Op 2004-07-07, Peter Hansen schreef : > Antoon Pardon wrote: > >> Op 2004-07-06, Peter Hansen schreef : > [about using finally and except on the same try block] >>>You used to be able to do that, according to a recent thread on the >>>subject. It was removed because it was ambiguous what would happen. >>>For example, if an exception were raised in a finally clause which >>>came just before the except clause, would the except clause catch it? >>>Since the finally is technically outside of the try block, some >>>people thought it shouldn't be caught by the following except. >>>Others did. Guido nuked it. >>> >>>Anyway, it would be purely syntactic sugar for what we have now, >>>saving you a few keystrokes and one extra level of indentation. >>>No big deal. >> >> I don't agree. > > With what statement don't you agree? The part about "you used to > be able to do that... [but] it was ambiguous ... Guido nuked it."? That it is no big deal. > Because that's a fact. It's hard not to agree with it... > > And if it's the part about "syntactic sugar", then you should > understand that the term refers to alternate syntax which is > seen as "cleaner" or "simpler" in some way, but which is not > otherwise different in any way that affects the parse tree or > resulting code. And unless you think combined finally/except > clauses should be treated differently in the generated bytecode > than nested try/finally/except, it's *still* a fact that it > would just be "syntactic sugar", and arguing against facts is > pretty hard to do... > >> It is not unusual to nest try blocks. If you then >> need to two instead of one because you can't combine a finally >> with an except clause, you almost double the level of indentations. > > In fact, you would precisely double the level of indentations. > It seems that's the price we have to pay for being human, since > apparently our brains aren't all wired the same way and allowing > finally/except to be combined was likely to lead to subtle bugs. Oh come on, I though python was for consenting adults? Personnaly I think that allowing += operators for unmutable object will lead to subtle bugs too, because if you see code like b = a a += c You don't know whether a and b are still the same object or not. This will IMO be more confusing then a combined finally, except clause, because the latter can be clearly documented in how it behaves, while the above depends on the type of the variables. >> IMO it is almost as bad as would not having an elif and needing >> an extra indentation level for each else .. if > > Almost, perhaps. But can you see any way for similar ambiguity > to arise in the case of if/elif/else blocks? I think everybody > understands how they work just fine. The whole point is that > not everybody understood how the try/finally/except thing worked > (or they didn't agree with how it _should_ work). So what? When I complained about the ambiguity that was introduced by the introduction of the += and like operators, people told me that: 1) Error caused by not reading the docs carefull enough were my own fault 2) That I could always write things in such a way that there would be no ambiguity. So these arguments seem to be just as valid with a combined except: finaly: clause. > I understand that you are arguing that it would be nicer to > allow try/finally/except. I agree! Unfortunately, (a) it was > removed and is probably unlikely to be added back in, (b) it > was ambiguous, and the ambiguity has not been resolved, so > until you or someone else can come up with a better approach > (and write a PEP) it will stay the way it is. And that's just > another fact, so it's pointless to try to argue against it. Well I think it really isn't that hard to define the behaviour of try: except expr1: finaly: except expr2: to be the same as try: try: try: except expr1: finaly: except expr2: In fact if it wasn't for the indentations rules in python I wouldn't care because without them I could simply write something like try: try: try: except expr1: finaly: except expr2: which is how I write my if ... else blocks in C. However I'm not going to write a PEP. The impression that there is some double standard going on is just too strong, where powerfull, flexible and/or ambiguous concepts that are in the language are defended with the argument that python is for consenting adults and powerfull, flexible and/or ambiguous concepts that are not in the language are opposed because they can lead to subtle bugs. Maybe the python community should make up its mind and decide what it wants. A language for consenting adults or protection against subtle bugs. > Hmm... Also, I think it really *is* unusual (as in, "not usual" > meaning not really common) to nest try blocks. At least, I > recall lone try/finally or try/except blocks being much much > more common in most code than a mix. Perhaps my memory is > poor on this. Perhaps someone will actually go and research > it and prove it one way or the other. If it really is > very common, it might be worth revisiting the subject... > If it's not very common, then this is once again just another > discussion about syntactic sugar for an uncommon use case, > and that kind of thing is so last year. And the year before. > And.... One can argue the opposite too. Why remove it, if the subtle bugs can occur only in unusual cases. Let those who need it and know what they are doing use it. That is what I understand about a language for consenting adults. -- Antoon Pardon From pinard at iro.umontreal.ca Mon Jul 12 10:59:45 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 12 Jul 2004 10:59:45 -0400 Subject: List Comprehension Syntax In-Reply-To: <2qCdnZEGRLd-AG_dRVn-iQ@powergate.ca> References: <8OXHc.13877$4y7.5713@newssvr27.news.prodigy.com> <2lc645Fb0cjgU2@uni-berlin.de> <2qCdnZEGRLd-AG_dRVn-iQ@powergate.ca> Message-ID: <20040712145945.GA4203@titan.progiciels-bpi.ca> [Peter Hansen] > Fran?ois Pinard wrote: > >... for me at least, the greatest virtue of Python is that one can > >write it legibly, and maintainability mainly results from legibility. > I don't find the legibility of the carefully aligned version of > that code to be higher than the simpler "indent the standard amount" > version of the code. That's the important point. Write for legibility! :-) > [...] same as how I used to waste time lining up the equals signs in > initialization sections of my code. Yes, this is often abused, with not much gain. Agreed! > (Wow... a simultaneous segue into both the tab war and the editor > wars! I think I'd better leave now...) We'll surely meet somewhere else, anyway! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ed-no at spam-eepatents.com Thu Jul 8 05:47:22 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 08 Jul 2004 02:47:22 -0700 Subject: Why would I learn Python over other languages? References: Message-ID: <9-6dnV__OcqChXDdRVn-ig@centurytel.net> Charif Lakchiri wrote: > Does it support server-side programming, say for web apps? > Does it have extensions and libraries, say for DB connectivity, serial com > or network programming...? Check out the twisted package (http://www.twistedmatrix.com/) for an incredibly powerful answer to these two questions. --- Ed Suominen * http://www.eepatents.com Registered Patent Agent * Open-Source Software Author (yes, both...) From ivoras at __geri.cc.fer.hr Thu Jul 29 18:25:11 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Fri, 30 Jul 2004 00:25:11 +0200 Subject: Importance of C# (was Re: IronPython-0.6 is now available!) In-Reply-To: References: <278de0e.0407281353.27b6a457@posting.google.com> <5dydnZSDZaARoZXcRVn-ug@powergate.ca> <1n5z28erh2m3u.dlg@baczek.net.invalid> Message-ID: Peter Hansen wrote: > Marek Baczy?ski wrote: > >> Dnia Wed, 28 Jul 2004 19:53:48 -0400, Peter Hansen napisa?(a): >> >>> As near as I can figure, those who find Python has significant >>> advantages for many applications over Java and C++ will likely >>> feel the same way about C#, only more so. Isn't it basically >>> a highly MS-centric remake of Java, but missing the very >>> cross-platform nature which has served Java (and Python) best? >> >> Isn't it MS-centricity that serves C#? IMHO it's so popular (relatively) >> because MS backs it. > > > That's exactly what I thought, but clearly the OP thinks > differently or (it seems to me) he wouldn't be asking the question > he asked (or in the way he asked it). Well, it is certainly a big factor. I watched development of Mono with interest, and I tried it very soon after it went "release", on FreeBSD. Now, it only runs on a recent development version of the system, due to unresolved quirks with pthreads that FreeBSD has, but the parts that do work, work well. (It was actually a suprise with me, I thought it had much reason to fail). That success lead me to get to know C# a bit better, so I got a book and started reading. I agree very much with posts further down the thread by Derek Thompson and Martin v. Lowis. The language itself is much more complex than Python (with which I didn't get a book and I think I know it pretty well), it certainly doesn't have Pythons elegance in some fields, like lambda functions, and I don't think it even has things like generators, but IMO, it's *way* cleaner than Java. I've done a lot of development with Borland Delphi (Pascal), so my judgement might be influenced by seeing so much of things I love and use in D. made it in C# (i think a Delphi architect was part of the C# team at MS), my favourite being "properties" and "indexers", (indexers = treating classes/properties as array; something like overriding [] operator), and "ignoreable" exceptions. Regarding similarity with Python, i though I saw recent Python versions also have properties and single-root-class (is this what 'new classes' are about?). C# (or rather, the class lib) also has modern structures like dictionaries, stacks, etc. The only part I'm really dissapointed by is the GUI development. It seems that while the Windows.Forms API is "standard" and published, many "real life" .net programs call Win32 API in addition to that, so it gets complicated. I hadn't had great success with Gtk#. It seems Python has much advantage here. Oh, I have to mention speed: I made some simple benchmarks, and the JIT in .net is fantastic! A simple numeric adder-loop in python (with 1e9 iterations, with xrange...) takes about 30min (hadn't tried psyco yet), while C# code is on par with compiled C code (about 2 sec.) - it seems they did a hell of a good job there. -- What part of "Ph'nglui mglw'nath Cthulhu R'lyeh wgah'nagl fhtagn" don't you understand? From ville at spammers.com Wed Jul 28 05:40:11 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Jul 2004 12:40:11 +0300 Subject: python for .NET References: Message-ID: >>>>> "Tor" == Tor Iver Wilhelmsen writes: Tor> They do claim Visual Python makes Python a "fully supported" Tor> language. Fully supported for VS.NET, perhaps, but not fully supported for .NET, which probably means the CLR these days... -- Ville Vainio http://tinyurl.com/2prnb From dave at pythonapocrypha.com Tue Jul 27 18:16:47 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 27 Jul 2004 16:16:47 -0600 Subject: atomic operations in presence of multithreading In-Reply-To: References: <4f24b4e5.0407271001.7d3bf9c4@posting.google.com> Message-ID: <4106D44F.2080403@pythonapocrypha.com> Paul Moore wrote: > Peter Hansen writes: > > >>Dave Brueck wrote: >> >> >>>Glenn Kasten wrote: >>> >>> >>>>I am wondering which operations in Python >>>>are guaranteed to be atomic in the presence >>>>of multi-threading. In particular, are assignment >>>>and reading of a dictionary entry atomic? >>> >> > [...] >> >>>Basically: multiple threads can't corrupt the interpreter's >>>internals (but a buggy C extension could). >> > > [...] > > >>The key instructions in the above are the dictionary lookup, >>which is merely "BINARY_SUBSCR" in func(), and the dictionary >>assignment, which is "STORE_SUBSCR" in func2(). If func >>and func2 were in separate threads, either the lookup or >>the store executes first, then the other, but they cannot >>both be executing at the same time. > > > As was pointed out to me when this came up recently, it is possible > for callbacks into python to screw this simple picture up a little. > > The obvious case is a user-defined class with a __setitem__ method. In > this case, STORE_SUBSCR calls arbitrary Python code, and so can be > interrupted by a thread switch. > > Given that the original question was about dictionaries, which are > coded in C (and so not subject to this issue) there is still the > following case: when the old value stored in the dictionary is > replaced, that could be the last reference to it. When the old value > is freed, its __del__ method gets called - arbitrary Python code > again. > > But the basic idea is sound. The interpreter releases the GIL *only* > between Python bytecodes. As long as you cater for recursive cases > like the above (and obvious ones like CALL_METHOD), you're OK. Yep, though I think the OP was mostly concerned with Python's internals gettin messed up by unlocked multithreaded access, so he doesn't have to be concerned about the above. -Dave From squirrel at WPI.EDU Thu Jul 22 10:02:38 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 22 Jul 2004 10:02:38 -0400 Subject: Getting information from OS In-Reply-To: References: Message-ID: On Wed, 21 Jul 2004 Skulled2003 at netscape.net wrote: > What i need to accomplish is a list of languages that are installed > or can be viewed on the system. I am not sure if i am making it clear, > but the list should contain information on the languages that a system > can recognize and use in applications etc. Is this on Unix or Windows? On Unix, something like the following would work: ----- import os from os.path import join from glob import glob binpath = os.environ['PATH'].split(':') def installed(bins): for bin in bins: for path in binpath: if glob(join(path,bin)): return True progs = { 'Python':['python','python2.?'], 'Perl':['perl','perl5.?.?'], 'Java':['java','javac','gcj'], 'C':['cc','gcc','bcc','icc'] } installed_progs = [prog for prog,bins in progs.items() if installed(bins)] for prog in installed_progs: print prog,'is installed!' ----- On Windows, something similar could be employed, but more places will have to be checked (or perhaps directories instead of binaries). From jzgoda at gazeta.usun.pl Sun Jul 4 15:37:22 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 4 Jul 2004 19:37:22 +0000 (UTC) Subject: Install MySQLdb for Python win32 need Visual Studio 6 References: <73bf7f21.0407040921.5ba6568a@posting.google.com> Message-ID: Thiago pisze: > I'm trying install the MySQLdb and i'm receiving the message when i > execute the command python setup.py install: > error: Python was built with version 6 of Visual Studio, and > extensions need to > be built with the same version of the compiler, but it isn't > installed. > > How can i correct this? Exist another way to connect mysql database > (different ODBC)? You can install binary package, cann't you? -- Jarek Zgoda http://jpa.berlios.de/ From rogerb at rogerbinns.com Fri Jul 9 03:21:56 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 9 Jul 2004 00:21:56 -0700 Subject: Looking for a Python PHP programmer References: <6EgGc.87734$335.61781@newssvr29.news.prodigy.com> <1c9je05nlfhinam0tcb2rj68usuq2d0u9l@4ax.com> <5hnke0tjtnkbkm5alicbsgerbb25a3mk19@4ax.com> Message-ID: <1lt1s1-pep.ln1@home.rogerbinns.com> Peter Maas wrote: > I think in Cheetah it's .capitalize and .escape (details may vary). Yes, but that is because you know they are available as string methods :-) Smarty is simpler and I think the syntax is better for expressing that sort of thing. It isn't as "powerful" as a result, but if you never use the "power" it doesn't matter. > The elegance of the Cheetah way is how they map Python code > to placeholders. Every method and every field of an object can > be addressed in a Cheetah template. But that mostly matters to programmers. If a non-programmer is reading/writing the template, then generally they care about what fields are available and various formatting options (such as defaults, case conversion, truncation etc). I think Smarty expresses that in a simpler way, but at the cost of not having methods etc. > But it's of course a neat idea to combine PHP and Python given > the overwhelming PHP predominance at ISPs. I was suprised at how well the XML-RPC worked between the two languages. I was even doing my state management and security in Python which PHP passed on to the browser as a cookie. It meant I could also do things like session timeouts in the Python. PHP was only used for display. Roger From tjreedy at udel.edu Wed Jul 28 15:15:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Jul 2004 15:15:46 -0400 Subject: Test failures on AIX 5.1 for 2.3.4 References: <3d4251a8.0407281003.5546de45@posting.google.com> Message-ID: "Jeff Smith" wrote in message news:3d4251a8.0407281003.5546de45 at posting.google.com... > I built Python 2.3.4 on AIX 5.1 with the AIX C compiler cc_r and had > three test failures during the "make test" phase: > test_coercion > test_mmap > test_pty I believe coercion is universally applicable and should pass on every machine. I am not sure about the other two. > Do I need to worry about these? Should I submit a bug report? Unless you get a more complete answer than mine, saying no, I would suggest so, including details of hardware, compiler switches, and failure messages. But first make sure you compiled with optimizations turned off. It might be helpful to either you or the developers if you also tried 2.4a1. Terry J. Reedy From jlenton at gmail.com Wed Jul 14 15:58:20 2004 From: jlenton at gmail.com (John Lenton) Date: Wed, 14 Jul 2004 16:58:20 -0300 Subject: design methodology question In-Reply-To: References: Message-ID: <2d9e37f904071412585e7e16db@mail.gmail.com> On Wed, 14 Jul 2004 15:32:19 +0200, Jaco Smuts said: > I've looked at http://modeling.sourceforge.net/ and other similar > projects, but I'm not yet convinced. Would be interested in your > experience with these type of bridging frameworks. I'm using Modeling a lot, both in zope and out, and it simplifies my life no end. It has no major issues I've come across, and the minor issues I've been able to work out in no time thanks to S?bastien's excellent help. Do you have any specific questions about it? -- John Lenton (jlenton at gmail.com) -- Random fortune: bash: fortune: command not found From look at in.signature Wed Jul 7 05:44:42 2004 From: look at in.signature (seguso) Date: Wed, 07 Jul 2004 09:44:42 GMT Subject: python desktop References: Message-ID: David Fraser wrote: > > great to see this, was looking at the old version before... :-) > could you perhaps split the logicaldesktop.py into separate modules? it > makes it a bit difficult to find code to do improvements when its 3200 > lines long... Why? I mean, actually it is easier in a single file if you use emacs, because you use IM-Python to browse the classes. And if you use eric3, you don't care about how many files, since you use the class browser to move. Maybe I don't realize some advantage of splitting the code... Anyway, I will need to partition the code in some way, because I want to make two versions eventually: a gnome-panel applet and a kicker applet. > Anyway what I was going to try and do: > - make filters work as you type, not just when you press Enter ala > Thunderbird's mail filters This was my first thought, but then I thought 1) it would be too slow 2) you type only once anyway. The preferred method is to use the recent filters list. > - Try and work out why it thinks my HP CD writer is a Plextor CDROM - > where do you pick up this information? I am a bit ashamed, but here it is: THE DEVICES ARE COMPLETELY INVENTED. I need to scan the devices in the computer, but I am clueless how to do that. > Anyway I love some of the concepts and its looking nice... Are you implying that there is some concept you don't like? Thanks a lot for the feedback! -- Best Regards, Maurizio Colucci Please remove the uppercase letters "S,P,A,M": seSgPuAsMo.forever at tin.it From DesertLinux at netscape.net Thu Jul 22 16:34:31 2004 From: DesertLinux at netscape.net (Byron) Date: Thu, 22 Jul 2004 20:34:31 GMT Subject: Problem in splitting a string In-Reply-To: References: Message-ID: HI Angelo, Here's a function that will take care of what you need: ----------- def splitrecord(stringRec): theRec = string.split(stringRec, ',') # Split record into a list. name = theRec[14] # Store name in memory. surname = theRec[15] # Store surname in memory. name = name[1:] # Trim quote from name. surname = surname[0:len(surname)-1] # Trim quote from surname. theRec[14] = "%s, %s" % (name, surname) # Merge and store name, surname in list. del(theRec[15]) # Remove list item 15 from list. Not needed. return theRec # Return list to user. ----------- To use this list, do the following: recordstring = ',,,,,,23,,,asd,,,,,"name,surname",,,,,,,\n' newRecord = splitrecord(recordstring) print newRecord Result is: ['', '', '', '', '', '', '23', '', '', 'asd', '', '', '', '', 'name, surname', '', '', '', '', '', '', '\n'] Hope this helps, Byron --- Angelo Secchi wrote: > Hi, > I have string of numbers and words like > > ',,,,,,23,,,asd,,,,,"name,surname",,,,,,,\n' > > and I would like to split (I'm using string.split()) it using comma as > separator but I do not want to split in two also the "name,surname" > field. In other word I would like python in separating fields to skip > that particular comma. > > How can I do that? > > Thanks in advance > > Angelo From m.boeren at guidance.nl Tue Jul 20 08:05:15 2004 From: m.boeren at guidance.nl (Marc Boeren) Date: Tue, 20 Jul 2004 14:05:15 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 19) Message-ID: <0C77C7530EA52A4EBD1C47C80D1D291E07F99D@sbs.GuidanceBV.local> > "Anytime you need to do something on corresponding items in > two lists, you > should think of zip(), as this binds the matching elements > together." -- > Marc Boeren While it's true I said that, a quick googling shows that it was a bit more than a week ago (november 2003, actually :-) Cheerio, Marc. From lconrad at laymusic.org Thu Jul 29 07:34:12 2004 From: lconrad at laymusic.org (Laura Conrad) Date: Thu, 29 Jul 2004 07:34:12 -0400 Subject: Blt/Pmw/Tkinter under cygwin @)x_C2fgA~Wi&@/V"f6vs*B.1`(};T=]?M6O;HvGS Message-ID: <871xivqc7f.fsf@debian.laymusic.org> I'm writing a GUI application in python, which will need to work on a Windows XP box. Mostly it does, but the feature where results are graphed in real time, which works fine on a debian LINUX box, refuses to run on windows. I'm currently running on cygwin, and changing to a standalone python app would be a pain, but possible. The BltGraph demo which comes with Pmw also refuses to run. The code in that case is: if not Pmw.Blt.haveblt(parent): message = 'Sorry\nThe BLT package has not been\n' + \ 'installed on this system.\n' + \ 'Please install it and try again.' w = Tkinter.Label(parent, text = message) w.pack(padx = 8, pady = 8) return I have done something that I thought was installing Blt, but it doesn't seem to have given this code what it wanted. As far as I can tell from a simple-minded find/locate, the same Blt-related python files are installed on the Debian box as on the Windows box. So what do I do now? -- Laura (mailto:lconrad at laymusic.org , http://www.laymusic.org/ ) (617) 661-8097 fax: (501) 641-5011 233 Broadway, Cambridge, MA 02139 From say-no-to-spam at gmx.net Mon Jul 5 08:18:22 2004 From: say-no-to-spam at gmx.net (Matthias Gutfeldt) Date: Mon, 05 Jul 2004 14:18:22 +0200 Subject: eMaximarket Auctions provides RSS feeds In-Reply-To: <1EbGc.79542$sj4.30503@news-server.bigpond.net.au> References: <7fbe4113.0407050230.2981e62f@posting.google.com> <2ksrj9F5u9l1U1@uni-berlin.de> <1EbGc.79542$sj4.30503@news-server.bigpond.net.au> Message-ID: <2ksv8fF5v7leU1@uni-berlin.de> rf wrote: > SpaceGir lwrote > > >>*sighs* >> >>Well, had a bored 5 minutes waiting for a colour print. So, reported to >>ISP for spam. > > > So why did you repeat the entire spam? ... and x-post it all over usenet? The least one could do is set a suitable follow-up. Matthias From udodenko at hotmail.com Mon Jul 12 08:03:05 2004 From: udodenko at hotmail.com (Alex Mizrahi) Date: Mon, 12 Jul 2004 15:03:05 +0300 Subject: lisp is winner in DOM parsing contest! 8-] References: <2le3nlFb82reU1@uni-berlin.de> Message-ID: <2lfcvoFbs9m0U1@uni-berlin.de> (message (Hello 'Peter) (you :wrote :on '(Sun, 11 Jul 2004 22:15:50 -0400)) ( >> i have 3mb long XML document with about 150000 lines (i think it has >> about 200000 elements there) which i want to parse to DOM to work >> with. PH> Often, problems with performance come down the using the wrong PH> algorithm, or using the wrong architecture for the problem at hand. i see nothing wrong in loading 3 mb data into RAM. however, implementation details made it 100 times larger and it was the problem.. PH> Are you absolutely certain that using a full in-memory DOM PH> representation is the best for your problem? It seems very unlikely PH> to me that it really is... format i'm dealing with is quite chaotic and i'm going to work with it interactively - track down myself where data i need lie and see how can i extract data.. it's only a small part of task and it's needed only temporarily, so i don't need best thing possible - i need something that just works.. ) (With-best-regards '(Alex Mizrahi) :aka 'killer_storm) (prin1 "Jane dates only Lisp programmers")) From anthonybaxter at gmail.com Sat Jul 3 11:09:27 2004 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Sun, 4 Jul 2004 01:09:27 +1000 Subject: Time delay loop - better way? In-Reply-To: <20040703002129.6EAB.JCARLSON@uci.edu> References: <20040703002129.6EAB.JCARLSON@uci.edu> Message-ID: On Sat, 03 Jul 2004 00:50:40 -0700, Josiah Carlson wrote: > I have used wxTimers for doing asyncore.poll() scheduling every 1/100th > a second, and it seemed to work pretty reliably on my celeron 400. On Windows, shtoom was completely unable to use the wxTimer approach - it's timer precision is just horrific. We ended up splitting the UI off into a separate thread than all the time-senstive network stuff. I will admit that shtoom's requirements are a hell of a lot harsher than your "typical" application's, though. (twisted's wxreactor uses wxTimer) Anthony From jeff at ccvcorp.com Wed Jul 14 16:05:04 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 14 Jul 2004 13:05:04 -0700 Subject: returning a value from a thread In-Reply-To: References: <10fatb8dknikr58@corp.supernews.com> Message-ID: <10fb49dtbqk74d0@corp.supernews.com> Christopher T King wrote: >On Wed, 14 Jul 2004, Jeff Shannon wrote: > > > >>Christopher T King wrote: >> >> >> >>>Just don't forget to .join() on the thread in module1 before accessing the >>>container object! (Assuming you're using threading) I just wish Python's >>>.join() could return values, like pthread_join can. >>> >>> >>This may work if the worker thread will perform a relatively short task >>and then die *before* you access the result. But lists and dictionaries >>are not thread-safe -- if they are potentially accessed by multiple >>threads concurrently, then the behavior will be unpredictable. >> >> > >That's where the .join() comes in handy (it blocks until the thread dies) >;) > > True, but quite frankly, I don't see much value in starting a new thread if you're only going to be sitting around waiting for that thread to finish. At that point, where's the gain over simply calling a function? This may be a matter of style, but I see two major uses for worker threads. In one case, you're doing a little bit of work here, a little bit of work there, a little bit here again... back and forth. The other is the case where you have a long-running task, but want your user interface to remain responsive while that task running. (For instance, most GUI frameworks will have problems if their event queues aren't serviced regularly, and a lengthy calculation can prevent that unless you put it in another thread.) This would also include the case of a service/daemon which must remain responsive to new requests, so it fires up a separate thread to handle each incoming request. In the first case, you need to synchronize execution between the threads at multiple points; in the second, the threads each go about their own thing until the worker is finished, at which point it must notify the main thread. In neither case is it practical to join() the worker thread, because the whole point is that the main thread can't just sit and do nothing. If you *are* going to join(), then the advantages of concurrent execution get thrown away while sitting at that join(). I see no practical advantage of this: workerthread = threading.Thread(target=somefunc) workerthread.run() somestuff() someotherstuff() workerthread.join() vs this: somestuff() someotherstuff() somefunc() The only way you could possibly get a speed advantage from using a thread is on a multiprocessor machine, and I don't believe that Python currently makes use of multiple processors anyhow (though I think that it's possible for C extension modules to do so). The flow-control advantage of using a thread, that your program flow doesn't have to wait for the task to finish, is lost when you are waiting to join(). All you're left with is the added complexity. Now, if the worker thread needs to finish some subtask before, say, someotherstuff() is called, then you've got a potential for flow-control advantage... but you also need synchronization that's a lot more advanced than just waiting for the thread to die. If you don't need thread-safe communication between the threads, then you don't need threads, at least IMO. Jeff Shannon Technician/Programmer Credit International From lonetwin at gmail.com Tue Jul 20 02:45:42 2004 From: lonetwin at gmail.com (Steve) Date: Tue, 20 Jul 2004 12:15:42 +0530 Subject: Parsing other languages -> function map In-Reply-To: <282f826a.0407191652.95f986b@posting.google.com> References: <282f826a.0407191652.95f986b@posting.google.com> Message-ID: <5a309bd304071923457a61834e@mail.gmail.com> Hi Richard, On 19 Jul 2004 17:52:32 -0700, Richard Shea wrote: > Hi - [This is a Python question - bear with me !] I've got quite a > number of PHP scripts which include many functions which call each > other. I'm interested in having a means to determine which function > gets called from which other functions. I use cscope ( http://cscope.sourceforge.net/ ) for most of my code browsing (actually cscope+the cscope_maps.vim plugin). Although it was designed for looking at C code, due to the fact that it's parsing is more text oriented rather than specific to any language, it does a great job with python. I suggest you give it a spin with php code and see how things work. At a tangential thread, the idea of a tool like cscope which can support different languages using a plugin mechanism is really appealing. There always are things like source-navigator ( http://sourcenav.sourceforge.net/ ) , but that is more of an IDE including the kitchen-sink, which I personally do not like. It'd be cool to have a tool that just does one thing and does it properly, also, the coolness factor increases tremendously when the output can be obtained at stdout because we can then write a nice lil' plugin for our editor and instantly gloat that the _other_ editor cannot do this :). I'd be interested in writing one up if there is someone out there who could help out with the design and stuff. (pyscope anyone ?) Regards Steve From bvande at po-box.mcgill.ca Sat Jul 31 13:10:26 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 31 Jul 2004 13:10:26 -0400 Subject: Module Import Path? In-Reply-To: References: Message-ID: <410BD282.2050708@po-box.mcgill.ca> Jesse B. said unto the world upon 31/07/2004 15:42: > I have just begun to learn python using o'reilly's Learning Python, and in > chapter 3 it talks about importing modules. It has me make modules to > practice using the 'import' and 'from' statements from the python command > line. > > I don't know what directory to save these files in because I'm not sure what > directories 'import' is looking in to find modules. I've done some google > searches trying to find out where the 'import' search path is, but I'm not > familiar enough with python to do a clear enough search. I'd appriciate it > if anyone can help me out or point me in the right direction. > > Hi, Typing too quickly, I wrote > import sys > sys.path > > will tell you how your Python Path is configured. Not everything returned by sys.path is there because of your PYTHONPATH environment variable. For instance, the first entry is the one from which your running script was loaded. Likewise, the standard Library Dirs are there, too. Check out the sys module documentation for the full details. Best, Brian vdB From mwh at python.net Wed Jul 21 09:18:15 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 21 Jul 2004 13:18:15 GMT Subject: .__self__ References: Message-ID: Hallvard B Furuseth writes: > What's the difference between a built-in method and a method-wrapper > object? I *think* method-wrapper's are wrappers around type methods, aka tp_wotsit slots at the C level. builtin-methods are, well, builtin methods, similar to method's on regular Python classes but implemented in C. > Why has only the former a __self__, even though both are tied to the > object on which to perform the operation? Because. Probably an oversight. > Why do list.pop and list.__len__ have different types at all? Well, because they do :-) See above. If you want to really dig into this sort of thing, you're going to need to read some source. Cheers, mwh -- Windows 2000: Smaller cow. Just as much crap. -- Jim's pedigree of operating systems, asr From theller at python.net Wed Jul 28 16:08:46 2004 From: theller at python.net (Thomas Heller) Date: Wed, 28 Jul 2004 22:08:46 +0200 Subject: aspn python References: Message-ID: <3c3b51yp.fsf@python.net> "dw" writes: > Thought that someone would need ASPN's python cookie book > inside chm for easy offline-searching. > > http://miaw.compeng.org/~dody/aspncookbook.chm > > last grabbed around 15jan04. Yes, it's useful. Although I have to remember to use that more often. Thanks, Thomas From jacek.generowicz at cern.ch Mon Jul 12 03:21:29 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Jul 2004 09:21:29 +0200 Subject: Modifying func_closure References: Message-ID: Christopher T King writes: > Is there a reason you couldn't encapsule the functions and 'enclosed' in a > class (assuming you can move the function definitions into a class)? Yes. See http://www.google.com/groups?as_umsgid=mailman.221.1089519729.5135.python-list at python.org From jarausch at igpm.rwth-aachen.de Fri Jul 23 05:25:28 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 23 Jul 2004 11:25:28 +0200 Subject: Python C++ In-Reply-To: References: <40FE46ED.7000203@igpm.rwth-aachen.de> Message-ID: <4100D988.4050804@igpm.rwth-aachen.de> Neal D. Becker wrote: > Helmut Jarausch wrote: > > >>Francois Fernandes wrote: >> >>>Hi! >>> >>>Is it possible to easyly integrate c++ classes in python? >>> >>>I don't want to use boost c++. >>> >>>Does anyone know how to start or where to find documentation for this? >>> >> >>I prefer PyCXX http://cxx.sourceforge.net >> >> > > > Looks interesting. I want to expose lots of signal processing algorithms > written in C++ to python. I want to use std::vector for containers, > because they are fast. I need to create python types for > std::vector and std::vector> at minimum. The > Python interface doesn't need to know much about these types, just be able > to create vectors of a given size. > > Would PyCXX be a good choice for this? Are there any samples of code > similar to this? > I think, yes. PyCXX allows for use of the STL. For each type FOO in your module you provide a new_FOO which is called when you create an object. There you can call any C++ code including class constructors. PyCXX helps you in filling out these long structs needed for a new type. It helps with exception handling and reference counting. I am new to PyCXX myself, but it worked very soon. There is a rather general example in the Demo directory. I've just copied and modified the code and it worked like expected - GREAT! The documentation is not too long but suffucient and very readable. It does NOT (try to) wrap your C++ classes automatically like other tools. I prefer this (since I don't have hundreds of classes). One can easily fully understand what's going on and if something is missing (e.g. I think conversion of an unsigned int to a Python long int) one can easily add this feature using calls from the C-API himself. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From squirrel at WPI.EDU Tue Jul 27 11:28:29 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 27 Jul 2004 11:28:29 -0400 Subject: using generators with format strings In-Reply-To: References: Message-ID: On Tue, 27 Jul 2004, John Lenton wrote: > does anyone else get the feeling that (str %) should have a third > behaviour wrt generators? By this I mean that str % seq is one > behaviour, str % dict is another, and there should be a str % iter, > probably consuming items from the iterator up to the number of > arguments of the format string? The only argument I see against this is that it could break existing code of the form '%r' % some_object, where some_object could easily be an iterable object (say, a numarray array). Of course, limiting it to only generators rather than iterators in general would fix this, but then the benefit gained seems too small to justify the cost of implementing another exception to the rule. From fumanchu at amor.org Thu Jul 8 11:03:35 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Jul 2004 08:03:35 -0700 Subject: Proper tail recursion Message-ID: Christopher T King wrote: > Methinks tail calls > will have to wait for Stackless. Well, *compiler optimization* of tail calls will have to wait, perhaps. But you can always do your own transformations: http://www.cs.indiana.edu/~dfried/dfried/dfried/mex.pdf Robert Brewer MIS Amor Ministries fumanchu at amor.org From __peter__ at web.de Tue Jul 13 18:42:59 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Jul 2004 00:42:59 +0200 Subject: object attributes from a dictionary References: Message-ID: Darren Dale wrote: > Is there a more direct way than this to turn a dictionary into an object? > > class pupa: > def __init__(self,initDict,*args,**kwargs): > [setattr(self,key,initDict[key]) for key in initDict.keys()] > > larva={'a':1,'b':2} > moth=pupa(larva) > > (ok, so I'm dorking a bit here. I havent slept in two days.) The most direct way is: >>> class pupa: ... def __init__(self, d): ... self.__dict__ = d ... >>> larva = {"a": 1, "b": 2} >>> moth = pupa(larva) >>> moth.a 1 >>> moth.c = 3 >>> larva {'a': 1, 'c': 3, 'b': 2} >>> larva["x"] = 5 >>> moth.x 5 So every change in moth affects larva and vice versa. If that is too direct, change the initializer to update instead of rebind __dict__: >>> class pupa2: ... def __init__(self, d): ... self.__dict__.update(d) ... >>> moth2 = pupa2(larva) >>> moth2.c 3 >>> moth2.d = 4 >>> larva {'a': 1, 'x': 5, 'c': 3, 'b': 2} # no "d" key >>> Peter From tim.peters at gmail.com Mon Jul 19 16:53:05 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 19 Jul 2004 16:53:05 -0400 Subject: Sorted list as an alternative to dictionary for when you only need keys? In-Reply-To: <20040719204415.GM7839@unpythonic.net> References: <000d01c46dcd$9f624f80$4b00a8c0@RR2> <20040719204415.GM7839@unpythonic.net> Message-ID: <1f7befae04071913534d7c0fab@mail.gmail.com> [Jeff Epler] > ... > Python 2.2 and above also have a "bisect" module which can be used for O(lg n) > insertions, deletions, and searches for items in sorted lists, but > there's not a simple OO interface for it. The bisect module is much older than 2.2 (I can't remember a time when Python didn't have it), but insertion and deletion are O(n), only lookup is O(log n) with bisect. Expected time is O(1) for insertion, deletion, and lookup with a dict. Sets are the same as dicts. From ialbert at mailblocks.com Wed Jul 21 09:19:47 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 21 Jul 2004 09:19:47 -0400 Subject: Call for Grant Proposals In-Reply-To: References: <40fcaa90$0$27091$9b622d9e@news.freenet.de> Message-ID: Peter Hansen wrote: > See http://www.python.org/psf/donations.html for just why this is so... > and consider getting your own name on the list. will do. i. From davidf at sjsoft.com Mon Jul 19 06:41:38 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 19 Jul 2004 12:41:38 +0200 Subject: extension module In-Reply-To: References: Message-ID: User At wrote: > > Besides the python docs, where else can I find information (including > well examples) on extending python using C/C++? On the web :-) If you want a clearer answer, then say why the python docs are insufficient... David From nobody at nowhere.com Tue Jul 27 13:19:36 2004 From: nobody at nowhere.com (Yannick Turgeon) Date: Tue, 27 Jul 2004 13:19:36 -0400 Subject: IPC Message-ID: Hi, I'm relatively new to Python. I'm using 2.3.4 on W2K. What I want to do is to start a program and interact with it. Say my program is FTP, I want to start FTP then send the commande "open x.x.x.x" then look for the answer (if the connection is opened or not), then do something dependant of the success or error. I tried with popen3. The problem I got with this: it seems that I have to end the program before being able to read the output. Or maybe I'm not using it correctly. I do test the communication with FTP exec. but it will be a custom program in real. Here is my code: def test(self): cmd = "ftp" r, w, e = popen2.popen3(cmd) cmd = "?\n" # A simple FTP commande w.write(cmd) w.flush() # That is what I would like but it's hanging here. I have to remove this group and read at the end. for line in e.readlines(): # Do something conditionnal to the result of "line" pass for line in r.readlines(): # Do something conditionnal to the result of "line" pass cmd = "quit\n" w.write(cmd) w.flush() for line in e.readlines(): print line for line in r.readlines(): print line w.close() r.close() e.close() ---------------------- Anybody can help? Thanks for your time. Yannick From jeff at ccvcorp.com Wed Jul 14 19:11:21 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 14 Jul 2004 16:11:21 -0700 Subject: returning a value from a thread In-Reply-To: References: Message-ID: <10fbf6nc1q3rab7@corp.supernews.com> Ken Godee wrote: > I'm weaving quite a snake here already, there's even more modules > in the flow then what I've mentioned, including GUI stuff. > Didn't want to rewrite or make it tougher than need be just > to get a single value back to module1. You may want to look further into your GUI toolkit, as well. I know that wxPython has a thread-safe way of sending messages to a particular window (wxPostEvent), which can be used to signal task completion. I don't specifically know about other toolkits, but I wouldn't be at all surprised if this is a common feature, since signalling worker-thread completion *is* a fairly common task in GUI programs. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Fri Jul 16 14:15:17 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 16 Jul 2004 11:15:17 -0700 Subject: try: finally: question In-Reply-To: References: <40eadf77@usenet01.boi.hp.com> <40eb00db@usenet01.boi.hp.com> <35-dnVL-0qrXtnbdRVn-jg@powergate.ca> <2IadnfA7t7M3vXHdRVn-ug@powergate.ca> Message-ID: <10fg6jmfijtp83a@corp.supernews.com> Joshua Marshall wrote: > Why is this not an argument for disallowing multiple except blocks, like: > > try: > raise A() > except A: > raise B() > except B: > print 'Did we get here?' > >This is legal and well-defined in Python. If try/except/finally was >removed it seems like multiple except blocks should have been removed >too--the behavior of one is as obvious as the other. > > I'd like to note that, in this case, exactly one of the except blocks gets executed. If an exception is raised within one of the branches, it doesn't get caught by later branches. In the 'finally' case, it's unclear whether it should catch such a secondary exception or not. On the one hand, we have the established precedent that an exception within an exception handler goes up to the caller. On the other hand, we have the expectation that 'finally' should always be executed when leaving the specified code block. But which block is being specified -- just the 'try' section, or all of the 'except' clauses as well? Syntactically, it seems that try-clause-only should be the correct answer, but including all of the except clauses would be the most common desire... Given the different semantics of finally vs except, I can certainly see a *lot* of room for confusion. Jeff Shannon Technician/Programmer Credit International From pwatson at redlinepy.com Thu Jul 8 14:09:05 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 8 Jul 2004 13:09:05 -0500 Subject: open is not obsolete (was Re: understanding self References: <5OaHc.45662$JG5.971334@news20.bellglobal.com> Message-ID: <2l5gtsF8le87U1@uni-berlin.de> "Colin J. Williams" wrote in message news:5OaHc.45662$JG5.971334 at news20.bellglobal.com... > > > Delaney, Timothy C (Timothy) wrote: > > > Jeff Shannon wrote: > > > > > >>Okay, perhaps "legacy" is a better term than "obsolete". In either > >>case, it's recommended that it not be used in new code, even if there > >>is no current plan to remove it. Not that the specifics of this case > >>are particularly germane to the point I was making... > > > > > > As mentioned by Tony, this is not the case. From python-dev: > > > > > >>>Then should the following line in the reference be changed? > >>> > >>>"The file() constructor is new in Python 2.2. The previous spelling, > >>>open(), is retained for compatibility, and is an alias for file()." > >>> > >>>That *strongly* suggests that the preferred spelling is file(), and > >>>that open() shouldn't be used for new code. > >> > >>Oops, yes. I didn't write that, and it doesn't convey my feelings > >>about file() vs. open(). Here's a suggestion for better words: > >> > >>"The file class is new in Python 2.2. It represents the type (class) > >>of objects returned by the built-in open() function. Its constructor > >>is an alias for open(), but for future and backwards compatibility, > >>open() remains preferred." > >> > >>--Guido van Rossum (home page: http://www.python.org/~guido/) > > > > > > Tim Delaney > > "file" is analogous to a class constructor, while "open" becomes a > factory function for that class, with the same signature. > > This raises the question as to which is the better way of creating an > instance of a class. > > It seems to me that the constructor is, for simple cass, the better way > to go. It provides one way and avoids the question of "Should I use A > or B when there are more than one ways of doing some task. > > What is the general view? > > Colin W. It would appear that the "General DBFL" view is to use open(). From __peter__ at web.de Wed Jul 14 02:54:21 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Jul 2004 08:54:21 +0200 Subject: timeit.timeit and timeit.repeat give different answers References: <87pt72bdmi.fsf@uwo.ca> <87hdsbdeir.fsf@uwo.ca> <87d62zh1rb.fsf@uwo.ca> Message-ID: Dan Christensen wrote: > Hmm, if I type this at the python prompt: > > r = [] > for i in range(1): # Note: only one loop! > ti = t.timeit() > r.append(ti) > print r > > I get data that agrees with t.repeat but disagrees with: ... > t.timeit() You could try "intermediate simplifications" to spot the culprit: r = [None] for i in range(1): r[i] = t.timeit() and for i in range(1): ti = t.timeit() I've no idea what's happening. Peter From michael at stroeder.com Wed Jul 28 19:49:51 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 29 Jul 2004 01:49:51 +0200 Subject: ANN: python-ldap-2.0.1 Message-ID: Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.2 2004-07-29 Changes since 2.0.1: Modules: * Fixed detecting appropriate OpenLDAP libs version for determining whether ldap_whoami_s() is available or not. This fixes build problems with OpenLDAP libs 2.1.0 up to 2.1.12. From google at spiceaid.com Wed Jul 28 14:03:41 2004 From: google at spiceaid.com (Jeff Smith) Date: 28 Jul 2004 11:03:41 -0700 Subject: Test failures on AIX 5.1 for 2.3.4 Message-ID: <3d4251a8.0407281003.5546de45@posting.google.com> I built Python 2.3.4 on AIX 5.1 with the AIX C compiler cc_r and had three test failures during the "make test" phase: test_coercion test_mmap test_pty Do I need to worry about these? Should I submit a bug report? Thanks, Jeff From fgeiger at datec.at Sun Jul 18 04:44:56 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 18 Jul 2004 10:44:56 +0200 Subject: Recommendation for GUI/OpenGL (or similar 3D functionality) environment References: Message-ID: I did some 3D things on Win2k and WinXP. I used wxPython and PyOpenGL. I tend to advise to forget alle the tools helping you build a GUI. That's the best way to remain in full control over what happens in your app. YMMV. What you really *should* use is an IDE like Wingware (IDLE, Kommodo etc.). Again for the GUI lib: When I encounter a new lib, I first see what features it offers that my current platform (wxPython for now) does not and if I really could have a need for them in future. Then I look at the sample code to see how it achieves all that. This gives me a good first impression. On this I decide whether I go on investigating it or not. Doing so may help you too. Again: YMMV. HTH Franz GEIGER "jc" schrieb im Newsbeitrag news:HdoKc.31$lm3.24 at fe1.columbus.rr.com... > I am pretty new to Python but am thrilled with its elegant syntax, > style, efficiency... > > I want to use Python for database query device that can also display > 3D objects (up to several thousand, small primitives (more like > specks)but with some alpha channel control) > on a 3D Cartesian volume. I guess in simple terms a 3D window embedded > in a DB query device. > > I have looked at Boa Constructor, PyhtonCard, Tkinter, a bunch of others > and the choices can get pretty bewildering! > > Could I get some recommendations on a GUI environment that can do what I > stated above but is the 'easiest'. > > I'm willing to spend some time learning but would prefer to stick to the > one 'best' decision. > > Other important points would be how robust the system is, how good is > the documentation, is it maintained regularly, etc. > I am on WinXP. From eric_brunel at despammed.com Fri Jul 2 04:28:26 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 02 Jul 2004 10:28:26 +0200 Subject: Pmw EntryWidget Help References: Message-ID: Greg Lindstrom wrote: > Hello- > > I am working with the Pmw EntryWidget and would like to know how to set the > length of the field that contains the entered text (not the label portion). > I would like to extend the field to hold (and display) longer values than > the default. The options for the individual widgets in Pmw mega-widgets are usually of the form _